Bug Summary

File:tools/clang/lib/AST/ASTImporter.cpp
Warning:line 8026, column 47
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-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 -analyzer-config-compatibility-mode=true -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-9/lib/clang/9.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-9~svn362543/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/include -I /build/llvm-toolchain-snapshot-9~svn362543/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/include/clang/9.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-9/lib/clang/9.0.0/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-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-9~svn362543/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-9~svn362543=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -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-2019-06-05-060531-1271-1 -x c++ /build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp -faddrsig

/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp

1//===- ASTImporter.cpp - Importing ASTs from other Contexts ---------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file defines the ASTImporter class which imports AST nodes from one
10// context into another context.
11//
12//===----------------------------------------------------------------------===//
13
14#include "clang/AST/ASTImporter.h"
15#include "clang/AST/ASTImporterLookupTable.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 using llvm::make_error;
75 using llvm::Error;
76 using llvm::Expected;
77 using ExpectedType = llvm::Expected<QualType>;
78 using ExpectedStmt = llvm::Expected<Stmt *>;
79 using ExpectedExpr = llvm::Expected<Expr *>;
80 using ExpectedDecl = llvm::Expected<Decl *>;
81 using ExpectedSLoc = llvm::Expected<SourceLocation>;
82
83 std::string ImportError::toString() const {
84 // FIXME: Improve error texts.
85 switch (Error) {
86 case NameConflict:
87 return "NameConflict";
88 case UnsupportedConstruct:
89 return "UnsupportedConstruct";
90 case Unknown:
91 return "Unknown error";
92 }
93 llvm_unreachable("Invalid error code.")::llvm::llvm_unreachable_internal("Invalid error code.", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp"
, 93)
;
94 return "Invalid error code.";
95 }
96
97 void ImportError::log(raw_ostream &OS) const {
98 OS << toString();
99 }
100
101 std::error_code ImportError::convertToErrorCode() const {
102 llvm_unreachable("Function not implemented.")::llvm::llvm_unreachable_internal("Function not implemented."
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp"
, 102)
;
103 }
104
105 char ImportError::ID;
106
107 template <class T>
108 SmallVector<Decl *, 2>
109 getCanonicalForwardRedeclChain(Redeclarable<T>* D) {
110 SmallVector<Decl *, 2> Redecls;
111 for (auto *R : D->getFirstDecl()->redecls()) {
112 if (R != D->getFirstDecl())
113 Redecls.push_back(R);
114 }
115 Redecls.push_back(D->getFirstDecl());
116 std::reverse(Redecls.begin(), Redecls.end());
117 return Redecls;
118 }
119
120 SmallVector<Decl*, 2> getCanonicalForwardRedeclChain(Decl* D) {
121 if (auto *FD = dyn_cast<FunctionDecl>(D))
122 return getCanonicalForwardRedeclChain<FunctionDecl>(FD);
123 if (auto *VD = dyn_cast<VarDecl>(D))
124 return getCanonicalForwardRedeclChain<VarDecl>(VD);
125 if (auto *TD = dyn_cast<TagDecl>(D))
126 return getCanonicalForwardRedeclChain<TagDecl>(TD);
127 llvm_unreachable("Bad declaration kind")::llvm::llvm_unreachable_internal("Bad declaration kind", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp"
, 127)
;
128 }
129
130 void updateFlags(const Decl *From, Decl *To) {
131 // Check if some flags or attrs are new in 'From' and copy into 'To'.
132 // FIXME: Other flags or attrs?
133 if (From->isUsed(false) && !To->isUsed(false))
134 To->setIsUsed();
135 }
136
137 class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, ExpectedType>,
138 public DeclVisitor<ASTNodeImporter, ExpectedDecl>,
139 public StmtVisitor<ASTNodeImporter, ExpectedStmt> {
140 ASTImporter &Importer;
141
142 // Use this instead of Importer.importInto .
143 template <typename ImportT>
144 LLVM_NODISCARD[[clang::warn_unused_result]] Error importInto(ImportT &To, const ImportT &From) {
145 return Importer.importInto(To, From);
146 }
147
148 // Use this to import pointers of specific type.
149 template <typename ImportT>
150 LLVM_NODISCARD[[clang::warn_unused_result]] Error importInto(ImportT *&To, ImportT *From) {
151 auto ToOrErr = Importer.Import(From);
152 if (ToOrErr)
153 To = cast_or_null<ImportT>(*ToOrErr);
154 return ToOrErr.takeError();
155 }
156
157 // Call the import function of ASTImporter for a baseclass of type `T` and
158 // cast the return value to `T`.
159 template <typename T>
160 Expected<T *> import(T *From) {
161 auto ToOrErr = Importer.Import(From);
162 if (!ToOrErr)
163 return ToOrErr.takeError();
164 return cast_or_null<T>(*ToOrErr);
165 }
166
167 template <typename T>
168 Expected<T *> import(const T *From) {
169 return import(const_cast<T *>(From));
170 }
171
172 // Call the import function of ASTImporter for type `T`.
173 template <typename T>
174 Expected<T> import(const T &From) {
175 return Importer.Import(From);
6
Calling 'ASTImporter::Import'
176 }
177
178 // Import an Optional<T> by importing the contained T, if any.
179 template<typename T>
180 Expected<Optional<T>> import(Optional<T> From) {
181 if (!From)
182 return Optional<T>();
183 return import(*From);
184 }
185
186 template <class T>
187 Expected<std::tuple<T>>
188 importSeq(const T &From) {
189 Expected<T> ToOrErr = import(From);
5
Calling 'ASTNodeImporter::import'
190 if (!ToOrErr)
191 return ToOrErr.takeError();
192 return std::make_tuple<T>(std::move(*ToOrErr));
193 }
194
195 // Import multiple objects with a single function call.
196 // This should work for every type for which a variant of `import` exists.
197 // The arguments are processed from left to right and import is stopped on
198 // first error.
199 template <class THead, class... TTail>
200 Expected<std::tuple<THead, TTail...>>
201 importSeq(const THead &FromHead, const TTail &...FromTail) {
202 Expected<std::tuple<THead>> ToHeadOrErr = importSeq(FromHead);
203 if (!ToHeadOrErr)
1
Taking false branch
3
Taking false branch
204 return ToHeadOrErr.takeError();
205 Expected<std::tuple<TTail...>> ToTailOrErr = importSeq(FromTail...);
2
Calling 'ASTNodeImporter::importSeq'
4
Calling 'ASTNodeImporter::importSeq'
206 if (!ToTailOrErr)
207 return ToTailOrErr.takeError();
208 return std::tuple_cat(*ToHeadOrErr, *ToTailOrErr);
209 }
210
211// Wrapper for an overload set.
212 template <typename ToDeclT> struct CallOverloadedCreateFun {
213 template <typename... Args>
214 auto operator()(Args &&... args)
215 -> decltype(ToDeclT::Create(std::forward<Args>(args)...)) {
216 return ToDeclT::Create(std::forward<Args>(args)...);
217 }
218 };
219
220 // Always use these functions to create a Decl during import. There are
221 // certain tasks which must be done after the Decl was created, e.g. we
222 // must immediately register that as an imported Decl. The parameter `ToD`
223 // will be set to the newly created Decl or if had been imported before
224 // then to the already imported Decl. Returns a bool value set to true if
225 // the `FromD` had been imported before.
226 template <typename ToDeclT, typename FromDeclT, typename... Args>
227 LLVM_NODISCARD[[clang::warn_unused_result]] bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
228 Args &&... args) {
229 // There may be several overloads of ToDeclT::Create. We must make sure
230 // to call the one which would be chosen by the arguments, thus we use a
231 // wrapper for the overload set.
232 CallOverloadedCreateFun<ToDeclT> OC;
233 return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
234 std::forward<Args>(args)...);
235 }
236 // Use this overload if a special Type is needed to be created. E.g if we
237 // want to create a `TypeAliasDecl` and assign that to a `TypedefNameDecl`
238 // then:
239 // TypedefNameDecl *ToTypedef;
240 // GetImportedOrCreateDecl<TypeAliasDecl>(ToTypedef, FromD, ...);
241 template <typename NewDeclT, typename ToDeclT, typename FromDeclT,
242 typename... Args>
243 LLVM_NODISCARD[[clang::warn_unused_result]] bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD,
244 Args &&... args) {
245 CallOverloadedCreateFun<NewDeclT> OC;
246 return GetImportedOrCreateSpecialDecl(ToD, OC, FromD,
247 std::forward<Args>(args)...);
248 }
249 // Use this version if a special create function must be
250 // used, e.g. CXXRecordDecl::CreateLambda .
251 template <typename ToDeclT, typename CreateFunT, typename FromDeclT,
252 typename... Args>
253 LLVM_NODISCARD[[clang::warn_unused_result]] bool
254 GetImportedOrCreateSpecialDecl(ToDeclT *&ToD, CreateFunT CreateFun,
255 FromDeclT *FromD, Args &&... args) {
256 // FIXME: This code is needed later.
257 //if (Importer.getImportDeclErrorIfAny(FromD)) {
258 // ToD = nullptr;
259 // return true; // Already imported but with error.
260 //}
261 ToD = cast_or_null<ToDeclT>(Importer.GetAlreadyImportedOrNull(FromD));
262 if (ToD)
263 return true; // Already imported.
264 ToD = CreateFun(std::forward<Args>(args)...);
265 // Keep track of imported Decls.
266 Importer.RegisterImportedDecl(FromD, ToD);
267 InitializeImportedDecl(FromD, ToD);
268 return false; // A new Decl is created.
269 }
270
271 void InitializeImportedDecl(Decl *FromD, Decl *ToD) {
272 ToD->IdentifierNamespace = FromD->IdentifierNamespace;
273 if (FromD->hasAttrs())
274 for (const Attr *FromAttr : FromD->getAttrs()) {
275 // FIXME: Return of the error here is not possible until store of
276 // import errors is implemented.
277 auto ToAttrOrErr = import(FromAttr);
278 if (ToAttrOrErr)
279 ToD->addAttr(*ToAttrOrErr);
280 else
281 llvm::consumeError(ToAttrOrErr.takeError());
282 }
283 if (FromD->isUsed())
284 ToD->setIsUsed();
285 if (FromD->isImplicit())
286 ToD->setImplicit();
287 }
288
289 // Check if we have found an existing definition. Returns with that
290 // definition if yes, otherwise returns null.
291 Decl *FindAndMapDefinition(FunctionDecl *D, FunctionDecl *FoundFunction) {
292 const FunctionDecl *Definition = nullptr;
293 if (D->doesThisDeclarationHaveABody() &&
294 FoundFunction->hasBody(Definition))
295 return Importer.MapImported(D, const_cast<FunctionDecl *>(Definition));
296 return nullptr;
297 }
298
299 public:
300 explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {}
301
302 using TypeVisitor<ASTNodeImporter, ExpectedType>::Visit;
303 using DeclVisitor<ASTNodeImporter, ExpectedDecl>::Visit;
304 using StmtVisitor<ASTNodeImporter, ExpectedStmt>::Visit;
305
306 // Importing types
307 ExpectedType VisitType(const Type *T);
308 ExpectedType VisitAtomicType(const AtomicType *T);
309 ExpectedType VisitBuiltinType(const BuiltinType *T);
310 ExpectedType VisitDecayedType(const DecayedType *T);
311 ExpectedType VisitComplexType(const ComplexType *T);
312 ExpectedType VisitPointerType(const PointerType *T);
313 ExpectedType VisitBlockPointerType(const BlockPointerType *T);
314 ExpectedType VisitLValueReferenceType(const LValueReferenceType *T);
315 ExpectedType VisitRValueReferenceType(const RValueReferenceType *T);
316 ExpectedType VisitMemberPointerType(const MemberPointerType *T);
317 ExpectedType VisitConstantArrayType(const ConstantArrayType *T);
318 ExpectedType VisitIncompleteArrayType(const IncompleteArrayType *T);
319 ExpectedType VisitVariableArrayType(const VariableArrayType *T);
320 ExpectedType VisitDependentSizedArrayType(const DependentSizedArrayType *T);
321 // FIXME: DependentSizedExtVectorType
322 ExpectedType VisitVectorType(const VectorType *T);
323 ExpectedType VisitExtVectorType(const ExtVectorType *T);
324 ExpectedType VisitFunctionNoProtoType(const FunctionNoProtoType *T);
325 ExpectedType VisitFunctionProtoType(const FunctionProtoType *T);
326 ExpectedType VisitUnresolvedUsingType(const UnresolvedUsingType *T);
327 ExpectedType VisitParenType(const ParenType *T);
328 ExpectedType VisitTypedefType(const TypedefType *T);
329 ExpectedType VisitTypeOfExprType(const TypeOfExprType *T);
330 // FIXME: DependentTypeOfExprType
331 ExpectedType VisitTypeOfType(const TypeOfType *T);
332 ExpectedType VisitDecltypeType(const DecltypeType *T);
333 ExpectedType VisitUnaryTransformType(const UnaryTransformType *T);
334 ExpectedType VisitAutoType(const AutoType *T);
335 ExpectedType VisitInjectedClassNameType(const InjectedClassNameType *T);
336 // FIXME: DependentDecltypeType
337 ExpectedType VisitRecordType(const RecordType *T);
338 ExpectedType VisitEnumType(const EnumType *T);
339 ExpectedType VisitAttributedType(const AttributedType *T);
340 ExpectedType VisitTemplateTypeParmType(const TemplateTypeParmType *T);
341 ExpectedType VisitSubstTemplateTypeParmType(
342 const SubstTemplateTypeParmType *T);
343 ExpectedType VisitTemplateSpecializationType(
344 const TemplateSpecializationType *T);
345 ExpectedType VisitElaboratedType(const ElaboratedType *T);
346 ExpectedType VisitDependentNameType(const DependentNameType *T);
347 ExpectedType VisitPackExpansionType(const PackExpansionType *T);
348 ExpectedType VisitDependentTemplateSpecializationType(
349 const DependentTemplateSpecializationType *T);
350 ExpectedType VisitObjCInterfaceType(const ObjCInterfaceType *T);
351 ExpectedType VisitObjCObjectType(const ObjCObjectType *T);
352 ExpectedType VisitObjCObjectPointerType(const ObjCObjectPointerType *T);
353
354 // Importing declarations
355 Error ImportDeclParts(
356 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
357 DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc);
358 Error ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr);
359 Error ImportDeclarationNameLoc(
360 const DeclarationNameInfo &From, DeclarationNameInfo &To);
361 Error ImportDeclContext(DeclContext *FromDC, bool ForceImport = false);
362 Error ImportDeclContext(
363 Decl *From, DeclContext *&ToDC, DeclContext *&ToLexicalDC);
364 Error ImportImplicitMethods(const CXXRecordDecl *From, CXXRecordDecl *To);
365
366 Expected<CXXCastPath> ImportCastPath(CastExpr *E);
367
368 using Designator = DesignatedInitExpr::Designator;
369
370 /// What we should import from the definition.
371 enum ImportDefinitionKind {
372 /// Import the default subset of the definition, which might be
373 /// nothing (if minimal import is set) or might be everything (if minimal
374 /// import is not set).
375 IDK_Default,
376 /// Import everything.
377 IDK_Everything,
378 /// Import only the bare bones needed to establish a valid
379 /// DeclContext.
380 IDK_Basic
381 };
382
383 bool shouldForceImportDeclContext(ImportDefinitionKind IDK) {
384 return IDK == IDK_Everything ||
385 (IDK == IDK_Default && !Importer.isMinimalImport());
386 }
387
388 Error ImportInitializer(VarDecl *From, VarDecl *To);
389 Error ImportDefinition(
390 RecordDecl *From, RecordDecl *To,
391 ImportDefinitionKind Kind = IDK_Default);
392 Error ImportDefinition(
393 EnumDecl *From, EnumDecl *To,
394 ImportDefinitionKind Kind = IDK_Default);
395 Error ImportDefinition(
396 ObjCInterfaceDecl *From, ObjCInterfaceDecl *To,
397 ImportDefinitionKind Kind = IDK_Default);
398 Error ImportDefinition(
399 ObjCProtocolDecl *From, ObjCProtocolDecl *To,
400 ImportDefinitionKind Kind = IDK_Default);
401 Error ImportTemplateArguments(
402 const TemplateArgument *FromArgs, unsigned NumFromArgs,
403 SmallVectorImpl<TemplateArgument> &ToArgs);
404 Expected<TemplateArgument>
405 ImportTemplateArgument(const TemplateArgument &From);
406
407 template <typename InContainerTy>
408 Error ImportTemplateArgumentListInfo(
409 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo);
410
411 template<typename InContainerTy>
412 Error ImportTemplateArgumentListInfo(
413 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
414 const InContainerTy &Container, TemplateArgumentListInfo &Result);
415
416 using TemplateArgsTy = SmallVector<TemplateArgument, 8>;
417 using FunctionTemplateAndArgsTy =
418 std::tuple<FunctionTemplateDecl *, TemplateArgsTy>;
419 Expected<FunctionTemplateAndArgsTy>
420 ImportFunctionTemplateWithTemplateArgsFromSpecialization(
421 FunctionDecl *FromFD);
422 Error ImportTemplateParameterLists(const DeclaratorDecl *FromD,
423 DeclaratorDecl *ToD);
424
425 Error ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD);
426
427 Error ImportFunctionDeclBody(FunctionDecl *FromFD, FunctionDecl *ToFD);
428
429 template <typename T>
430 bool hasSameVisibilityContext(T *Found, T *From);
431
432 bool IsStructuralMatch(Decl *From, Decl *To, bool Complain);
433 bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord,
434 bool Complain = true);
435 bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
436 bool Complain = true);
437 bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord);
438 bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC);
439 bool IsStructuralMatch(FunctionTemplateDecl *From,
440 FunctionTemplateDecl *To);
441 bool IsStructuralMatch(FunctionDecl *From, FunctionDecl *To);
442 bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To);
443 bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To);
444 ExpectedDecl VisitDecl(Decl *D);
445 ExpectedDecl VisitImportDecl(ImportDecl *D);
446 ExpectedDecl VisitEmptyDecl(EmptyDecl *D);
447 ExpectedDecl VisitAccessSpecDecl(AccessSpecDecl *D);
448 ExpectedDecl VisitStaticAssertDecl(StaticAssertDecl *D);
449 ExpectedDecl VisitTranslationUnitDecl(TranslationUnitDecl *D);
450 ExpectedDecl VisitNamespaceDecl(NamespaceDecl *D);
451 ExpectedDecl VisitNamespaceAliasDecl(NamespaceAliasDecl *D);
452 ExpectedDecl VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias);
453 ExpectedDecl VisitTypedefDecl(TypedefDecl *D);
454 ExpectedDecl VisitTypeAliasDecl(TypeAliasDecl *D);
455 ExpectedDecl VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D);
456 ExpectedDecl VisitLabelDecl(LabelDecl *D);
457 ExpectedDecl VisitEnumDecl(EnumDecl *D);
458 ExpectedDecl VisitRecordDecl(RecordDecl *D);
459 ExpectedDecl VisitEnumConstantDecl(EnumConstantDecl *D);
460 ExpectedDecl VisitFunctionDecl(FunctionDecl *D);
461 ExpectedDecl VisitCXXMethodDecl(CXXMethodDecl *D);
462 ExpectedDecl VisitCXXConstructorDecl(CXXConstructorDecl *D);
463 ExpectedDecl VisitCXXDestructorDecl(CXXDestructorDecl *D);
464 ExpectedDecl VisitCXXConversionDecl(CXXConversionDecl *D);
465 ExpectedDecl VisitFieldDecl(FieldDecl *D);
466 ExpectedDecl VisitIndirectFieldDecl(IndirectFieldDecl *D);
467 ExpectedDecl VisitFriendDecl(FriendDecl *D);
468 ExpectedDecl VisitObjCIvarDecl(ObjCIvarDecl *D);
469 ExpectedDecl VisitVarDecl(VarDecl *D);
470 ExpectedDecl VisitImplicitParamDecl(ImplicitParamDecl *D);
471 ExpectedDecl VisitParmVarDecl(ParmVarDecl *D);
472 ExpectedDecl VisitObjCMethodDecl(ObjCMethodDecl *D);
473 ExpectedDecl VisitObjCTypeParamDecl(ObjCTypeParamDecl *D);
474 ExpectedDecl VisitObjCCategoryDecl(ObjCCategoryDecl *D);
475 ExpectedDecl VisitObjCProtocolDecl(ObjCProtocolDecl *D);
476 ExpectedDecl VisitLinkageSpecDecl(LinkageSpecDecl *D);
477 ExpectedDecl VisitUsingDecl(UsingDecl *D);
478 ExpectedDecl VisitUsingShadowDecl(UsingShadowDecl *D);
479 ExpectedDecl VisitUsingDirectiveDecl(UsingDirectiveDecl *D);
480 ExpectedDecl VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D);
481 ExpectedDecl VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D);
482
483 Expected<ObjCTypeParamList *>
484 ImportObjCTypeParamList(ObjCTypeParamList *list);
485
486 ExpectedDecl VisitObjCInterfaceDecl(ObjCInterfaceDecl *D);
487 ExpectedDecl VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D);
488 ExpectedDecl VisitObjCImplementationDecl(ObjCImplementationDecl *D);
489 ExpectedDecl VisitObjCPropertyDecl(ObjCPropertyDecl *D);
490 ExpectedDecl VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D);
491 ExpectedDecl VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D);
492 ExpectedDecl VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D);
493 ExpectedDecl VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D);
494 ExpectedDecl VisitClassTemplateDecl(ClassTemplateDecl *D);
495 ExpectedDecl VisitClassTemplateSpecializationDecl(
496 ClassTemplateSpecializationDecl *D);
497 ExpectedDecl VisitVarTemplateDecl(VarTemplateDecl *D);
498 ExpectedDecl VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D);
499 ExpectedDecl VisitFunctionTemplateDecl(FunctionTemplateDecl *D);
500
501 // Importing statements
502 ExpectedStmt VisitStmt(Stmt *S);
503 ExpectedStmt VisitGCCAsmStmt(GCCAsmStmt *S);
504 ExpectedStmt VisitDeclStmt(DeclStmt *S);
505 ExpectedStmt VisitNullStmt(NullStmt *S);
506 ExpectedStmt VisitCompoundStmt(CompoundStmt *S);
507 ExpectedStmt VisitCaseStmt(CaseStmt *S);
508 ExpectedStmt VisitDefaultStmt(DefaultStmt *S);
509 ExpectedStmt VisitLabelStmt(LabelStmt *S);
510 ExpectedStmt VisitAttributedStmt(AttributedStmt *S);
511 ExpectedStmt VisitIfStmt(IfStmt *S);
512 ExpectedStmt VisitSwitchStmt(SwitchStmt *S);
513 ExpectedStmt VisitWhileStmt(WhileStmt *S);
514 ExpectedStmt VisitDoStmt(DoStmt *S);
515 ExpectedStmt VisitForStmt(ForStmt *S);
516 ExpectedStmt VisitGotoStmt(GotoStmt *S);
517 ExpectedStmt VisitIndirectGotoStmt(IndirectGotoStmt *S);
518 ExpectedStmt VisitContinueStmt(ContinueStmt *S);
519 ExpectedStmt VisitBreakStmt(BreakStmt *S);
520 ExpectedStmt VisitReturnStmt(ReturnStmt *S);
521 // FIXME: MSAsmStmt
522 // FIXME: SEHExceptStmt
523 // FIXME: SEHFinallyStmt
524 // FIXME: SEHTryStmt
525 // FIXME: SEHLeaveStmt
526 // FIXME: CapturedStmt
527 ExpectedStmt VisitCXXCatchStmt(CXXCatchStmt *S);
528 ExpectedStmt VisitCXXTryStmt(CXXTryStmt *S);
529 ExpectedStmt VisitCXXForRangeStmt(CXXForRangeStmt *S);
530 // FIXME: MSDependentExistsStmt
531 ExpectedStmt VisitObjCForCollectionStmt(ObjCForCollectionStmt *S);
532 ExpectedStmt VisitObjCAtCatchStmt(ObjCAtCatchStmt *S);
533 ExpectedStmt VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S);
534 ExpectedStmt VisitObjCAtTryStmt(ObjCAtTryStmt *S);
535 ExpectedStmt VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S);
536 ExpectedStmt VisitObjCAtThrowStmt(ObjCAtThrowStmt *S);
537 ExpectedStmt VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
538
539 // Importing expressions
540 ExpectedStmt VisitExpr(Expr *E);
541 ExpectedStmt VisitVAArgExpr(VAArgExpr *E);
542 ExpectedStmt VisitChooseExpr(ChooseExpr *E);
543 ExpectedStmt VisitGNUNullExpr(GNUNullExpr *E);
544 ExpectedStmt VisitPredefinedExpr(PredefinedExpr *E);
545 ExpectedStmt VisitDeclRefExpr(DeclRefExpr *E);
546 ExpectedStmt VisitImplicitValueInitExpr(ImplicitValueInitExpr *E);
547 ExpectedStmt VisitDesignatedInitExpr(DesignatedInitExpr *E);
548 ExpectedStmt VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E);
549 ExpectedStmt VisitIntegerLiteral(IntegerLiteral *E);
550 ExpectedStmt VisitFloatingLiteral(FloatingLiteral *E);
551 ExpectedStmt VisitImaginaryLiteral(ImaginaryLiteral *E);
552 ExpectedStmt VisitCharacterLiteral(CharacterLiteral *E);
553 ExpectedStmt VisitStringLiteral(StringLiteral *E);
554 ExpectedStmt VisitCompoundLiteralExpr(CompoundLiteralExpr *E);
555 ExpectedStmt VisitAtomicExpr(AtomicExpr *E);
556 ExpectedStmt VisitAddrLabelExpr(AddrLabelExpr *E);
557 ExpectedStmt VisitConstantExpr(ConstantExpr *E);
558 ExpectedStmt VisitParenExpr(ParenExpr *E);
559 ExpectedStmt VisitParenListExpr(ParenListExpr *E);
560 ExpectedStmt VisitStmtExpr(StmtExpr *E);
561 ExpectedStmt VisitUnaryOperator(UnaryOperator *E);
562 ExpectedStmt VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E);
563 ExpectedStmt VisitBinaryOperator(BinaryOperator *E);
564 ExpectedStmt VisitConditionalOperator(ConditionalOperator *E);
565 ExpectedStmt VisitBinaryConditionalOperator(BinaryConditionalOperator *E);
566 ExpectedStmt VisitOpaqueValueExpr(OpaqueValueExpr *E);
567 ExpectedStmt VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E);
568 ExpectedStmt VisitExpressionTraitExpr(ExpressionTraitExpr *E);
569 ExpectedStmt VisitArraySubscriptExpr(ArraySubscriptExpr *E);
570 ExpectedStmt VisitCompoundAssignOperator(CompoundAssignOperator *E);
571 ExpectedStmt VisitImplicitCastExpr(ImplicitCastExpr *E);
572 ExpectedStmt VisitExplicitCastExpr(ExplicitCastExpr *E);
573 ExpectedStmt VisitOffsetOfExpr(OffsetOfExpr *OE);
574 ExpectedStmt VisitCXXThrowExpr(CXXThrowExpr *E);
575 ExpectedStmt VisitCXXNoexceptExpr(CXXNoexceptExpr *E);
576 ExpectedStmt VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E);
577 ExpectedStmt VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E);
578 ExpectedStmt VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
579 ExpectedStmt VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E);
580 ExpectedStmt VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E);
581 ExpectedStmt VisitPackExpansionExpr(PackExpansionExpr *E);
582 ExpectedStmt VisitSizeOfPackExpr(SizeOfPackExpr *E);
583 ExpectedStmt VisitCXXNewExpr(CXXNewExpr *E);
584 ExpectedStmt VisitCXXDeleteExpr(CXXDeleteExpr *E);
585 ExpectedStmt VisitCXXConstructExpr(CXXConstructExpr *E);
586 ExpectedStmt VisitCXXMemberCallExpr(CXXMemberCallExpr *E);
587 ExpectedStmt VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E);
588 ExpectedStmt VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E);
589 ExpectedStmt VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E);
590 ExpectedStmt VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E);
591 ExpectedStmt VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E);
592 ExpectedStmt VisitExprWithCleanups(ExprWithCleanups *E);
593 ExpectedStmt VisitCXXThisExpr(CXXThisExpr *E);
594 ExpectedStmt VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E);
595 ExpectedStmt VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E);
596 ExpectedStmt VisitMemberExpr(MemberExpr *E);
597 ExpectedStmt VisitCallExpr(CallExpr *E);
598 ExpectedStmt VisitLambdaExpr(LambdaExpr *LE);
599 ExpectedStmt VisitInitListExpr(InitListExpr *E);
600 ExpectedStmt VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E);
601 ExpectedStmt VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E);
602 ExpectedStmt VisitArrayInitLoopExpr(ArrayInitLoopExpr *E);
603 ExpectedStmt VisitArrayInitIndexExpr(ArrayInitIndexExpr *E);
604 ExpectedStmt VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E);
605 ExpectedStmt VisitCXXNamedCastExpr(CXXNamedCastExpr *E);
606 ExpectedStmt VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E);
607 ExpectedStmt VisitTypeTraitExpr(TypeTraitExpr *E);
608 ExpectedStmt VisitCXXTypeidExpr(CXXTypeidExpr *E);
609
610 template<typename IIter, typename OIter>
611 Error ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) {
612 using ItemT = typename std::remove_reference<decltype(*Obegin)>::type;
613 for (; Ibegin != Iend; ++Ibegin, ++Obegin) {
614 Expected<ItemT> ToOrErr = import(*Ibegin);
615 if (!ToOrErr)
616 return ToOrErr.takeError();
617 *Obegin = *ToOrErr;
618 }
619 return Error::success();
620 }
621
622 // Import every item from a container structure into an output container.
623 // If error occurs, stops at first error and returns the error.
624 // The output container should have space for all needed elements (it is not
625 // expanded, new items are put into from the beginning).
626 template<typename InContainerTy, typename OutContainerTy>
627 Error ImportContainerChecked(
628 const InContainerTy &InContainer, OutContainerTy &OutContainer) {
629 return ImportArrayChecked(
630 InContainer.begin(), InContainer.end(), OutContainer.begin());
631 }
632
633 template<typename InContainerTy, typename OIter>
634 Error ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) {
635 return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin);
636 }
637
638 void ImportOverrides(CXXMethodDecl *ToMethod, CXXMethodDecl *FromMethod);
639
640 Expected<FunctionDecl *> FindFunctionTemplateSpecialization(
641 FunctionDecl *FromFD);
642 };
643
644template <typename InContainerTy>
645Error ASTNodeImporter::ImportTemplateArgumentListInfo(
646 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc,
647 const InContainerTy &Container, TemplateArgumentListInfo &Result) {
648 auto ToLAngleLocOrErr = import(FromLAngleLoc);
649 if (!ToLAngleLocOrErr)
650 return ToLAngleLocOrErr.takeError();
651 auto ToRAngleLocOrErr = import(FromRAngleLoc);
652 if (!ToRAngleLocOrErr)
653 return ToRAngleLocOrErr.takeError();
654
655 TemplateArgumentListInfo ToTAInfo(*ToLAngleLocOrErr, *ToRAngleLocOrErr);
656 if (auto Err = ImportTemplateArgumentListInfo(Container, ToTAInfo))
657 return Err;
658 Result = ToTAInfo;
659 return Error::success();
660}
661
662template <>
663Error ASTNodeImporter::ImportTemplateArgumentListInfo<TemplateArgumentListInfo>(
664 const TemplateArgumentListInfo &From, TemplateArgumentListInfo &Result) {
665 return ImportTemplateArgumentListInfo(
666 From.getLAngleLoc(), From.getRAngleLoc(), From.arguments(), Result);
667}
668
669template <>
670Error ASTNodeImporter::ImportTemplateArgumentListInfo<
671 ASTTemplateArgumentListInfo>(
672 const ASTTemplateArgumentListInfo &From,
673 TemplateArgumentListInfo &Result) {
674 return ImportTemplateArgumentListInfo(
675 From.LAngleLoc, From.RAngleLoc, From.arguments(), Result);
676}
677
678Expected<ASTNodeImporter::FunctionTemplateAndArgsTy>
679ASTNodeImporter::ImportFunctionTemplateWithTemplateArgsFromSpecialization(
680 FunctionDecl *FromFD) {
681 assert(FromFD->getTemplatedKind() ==((FromFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization
) ? static_cast<void> (0) : __assert_fail ("FromFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp"
, 682, __PRETTY_FUNCTION__))
682 FunctionDecl::TK_FunctionTemplateSpecialization)((FromFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization
) ? static_cast<void> (0) : __assert_fail ("FromFD->getTemplatedKind() == FunctionDecl::TK_FunctionTemplateSpecialization"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp"
, 682, __PRETTY_FUNCTION__))
;
683
684 FunctionTemplateAndArgsTy Result;
685
686 auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
687 if (Error Err = importInto(std::get<0>(Result), FTSInfo->getTemplate()))
688 return std::move(Err);
689
690 // Import template arguments.
691 auto TemplArgs = FTSInfo->TemplateArguments->asArray();
692 if (Error Err = ImportTemplateArguments(TemplArgs.data(), TemplArgs.size(),
693 std::get<1>(Result)))
694 return std::move(Err);
695
696 return Result;
697}
698
699template <>
700Expected<TemplateParameterList *>
701ASTNodeImporter::import(TemplateParameterList *From) {
702 SmallVector<NamedDecl *, 4> To(From->size());
703 if (Error Err = ImportContainerChecked(*From, To))
704 return std::move(Err);
705
706 ExpectedExpr ToRequiresClause = import(From->getRequiresClause());
707 if (!ToRequiresClause)
708 return ToRequiresClause.takeError();
709
710 auto ToTemplateLocOrErr = import(From->getTemplateLoc());
711 if (!ToTemplateLocOrErr)
712 return ToTemplateLocOrErr.takeError();
713 auto ToLAngleLocOrErr = import(From->getLAngleLoc());
714 if (!ToLAngleLocOrErr)
715 return ToLAngleLocOrErr.takeError();
716 auto ToRAngleLocOrErr = import(From->getRAngleLoc());
717 if (!ToRAngleLocOrErr)
718 return ToRAngleLocOrErr.takeError();
719
720 return TemplateParameterList::Create(
721 Importer.getToContext(),
722 *ToTemplateLocOrErr,
723 *ToLAngleLocOrErr,
724 To,
725 *ToRAngleLocOrErr,
726 *ToRequiresClause);
727}
728
729template <>
730Expected<TemplateArgument>
731ASTNodeImporter::import(const TemplateArgument &From) {
732 switch (From.getKind()) {
733 case TemplateArgument::Null:
734 return TemplateArgument();
735
736 case TemplateArgument::Type: {
737 ExpectedType ToTypeOrErr = import(From.getAsType());
738 if (!ToTypeOrErr)
739 return ToTypeOrErr.takeError();
740 return TemplateArgument(*ToTypeOrErr);
741 }
742
743 case TemplateArgument::Integral: {
744 ExpectedType ToTypeOrErr = import(From.getIntegralType());
745 if (!ToTypeOrErr)
746 return ToTypeOrErr.takeError();
747 return TemplateArgument(From, *ToTypeOrErr);
748 }
749
750 case TemplateArgument::Declaration: {
751 Expected<ValueDecl *> ToOrErr = import(From.getAsDecl());
752 if (!ToOrErr)
753 return ToOrErr.takeError();
754 ExpectedType ToTypeOrErr = import(From.getParamTypeForDecl());
755 if (!ToTypeOrErr)
756 return ToTypeOrErr.takeError();
757 return TemplateArgument(*ToOrErr, *ToTypeOrErr);
758 }
759
760 case TemplateArgument::NullPtr: {
761 ExpectedType ToTypeOrErr = import(From.getNullPtrType());
762 if (!ToTypeOrErr)
763 return ToTypeOrErr.takeError();
764 return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/true);
765 }
766
767 case TemplateArgument::Template: {
768 Expected<TemplateName> ToTemplateOrErr = import(From.getAsTemplate());
769 if (!ToTemplateOrErr)
770 return ToTemplateOrErr.takeError();
771
772 return TemplateArgument(*ToTemplateOrErr);
773 }
774
775 case TemplateArgument::TemplateExpansion: {
776 Expected<TemplateName> ToTemplateOrErr =
777 import(From.getAsTemplateOrTemplatePattern());
778 if (!ToTemplateOrErr)
779 return ToTemplateOrErr.takeError();
780
781 return TemplateArgument(
782 *ToTemplateOrErr, From.getNumTemplateExpansions());
783 }
784
785 case TemplateArgument::Expression:
786 if (ExpectedExpr ToExpr = import(From.getAsExpr()))
787 return TemplateArgument(*ToExpr);
788 else
789 return ToExpr.takeError();
790
791 case TemplateArgument::Pack: {
792 SmallVector<TemplateArgument, 2> ToPack;
793 ToPack.reserve(From.pack_size());
794 if (Error Err = ImportTemplateArguments(
795 From.pack_begin(), From.pack_size(), ToPack))
796 return std::move(Err);
797
798 return TemplateArgument(
799 llvm::makeArrayRef(ToPack).copy(Importer.getToContext()));
800 }
801 }
802
803 llvm_unreachable("Invalid template argument kind")::llvm::llvm_unreachable_internal("Invalid template argument kind"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp"
, 803)
;
804}
805
806template <>
807Expected<TemplateArgumentLoc>
808ASTNodeImporter::import(const TemplateArgumentLoc &TALoc) {
809 Expected<TemplateArgument> ArgOrErr = import(TALoc.getArgument());
810 if (!ArgOrErr)
811 return ArgOrErr.takeError();
812 TemplateArgument Arg = *ArgOrErr;
813
814 TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo();
815
816 TemplateArgumentLocInfo ToInfo;
817 if (Arg.getKind() == TemplateArgument::Expression) {
818 ExpectedExpr E = import(FromInfo.getAsExpr());
819 if (!E)
820 return E.takeError();
821 ToInfo = TemplateArgumentLocInfo(*E);
822 } else if (Arg.getKind() == TemplateArgument::Type) {
823 if (auto TSIOrErr = import(FromInfo.getAsTypeSourceInfo()))
824 ToInfo = TemplateArgumentLocInfo(*TSIOrErr);
825 else
826 return TSIOrErr.takeError();
827 } else {
828 auto ToTemplateQualifierLocOrErr =
829 import(FromInfo.getTemplateQualifierLoc());
830 if (!ToTemplateQualifierLocOrErr)
831 return ToTemplateQualifierLocOrErr.takeError();
832 auto ToTemplateNameLocOrErr = import(FromInfo.getTemplateNameLoc());
833 if (!ToTemplateNameLocOrErr)
834 return ToTemplateNameLocOrErr.takeError();
835 auto ToTemplateEllipsisLocOrErr =
836 import(FromInfo.getTemplateEllipsisLoc());
837 if (!ToTemplateEllipsisLocOrErr)
838 return ToTemplateEllipsisLocOrErr.takeError();
839
840 ToInfo = TemplateArgumentLocInfo(
841 *ToTemplateQualifierLocOrErr,
842 *ToTemplateNameLocOrErr,
843 *ToTemplateEllipsisLocOrErr);
844 }
845
846 return TemplateArgumentLoc(Arg, ToInfo);
847}
848
849template <>
850Expected<DeclGroupRef> ASTNodeImporter::import(const DeclGroupRef &DG) {
851 if (DG.isNull())
852 return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0);
853 size_t NumDecls = DG.end() - DG.begin();
854 SmallVector<Decl *, 1> ToDecls;
855 ToDecls.reserve(NumDecls);
856 for (Decl *FromD : DG) {
857 if (auto ToDOrErr = import(FromD))
858 ToDecls.push_back(*ToDOrErr);
859 else
860 return ToDOrErr.takeError();
861 }
862 return DeclGroupRef::Create(Importer.getToContext(),
863 ToDecls.begin(),
864 NumDecls);
865}
866
867template <>
868Expected<ASTNodeImporter::Designator>
869ASTNodeImporter::import(const Designator &D) {
870 if (D.isFieldDesignator()) {
871 IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName());
872
873 ExpectedSLoc ToDotLocOrErr = import(D.getDotLoc());
874 if (!ToDotLocOrErr)
875 return ToDotLocOrErr.takeError();
876
877 ExpectedSLoc ToFieldLocOrErr = import(D.getFieldLoc());
878 if (!ToFieldLocOrErr)
879 return ToFieldLocOrErr.takeError();
880
881 return Designator(ToFieldName, *ToDotLocOrErr, *ToFieldLocOrErr);
882 }
883
884 ExpectedSLoc ToLBracketLocOrErr = import(D.getLBracketLoc());
885 if (!ToLBracketLocOrErr)
886 return ToLBracketLocOrErr.takeError();
887
888 ExpectedSLoc ToRBracketLocOrErr = import(D.getRBracketLoc());
889 if (!ToRBracketLocOrErr)
890 return ToRBracketLocOrErr.takeError();
891
892 if (D.isArrayDesignator())
893 return Designator(D.getFirstExprIndex(),
894 *ToLBracketLocOrErr, *ToRBracketLocOrErr);
895
896 ExpectedSLoc ToEllipsisLocOrErr = import(D.getEllipsisLoc());
897 if (!ToEllipsisLocOrErr)
898 return ToEllipsisLocOrErr.takeError();
899
900 assert(D.isArrayRangeDesignator())((D.isArrayRangeDesignator()) ? static_cast<void> (0) :
__assert_fail ("D.isArrayRangeDesignator()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp"
, 900, __PRETTY_FUNCTION__))
;
901 return Designator(
902 D.getFirstExprIndex(), *ToLBracketLocOrErr, *ToEllipsisLocOrErr,
903 *ToRBracketLocOrErr);
904}
905
906template <>
907Expected<LambdaCapture> ASTNodeImporter::import(const LambdaCapture &From) {
908 VarDecl *Var = nullptr;
909 if (From.capturesVariable()) {
910 if (auto VarOrErr = import(From.getCapturedVar()))
911 Var = *VarOrErr;
912 else
913 return VarOrErr.takeError();
914 }
915
916 auto LocationOrErr = import(From.getLocation());
917 if (!LocationOrErr)
918 return LocationOrErr.takeError();
919
920 SourceLocation EllipsisLoc;
921 if (From.isPackExpansion())
922 if (Error Err = importInto(EllipsisLoc, From.getEllipsisLoc()))
923 return std::move(Err);
924
925 return LambdaCapture(
926 *LocationOrErr, From.isImplicit(), From.getCaptureKind(), Var,
927 EllipsisLoc);
928}
929
930} // namespace clang
931
932//----------------------------------------------------------------------------
933// Import Types
934//----------------------------------------------------------------------------
935
936using namespace clang;
937
938ExpectedType ASTNodeImporter::VisitType(const Type *T) {
939 Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node)
940 << T->getTypeClassName();
941 return make_error<ImportError>(ImportError::UnsupportedConstruct);
942}
943
944ExpectedType ASTNodeImporter::VisitAtomicType(const AtomicType *T){
945 ExpectedType UnderlyingTypeOrErr = import(T->getValueType());
946 if (!UnderlyingTypeOrErr)
947 return UnderlyingTypeOrErr.takeError();
948
949 return Importer.getToContext().getAtomicType(*UnderlyingTypeOrErr);
950}
951
952ExpectedType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) {
953 switch (T->getKind()) {
954#define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \
955 case BuiltinType::Id: \
956 return Importer.getToContext().SingletonId;
957#include "clang/Basic/OpenCLImageTypes.def"
958#define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \
959 case BuiltinType::Id: \
960 return Importer.getToContext().Id##Ty;
961#include "clang/Basic/OpenCLExtensionTypes.def"
962#define SHARED_SINGLETON_TYPE(Expansion)
963#define BUILTIN_TYPE(Id, SingletonId) \
964 case BuiltinType::Id: return Importer.getToContext().SingletonId;
965#include "clang/AST/BuiltinTypes.def"
966
967 // FIXME: for Char16, Char32, and NullPtr, make sure that the "to"
968 // context supports C++.
969
970 // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to"
971 // context supports ObjC.
972
973 case BuiltinType::Char_U:
974 // The context we're importing from has an unsigned 'char'. If we're
975 // importing into a context with a signed 'char', translate to
976 // 'unsigned char' instead.
977 if (Importer.getToContext().getLangOpts().CharIsSigned)
978 return Importer.getToContext().UnsignedCharTy;
979
980 return Importer.getToContext().CharTy;
981
982 case BuiltinType::Char_S:
983 // The context we're importing from has an unsigned 'char'. If we're
984 // importing into a context with a signed 'char', translate to
985 // 'unsigned char' instead.
986 if (!Importer.getToContext().getLangOpts().CharIsSigned)
987 return Importer.getToContext().SignedCharTy;
988
989 return Importer.getToContext().CharTy;
990
991 case BuiltinType::WChar_S:
992 case BuiltinType::WChar_U:
993 // FIXME: If not in C++, shall we translate to the C equivalent of
994 // wchar_t?
995 return Importer.getToContext().WCharTy;
996 }
997
998 llvm_unreachable("Invalid BuiltinType Kind!")::llvm::llvm_unreachable_internal("Invalid BuiltinType Kind!"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp"
, 998)
;
999}
1000
1001ExpectedType ASTNodeImporter::VisitDecayedType(const DecayedType *T) {
1002 ExpectedType ToOriginalTypeOrErr = import(T->getOriginalType());
1003 if (!ToOriginalTypeOrErr)
1004 return ToOriginalTypeOrErr.takeError();
1005
1006 return Importer.getToContext().getDecayedType(*ToOriginalTypeOrErr);
1007}
1008
1009ExpectedType ASTNodeImporter::VisitComplexType(const ComplexType *T) {
1010 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1011 if (!ToElementTypeOrErr)
1012 return ToElementTypeOrErr.takeError();
1013
1014 return Importer.getToContext().getComplexType(*ToElementTypeOrErr);
1015}
1016
1017ExpectedType ASTNodeImporter::VisitPointerType(const PointerType *T) {
1018 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1019 if (!ToPointeeTypeOrErr)
1020 return ToPointeeTypeOrErr.takeError();
1021
1022 return Importer.getToContext().getPointerType(*ToPointeeTypeOrErr);
1023}
1024
1025ExpectedType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) {
1026 // FIXME: Check for blocks support in "to" context.
1027 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1028 if (!ToPointeeTypeOrErr)
1029 return ToPointeeTypeOrErr.takeError();
1030
1031 return Importer.getToContext().getBlockPointerType(*ToPointeeTypeOrErr);
1032}
1033
1034ExpectedType
1035ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) {
1036 // FIXME: Check for C++ support in "to" context.
1037 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1038 if (!ToPointeeTypeOrErr)
1039 return ToPointeeTypeOrErr.takeError();
1040
1041 return Importer.getToContext().getLValueReferenceType(*ToPointeeTypeOrErr);
1042}
1043
1044ExpectedType
1045ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) {
1046 // FIXME: Check for C++0x support in "to" context.
1047 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten());
1048 if (!ToPointeeTypeOrErr)
1049 return ToPointeeTypeOrErr.takeError();
1050
1051 return Importer.getToContext().getRValueReferenceType(*ToPointeeTypeOrErr);
1052}
1053
1054ExpectedType
1055ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) {
1056 // FIXME: Check for C++ support in "to" context.
1057 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1058 if (!ToPointeeTypeOrErr)
1059 return ToPointeeTypeOrErr.takeError();
1060
1061 ExpectedType ClassTypeOrErr = import(QualType(T->getClass(), 0));
1062 if (!ClassTypeOrErr)
1063 return ClassTypeOrErr.takeError();
1064
1065 return Importer.getToContext().getMemberPointerType(
1066 *ToPointeeTypeOrErr, (*ClassTypeOrErr).getTypePtr());
1067}
1068
1069ExpectedType
1070ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) {
1071 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1072 if (!ToElementTypeOrErr)
1073 return ToElementTypeOrErr.takeError();
1074
1075 return Importer.getToContext().getConstantArrayType(*ToElementTypeOrErr,
1076 T->getSize(),
1077 T->getSizeModifier(),
1078 T->getIndexTypeCVRQualifiers());
1079}
1080
1081ExpectedType
1082ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) {
1083 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1084 if (!ToElementTypeOrErr)
1085 return ToElementTypeOrErr.takeError();
1086
1087 return Importer.getToContext().getIncompleteArrayType(*ToElementTypeOrErr,
1088 T->getSizeModifier(),
1089 T->getIndexTypeCVRQualifiers());
1090}
1091
1092ExpectedType
1093ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) {
1094 QualType ToElementType;
1095 Expr *ToSizeExpr;
1096 SourceRange ToBracketsRange;
1097 if (auto Imp = importSeq(
1098 T->getElementType(), T->getSizeExpr(), T->getBracketsRange()))
1099 std::tie(ToElementType, ToSizeExpr, ToBracketsRange) = *Imp;
1100 else
1101 return Imp.takeError();
1102
1103 return Importer.getToContext().getVariableArrayType(
1104 ToElementType, ToSizeExpr, T->getSizeModifier(),
1105 T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1106}
1107
1108ExpectedType ASTNodeImporter::VisitDependentSizedArrayType(
1109 const DependentSizedArrayType *T) {
1110 QualType ToElementType;
1111 Expr *ToSizeExpr;
1112 SourceRange ToBracketsRange;
1113 if (auto Imp = importSeq(
1114 T->getElementType(), T->getSizeExpr(), T->getBracketsRange()))
1115 std::tie(ToElementType, ToSizeExpr, ToBracketsRange) = *Imp;
1116 else
1117 return Imp.takeError();
1118 // SizeExpr may be null if size is not specified directly.
1119 // For example, 'int a[]'.
1120
1121 return Importer.getToContext().getDependentSizedArrayType(
1122 ToElementType, ToSizeExpr, T->getSizeModifier(),
1123 T->getIndexTypeCVRQualifiers(), ToBracketsRange);
1124}
1125
1126ExpectedType ASTNodeImporter::VisitVectorType(const VectorType *T) {
1127 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1128 if (!ToElementTypeOrErr)
1129 return ToElementTypeOrErr.takeError();
1130
1131 return Importer.getToContext().getVectorType(*ToElementTypeOrErr,
1132 T->getNumElements(),
1133 T->getVectorKind());
1134}
1135
1136ExpectedType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) {
1137 ExpectedType ToElementTypeOrErr = import(T->getElementType());
1138 if (!ToElementTypeOrErr)
1139 return ToElementTypeOrErr.takeError();
1140
1141 return Importer.getToContext().getExtVectorType(*ToElementTypeOrErr,
1142 T->getNumElements());
1143}
1144
1145ExpectedType
1146ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) {
1147 // FIXME: What happens if we're importing a function without a prototype
1148 // into C++? Should we make it variadic?
1149 ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1150 if (!ToReturnTypeOrErr)
1151 return ToReturnTypeOrErr.takeError();
1152
1153 return Importer.getToContext().getFunctionNoProtoType(*ToReturnTypeOrErr,
1154 T->getExtInfo());
1155}
1156
1157ExpectedType
1158ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) {
1159 ExpectedType ToReturnTypeOrErr = import(T->getReturnType());
1160 if (!ToReturnTypeOrErr)
1161 return ToReturnTypeOrErr.takeError();
1162
1163 // Import argument types
1164 SmallVector<QualType, 4> ArgTypes;
1165 for (const auto &A : T->param_types()) {
1166 ExpectedType TyOrErr = import(A);
1167 if (!TyOrErr)
1168 return TyOrErr.takeError();
1169 ArgTypes.push_back(*TyOrErr);
1170 }
1171
1172 // Import exception types
1173 SmallVector<QualType, 4> ExceptionTypes;
1174 for (const auto &E : T->exceptions()) {
1175 ExpectedType TyOrErr = import(E);
1176 if (!TyOrErr)
1177 return TyOrErr.takeError();
1178 ExceptionTypes.push_back(*TyOrErr);
1179 }
1180
1181 FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo();
1182 FunctionProtoType::ExtProtoInfo ToEPI;
1183
1184 auto Imp = importSeq(
1185 FromEPI.ExceptionSpec.NoexceptExpr,
1186 FromEPI.ExceptionSpec.SourceDecl,
1187 FromEPI.ExceptionSpec.SourceTemplate);
1188 if (!Imp)
1189 return Imp.takeError();
1190
1191 ToEPI.ExtInfo = FromEPI.ExtInfo;
1192 ToEPI.Variadic = FromEPI.Variadic;
1193 ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn;
1194 ToEPI.TypeQuals = FromEPI.TypeQuals;
1195 ToEPI.RefQualifier = FromEPI.RefQualifier;
1196 ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type;
1197 ToEPI.ExceptionSpec.Exceptions = ExceptionTypes;
1198 std::tie(
1199 ToEPI.ExceptionSpec.NoexceptExpr,
1200 ToEPI.ExceptionSpec.SourceDecl,
1201 ToEPI.ExceptionSpec.SourceTemplate) = *Imp;
1202
1203 return Importer.getToContext().getFunctionType(
1204 *ToReturnTypeOrErr, ArgTypes, ToEPI);
1205}
1206
1207ExpectedType ASTNodeImporter::VisitUnresolvedUsingType(
1208 const UnresolvedUsingType *T) {
1209 UnresolvedUsingTypenameDecl *ToD;
1210 Decl *ToPrevD;
1211 if (auto Imp = importSeq(T->getDecl(), T->getDecl()->getPreviousDecl()))
1212 std::tie(ToD, ToPrevD) = *Imp;
1213 else
1214 return Imp.takeError();
1215
1216 return Importer.getToContext().getTypeDeclType(
1217 ToD, cast_or_null<TypeDecl>(ToPrevD));
1218}
1219
1220ExpectedType ASTNodeImporter::VisitParenType(const ParenType *T) {
1221 ExpectedType ToInnerTypeOrErr = import(T->getInnerType());
1222 if (!ToInnerTypeOrErr)
1223 return ToInnerTypeOrErr.takeError();
1224
1225 return Importer.getToContext().getParenType(*ToInnerTypeOrErr);
1226}
1227
1228ExpectedType ASTNodeImporter::VisitTypedefType(const TypedefType *T) {
1229 Expected<TypedefNameDecl *> ToDeclOrErr = import(T->getDecl());
1230 if (!ToDeclOrErr)
1231 return ToDeclOrErr.takeError();
1232
1233 return Importer.getToContext().getTypeDeclType(*ToDeclOrErr);
1234}
1235
1236ExpectedType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) {
1237 ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1238 if (!ToExprOrErr)
1239 return ToExprOrErr.takeError();
1240
1241 return Importer.getToContext().getTypeOfExprType(*ToExprOrErr);
1242}
1243
1244ExpectedType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) {
1245 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1246 if (!ToUnderlyingTypeOrErr)
1247 return ToUnderlyingTypeOrErr.takeError();
1248
1249 return Importer.getToContext().getTypeOfType(*ToUnderlyingTypeOrErr);
1250}
1251
1252ExpectedType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) {
1253 // FIXME: Make sure that the "to" context supports C++0x!
1254 ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr());
1255 if (!ToExprOrErr)
1256 return ToExprOrErr.takeError();
1257
1258 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1259 if (!ToUnderlyingTypeOrErr)
1260 return ToUnderlyingTypeOrErr.takeError();
1261
1262 return Importer.getToContext().getDecltypeType(
1263 *ToExprOrErr, *ToUnderlyingTypeOrErr);
1264}
1265
1266ExpectedType
1267ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
1268 ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1269 if (!ToBaseTypeOrErr)
1270 return ToBaseTypeOrErr.takeError();
1271
1272 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType());
1273 if (!ToUnderlyingTypeOrErr)
1274 return ToUnderlyingTypeOrErr.takeError();
1275
1276 return Importer.getToContext().getUnaryTransformType(
1277 *ToBaseTypeOrErr, *ToUnderlyingTypeOrErr, T->getUTTKind());
1278}
1279
1280ExpectedType ASTNodeImporter::VisitAutoType(const AutoType *T) {
1281 // FIXME: Make sure that the "to" context supports C++11!
1282 ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType());
1283 if (!ToDeducedTypeOrErr)
1284 return ToDeducedTypeOrErr.takeError();
1285
1286 return Importer.getToContext().getAutoType(*ToDeducedTypeOrErr,
1287 T->getKeyword(),
1288 /*IsDependent*/false);
1289}
1290
1291ExpectedType ASTNodeImporter::VisitInjectedClassNameType(
1292 const InjectedClassNameType *T) {
1293 Expected<CXXRecordDecl *> ToDeclOrErr = import(T->getDecl());
1294 if (!ToDeclOrErr)
1295 return ToDeclOrErr.takeError();
1296
1297 ExpectedType ToInjTypeOrErr = import(T->getInjectedSpecializationType());
1298 if (!ToInjTypeOrErr)
1299 return ToInjTypeOrErr.takeError();
1300
1301 // FIXME: ASTContext::getInjectedClassNameType is not suitable for AST reading
1302 // See comments in InjectedClassNameType definition for details
1303 // return Importer.getToContext().getInjectedClassNameType(D, InjType);
1304 enum {
1305 TypeAlignmentInBits = 4,
1306 TypeAlignment = 1 << TypeAlignmentInBits
1307 };
1308
1309 return QualType(new (Importer.getToContext(), TypeAlignment)
1310 InjectedClassNameType(*ToDeclOrErr, *ToInjTypeOrErr), 0);
1311}
1312
1313ExpectedType ASTNodeImporter::VisitRecordType(const RecordType *T) {
1314 Expected<RecordDecl *> ToDeclOrErr = import(T->getDecl());
1315 if (!ToDeclOrErr)
1316 return ToDeclOrErr.takeError();
1317
1318 return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1319}
1320
1321ExpectedType ASTNodeImporter::VisitEnumType(const EnumType *T) {
1322 Expected<EnumDecl *> ToDeclOrErr = import(T->getDecl());
1323 if (!ToDeclOrErr)
1324 return ToDeclOrErr.takeError();
1325
1326 return Importer.getToContext().getTagDeclType(*ToDeclOrErr);
1327}
1328
1329ExpectedType ASTNodeImporter::VisitAttributedType(const AttributedType *T) {
1330 ExpectedType ToModifiedTypeOrErr = import(T->getModifiedType());
1331 if (!ToModifiedTypeOrErr)
1332 return ToModifiedTypeOrErr.takeError();
1333 ExpectedType ToEquivalentTypeOrErr = import(T->getEquivalentType());
1334 if (!ToEquivalentTypeOrErr)
1335 return ToEquivalentTypeOrErr.takeError();
1336
1337 return Importer.getToContext().getAttributedType(T->getAttrKind(),
1338 *ToModifiedTypeOrErr, *ToEquivalentTypeOrErr);
1339}
1340
1341ExpectedType ASTNodeImporter::VisitTemplateTypeParmType(
1342 const TemplateTypeParmType *T) {
1343 Expected<TemplateTypeParmDecl *> ToDeclOrErr = import(T->getDecl());
1344 if (!ToDeclOrErr)
1345 return ToDeclOrErr.takeError();
1346
1347 return Importer.getToContext().getTemplateTypeParmType(
1348 T->getDepth(), T->getIndex(), T->isParameterPack(), *ToDeclOrErr);
1349}
1350
1351ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmType(
1352 const SubstTemplateTypeParmType *T) {
1353 ExpectedType ReplacedOrErr = import(QualType(T->getReplacedParameter(), 0));
1354 if (!ReplacedOrErr)
1355 return ReplacedOrErr.takeError();
1356 const TemplateTypeParmType *Replaced =
1357 cast<TemplateTypeParmType>((*ReplacedOrErr).getTypePtr());
1358
1359 ExpectedType ToReplacementTypeOrErr = import(T->getReplacementType());
1360 if (!ToReplacementTypeOrErr)
1361 return ToReplacementTypeOrErr.takeError();
1362
1363 return Importer.getToContext().getSubstTemplateTypeParmType(
1364 Replaced, (*ToReplacementTypeOrErr).getCanonicalType());
1365}
1366
1367ExpectedType ASTNodeImporter::VisitTemplateSpecializationType(
1368 const TemplateSpecializationType *T) {
1369 auto ToTemplateOrErr = import(T->getTemplateName());
1370 if (!ToTemplateOrErr)
1371 return ToTemplateOrErr.takeError();
1372
1373 SmallVector<TemplateArgument, 2> ToTemplateArgs;
1374 if (Error Err = ImportTemplateArguments(
1375 T->getArgs(), T->getNumArgs(), ToTemplateArgs))
1376 return std::move(Err);
1377
1378 QualType ToCanonType;
1379 if (!QualType(T, 0).isCanonical()) {
1380 QualType FromCanonType
1381 = Importer.getFromContext().getCanonicalType(QualType(T, 0));
1382 if (ExpectedType TyOrErr = import(FromCanonType))
1383 ToCanonType = *TyOrErr;
1384 else
1385 return TyOrErr.takeError();
1386 }
1387 return Importer.getToContext().getTemplateSpecializationType(*ToTemplateOrErr,
1388 ToTemplateArgs,
1389 ToCanonType);
1390}
1391
1392ExpectedType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) {
1393 // Note: the qualifier in an ElaboratedType is optional.
1394 auto ToQualifierOrErr = import(T->getQualifier());
1395 if (!ToQualifierOrErr)
1396 return ToQualifierOrErr.takeError();
1397
1398 ExpectedType ToNamedTypeOrErr = import(T->getNamedType());
1399 if (!ToNamedTypeOrErr)
1400 return ToNamedTypeOrErr.takeError();
1401
1402 Expected<TagDecl *> ToOwnedTagDeclOrErr = import(T->getOwnedTagDecl());
1403 if (!ToOwnedTagDeclOrErr)
1404 return ToOwnedTagDeclOrErr.takeError();
1405
1406 return Importer.getToContext().getElaboratedType(T->getKeyword(),
1407 *ToQualifierOrErr,
1408 *ToNamedTypeOrErr,
1409 *ToOwnedTagDeclOrErr);
1410}
1411
1412ExpectedType
1413ASTNodeImporter::VisitPackExpansionType(const PackExpansionType *T) {
1414 ExpectedType ToPatternOrErr = import(T->getPattern());
1415 if (!ToPatternOrErr)
1416 return ToPatternOrErr.takeError();
1417
1418 return Importer.getToContext().getPackExpansionType(*ToPatternOrErr,
1419 T->getNumExpansions());
1420}
1421
1422ExpectedType ASTNodeImporter::VisitDependentTemplateSpecializationType(
1423 const DependentTemplateSpecializationType *T) {
1424 auto ToQualifierOrErr = import(T->getQualifier());
1425 if (!ToQualifierOrErr)
1426 return ToQualifierOrErr.takeError();
1427
1428 IdentifierInfo *ToName = Importer.Import(T->getIdentifier());
1429
1430 SmallVector<TemplateArgument, 2> ToPack;
1431 ToPack.reserve(T->getNumArgs());
1432 if (Error Err = ImportTemplateArguments(
1433 T->getArgs(), T->getNumArgs(), ToPack))
1434 return std::move(Err);
1435
1436 return Importer.getToContext().getDependentTemplateSpecializationType(
1437 T->getKeyword(), *ToQualifierOrErr, ToName, ToPack);
1438}
1439
1440ExpectedType
1441ASTNodeImporter::VisitDependentNameType(const DependentNameType *T) {
1442 auto ToQualifierOrErr = import(T->getQualifier());
1443 if (!ToQualifierOrErr)
1444 return ToQualifierOrErr.takeError();
1445
1446 IdentifierInfo *Name = Importer.Import(T->getIdentifier());
1447
1448 QualType Canon;
1449 if (T != T->getCanonicalTypeInternal().getTypePtr()) {
1450 if (ExpectedType TyOrErr = import(T->getCanonicalTypeInternal()))
1451 Canon = (*TyOrErr).getCanonicalType();
1452 else
1453 return TyOrErr.takeError();
1454 }
1455
1456 return Importer.getToContext().getDependentNameType(T->getKeyword(),
1457 *ToQualifierOrErr,
1458 Name, Canon);
1459}
1460
1461ExpectedType
1462ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) {
1463 Expected<ObjCInterfaceDecl *> ToDeclOrErr = import(T->getDecl());
1464 if (!ToDeclOrErr)
1465 return ToDeclOrErr.takeError();
1466
1467 return Importer.getToContext().getObjCInterfaceType(*ToDeclOrErr);
1468}
1469
1470ExpectedType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) {
1471 ExpectedType ToBaseTypeOrErr = import(T->getBaseType());
1472 if (!ToBaseTypeOrErr)
1473 return ToBaseTypeOrErr.takeError();
1474
1475 SmallVector<QualType, 4> TypeArgs;
1476 for (auto TypeArg : T->getTypeArgsAsWritten()) {
1477 if (ExpectedType TyOrErr = import(TypeArg))
1478 TypeArgs.push_back(*TyOrErr);
1479 else
1480 return TyOrErr.takeError();
1481 }
1482
1483 SmallVector<ObjCProtocolDecl *, 4> Protocols;
1484 for (auto *P : T->quals()) {
1485 if (Expected<ObjCProtocolDecl *> ProtocolOrErr = import(P))
1486 Protocols.push_back(*ProtocolOrErr);
1487 else
1488 return ProtocolOrErr.takeError();
1489
1490 }
1491
1492 return Importer.getToContext().getObjCObjectType(*ToBaseTypeOrErr, TypeArgs,
1493 Protocols,
1494 T->isKindOfTypeAsWritten());
1495}
1496
1497ExpectedType
1498ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) {
1499 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType());
1500 if (!ToPointeeTypeOrErr)
1501 return ToPointeeTypeOrErr.takeError();
1502
1503 return Importer.getToContext().getObjCObjectPointerType(*ToPointeeTypeOrErr);
1504}
1505
1506//----------------------------------------------------------------------------
1507// Import Declarations
1508//----------------------------------------------------------------------------
1509Error ASTNodeImporter::ImportDeclParts(
1510 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC,
1511 DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc) {
1512 // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop.
1513 // example: int struct_in_proto(struct data_t{int a;int b;} *d);
1514 DeclContext *OrigDC = D->getDeclContext();
1515 FunctionDecl *FunDecl;
1516 if (isa<RecordDecl>(D) && (FunDecl = dyn_cast<FunctionDecl>(OrigDC)) &&
1517 FunDecl->hasBody()) {
1518 auto getLeafPointeeType = [](const Type *T) {
1519 while (T->isPointerType() || T->isArrayType()) {
1520 T = T->getPointeeOrArrayElementType();
1521 }
1522 return T;
1523 };
1524 for (const ParmVarDecl *P : FunDecl->parameters()) {
1525 const Type *LeafT =
1526 getLeafPointeeType(P->getType().getCanonicalType().getTypePtr());
1527 auto *RT = dyn_cast<RecordType>(LeafT);
1528 if (RT && RT->getDecl() == D) {
1529 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
1530 << D->getDeclKindName();
1531 return make_error<ImportError>(ImportError::UnsupportedConstruct);
1532 }
1533 }
1534 }
1535
1536 // Import the context of this declaration.
1537 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
1538 return Err;
1539
1540 // Import the name of this declaration.
1541 if (Error Err = importInto(Name, D->getDeclName()))
1542 return Err;
1543
1544 // Import the location of this declaration.
1545 if (Error Err = importInto(Loc, D->getLocation()))
1546 return Err;
1547
1548 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D));
1549 if (ToD)
1550 if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD))
1551 return Err;
1552
1553 return Error::success();
1554}
1555
1556Error ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) {
1557 if (!FromD)
1558 return Error::success();
1559
1560 if (!ToD)
1561 if (Error Err = importInto(ToD, FromD))
1562 return Err;
1563
1564 if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) {
1565 if (RecordDecl *ToRecord = cast<RecordDecl>(ToD)) {
1566 if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() &&
1567 !ToRecord->getDefinition()) {
1568 if (Error Err = ImportDefinition(FromRecord, ToRecord))
1569 return Err;
1570 }
1571 }
1572 return Error::success();
1573 }
1574
1575 if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) {
1576 if (EnumDecl *ToEnum = cast<EnumDecl>(ToD)) {
1577 if (FromEnum->getDefinition() && !ToEnum->getDefinition()) {
1578 if (Error Err = ImportDefinition(FromEnum, ToEnum))
1579 return Err;
1580 }
1581 }
1582 return Error::success();
1583 }
1584
1585 return Error::success();
1586}
1587
1588Error
1589ASTNodeImporter::ImportDeclarationNameLoc(
1590 const DeclarationNameInfo &From, DeclarationNameInfo& To) {
1591 // NOTE: To.Name and To.Loc are already imported.
1592 // We only have to import To.LocInfo.
1593 switch (To.getName().getNameKind()) {
1594 case DeclarationName::Identifier:
1595 case DeclarationName::ObjCZeroArgSelector:
1596 case DeclarationName::ObjCOneArgSelector:
1597 case DeclarationName::ObjCMultiArgSelector:
1598 case DeclarationName::CXXUsingDirective:
1599 case DeclarationName::CXXDeductionGuideName:
1600 return Error::success();
1601
1602 case DeclarationName::CXXOperatorName: {
1603 if (auto ToRangeOrErr = import(From.getCXXOperatorNameRange()))
1604 To.setCXXOperatorNameRange(*ToRangeOrErr);
1605 else
1606 return ToRangeOrErr.takeError();
1607 return Error::success();
1608 }
1609 case DeclarationName::CXXLiteralOperatorName: {
1610 if (ExpectedSLoc LocOrErr = import(From.getCXXLiteralOperatorNameLoc()))
1611 To.setCXXLiteralOperatorNameLoc(*LocOrErr);
1612 else
1613 return LocOrErr.takeError();
1614 return Error::success();
1615 }
1616 case DeclarationName::CXXConstructorName:
1617 case DeclarationName::CXXDestructorName:
1618 case DeclarationName::CXXConversionFunctionName: {
1619 if (auto ToTInfoOrErr = import(From.getNamedTypeInfo()))
1620 To.setNamedTypeInfo(*ToTInfoOrErr);
1621 else
1622 return ToTInfoOrErr.takeError();
1623 return Error::success();
1624 }
1625 }
1626 llvm_unreachable("Unknown name kind.")::llvm::llvm_unreachable_internal("Unknown name kind.", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp"
, 1626)
;
1627}
1628
1629Error
1630ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) {
1631 if (Importer.isMinimalImport() && !ForceImport) {
1632 auto ToDCOrErr = Importer.ImportContext(FromDC);
1633 return ToDCOrErr.takeError();
1634 }
1635 llvm::SmallVector<Decl *, 8> ImportedDecls;
1636 for (auto *From : FromDC->decls()) {
1637 ExpectedDecl ImportedOrErr = import(From);
1638 if (!ImportedOrErr)
1639 // Ignore the error, continue with next Decl.
1640 // FIXME: Handle this case somehow better.
1641 consumeError(ImportedOrErr.takeError());
1642 }
1643
1644 return Error::success();
1645}
1646
1647Error ASTNodeImporter::ImportDeclContext(
1648 Decl *FromD, DeclContext *&ToDC, DeclContext *&ToLexicalDC) {
1649 auto ToDCOrErr = Importer.ImportContext(FromD->getDeclContext());
1650 if (!ToDCOrErr)
1651 return ToDCOrErr.takeError();
1652 ToDC = *ToDCOrErr;
1653
1654 if (FromD->getDeclContext() != FromD->getLexicalDeclContext()) {
1655 auto ToLexicalDCOrErr = Importer.ImportContext(
1656 FromD->getLexicalDeclContext());
1657 if (!ToLexicalDCOrErr)
1658 return ToLexicalDCOrErr.takeError();
1659 ToLexicalDC = *ToLexicalDCOrErr;
1660 } else
1661 ToLexicalDC = ToDC;
1662
1663 return Error::success();
1664}
1665
1666Error ASTNodeImporter::ImportImplicitMethods(
1667 const CXXRecordDecl *From, CXXRecordDecl *To) {
1668 assert(From->isCompleteDefinition() && To->getDefinition() == To &&((From->isCompleteDefinition() && To->getDefinition
() == To && "Import implicit methods to or from non-definition"
) ? static_cast<void> (0) : __assert_fail ("From->isCompleteDefinition() && To->getDefinition() == To && \"Import implicit methods to or from non-definition\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp"
, 1669, __PRETTY_FUNCTION__))
1669 "Import implicit methods to or from non-definition")((From->isCompleteDefinition() && To->getDefinition
() == To && "Import implicit methods to or from non-definition"
) ? static_cast<void> (0) : __assert_fail ("From->isCompleteDefinition() && To->getDefinition() == To && \"Import implicit methods to or from non-definition\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp"
, 1669, __PRETTY_FUNCTION__))
;
1670
1671 for (CXXMethodDecl *FromM : From->methods())
1672 if (FromM->isImplicit()) {
1673 Expected<CXXMethodDecl *> ToMOrErr = import(FromM);
1674 if (!ToMOrErr)
1675 return ToMOrErr.takeError();
1676 }
1677
1678 return Error::success();
1679}
1680
1681static Error setTypedefNameForAnonDecl(TagDecl *From, TagDecl *To,
1682 ASTImporter &Importer) {
1683 if (TypedefNameDecl *FromTypedef = From->getTypedefNameForAnonDecl()) {
1684 if (ExpectedDecl ToTypedefOrErr = Importer.Import(FromTypedef))
1685 To->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(*ToTypedefOrErr));
1686 else
1687 return ToTypedefOrErr.takeError();
1688 }
1689 return Error::success();
1690}
1691
1692Error ASTNodeImporter::ImportDefinition(
1693 RecordDecl *From, RecordDecl *To, ImportDefinitionKind Kind) {
1694 if (To->getDefinition() || To->isBeingDefined()) {
1695 if (Kind == IDK_Everything)
1696 return ImportDeclContext(From, /*ForceImport=*/true);
1697
1698 return Error::success();
1699 }
1700
1701 To->startDefinition();
1702
1703 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
1704 return Err;
1705
1706 // Add base classes.
1707 auto *ToCXX = dyn_cast<CXXRecordDecl>(To);
1708 auto *FromCXX = dyn_cast<CXXRecordDecl>(From);
1709 if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) {
1710
1711 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data();
1712 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data();
1713 ToData.UserDeclaredConstructor = FromData.UserDeclaredConstructor;
1714 ToData.UserDeclaredSpecialMembers = FromData.UserDeclaredSpecialMembers;
1715 ToData.Aggregate = FromData.Aggregate;
1716 ToData.PlainOldData = FromData.PlainOldData;
1717 ToData.Empty = FromData.Empty;
1718 ToData.Polymorphic = FromData.Polymorphic;
1719 ToData.Abstract = FromData.Abstract;
1720 ToData.IsStandardLayout = FromData.IsStandardLayout;
1721 ToData.IsCXX11StandardLayout = FromData.IsCXX11StandardLayout;
1722 ToData.HasBasesWithFields = FromData.HasBasesWithFields;
1723 ToData.HasBasesWithNonStaticDataMembers =
1724 FromData.HasBasesWithNonStaticDataMembers;
1725 ToData.HasPrivateFields = FromData.HasPrivateFields;
1726 ToData.HasProtectedFields = FromData.HasProtectedFields;
1727 ToData.HasPublicFields = FromData.HasPublicFields;
1728 ToData.HasMutableFields = FromData.HasMutableFields;
1729 ToData.HasVariantMembers = FromData.HasVariantMembers;
1730 ToData.HasOnlyCMembers = FromData.HasOnlyCMembers;
1731 ToData.HasInClassInitializer = FromData.HasInClassInitializer;
1732 ToData.HasUninitializedReferenceMember
1733 = FromData.HasUninitializedReferenceMember;
1734 ToData.HasUninitializedFields = FromData.HasUninitializedFields;
1735 ToData.HasInheritedConstructor = FromData.HasInheritedConstructor;
1736 ToData.HasInheritedAssignment = FromData.HasInheritedAssignment;
1737 ToData.NeedOverloadResolutionForCopyConstructor
1738 = FromData.NeedOverloadResolutionForCopyConstructor;
1739 ToData.NeedOverloadResolutionForMoveConstructor
1740 = FromData.NeedOverloadResolutionForMoveConstructor;
1741 ToData.NeedOverloadResolutionForMoveAssignment
1742 = FromData.NeedOverloadResolutionForMoveAssignment;
1743 ToData.NeedOverloadResolutionForDestructor
1744 = FromData.NeedOverloadResolutionForDestructor;
1745 ToData.DefaultedCopyConstructorIsDeleted
1746 = FromData.DefaultedCopyConstructorIsDeleted;
1747 ToData.DefaultedMoveConstructorIsDeleted
1748 = FromData.DefaultedMoveConstructorIsDeleted;
1749 ToData.DefaultedMoveAssignmentIsDeleted
1750 = FromData.DefaultedMoveAssignmentIsDeleted;
1751 ToData.DefaultedDestructorIsDeleted = FromData.DefaultedDestructorIsDeleted;
1752 ToData.HasTrivialSpecialMembers = FromData.HasTrivialSpecialMembers;
1753 ToData.HasIrrelevantDestructor = FromData.HasIrrelevantDestructor;
1754 ToData.HasConstexprNonCopyMoveConstructor
1755 = FromData.HasConstexprNonCopyMoveConstructor;
1756 ToData.HasDefaultedDefaultConstructor
1757 = FromData.HasDefaultedDefaultConstructor;
1758 ToData.DefaultedDefaultConstructorIsConstexpr
1759 = FromData.DefaultedDefaultConstructorIsConstexpr;
1760 ToData.HasConstexprDefaultConstructor
1761 = FromData.HasConstexprDefaultConstructor;
1762 ToData.HasNonLiteralTypeFieldsOrBases
1763 = FromData.HasNonLiteralTypeFieldsOrBases;
1764 // ComputedVisibleConversions not imported.
1765 ToData.UserProvidedDefaultConstructor
1766 = FromData.UserProvidedDefaultConstructor;
1767 ToData.DeclaredSpecialMembers = FromData.DeclaredSpecialMembers;
1768 ToData.ImplicitCopyConstructorCanHaveConstParamForVBase
1769 = FromData.ImplicitCopyConstructorCanHaveConstParamForVBase;
1770 ToData.ImplicitCopyConstructorCanHaveConstParamForNonVBase
1771 = FromData.ImplicitCopyConstructorCanHaveConstParamForNonVBase;
1772 ToData.ImplicitCopyAssignmentHasConstParam
1773 = FromData.ImplicitCopyAssignmentHasConstParam;
1774 ToData.HasDeclaredCopyConstructorWithConstParam
1775 = FromData.HasDeclaredCopyConstructorWithConstParam;
1776 ToData.HasDeclaredCopyAssignmentWithConstParam
1777 = FromData.HasDeclaredCopyAssignmentWithConstParam;
1778
1779 // Copy over the data stored in RecordDeclBits
1780 ToCXX->setArgPassingRestrictions(FromCXX->getArgPassingRestrictions());
1781
1782 SmallVector<CXXBaseSpecifier *, 4> Bases;
1783 for (const auto &Base1 : FromCXX->bases()) {
1784 ExpectedType TyOrErr = import(Base1.getType());
1785 if (!TyOrErr)
1786 return TyOrErr.takeError();
1787
1788 SourceLocation EllipsisLoc;
1789 if (Base1.isPackExpansion()) {
1790 if (ExpectedSLoc LocOrErr = import(Base1.getEllipsisLoc()))
1791 EllipsisLoc = *LocOrErr;
1792 else
1793 return LocOrErr.takeError();
1794 }
1795
1796 // Ensure that we have a definition for the base.
1797 if (Error Err =
1798 ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl()))
1799 return Err;
1800
1801 auto RangeOrErr = import(Base1.getSourceRange());
1802 if (!RangeOrErr)
1803 return RangeOrErr.takeError();
1804
1805 auto TSIOrErr = import(Base1.getTypeSourceInfo());
1806 if (!TSIOrErr)
1807 return TSIOrErr.takeError();
1808
1809 Bases.push_back(
1810 new (Importer.getToContext()) CXXBaseSpecifier(
1811 *RangeOrErr,
1812 Base1.isVirtual(),
1813 Base1.isBaseOfClass(),
1814 Base1.getAccessSpecifierAsWritten(),
1815 *TSIOrErr,
1816 EllipsisLoc));
1817 }
1818 if (!Bases.empty())
1819 ToCXX->setBases(Bases.data(), Bases.size());
1820 }
1821
1822 if (shouldForceImportDeclContext(Kind))
1823 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
1824 return Err;
1825
1826 To->completeDefinition();
1827 return Error::success();
1828}
1829
1830Error ASTNodeImporter::ImportInitializer(VarDecl *From, VarDecl *To) {
1831 if (To->getAnyInitializer())
1832 return Error::success();
1833
1834 Expr *FromInit = From->getInit();
1835 if (!FromInit)
1836 return Error::success();
1837
1838 ExpectedExpr ToInitOrErr = import(FromInit);
1839 if (!ToInitOrErr)
1840 return ToInitOrErr.takeError();
1841
1842 To->setInit(*ToInitOrErr);
1843 if (From->isInitKnownICE()) {
1844 EvaluatedStmt *Eval = To->ensureEvaluatedStmt();
1845 Eval->CheckedICE = true;
1846 Eval->IsICE = From->isInitICE();
1847 }
1848
1849 // FIXME: Other bits to merge?
1850 return Error::success();
1851}
1852
1853Error ASTNodeImporter::ImportDefinition(
1854 EnumDecl *From, EnumDecl *To, ImportDefinitionKind Kind) {
1855 if (To->getDefinition() || To->isBeingDefined()) {
1856 if (Kind == IDK_Everything)
1857 return ImportDeclContext(From, /*ForceImport=*/true);
1858 return Error::success();
1859 }
1860
1861 To->startDefinition();
1862
1863 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer))
1864 return Err;
1865
1866 ExpectedType ToTypeOrErr =
1867 import(Importer.getFromContext().getTypeDeclType(From));
1868 if (!ToTypeOrErr)
1869 return ToTypeOrErr.takeError();
1870
1871 ExpectedType ToPromotionTypeOrErr = import(From->getPromotionType());
1872 if (!ToPromotionTypeOrErr)
1873 return ToPromotionTypeOrErr.takeError();
1874
1875 if (shouldForceImportDeclContext(Kind))
1876 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
1877 return Err;
1878
1879 // FIXME: we might need to merge the number of positive or negative bits
1880 // if the enumerator lists don't match.
1881 To->completeDefinition(*ToTypeOrErr, *ToPromotionTypeOrErr,
1882 From->getNumPositiveBits(),
1883 From->getNumNegativeBits());
1884 return Error::success();
1885}
1886
1887Error ASTNodeImporter::ImportTemplateArguments(
1888 const TemplateArgument *FromArgs, unsigned NumFromArgs,
1889 SmallVectorImpl<TemplateArgument> &ToArgs) {
1890 for (unsigned I = 0; I != NumFromArgs; ++I) {
1891 if (auto ToOrErr = import(FromArgs[I]))
1892 ToArgs.push_back(*ToOrErr);
1893 else
1894 return ToOrErr.takeError();
1895 }
1896
1897 return Error::success();
1898}
1899
1900// FIXME: Do not forget to remove this and use only 'import'.
1901Expected<TemplateArgument>
1902ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) {
1903 return import(From);
1904}
1905
1906template <typename InContainerTy>
1907Error ASTNodeImporter::ImportTemplateArgumentListInfo(
1908 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) {
1909 for (const auto &FromLoc : Container) {
1910 if (auto ToLocOrErr = import(FromLoc))
1911 ToTAInfo.addArgument(*ToLocOrErr);
1912 else
1913 return ToLocOrErr.takeError();
1914 }
1915 return Error::success();
1916}
1917
1918static StructuralEquivalenceKind
1919getStructuralEquivalenceKind(const ASTImporter &Importer) {
1920 return Importer.isMinimalImport() ? StructuralEquivalenceKind::Minimal
1921 : StructuralEquivalenceKind::Default;
1922}
1923
1924bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain) {
1925 StructuralEquivalenceContext Ctx(
1926 Importer.getFromContext(), Importer.getToContext(),
1927 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
1928 false, Complain);
1929 return Ctx.IsEquivalent(From, To);
1930}
1931
1932bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord,
1933 RecordDecl *ToRecord, bool Complain) {
1934 // Eliminate a potential failure point where we attempt to re-import
1935 // something we're trying to import while completing ToRecord.
1936 Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord);
1937 if (ToOrigin) {
1938 auto *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin);
1939 if (ToOriginRecord)
1940 ToRecord = ToOriginRecord;
1941 }
1942
1943 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
1944 ToRecord->getASTContext(),
1945 Importer.getNonEquivalentDecls(),
1946 getStructuralEquivalenceKind(Importer),
1947 false, Complain);
1948 return Ctx.IsEquivalent(FromRecord, ToRecord);
1949}
1950
1951bool ASTNodeImporter::IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar,
1952 bool Complain) {
1953 StructuralEquivalenceContext Ctx(
1954 Importer.getFromContext(), Importer.getToContext(),
1955 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
1956 false, Complain);
1957 return Ctx.IsEquivalent(FromVar, ToVar);
1958}
1959
1960bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) {
1961 // Eliminate a potential failure point where we attempt to re-import
1962 // something we're trying to import while completing ToEnum.
1963 if (Decl *ToOrigin = Importer.GetOriginalDecl(ToEnum))
1964 if (auto *ToOriginEnum = dyn_cast<EnumDecl>(ToOrigin))
1965 ToEnum = ToOriginEnum;
1966
1967 StructuralEquivalenceContext Ctx(
1968 Importer.getFromContext(), Importer.getToContext(),
1969 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer));
1970 return Ctx.IsEquivalent(FromEnum, ToEnum);
1971}
1972
1973bool ASTNodeImporter::IsStructuralMatch(FunctionTemplateDecl *From,
1974 FunctionTemplateDecl *To) {
1975 StructuralEquivalenceContext Ctx(
1976 Importer.getFromContext(), Importer.getToContext(),
1977 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
1978 false, false);
1979 return Ctx.IsEquivalent(From, To);
1980}
1981
1982bool ASTNodeImporter::IsStructuralMatch(FunctionDecl *From, FunctionDecl *To) {
1983 StructuralEquivalenceContext Ctx(
1984 Importer.getFromContext(), Importer.getToContext(),
1985 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer),
1986 false, false);
1987 return Ctx.IsEquivalent(From, To);
1988}
1989
1990bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC,
1991 EnumConstantDecl *ToEC) {
1992 const llvm::APSInt &FromVal = FromEC->getInitVal();
1993 const llvm::APSInt &ToVal = ToEC->getInitVal();
1994
1995 return FromVal.isSigned() == ToVal.isSigned() &&
1996 FromVal.getBitWidth() == ToVal.getBitWidth() &&
1997 FromVal == ToVal;
1998}
1999
2000bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From,
2001 ClassTemplateDecl *To) {
2002 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2003 Importer.getToContext(),
2004 Importer.getNonEquivalentDecls(),
2005 getStructuralEquivalenceKind(Importer));
2006 return Ctx.IsEquivalent(From, To);
2007}
2008
2009bool ASTNodeImporter::IsStructuralMatch(VarTemplateDecl *From,
2010 VarTemplateDecl *To) {
2011 StructuralEquivalenceContext Ctx(Importer.getFromContext(),
2012 Importer.getToContext(),
2013 Importer.getNonEquivalentDecls(),
2014 getStructuralEquivalenceKind(Importer));
2015 return Ctx.IsEquivalent(From, To);
2016}
2017
2018ExpectedDecl ASTNodeImporter::VisitDecl(Decl *D) {
2019 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2020 << D->getDeclKindName();
2021 return make_error<ImportError>(ImportError::UnsupportedConstruct);
2022}
2023
2024ExpectedDecl ASTNodeImporter::VisitImportDecl(ImportDecl *D) {
2025 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node)
2026 << D->getDeclKindName();
2027 return make_error<ImportError>(ImportError::UnsupportedConstruct);
2028}
2029
2030ExpectedDecl ASTNodeImporter::VisitEmptyDecl(EmptyDecl *D) {
2031 // Import the context of this declaration.
2032 DeclContext *DC, *LexicalDC;
2033 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
2034 return std::move(Err);
2035
2036 // Import the location of this declaration.
2037 ExpectedSLoc LocOrErr = import(D->getLocation());
2038 if (!LocOrErr)
2039 return LocOrErr.takeError();
2040
2041 EmptyDecl *ToD;
2042 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, *LocOrErr))
2043 return ToD;
2044
2045 ToD->setLexicalDeclContext(LexicalDC);
2046 LexicalDC->addDeclInternal(ToD);
2047 return ToD;
2048}
2049
2050ExpectedDecl ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) {
2051 TranslationUnitDecl *ToD =
2052 Importer.getToContext().getTranslationUnitDecl();
2053
2054 Importer.MapImported(D, ToD);
2055
2056 return ToD;
2057}
2058
2059ExpectedDecl ASTNodeImporter::VisitAccessSpecDecl(AccessSpecDecl *D) {
2060 ExpectedSLoc LocOrErr = import(D->getLocation());
2061 if (!LocOrErr)
2062 return LocOrErr.takeError();
2063 auto ColonLocOrErr = import(D->getColonLoc());
2064 if (!ColonLocOrErr)
2065 return ColonLocOrErr.takeError();
2066
2067 // Import the context of this declaration.
2068 auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2069 if (!DCOrErr)
2070 return DCOrErr.takeError();
2071 DeclContext *DC = *DCOrErr;
2072
2073 AccessSpecDecl *ToD;
2074 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), D->getAccess(),
2075 DC, *LocOrErr, *ColonLocOrErr))
2076 return ToD;
2077
2078 // Lexical DeclContext and Semantic DeclContext
2079 // is always the same for the accessSpec.
2080 ToD->setLexicalDeclContext(DC);
2081 DC->addDeclInternal(ToD);
2082
2083 return ToD;
2084}
2085
2086ExpectedDecl ASTNodeImporter::VisitStaticAssertDecl(StaticAssertDecl *D) {
2087 auto DCOrErr = Importer.ImportContext(D->getDeclContext());
2088 if (!DCOrErr)
2089 return DCOrErr.takeError();
2090 DeclContext *DC = *DCOrErr;
2091 DeclContext *LexicalDC = DC;
2092
2093 SourceLocation ToLocation, ToRParenLoc;
2094 Expr *ToAssertExpr;
2095 StringLiteral *ToMessage;
2096 if (auto Imp = importSeq(
2097 D->getLocation(), D->getAssertExpr(), D->getMessage(), D->getRParenLoc()))
2098 std::tie(ToLocation, ToAssertExpr, ToMessage, ToRParenLoc) = *Imp;
2099 else
2100 return Imp.takeError();
2101
2102 StaticAssertDecl *ToD;
2103 if (GetImportedOrCreateDecl(
2104 ToD, D, Importer.getToContext(), DC, ToLocation, ToAssertExpr, ToMessage,
2105 ToRParenLoc, D->isFailed()))
2106 return ToD;
2107
2108 ToD->setLexicalDeclContext(LexicalDC);
2109 LexicalDC->addDeclInternal(ToD);
2110 return ToD;
2111}
2112
2113ExpectedDecl ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) {
2114 // Import the major distinguishing characteristics of this namespace.
2115 DeclContext *DC, *LexicalDC;
2116 DeclarationName Name;
2117 SourceLocation Loc;
2118 NamedDecl *ToD;
2119 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2120 return std::move(Err);
2121 if (ToD)
2122 return ToD;
2123
2124 NamespaceDecl *MergeWithNamespace = nullptr;
2125 if (!Name) {
2126 // This is an anonymous namespace. Adopt an existing anonymous
2127 // namespace if we can.
2128 // FIXME: Not testable.
2129 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2130 MergeWithNamespace = TU->getAnonymousNamespace();
2131 else
2132 MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace();
2133 } else {
2134 SmallVector<NamedDecl *, 4> ConflictingDecls;
2135 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2136 for (auto *FoundDecl : FoundDecls) {
2137 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Namespace))
2138 continue;
2139
2140 if (auto *FoundNS = dyn_cast<NamespaceDecl>(FoundDecl)) {
2141 MergeWithNamespace = FoundNS;
2142 ConflictingDecls.clear();
2143 break;
2144 }
2145
2146 ConflictingDecls.push_back(FoundDecl);
2147 }
2148
2149 if (!ConflictingDecls.empty()) {
2150 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Namespace,
2151 ConflictingDecls.data(),
2152 ConflictingDecls.size());
2153 if (!Name)
2154 return make_error<ImportError>(ImportError::NameConflict);
2155 }
2156 }
2157
2158 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2159 if (!BeginLocOrErr)
2160 return BeginLocOrErr.takeError();
2161
2162 // Create the "to" namespace, if needed.
2163 NamespaceDecl *ToNamespace = MergeWithNamespace;
2164 if (!ToNamespace) {
2165 if (GetImportedOrCreateDecl(
2166 ToNamespace, D, Importer.getToContext(), DC, D->isInline(),
2167 *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
2168 /*PrevDecl=*/nullptr))
2169 return ToNamespace;
2170 ToNamespace->setLexicalDeclContext(LexicalDC);
2171 LexicalDC->addDeclInternal(ToNamespace);
2172
2173 // If this is an anonymous namespace, register it as the anonymous
2174 // namespace within its context.
2175 if (!Name) {
2176 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC))
2177 TU->setAnonymousNamespace(ToNamespace);
2178 else
2179 cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace);
2180 }
2181 }
2182 Importer.MapImported(D, ToNamespace);
2183
2184 if (Error Err = ImportDeclContext(D))
2185 return std::move(Err);
2186
2187 return ToNamespace;
2188}
2189
2190ExpectedDecl ASTNodeImporter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) {
2191 // Import the major distinguishing characteristics of this namespace.
2192 DeclContext *DC, *LexicalDC;
2193 DeclarationName Name;
2194 SourceLocation Loc;
2195 NamedDecl *LookupD;
2196 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, LookupD, Loc))
2197 return std::move(Err);
2198 if (LookupD)
2199 return LookupD;
2200
2201 // NOTE: No conflict resolution is done for namespace aliases now.
2202
2203 SourceLocation ToNamespaceLoc, ToAliasLoc, ToTargetNameLoc;
2204 NestedNameSpecifierLoc ToQualifierLoc;
2205 NamespaceDecl *ToNamespace;
2206 if (auto Imp = importSeq(
2207 D->getNamespaceLoc(), D->getAliasLoc(), D->getQualifierLoc(),
2208 D->getTargetNameLoc(), D->getNamespace()))
2209 std::tie(
2210 ToNamespaceLoc, ToAliasLoc, ToQualifierLoc, ToTargetNameLoc,
2211 ToNamespace) = *Imp;
2212 else
2213 return Imp.takeError();
2214 IdentifierInfo *ToIdentifier = Importer.Import(D->getIdentifier());
2215
2216 NamespaceAliasDecl *ToD;
2217 if (GetImportedOrCreateDecl(
2218 ToD, D, Importer.getToContext(), DC, ToNamespaceLoc, ToAliasLoc,
2219 ToIdentifier, ToQualifierLoc, ToTargetNameLoc, ToNamespace))
2220 return ToD;
2221
2222 ToD->setLexicalDeclContext(LexicalDC);
2223 LexicalDC->addDeclInternal(ToD);
2224
2225 return ToD;
2226}
2227
2228ExpectedDecl
2229ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) {
2230 // Import the major distinguishing characteristics of this typedef.
2231 DeclContext *DC, *LexicalDC;
2232 DeclarationName Name;
2233 SourceLocation Loc;
2234 NamedDecl *ToD;
2235 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2236 return std::move(Err);
2237 if (ToD)
2238 return ToD;
2239
2240 // If this typedef is not in block scope, determine whether we've
2241 // seen a typedef with the same name (that we can merge with) or any
2242 // other entity by that name (which name lookup could conflict with).
2243 if (!DC->isFunctionOrMethod()) {
2244 SmallVector<NamedDecl *, 4> ConflictingDecls;
2245 unsigned IDNS = Decl::IDNS_Ordinary;
2246 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2247 for (auto *FoundDecl : FoundDecls) {
2248 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2249 continue;
2250 if (auto *FoundTypedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2251 QualType FromUT = D->getUnderlyingType();
2252 QualType FoundUT = FoundTypedef->getUnderlyingType();
2253 if (Importer.IsStructurallyEquivalent(FromUT, FoundUT)) {
2254 // If the "From" context has a complete underlying type but we
2255 // already have a complete underlying type then return with that.
2256 if (!FromUT->isIncompleteType() && !FoundUT->isIncompleteType())
2257 return Importer.MapImported(D, FoundTypedef);
2258 }
2259 // FIXME Handle redecl chain.
2260 break;
2261 }
2262
2263 ConflictingDecls.push_back(FoundDecl);
2264 }
2265
2266 if (!ConflictingDecls.empty()) {
2267 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2268 ConflictingDecls.data(),
2269 ConflictingDecls.size());
2270 if (!Name)
2271 return make_error<ImportError>(ImportError::NameConflict);
2272 }
2273 }
2274
2275 QualType ToUnderlyingType;
2276 TypeSourceInfo *ToTypeSourceInfo;
2277 SourceLocation ToBeginLoc;
2278 if (auto Imp = importSeq(
2279 D->getUnderlyingType(), D->getTypeSourceInfo(), D->getBeginLoc()))
2280 std::tie(ToUnderlyingType, ToTypeSourceInfo, ToBeginLoc) = *Imp;
2281 else
2282 return Imp.takeError();
2283
2284 // Create the new typedef node.
2285 // FIXME: ToUnderlyingType is not used.
2286 TypedefNameDecl *ToTypedef;
2287 if (IsAlias) {
2288 if (GetImportedOrCreateDecl<TypeAliasDecl>(
2289 ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2290 Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2291 return ToTypedef;
2292 } else if (GetImportedOrCreateDecl<TypedefDecl>(
2293 ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc,
2294 Name.getAsIdentifierInfo(), ToTypeSourceInfo))
2295 return ToTypedef;
2296
2297 ToTypedef->setAccess(D->getAccess());
2298 ToTypedef->setLexicalDeclContext(LexicalDC);
2299
2300 // Templated declarations should not appear in DeclContext.
2301 TypeAliasDecl *FromAlias = IsAlias ? cast<TypeAliasDecl>(D) : nullptr;
2302 if (!FromAlias || !FromAlias->getDescribedAliasTemplate())
2303 LexicalDC->addDeclInternal(ToTypedef);
2304
2305 return ToTypedef;
2306}
2307
2308ExpectedDecl ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) {
2309 return VisitTypedefNameDecl(D, /*IsAlias=*/false);
2310}
2311
2312ExpectedDecl ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) {
2313 return VisitTypedefNameDecl(D, /*IsAlias=*/true);
2314}
2315
2316ExpectedDecl
2317ASTNodeImporter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) {
2318 // Import the major distinguishing characteristics of this typedef.
2319 DeclContext *DC, *LexicalDC;
2320 DeclarationName Name;
2321 SourceLocation Loc;
2322 NamedDecl *FoundD;
2323 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, FoundD, Loc))
2324 return std::move(Err);
2325 if (FoundD)
2326 return FoundD;
2327
2328 // If this typedef is not in block scope, determine whether we've
2329 // seen a typedef with the same name (that we can merge with) or any
2330 // other entity by that name (which name lookup could conflict with).
2331 if (!DC->isFunctionOrMethod()) {
2332 SmallVector<NamedDecl *, 4> ConflictingDecls;
2333 unsigned IDNS = Decl::IDNS_Ordinary;
2334 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2335 for (auto *FoundDecl : FoundDecls) {
2336 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2337 continue;
2338 if (auto *FoundAlias = dyn_cast<TypeAliasTemplateDecl>(FoundDecl))
2339 return Importer.MapImported(D, FoundAlias);
2340 ConflictingDecls.push_back(FoundDecl);
2341 }
2342
2343 if (!ConflictingDecls.empty()) {
2344 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2345 ConflictingDecls.data(),
2346 ConflictingDecls.size());
2347 if (!Name)
2348 return make_error<ImportError>(ImportError::NameConflict);
2349 }
2350 }
2351
2352 TemplateParameterList *ToTemplateParameters;
2353 TypeAliasDecl *ToTemplatedDecl;
2354 if (auto Imp = importSeq(D->getTemplateParameters(), D->getTemplatedDecl()))
2355 std::tie(ToTemplateParameters, ToTemplatedDecl) = *Imp;
2356 else
2357 return Imp.takeError();
2358
2359 TypeAliasTemplateDecl *ToAlias;
2360 if (GetImportedOrCreateDecl(ToAlias, D, Importer.getToContext(), DC, Loc,
2361 Name, ToTemplateParameters, ToTemplatedDecl))
2362 return ToAlias;
2363
2364 ToTemplatedDecl->setDescribedAliasTemplate(ToAlias);
2365
2366 ToAlias->setAccess(D->getAccess());
2367 ToAlias->setLexicalDeclContext(LexicalDC);
2368 LexicalDC->addDeclInternal(ToAlias);
2369 return ToAlias;
2370}
2371
2372ExpectedDecl ASTNodeImporter::VisitLabelDecl(LabelDecl *D) {
2373 // Import the major distinguishing characteristics of this label.
2374 DeclContext *DC, *LexicalDC;
2375 DeclarationName Name;
2376 SourceLocation Loc;
2377 NamedDecl *ToD;
2378 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2379 return std::move(Err);
2380 if (ToD)
2381 return ToD;
2382
2383 assert(LexicalDC->isFunctionOrMethod())((LexicalDC->isFunctionOrMethod()) ? static_cast<void>
(0) : __assert_fail ("LexicalDC->isFunctionOrMethod()", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp"
, 2383, __PRETTY_FUNCTION__))
;
2384
2385 LabelDecl *ToLabel;
2386 if (D->isGnuLocal()) {
2387 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2388 if (!BeginLocOrErr)
2389 return BeginLocOrErr.takeError();
2390 if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2391 Name.getAsIdentifierInfo(), *BeginLocOrErr))
2392 return ToLabel;
2393
2394 } else {
2395 if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc,
2396 Name.getAsIdentifierInfo()))
2397 return ToLabel;
2398
2399 }
2400
2401 Expected<LabelStmt *> ToStmtOrErr = import(D->getStmt());
2402 if (!ToStmtOrErr)
2403 return ToStmtOrErr.takeError();
2404
2405 ToLabel->setStmt(*ToStmtOrErr);
2406 ToLabel->setLexicalDeclContext(LexicalDC);
2407 LexicalDC->addDeclInternal(ToLabel);
2408 return ToLabel;
2409}
2410
2411ExpectedDecl ASTNodeImporter::VisitEnumDecl(EnumDecl *D) {
2412 // Import the major distinguishing characteristics of this enum.
2413 DeclContext *DC, *LexicalDC;
2414 DeclarationName Name;
2415 SourceLocation Loc;
2416 NamedDecl *ToD;
2417 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2418 return std::move(Err);
2419 if (ToD)
2420 return ToD;
2421
2422 // Figure out what enum name we're looking for.
2423 unsigned IDNS = Decl::IDNS_Tag;
2424 DeclarationName SearchName = Name;
2425 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2426 if (Error Err = importInto(
2427 SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2428 return std::move(Err);
2429 IDNS = Decl::IDNS_Ordinary;
2430 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2431 IDNS |= Decl::IDNS_Ordinary;
2432
2433 // We may already have an enum of the same name; try to find and match it.
2434 if (!DC->isFunctionOrMethod() && SearchName) {
2435 SmallVector<NamedDecl *, 4> ConflictingDecls;
2436 auto FoundDecls =
2437 Importer.findDeclsInToCtx(DC, SearchName);
2438 for (auto *FoundDecl : FoundDecls) {
2439 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2440 continue;
2441
2442 if (auto *Typedef = dyn_cast<TypedefNameDecl>(FoundDecl)) {
2443 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2444 FoundDecl = Tag->getDecl();
2445 }
2446
2447 if (auto *FoundEnum = dyn_cast<EnumDecl>(FoundDecl)) {
2448 if (IsStructuralMatch(D, FoundEnum))
2449 return Importer.MapImported(D, FoundEnum);
2450 }
2451
2452 ConflictingDecls.push_back(FoundDecl);
2453 }
2454
2455 if (!ConflictingDecls.empty()) {
2456 Name = Importer.HandleNameConflict(SearchName, DC, IDNS,
2457 ConflictingDecls.data(),
2458 ConflictingDecls.size());
2459 if (!Name)
2460 return make_error<ImportError>(ImportError::NameConflict);
2461 }
2462 }
2463
2464 SourceLocation ToBeginLoc;
2465 NestedNameSpecifierLoc ToQualifierLoc;
2466 QualType ToIntegerType;
2467 if (auto Imp = importSeq(
2468 D->getBeginLoc(), D->getQualifierLoc(), D->getIntegerType()))
2469 std::tie(ToBeginLoc, ToQualifierLoc, ToIntegerType) = *Imp;
2470 else
2471 return Imp.takeError();
2472
2473 // Create the enum declaration.
2474 EnumDecl *D2;
2475 if (GetImportedOrCreateDecl(
2476 D2, D, Importer.getToContext(), DC, ToBeginLoc,
2477 Loc, Name.getAsIdentifierInfo(), nullptr, D->isScoped(),
2478 D->isScopedUsingClassTag(), D->isFixed()))
2479 return D2;
2480
2481 D2->setQualifierInfo(ToQualifierLoc);
2482 D2->setIntegerType(ToIntegerType);
2483 D2->setAccess(D->getAccess());
2484 D2->setLexicalDeclContext(LexicalDC);
2485 LexicalDC->addDeclInternal(D2);
2486
2487 // Import the definition
2488 if (D->isCompleteDefinition())
2489 if (Error Err = ImportDefinition(D, D2))
2490 return std::move(Err);
2491
2492 return D2;
2493}
2494
2495ExpectedDecl ASTNodeImporter::VisitRecordDecl(RecordDecl *D) {
2496 bool IsFriendTemplate = false;
2497 if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2498 IsFriendTemplate =
2499 DCXX->getDescribedClassTemplate() &&
2500 DCXX->getDescribedClassTemplate()->getFriendObjectKind() !=
2501 Decl::FOK_None;
2502 }
2503
2504 // Import the major distinguishing characteristics of this record.
2505 DeclContext *DC, *LexicalDC;
2506 DeclarationName Name;
2507 SourceLocation Loc;
2508 NamedDecl *ToD;
2509 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2510 return std::move(Err);
2511 if (ToD)
2512 return ToD;
2513
2514 // Figure out what structure name we're looking for.
2515 unsigned IDNS = Decl::IDNS_Tag;
2516 DeclarationName SearchName = Name;
2517 if (!SearchName && D->getTypedefNameForAnonDecl()) {
2518 if (Error Err = importInto(
2519 SearchName, D->getTypedefNameForAnonDecl()->getDeclName()))
2520 return std::move(Err);
2521 IDNS = Decl::IDNS_Ordinary;
2522 } else if (Importer.getToContext().getLangOpts().CPlusPlus)
2523 IDNS |= Decl::IDNS_Ordinary | Decl::IDNS_TagFriend;
2524
2525 // We may already have a record of the same name; try to find and match it.
2526 RecordDecl *PrevDecl = nullptr;
2527 if (!DC->isFunctionOrMethod()) {
2528 SmallVector<NamedDecl *, 4> ConflictingDecls;
2529 auto FoundDecls =
2530 Importer.findDeclsInToCtx(DC, SearchName);
2531 if (!FoundDecls.empty()) {
2532 // We're going to have to compare D against potentially conflicting Decls,
2533 // so complete it.
2534 if (D->hasExternalLexicalStorage() && !D->isCompleteDefinition())
2535 D->getASTContext().getExternalSource()->CompleteType(D);
2536 }
2537
2538 for (auto *FoundDecl : FoundDecls) {
2539 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2540 continue;
2541
2542 Decl *Found = FoundDecl;
2543 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) {
2544 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>())
2545 Found = Tag->getDecl();
2546 }
2547
2548 if (auto *FoundRecord = dyn_cast<RecordDecl>(Found)) {
2549 // Do not emit false positive diagnostic in case of unnamed
2550 // struct/union and in case of anonymous structs. Would be false
2551 // because there may be several anonymous/unnamed structs in a class.
2552 // E.g. these are both valid:
2553 // struct A { // unnamed structs
2554 // struct { struct A *next; } entry0;
2555 // struct { struct A *next; } entry1;
2556 // };
2557 // struct X { struct { int a; }; struct { int b; }; }; // anon structs
2558 if (!SearchName)
2559 if (!IsStructuralMatch(D, FoundRecord, false))
2560 continue;
2561
2562 if (!hasSameVisibilityContext(FoundRecord, D))
2563 continue;
2564
2565 if (IsStructuralMatch(D, FoundRecord)) {
2566 RecordDecl *FoundDef = FoundRecord->getDefinition();
2567 if (D->isThisDeclarationADefinition() && FoundDef) {
2568 // FIXME: Structural equivalence check should check for same
2569 // user-defined methods.
2570 Importer.MapImported(D, FoundDef);
2571 if (const auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2572 auto *FoundCXX = dyn_cast<CXXRecordDecl>(FoundDef);
2573 assert(FoundCXX && "Record type mismatch")((FoundCXX && "Record type mismatch") ? static_cast<
void> (0) : __assert_fail ("FoundCXX && \"Record type mismatch\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp"
, 2573, __PRETTY_FUNCTION__))
;
2574
2575 if (!Importer.isMinimalImport())
2576 // FoundDef may not have every implicit method that D has
2577 // because implicit methods are created only if they are used.
2578 if (Error Err = ImportImplicitMethods(DCXX, FoundCXX))
2579 return std::move(Err);
2580 }
2581 }
2582 PrevDecl = FoundRecord->getMostRecentDecl();
2583 break;
2584 }
2585 }
2586
2587 ConflictingDecls.push_back(FoundDecl);
2588 } // for
2589
2590 if (!ConflictingDecls.empty() && SearchName) {
2591 Name = Importer.HandleNameConflict(SearchName, DC, IDNS,
2592 ConflictingDecls.data(),
2593 ConflictingDecls.size());
2594 if (!Name)
2595 return make_error<ImportError>(ImportError::NameConflict);
2596 }
2597 }
2598
2599 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
2600 if (!BeginLocOrErr)
2601 return BeginLocOrErr.takeError();
2602
2603 // Create the record declaration.
2604 RecordDecl *D2 = nullptr;
2605 CXXRecordDecl *D2CXX = nullptr;
2606 if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) {
2607 if (DCXX->isLambda()) {
2608 auto TInfoOrErr = import(DCXX->getLambdaTypeInfo());
2609 if (!TInfoOrErr)
2610 return TInfoOrErr.takeError();
2611 if (GetImportedOrCreateSpecialDecl(
2612 D2CXX, CXXRecordDecl::CreateLambda, D, Importer.getToContext(),
2613 DC, *TInfoOrErr, Loc, DCXX->isDependentLambda(),
2614 DCXX->isGenericLambda(), DCXX->getLambdaCaptureDefault()))
2615 return D2CXX;
2616 ExpectedDecl CDeclOrErr = import(DCXX->getLambdaContextDecl());
2617 if (!CDeclOrErr)
2618 return CDeclOrErr.takeError();
2619 D2CXX->setLambdaMangling(DCXX->getLambdaManglingNumber(), *CDeclOrErr);
2620 } else if (DCXX->isInjectedClassName()) {
2621 // We have to be careful to do a similar dance to the one in
2622 // Sema::ActOnStartCXXMemberDeclarations
2623 const bool DelayTypeCreation = true;
2624 if (GetImportedOrCreateDecl(
2625 D2CXX, D, Importer.getToContext(), D->getTagKind(), DC,
2626 *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(),
2627 cast_or_null<CXXRecordDecl>(PrevDecl), DelayTypeCreation))
2628 return D2CXX;
2629 Importer.getToContext().getTypeDeclType(
2630 D2CXX, dyn_cast<CXXRecordDecl>(DC));
2631 } else {
2632 if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(),
2633 D->getTagKind(), DC, *BeginLocOrErr, Loc,
2634 Name.getAsIdentifierInfo(),
2635 cast_or_null<CXXRecordDecl>(PrevDecl)))
2636 return D2CXX;
2637 }
2638
2639 D2 = D2CXX;
2640 D2->setAccess(D->getAccess());
2641 D2->setLexicalDeclContext(LexicalDC);
2642 if (!DCXX->getDescribedClassTemplate() || DCXX->isImplicit())
2643 LexicalDC->addDeclInternal(D2);
2644
2645 if (LexicalDC != DC && D->isInIdentifierNamespace(Decl::IDNS_TagFriend))
2646 DC->makeDeclVisibleInContext(D2);
2647
2648 if (ClassTemplateDecl *FromDescribed =
2649 DCXX->getDescribedClassTemplate()) {
2650 ClassTemplateDecl *ToDescribed;
2651 if (Error Err = importInto(ToDescribed, FromDescribed))
2652 return std::move(Err);
2653 D2CXX->setDescribedClassTemplate(ToDescribed);
2654 if (!DCXX->isInjectedClassName() && !IsFriendTemplate) {
2655 // In a record describing a template the type should be an
2656 // InjectedClassNameType (see Sema::CheckClassTemplate). Update the
2657 // previously set type to the correct value here (ToDescribed is not
2658 // available at record create).
2659 // FIXME: The previous type is cleared but not removed from
2660 // ASTContext's internal storage.
2661 CXXRecordDecl *Injected = nullptr;
2662 for (NamedDecl *Found : D2CXX->noload_lookup(Name)) {
2663 auto *Record = dyn_cast<CXXRecordDecl>(Found);
2664 if (Record && Record->isInjectedClassName()) {
2665 Injected = Record;
2666 break;
2667 }
2668 }
2669 // Create an injected type for the whole redecl chain.
2670 SmallVector<Decl *, 2> Redecls =
2671 getCanonicalForwardRedeclChain(D2CXX);
2672 for (auto *R : Redecls) {
2673 auto *RI = cast<CXXRecordDecl>(R);
2674 RI->setTypeForDecl(nullptr);
2675 // Below we create a new injected type and assign that to the
2676 // canonical decl, subsequent declarations in the chain will reuse
2677 // that type.
2678 Importer.getToContext().getInjectedClassNameType(
2679 RI, ToDescribed->getInjectedClassNameSpecialization());
2680 }
2681 // Set the new type for the previous injected decl too.
2682 if (Injected) {
2683 Injected->setTypeForDecl(nullptr);
2684 Importer.getToContext().getTypeDeclType(Injected, D2CXX);
2685 }
2686 }
2687 } else if (MemberSpecializationInfo *MemberInfo =
2688 DCXX->getMemberSpecializationInfo()) {
2689 TemplateSpecializationKind SK =
2690 MemberInfo->getTemplateSpecializationKind();
2691 CXXRecordDecl *FromInst = DCXX->getInstantiatedFromMemberClass();
2692
2693 if (Expected<CXXRecordDecl *> ToInstOrErr = import(FromInst))
2694 D2CXX->setInstantiationOfMemberClass(*ToInstOrErr, SK);
2695 else
2696 return ToInstOrErr.takeError();
2697
2698 if (ExpectedSLoc POIOrErr =
2699 import(MemberInfo->getPointOfInstantiation()))
2700 D2CXX->getMemberSpecializationInfo()->setPointOfInstantiation(
2701 *POIOrErr);
2702 else
2703 return POIOrErr.takeError();
2704 }
2705
2706 } else {
2707 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(),
2708 D->getTagKind(), DC, *BeginLocOrErr, Loc,
2709 Name.getAsIdentifierInfo(), PrevDecl))
2710 return D2;
2711 D2->setLexicalDeclContext(LexicalDC);
2712 LexicalDC->addDeclInternal(D2);
2713 }
2714
2715 if (auto QualifierLocOrErr = import(D->getQualifierLoc()))
2716 D2->setQualifierInfo(*QualifierLocOrErr);
2717 else
2718 return QualifierLocOrErr.takeError();
2719
2720 if (D->isAnonymousStructOrUnion())
2721 D2->setAnonymousStructOrUnion(true);
2722
2723 if (D->isCompleteDefinition())
2724 if (Error Err = ImportDefinition(D, D2, IDK_Default))
2725 return std::move(Err);
2726
2727 return D2;
2728}
2729
2730ExpectedDecl ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) {
2731 // Import the major distinguishing characteristics of this enumerator.
2732 DeclContext *DC, *LexicalDC;
2733 DeclarationName Name;
2734 SourceLocation Loc;
2735 NamedDecl *ToD;
2736 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2737 return std::move(Err);
2738 if (ToD)
2739 return ToD;
2740
2741 // Determine whether there are any other declarations with the same name and
2742 // in the same context.
2743 if (!LexicalDC->isFunctionOrMethod()) {
2744 SmallVector<NamedDecl *, 4> ConflictingDecls;
2745 unsigned IDNS = Decl::IDNS_Ordinary;
2746 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2747 for (auto *FoundDecl : FoundDecls) {
2748 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2749 continue;
2750
2751 if (auto *FoundEnumConstant = dyn_cast<EnumConstantDecl>(FoundDecl)) {
2752 if (IsStructuralMatch(D, FoundEnumConstant))
2753 return Importer.MapImported(D, FoundEnumConstant);
2754 }
2755
2756 ConflictingDecls.push_back(FoundDecl);
2757 }
2758
2759 if (!ConflictingDecls.empty()) {
2760 Name = Importer.HandleNameConflict(Name, DC, IDNS,
2761 ConflictingDecls.data(),
2762 ConflictingDecls.size());
2763 if (!Name)
2764 return make_error<ImportError>(ImportError::NameConflict);
2765 }
2766 }
2767
2768 ExpectedType TypeOrErr = import(D->getType());
2769 if (!TypeOrErr)
2770 return TypeOrErr.takeError();
2771
2772 ExpectedExpr InitOrErr = import(D->getInitExpr());
2773 if (!InitOrErr)
2774 return InitOrErr.takeError();
2775
2776 EnumConstantDecl *ToEnumerator;
2777 if (GetImportedOrCreateDecl(
2778 ToEnumerator, D, Importer.getToContext(), cast<EnumDecl>(DC), Loc,
2779 Name.getAsIdentifierInfo(), *TypeOrErr, *InitOrErr, D->getInitVal()))
2780 return ToEnumerator;
2781
2782 ToEnumerator->setAccess(D->getAccess());
2783 ToEnumerator->setLexicalDeclContext(LexicalDC);
2784 LexicalDC->addDeclInternal(ToEnumerator);
2785 return ToEnumerator;
2786}
2787
2788Error ASTNodeImporter::ImportTemplateParameterLists(const DeclaratorDecl *FromD,
2789 DeclaratorDecl *ToD) {
2790 unsigned int Num = FromD->getNumTemplateParameterLists();
2791 if (Num == 0)
2792 return Error::success();
2793 SmallVector<TemplateParameterList *, 2> ToTPLists(Num);
2794 for (unsigned int I = 0; I < Num; ++I)
2795 if (Expected<TemplateParameterList *> ToTPListOrErr =
2796 import(FromD->getTemplateParameterList(I)))
2797 ToTPLists[I] = *ToTPListOrErr;
2798 else
2799 return ToTPListOrErr.takeError();
2800 ToD->setTemplateParameterListsInfo(Importer.ToContext, ToTPLists);
2801 return Error::success();
2802}
2803
2804Error ASTNodeImporter::ImportTemplateInformation(
2805 FunctionDecl *FromFD, FunctionDecl *ToFD) {
2806 switch (FromFD->getTemplatedKind()) {
2807 case FunctionDecl::TK_NonTemplate:
2808 case FunctionDecl::TK_FunctionTemplate:
2809 return Error::success();
2810
2811 case FunctionDecl::TK_MemberSpecialization: {
2812 TemplateSpecializationKind TSK = FromFD->getTemplateSpecializationKind();
2813
2814 if (Expected<FunctionDecl *> InstFDOrErr =
2815 import(FromFD->getInstantiatedFromMemberFunction()))
2816 ToFD->setInstantiationOfMemberFunction(*InstFDOrErr, TSK);
2817 else
2818 return InstFDOrErr.takeError();
2819
2820 if (ExpectedSLoc POIOrErr = import(
2821 FromFD->getMemberSpecializationInfo()->getPointOfInstantiation()))
2822 ToFD->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr);
2823 else
2824 return POIOrErr.takeError();
2825
2826 return Error::success();
2827 }
2828
2829 case FunctionDecl::TK_FunctionTemplateSpecialization: {
2830 auto FunctionAndArgsOrErr =
2831 ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
2832 if (!FunctionAndArgsOrErr)
2833 return FunctionAndArgsOrErr.takeError();
2834
2835 TemplateArgumentList *ToTAList = TemplateArgumentList::CreateCopy(
2836 Importer.getToContext(), std::get<1>(*FunctionAndArgsOrErr));
2837
2838 auto *FTSInfo = FromFD->getTemplateSpecializationInfo();
2839 TemplateArgumentListInfo ToTAInfo;
2840 const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten;
2841 if (FromTAArgsAsWritten)
2842 if (Error Err = ImportTemplateArgumentListInfo(
2843 *FromTAArgsAsWritten, ToTAInfo))
2844 return Err;
2845
2846 ExpectedSLoc POIOrErr = import(FTSInfo->getPointOfInstantiation());
2847 if (!POIOrErr)
2848 return POIOrErr.takeError();
2849
2850 if (Error Err = ImportTemplateParameterLists(FromFD, ToFD))
2851 return Err;
2852
2853 TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind();
2854 ToFD->setFunctionTemplateSpecialization(
2855 std::get<0>(*FunctionAndArgsOrErr), ToTAList, /* InsertPos= */ nullptr,
2856 TSK, FromTAArgsAsWritten ? &ToTAInfo : nullptr, *POIOrErr);
2857 return Error::success();
2858 }
2859
2860 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: {
2861 auto *FromInfo = FromFD->getDependentSpecializationInfo();
2862 UnresolvedSet<8> TemplDecls;
2863 unsigned NumTemplates = FromInfo->getNumTemplates();
2864 for (unsigned I = 0; I < NumTemplates; I++) {
2865 if (Expected<FunctionTemplateDecl *> ToFTDOrErr =
2866 import(FromInfo->getTemplate(I)))
2867 TemplDecls.addDecl(*ToFTDOrErr);
2868 else
2869 return ToFTDOrErr.takeError();
2870 }
2871
2872 // Import TemplateArgumentListInfo.
2873 TemplateArgumentListInfo ToTAInfo;
2874 if (Error Err = ImportTemplateArgumentListInfo(
2875 FromInfo->getLAngleLoc(), FromInfo->getRAngleLoc(),
2876 llvm::makeArrayRef(
2877 FromInfo->getTemplateArgs(), FromInfo->getNumTemplateArgs()),
2878 ToTAInfo))
2879 return Err;
2880
2881 ToFD->setDependentTemplateSpecialization(Importer.getToContext(),
2882 TemplDecls, ToTAInfo);
2883 return Error::success();
2884 }
2885 }
2886 llvm_unreachable("All cases should be covered!")::llvm::llvm_unreachable_internal("All cases should be covered!"
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp"
, 2886)
;
2887}
2888
2889Expected<FunctionDecl *>
2890ASTNodeImporter::FindFunctionTemplateSpecialization(FunctionDecl *FromFD) {
2891 auto FunctionAndArgsOrErr =
2892 ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD);
2893 if (!FunctionAndArgsOrErr)
2894 return FunctionAndArgsOrErr.takeError();
2895
2896 FunctionTemplateDecl *Template;
2897 TemplateArgsTy ToTemplArgs;
2898 std::tie(Template, ToTemplArgs) = *FunctionAndArgsOrErr;
2899 void *InsertPos = nullptr;
2900 auto *FoundSpec = Template->findSpecialization(ToTemplArgs, InsertPos);
2901 return FoundSpec;
2902}
2903
2904Error ASTNodeImporter::ImportFunctionDeclBody(FunctionDecl *FromFD,
2905 FunctionDecl *ToFD) {
2906 if (Stmt *FromBody = FromFD->getBody()) {
2907 if (ExpectedStmt ToBodyOrErr = import(FromBody))
2908 ToFD->setBody(*ToBodyOrErr);
2909 else
2910 return ToBodyOrErr.takeError();
2911 }
2912 return Error::success();
2913}
2914
2915template <typename T>
2916bool ASTNodeImporter::hasSameVisibilityContext(T *Found, T *From) {
2917 if (From->hasExternalFormalLinkage())
2918 return Found->hasExternalFormalLinkage();
2919 if (Importer.GetFromTU(Found) != From->getTranslationUnitDecl())
2920 return false;
2921 if (From->isInAnonymousNamespace())
2922 return Found->isInAnonymousNamespace();
2923 else
2924 return !Found->isInAnonymousNamespace() &&
2925 !Found->hasExternalFormalLinkage();
2926}
2927
2928ExpectedDecl ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) {
2929
2930 SmallVector<Decl *, 2> Redecls = getCanonicalForwardRedeclChain(D);
2931 auto RedeclIt = Redecls.begin();
2932 // Import the first part of the decl chain. I.e. import all previous
2933 // declarations starting from the canonical decl.
2934 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
2935 ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
2936 if (!ToRedeclOrErr)
2937 return ToRedeclOrErr.takeError();
2938 }
2939 assert(*RedeclIt == D)((*RedeclIt == D) ? static_cast<void> (0) : __assert_fail
("*RedeclIt == D", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp"
, 2939, __PRETTY_FUNCTION__))
;
2940
2941 // Import the major distinguishing characteristics of this function.
2942 DeclContext *DC, *LexicalDC;
2943 DeclarationName Name;
2944 SourceLocation Loc;
2945 NamedDecl *ToD;
2946 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
2947 return std::move(Err);
2948 if (ToD)
2949 return ToD;
2950
2951 FunctionDecl *FoundByLookup = nullptr;
2952 FunctionTemplateDecl *FromFT = D->getDescribedFunctionTemplate();
2953
2954 // If this is a function template specialization, then try to find the same
2955 // existing specialization in the "to" context. The lookup below will not
2956 // find any specialization, but would find the primary template; thus, we
2957 // have to skip normal lookup in case of specializations.
2958 // FIXME handle member function templates (TK_MemberSpecialization) similarly?
2959 if (D->getTemplatedKind() ==
2960 FunctionDecl::TK_FunctionTemplateSpecialization) {
2961 auto FoundFunctionOrErr = FindFunctionTemplateSpecialization(D);
2962 if (!FoundFunctionOrErr)
2963 return FoundFunctionOrErr.takeError();
2964 if (FunctionDecl *FoundFunction = *FoundFunctionOrErr) {
2965 if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
2966 return Def;
2967 FoundByLookup = FoundFunction;
2968 }
2969 }
2970 // Try to find a function in our own ("to") context with the same name, same
2971 // type, and in the same context as the function we're importing.
2972 else if (!LexicalDC->isFunctionOrMethod()) {
2973 SmallVector<NamedDecl *, 4> ConflictingDecls;
2974 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend;
2975 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
2976 for (auto *FoundDecl : FoundDecls) {
2977 if (!FoundDecl->isInIdentifierNamespace(IDNS))
2978 continue;
2979
2980 if (auto *FoundFunction = dyn_cast<FunctionDecl>(FoundDecl)) {
2981 if (!hasSameVisibilityContext(FoundFunction, D))
2982 continue;
2983
2984 if (IsStructuralMatch(D, FoundFunction)) {
2985 if (Decl *Def = FindAndMapDefinition(D, FoundFunction))
2986 return Def;
2987 FoundByLookup = FoundFunction;
2988 break;
2989 }
2990 // FIXME: Check for overloading more carefully, e.g., by boosting
2991 // Sema::IsOverload out to the AST library.
2992
2993 // Function overloading is okay in C++.
2994 if (Importer.getToContext().getLangOpts().CPlusPlus)
2995 continue;
2996
2997 // Complain about inconsistent function types.
2998 Importer.ToDiag(Loc, diag::warn_odr_function_type_inconsistent)
2999 << Name << D->getType() << FoundFunction->getType();
3000 Importer.ToDiag(FoundFunction->getLocation(), diag::note_odr_value_here)
3001 << FoundFunction->getType();
3002 }
3003
3004 ConflictingDecls.push_back(FoundDecl);
3005 }
3006
3007 if (!ConflictingDecls.empty()) {
3008 Name = Importer.HandleNameConflict(Name, DC, IDNS,
3009 ConflictingDecls.data(),
3010 ConflictingDecls.size());
3011 if (!Name)
3012 return make_error<ImportError>(ImportError::NameConflict);
3013 }
3014 }
3015
3016 // We do not allow more than one in-class declaration of a function. This is
3017 // because AST clients like VTableBuilder asserts on this. VTableBuilder
3018 // assumes there is only one in-class declaration. Building a redecl
3019 // chain would result in more than one in-class declaration for
3020 // overrides (even if they are part of the same redecl chain inside the
3021 // derived class.)
3022 if (FoundByLookup) {
3023 if (isa<CXXMethodDecl>(FoundByLookup)) {
3024 if (D->getLexicalDeclContext() == D->getDeclContext()) {
3025 if (!D->doesThisDeclarationHaveABody())
3026 return Importer.MapImported(D, FoundByLookup);
3027 else {
3028 // Let's continue and build up the redecl chain in this case.
3029 // FIXME Merge the functions into one decl.
3030 }
3031 }
3032 }
3033 }
3034
3035 DeclarationNameInfo NameInfo(Name, Loc);
3036 // Import additional name location/type info.
3037 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
3038 return std::move(Err);
3039
3040 QualType FromTy = D->getType();
3041 bool usedDifferentExceptionSpec = false;
3042
3043 if (const auto *FromFPT = D->getType()->getAs<FunctionProtoType>()) {
3044 FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo();
3045 // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the
3046 // FunctionDecl that we are importing the FunctionProtoType for.
3047 // To avoid an infinite recursion when importing, create the FunctionDecl
3048 // with a simplified function type and update it afterwards.
3049 if (FromEPI.ExceptionSpec.SourceDecl ||
3050 FromEPI.ExceptionSpec.SourceTemplate ||
3051 FromEPI.ExceptionSpec.NoexceptExpr) {
3052 FunctionProtoType::ExtProtoInfo DefaultEPI;
3053 FromTy = Importer.getFromContext().getFunctionType(
3054 FromFPT->getReturnType(), FromFPT->getParamTypes(), DefaultEPI);
3055 usedDifferentExceptionSpec = true;
3056 }
3057 }
3058
3059 QualType T;
3060 TypeSourceInfo *TInfo;
3061 SourceLocation ToInnerLocStart, ToEndLoc;
3062 NestedNameSpecifierLoc ToQualifierLoc;
3063 if (auto Imp = importSeq(
3064 FromTy, D->getTypeSourceInfo(), D->getInnerLocStart(),
3065 D->getQualifierLoc(), D->getEndLoc()))
3066 std::tie(T, TInfo, ToInnerLocStart, ToQualifierLoc, ToEndLoc) = *Imp;
3067 else
3068 return Imp.takeError();
3069
3070 // Import the function parameters.
3071 SmallVector<ParmVarDecl *, 8> Parameters;
3072 for (auto P : D->parameters()) {
3073 if (Expected<ParmVarDecl *> ToPOrErr = import(P))
3074 Parameters.push_back(*ToPOrErr);
3075 else
3076 return ToPOrErr.takeError();
3077 }
3078
3079 // Create the imported function.
3080 FunctionDecl *ToFunction = nullptr;
3081 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3082 Expr *ExplicitExpr = nullptr;
3083 if (FromConstructor->getExplicitSpecifier().getExpr()) {
3084 auto Imp = importSeq(FromConstructor->getExplicitSpecifier().getExpr());
3085 if (!Imp)
3086 return Imp.takeError();
3087 std::tie(ExplicitExpr) = *Imp;
3088 }
3089 if (GetImportedOrCreateDecl<CXXConstructorDecl>(
3090 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3091 ToInnerLocStart, NameInfo, T, TInfo,
3092 ExplicitSpecifier(
3093 ExplicitExpr,
3094 FromConstructor->getExplicitSpecifier().getKind()),
3095 D->isInlineSpecified(), D->isImplicit(), D->isConstexpr()))
3096 return ToFunction;
3097 } else if (CXXDestructorDecl *FromDtor = dyn_cast<CXXDestructorDecl>(D)) {
3098
3099 auto Imp =
3100 importSeq(const_cast<FunctionDecl *>(FromDtor->getOperatorDelete()),
3101 FromDtor->getOperatorDeleteThisArg());
3102
3103 if (!Imp)
3104 return Imp.takeError();
3105
3106 FunctionDecl *ToOperatorDelete;
3107 Expr *ToThisArg;
3108 std::tie(ToOperatorDelete, ToThisArg) = *Imp;
3109
3110 if (GetImportedOrCreateDecl<CXXDestructorDecl>(
3111 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3112 ToInnerLocStart, NameInfo, T, TInfo, D->isInlineSpecified(),
3113 D->isImplicit()))
3114 return ToFunction;
3115
3116 CXXDestructorDecl *ToDtor = cast<CXXDestructorDecl>(ToFunction);
3117
3118 ToDtor->setOperatorDelete(ToOperatorDelete, ToThisArg);
3119 } else if (CXXConversionDecl *FromConversion =
3120 dyn_cast<CXXConversionDecl>(D)) {
3121 Expr *ExplicitExpr = nullptr;
3122 if (FromConversion->getExplicitSpecifier().getExpr()) {
3123 auto Imp = importSeq(FromConversion->getExplicitSpecifier().getExpr());
3124 if (!Imp)
3125 return Imp.takeError();
3126 std::tie(ExplicitExpr) = *Imp;
3127 }
3128 if (GetImportedOrCreateDecl<CXXConversionDecl>(
3129 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3130 ToInnerLocStart, NameInfo, T, TInfo, D->isInlineSpecified(),
3131 ExplicitSpecifier(ExplicitExpr,
3132 FromConversion->getExplicitSpecifier().getKind()),
3133 D->isConstexpr(), SourceLocation()))
3134 return ToFunction;
3135 } else if (auto *Method = dyn_cast<CXXMethodDecl>(D)) {
3136 if (GetImportedOrCreateDecl<CXXMethodDecl>(
3137 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC),
3138 ToInnerLocStart, NameInfo, T, TInfo, Method->getStorageClass(),
3139 Method->isInlineSpecified(), D->isConstexpr(), SourceLocation()))
3140 return ToFunction;
3141 } else {
3142 if (GetImportedOrCreateDecl(ToFunction, D, Importer.getToContext(), DC,
3143 ToInnerLocStart, NameInfo, T, TInfo,
3144 D->getStorageClass(), D->isInlineSpecified(),
3145 D->hasWrittenPrototype(), D->isConstexpr()))
3146 return ToFunction;
3147 }
3148
3149 // Connect the redecl chain.
3150 if (FoundByLookup) {
3151 auto *Recent = const_cast<FunctionDecl *>(
3152 FoundByLookup->getMostRecentDecl());
3153 ToFunction->setPreviousDecl(Recent);
3154 // FIXME Probably we should merge exception specifications. E.g. In the
3155 // "To" context the existing function may have exception specification with
3156 // noexcept-unevaluated, while the newly imported function may have an
3157 // evaluated noexcept. A call to adjustExceptionSpec() on the imported
3158 // decl and its redeclarations may be required.
3159 }
3160
3161 // Import Ctor initializers.
3162 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) {
3163 if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) {
3164 SmallVector<CXXCtorInitializer *, 4> CtorInitializers(NumInitializers);
3165 // Import first, then allocate memory and copy if there was no error.
3166 if (Error Err = ImportContainerChecked(
3167 FromConstructor->inits(), CtorInitializers))
3168 return std::move(Err);
3169 auto **Memory =
3170 new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers];
3171 std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory);
3172 auto *ToCtor = cast<CXXConstructorDecl>(ToFunction);
3173 ToCtor->setCtorInitializers(Memory);
3174 ToCtor->setNumCtorInitializers(NumInitializers);
3175 }
3176 }
3177
3178 ToFunction->setQualifierInfo(ToQualifierLoc);
3179 ToFunction->setAccess(D->getAccess());
3180 ToFunction->setLexicalDeclContext(LexicalDC);
3181 ToFunction->setVirtualAsWritten(D->isVirtualAsWritten());
3182 ToFunction->setTrivial(D->isTrivial());
3183 ToFunction->setPure(D->isPure());
3184 ToFunction->setRangeEnd(ToEndLoc);
3185
3186 // Set the parameters.
3187 for (auto *Param : Parameters) {
3188 Param->setOwningFunction(ToFunction);
3189 ToFunction->addDeclInternal(Param);
3190 }
3191 ToFunction->setParams(Parameters);
3192
3193 // We need to complete creation of FunctionProtoTypeLoc manually with setting
3194 // params it refers to.
3195 if (TInfo) {
3196 if (auto ProtoLoc =
3197 TInfo->getTypeLoc().IgnoreParens().getAs<FunctionProtoTypeLoc>()) {
3198 for (unsigned I = 0, N = Parameters.size(); I != N; ++I)
3199 ProtoLoc.setParam(I, Parameters[I]);
3200 }
3201 }
3202
3203 if (usedDifferentExceptionSpec) {
3204 // Update FunctionProtoType::ExtProtoInfo.
3205 if (ExpectedType TyOrErr = import(D->getType()))
3206 ToFunction->setType(*TyOrErr);
3207 else
3208 return TyOrErr.takeError();
3209 }
3210
3211 // Import the describing template function, if any.
3212 if (FromFT) {
3213 auto ToFTOrErr = import(FromFT);
3214 if (!ToFTOrErr)
3215 return ToFTOrErr.takeError();
3216 }
3217
3218 if (D->doesThisDeclarationHaveABody()) {
3219 Error Err = ImportFunctionDeclBody(D, ToFunction);
3220
3221 if (Err)
3222 return std::move(Err);
3223 }
3224
3225 // FIXME: Other bits to merge?
3226
3227 // If it is a template, import all related things.
3228 if (Error Err = ImportTemplateInformation(D, ToFunction))
3229 return std::move(Err);
3230
3231 bool IsFriend = D->isInIdentifierNamespace(Decl::IDNS_OrdinaryFriend);
3232
3233 // TODO Can we generalize this approach to other AST nodes as well?
3234 if (D->getDeclContext()->containsDeclAndLoad(D))
3235 DC->addDeclInternal(ToFunction);
3236 if (DC != LexicalDC && D->getLexicalDeclContext()->containsDeclAndLoad(D))
3237 LexicalDC->addDeclInternal(ToFunction);
3238
3239 // Friend declaration's lexical context is the befriending class, but the
3240 // semantic context is the enclosing scope of the befriending class.
3241 // We want the friend functions to be found in the semantic context by lookup.
3242 // FIXME should we handle this generically in VisitFriendDecl?
3243 // In Other cases when LexicalDC != DC we don't want it to be added,
3244 // e.g out-of-class definitions like void B::f() {} .
3245 if (LexicalDC != DC && IsFriend) {
3246 DC->makeDeclVisibleInContext(ToFunction);
3247 }
3248
3249 if (auto *FromCXXMethod = dyn_cast<CXXMethodDecl>(D))
3250 ImportOverrides(cast<CXXMethodDecl>(ToFunction), FromCXXMethod);
3251
3252 // Import the rest of the chain. I.e. import all subsequent declarations.
3253 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
3254 ExpectedDecl ToRedeclOrErr = import(*RedeclIt);
3255 if (!ToRedeclOrErr)
3256 return ToRedeclOrErr.takeError();
3257 }
3258
3259 return ToFunction;
3260}
3261
3262ExpectedDecl ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) {
3263 return VisitFunctionDecl(D);
3264}
3265
3266ExpectedDecl ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) {
3267 return VisitCXXMethodDecl(D);
3268}
3269
3270ExpectedDecl ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) {
3271 return VisitCXXMethodDecl(D);
3272}
3273
3274ExpectedDecl ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) {
3275 return VisitCXXMethodDecl(D);
3276}
3277
3278ExpectedDecl ASTNodeImporter::VisitFieldDecl(FieldDecl *D) {
3279 // Import the major distinguishing characteristics of a variable.
3280 DeclContext *DC, *LexicalDC;
3281 DeclarationName Name;
3282 SourceLocation Loc;
3283 NamedDecl *ToD;
3284 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3285 return std::move(Err);
3286 if (ToD)
3287 return ToD;
3288
3289 // Determine whether we've already imported this field.
3290 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3291 for (auto *FoundDecl : FoundDecls) {
3292 if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecl)) {
3293 // For anonymous fields, match up by index.
3294 if (!Name &&
3295 ASTImporter::getFieldIndex(D) !=
3296 ASTImporter::getFieldIndex(FoundField))
3297 continue;
3298
3299 if (Importer.IsStructurallyEquivalent(D->getType(),
3300 FoundField->getType())) {
3301 Importer.MapImported(D, FoundField);
3302 // In case of a FieldDecl of a ClassTemplateSpecializationDecl, the
3303 // initializer of a FieldDecl might not had been instantiated in the
3304 // "To" context. However, the "From" context might instantiated that,
3305 // thus we have to merge that.
3306 if (Expr *FromInitializer = D->getInClassInitializer()) {
3307 // We don't have yet the initializer set.
3308 if (FoundField->hasInClassInitializer() &&
3309 !FoundField->getInClassInitializer()) {
3310 if (ExpectedExpr ToInitializerOrErr = import(FromInitializer))
3311 FoundField->setInClassInitializer(*ToInitializerOrErr);
3312 else {
3313 // We can't return error here,
3314 // since we already mapped D as imported.
3315 // FIXME: warning message?
3316 consumeError(ToInitializerOrErr.takeError());
3317 return FoundField;
3318 }
3319 }
3320 }
3321 return FoundField;
3322 }
3323
3324 // FIXME: Why is this case not handled with calling HandleNameConflict?
3325 Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
3326 << Name << D->getType() << FoundField->getType();
3327 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3328 << FoundField->getType();
3329
3330 return make_error<ImportError>(ImportError::NameConflict);
3331 }
3332 }
3333
3334 QualType ToType;
3335 TypeSourceInfo *ToTInfo;
3336 Expr *ToBitWidth;
3337 SourceLocation ToInnerLocStart;
3338 Expr *ToInitializer;
3339 if (auto Imp = importSeq(
3340 D->getType(), D->getTypeSourceInfo(), D->getBitWidth(),
3341 D->getInnerLocStart(), D->getInClassInitializer()))
3342 std::tie(
3343 ToType, ToTInfo, ToBitWidth, ToInnerLocStart, ToInitializer) = *Imp;
3344 else
3345 return Imp.takeError();
3346
3347 FieldDecl *ToField;
3348 if (GetImportedOrCreateDecl(ToField, D, Importer.getToContext(), DC,
3349 ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
3350 ToType, ToTInfo, ToBitWidth, D->isMutable(),
3351 D->getInClassInitStyle()))
3352 return ToField;
3353
3354 ToField->setAccess(D->getAccess());
3355 ToField->setLexicalDeclContext(LexicalDC);
3356 if (ToInitializer)
3357 ToField->setInClassInitializer(ToInitializer);
3358 ToField->setImplicit(D->isImplicit());
3359 LexicalDC->addDeclInternal(ToField);
3360 return ToField;
3361}
3362
3363ExpectedDecl ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) {
3364 // Import the major distinguishing characteristics of a variable.
3365 DeclContext *DC, *LexicalDC;
3366 DeclarationName Name;
3367 SourceLocation Loc;
3368 NamedDecl *ToD;
3369 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3370 return std::move(Err);
3371 if (ToD)
3372 return ToD;
3373
3374 // Determine whether we've already imported this field.
3375 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3376 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) {
3377 if (auto *FoundField = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) {
3378 // For anonymous indirect fields, match up by index.
3379 if (!Name &&
3380 ASTImporter::getFieldIndex(D) !=
3381 ASTImporter::getFieldIndex(FoundField))
3382 continue;
3383
3384 if (Importer.IsStructurallyEquivalent(D->getType(),
3385 FoundField->getType(),
3386 !Name.isEmpty())) {
3387 Importer.MapImported(D, FoundField);
3388 return FoundField;
3389 }
3390
3391 // If there are more anonymous fields to check, continue.
3392 if (!Name && I < N-1)
3393 continue;
3394
3395 // FIXME: Why is this case not handled with calling HandleNameConflict?
3396 Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent)
3397 << Name << D->getType() << FoundField->getType();
3398 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here)
3399 << FoundField->getType();
3400
3401 return make_error<ImportError>(ImportError::NameConflict);
3402 }
3403 }
3404
3405 // Import the type.
3406 auto TypeOrErr = import(D->getType());
3407 if (!TypeOrErr)
3408 return TypeOrErr.takeError();
3409
3410 auto **NamedChain =
3411 new (Importer.getToContext()) NamedDecl*[D->getChainingSize()];
3412
3413 unsigned i = 0;
3414 for (auto *PI : D->chain())
3415 if (Expected<NamedDecl *> ToD = import(PI))
3416 NamedChain[i++] = *ToD;
3417 else
3418 return ToD.takeError();
3419
3420 llvm::MutableArrayRef<NamedDecl *> CH = {NamedChain, D->getChainingSize()};
3421 IndirectFieldDecl *ToIndirectField;
3422 if (GetImportedOrCreateDecl(ToIndirectField, D, Importer.getToContext(), DC,
3423 Loc, Name.getAsIdentifierInfo(), *TypeOrErr, CH))
3424 // FIXME here we leak `NamedChain` which is allocated before
3425 return ToIndirectField;
3426
3427 ToIndirectField->setAccess(D->getAccess());
3428 ToIndirectField->setLexicalDeclContext(LexicalDC);
3429 LexicalDC->addDeclInternal(ToIndirectField);
3430 return ToIndirectField;
3431}
3432
3433ExpectedDecl ASTNodeImporter::VisitFriendDecl(FriendDecl *D) {
3434 // Import the major distinguishing characteristics of a declaration.
3435 DeclContext *DC, *LexicalDC;
3436 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
3437 return std::move(Err);
3438
3439 // Determine whether we've already imported this decl.
3440 // FriendDecl is not a NamedDecl so we cannot use lookup.
3441 auto *RD = cast<CXXRecordDecl>(DC);
3442 FriendDecl *ImportedFriend = RD->getFirstFriend();
3443
3444 while (ImportedFriend) {
3445 if (D->getFriendDecl() && ImportedFriend->getFriendDecl()) {
3446 if (IsStructuralMatch(D->getFriendDecl(), ImportedFriend->getFriendDecl(),
3447 /*Complain=*/false))
3448 return Importer.MapImported(D, ImportedFriend);
3449
3450 } else if (D->getFriendType() && ImportedFriend->getFriendType()) {
3451 if (Importer.IsStructurallyEquivalent(
3452 D->getFriendType()->getType(),
3453 ImportedFriend->getFriendType()->getType(), true))
3454 return Importer.MapImported(D, ImportedFriend);
3455 }
3456 ImportedFriend = ImportedFriend->getNextFriend();
3457 }
3458
3459 // Not found. Create it.
3460 FriendDecl::FriendUnion ToFU;
3461 if (NamedDecl *FriendD = D->getFriendDecl()) {
3462 NamedDecl *ToFriendD;
3463 if (Error Err = importInto(ToFriendD, FriendD))
3464 return std::move(Err);
3465
3466 if (FriendD->getFriendObjectKind() != Decl::FOK_None &&
3467 !(FriendD->isInIdentifierNamespace(Decl::IDNS_NonMemberOperator)))
3468 ToFriendD->setObjectOfFriendDecl(false);
3469
3470 ToFU = ToFriendD;
3471 } else { // The friend is a type, not a decl.
3472 if (auto TSIOrErr = import(D->getFriendType()))
3473 ToFU = *TSIOrErr;
3474 else
3475 return TSIOrErr.takeError();
3476 }
3477
3478 SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists);
3479 auto **FromTPLists = D->getTrailingObjects<TemplateParameterList *>();
3480 for (unsigned I = 0; I < D->NumTPLists; I++) {
3481 if (auto ListOrErr = import(FromTPLists[I]))
3482 ToTPLists[I] = *ListOrErr;
3483 else
3484 return ListOrErr.takeError();
3485 }
3486
3487 auto LocationOrErr = import(D->getLocation());
3488 if (!LocationOrErr)
3489 return LocationOrErr.takeError();
3490 auto FriendLocOrErr = import(D->getFriendLoc());
3491 if (!FriendLocOrErr)
3492 return FriendLocOrErr.takeError();
3493
3494 FriendDecl *FrD;
3495 if (GetImportedOrCreateDecl(FrD, D, Importer.getToContext(), DC,
3496 *LocationOrErr, ToFU,
3497 *FriendLocOrErr, ToTPLists))
3498 return FrD;
3499
3500 FrD->setAccess(D->getAccess());
3501 FrD->setLexicalDeclContext(LexicalDC);
3502 LexicalDC->addDeclInternal(FrD);
3503 return FrD;
3504}
3505
3506ExpectedDecl ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) {
3507 // Import the major distinguishing characteristics of an ivar.
3508 DeclContext *DC, *LexicalDC;
3509 DeclarationName Name;
3510 SourceLocation Loc;
3511 NamedDecl *ToD;
3512 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3513 return std::move(Err);
3514 if (ToD)
3515 return ToD;
3516
3517 // Determine whether we've already imported this ivar
3518 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3519 for (auto *FoundDecl : FoundDecls) {
3520 if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecl)) {
3521 if (Importer.IsStructurallyEquivalent(D->getType(),
3522 FoundIvar->getType())) {
3523 Importer.MapImported(D, FoundIvar);
3524 return FoundIvar;
3525 }
3526
3527 Importer.ToDiag(Loc, diag::warn_odr_ivar_type_inconsistent)
3528 << Name << D->getType() << FoundIvar->getType();
3529 Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here)
3530 << FoundIvar->getType();
3531
3532 return make_error<ImportError>(ImportError::NameConflict);
3533 }
3534 }
3535
3536 QualType ToType;
3537 TypeSourceInfo *ToTypeSourceInfo;
3538 Expr *ToBitWidth;
3539 SourceLocation ToInnerLocStart;
3540 if (auto Imp = importSeq(
3541 D->getType(), D->getTypeSourceInfo(), D->getBitWidth(), D->getInnerLocStart()))
3542 std::tie(ToType, ToTypeSourceInfo, ToBitWidth, ToInnerLocStart) = *Imp;
3543 else
3544 return Imp.takeError();
3545
3546 ObjCIvarDecl *ToIvar;
3547 if (GetImportedOrCreateDecl(
3548 ToIvar, D, Importer.getToContext(), cast<ObjCContainerDecl>(DC),
3549 ToInnerLocStart, Loc, Name.getAsIdentifierInfo(),
3550 ToType, ToTypeSourceInfo,
3551 D->getAccessControl(),ToBitWidth, D->getSynthesize()))
3552 return ToIvar;
3553
3554 ToIvar->setLexicalDeclContext(LexicalDC);
3555 LexicalDC->addDeclInternal(ToIvar);
3556 return ToIvar;
3557}
3558
3559ExpectedDecl ASTNodeImporter::VisitVarDecl(VarDecl *D) {
3560
3561 SmallVector<Decl*, 2> Redecls = getCanonicalForwardRedeclChain(D);
3562 auto RedeclIt = Redecls.begin();
3563 // Import the first part of the decl chain. I.e. import all previous
3564 // declarations starting from the canonical decl.
3565 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) {
3566 ExpectedDecl RedeclOrErr = import(*RedeclIt);
3567 if (!RedeclOrErr)
3568 return RedeclOrErr.takeError();
3569 }
3570 assert(*RedeclIt == D)((*RedeclIt == D) ? static_cast<void> (0) : __assert_fail
("*RedeclIt == D", "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp"
, 3570, __PRETTY_FUNCTION__))
;
3571
3572 // Import the major distinguishing characteristics of a variable.
3573 DeclContext *DC, *LexicalDC;
3574 DeclarationName Name;
3575 SourceLocation Loc;
3576 NamedDecl *ToD;
3577 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3578 return std::move(Err);
3579 if (ToD)
3580 return ToD;
3581
3582 // Try to find a variable in our own ("to") context with the same name and
3583 // in the same context as the variable we're importing.
3584 VarDecl *FoundByLookup = nullptr;
3585 if (D->isFileVarDecl()) {
3586 SmallVector<NamedDecl *, 4> ConflictingDecls;
3587 unsigned IDNS = Decl::IDNS_Ordinary;
3588 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3589 for (auto *FoundDecl : FoundDecls) {
3590 if (!FoundDecl->isInIdentifierNamespace(IDNS))
3591 continue;
3592
3593 if (auto *FoundVar = dyn_cast<VarDecl>(FoundDecl)) {
3594 if (!hasSameVisibilityContext(FoundVar, D))
3595 continue;
3596 if (Importer.IsStructurallyEquivalent(D->getType(),
3597 FoundVar->getType())) {
3598
3599 // The VarDecl in the "From" context has a definition, but in the
3600 // "To" context we already have a definition.
3601 VarDecl *FoundDef = FoundVar->getDefinition();
3602 if (D->isThisDeclarationADefinition() && FoundDef)
3603 // FIXME Check for ODR error if the two definitions have
3604 // different initializers?
3605 return Importer.MapImported(D, FoundDef);
3606
3607 // The VarDecl in the "From" context has an initializer, but in the
3608 // "To" context we already have an initializer.
3609 const VarDecl *FoundDInit = nullptr;
3610 if (D->getInit() && FoundVar->getAnyInitializer(FoundDInit))
3611 // FIXME Diagnose ODR error if the two initializers are different?
3612 return Importer.MapImported(D, const_cast<VarDecl*>(FoundDInit));
3613
3614 FoundByLookup = FoundVar;
3615 break;
3616 }
3617
3618 const ArrayType *FoundArray
3619 = Importer.getToContext().getAsArrayType(FoundVar->getType());
3620 const ArrayType *TArray
3621 = Importer.getToContext().getAsArrayType(D->getType());
3622 if (FoundArray && TArray) {
3623 if (isa<IncompleteArrayType>(FoundArray) &&
3624 isa<ConstantArrayType>(TArray)) {
3625 // Import the type.
3626 if (auto TyOrErr = import(D->getType()))
3627 FoundVar->setType(*TyOrErr);
3628 else
3629 return TyOrErr.takeError();
3630
3631 FoundByLookup = FoundVar;
3632 break;
3633 } else if (isa<IncompleteArrayType>(TArray) &&
3634 isa<ConstantArrayType>(FoundArray)) {
3635 FoundByLookup = FoundVar;
3636 break;
3637 }
3638 }
3639
3640 Importer.ToDiag(Loc, diag::warn_odr_variable_type_inconsistent)
3641 << Name << D->getType() << FoundVar->getType();
3642 Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here)
3643 << FoundVar->getType();
3644 }
3645
3646 ConflictingDecls.push_back(FoundDecl);
3647 }
3648
3649 if (!ConflictingDecls.empty()) {
3650 Name = Importer.HandleNameConflict(Name, DC, IDNS,
3651 ConflictingDecls.data(),
3652 ConflictingDecls.size());
3653 if (!Name)
3654 return make_error<ImportError>(ImportError::NameConflict);
3655 }
3656 }
3657
3658 QualType ToType;
3659 TypeSourceInfo *ToTypeSourceInfo;
3660 SourceLocation ToInnerLocStart;
3661 NestedNameSpecifierLoc ToQualifierLoc;
3662 if (auto Imp = importSeq(
3663 D->getType(), D->getTypeSourceInfo(), D->getInnerLocStart(),
3664 D->getQualifierLoc()))
3665 std::tie(ToType, ToTypeSourceInfo, ToInnerLocStart, ToQualifierLoc) = *Imp;
3666 else
3667 return Imp.takeError();
3668
3669 // Create the imported variable.
3670 VarDecl *ToVar;
3671 if (GetImportedOrCreateDecl(ToVar, D, Importer.getToContext(), DC,
3672 ToInnerLocStart, Loc,
3673 Name.getAsIdentifierInfo(),
3674 ToType, ToTypeSourceInfo,
3675 D->getStorageClass()))
3676 return ToVar;
3677
3678 ToVar->setQualifierInfo(ToQualifierLoc);
3679 ToVar->setAccess(D->getAccess());
3680 ToVar->setLexicalDeclContext(LexicalDC);
3681
3682 if (FoundByLookup) {
3683 auto *Recent = const_cast<VarDecl *>(FoundByLookup->getMostRecentDecl());
3684 ToVar->setPreviousDecl(Recent);
3685 }
3686
3687 if (Error Err = ImportInitializer(D, ToVar))
3688 return std::move(Err);
3689
3690 if (D->isConstexpr())
3691 ToVar->setConstexpr(true);
3692
3693 if (D->getDeclContext()->containsDeclAndLoad(D))
3694 DC->addDeclInternal(ToVar);
3695 if (DC != LexicalDC && D->getLexicalDeclContext()->containsDeclAndLoad(D))
3696 LexicalDC->addDeclInternal(ToVar);
3697
3698 // Import the rest of the chain. I.e. import all subsequent declarations.
3699 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) {
3700 ExpectedDecl RedeclOrErr = import(*RedeclIt);
3701 if (!RedeclOrErr)
3702 return RedeclOrErr.takeError();
3703 }
3704
3705 return ToVar;
3706}
3707
3708ExpectedDecl ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) {
3709 // Parameters are created in the translation unit's context, then moved
3710 // into the function declaration's context afterward.
3711 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3712
3713 DeclarationName ToDeclName;
3714 SourceLocation ToLocation;
3715 QualType ToType;
3716 if (auto Imp = importSeq(D->getDeclName(), D->getLocation(), D->getType()))
3717 std::tie(ToDeclName, ToLocation, ToType) = *Imp;
3718 else
3719 return Imp.takeError();
3720
3721 // Create the imported parameter.
3722 ImplicitParamDecl *ToParm = nullptr;
3723 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
3724 ToLocation, ToDeclName.getAsIdentifierInfo(),
3725 ToType, D->getParameterKind()))
3726 return ToParm;
3727 return ToParm;
3728}
3729
3730ExpectedDecl ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) {
3731 // Parameters are created in the translation unit's context, then moved
3732 // into the function declaration's context afterward.
3733 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl();
3734
3735 DeclarationName ToDeclName;
3736 SourceLocation ToLocation, ToInnerLocStart;
3737 QualType ToType;
3738 TypeSourceInfo *ToTypeSourceInfo;
3739 if (auto Imp = importSeq(
3740 D->getDeclName(), D->getLocation(), D->getType(), D->getInnerLocStart(),
3741 D->getTypeSourceInfo()))
3742 std::tie(
3743 ToDeclName, ToLocation, ToType, ToInnerLocStart,
3744 ToTypeSourceInfo) = *Imp;
3745 else
3746 return Imp.takeError();
3747
3748 ParmVarDecl *ToParm;
3749 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC,
3750 ToInnerLocStart, ToLocation,
3751 ToDeclName.getAsIdentifierInfo(), ToType,
3752 ToTypeSourceInfo, D->getStorageClass(),
3753 /*DefaultArg*/ nullptr))
3754 return ToParm;
3755
3756 // Set the default argument.
3757 ToParm->setHasInheritedDefaultArg(D->hasInheritedDefaultArg());
3758 ToParm->setKNRPromoted(D->isKNRPromoted());
3759
3760 if (D->hasUninstantiatedDefaultArg()) {
3761 if (auto ToDefArgOrErr = import(D->getUninstantiatedDefaultArg()))
3762 ToParm->setUninstantiatedDefaultArg(*ToDefArgOrErr);
3763 else
3764 return ToDefArgOrErr.takeError();
3765 } else if (D->hasUnparsedDefaultArg()) {
3766 ToParm->setUnparsedDefaultArg();
3767 } else if (D->hasDefaultArg()) {
3768 if (auto ToDefArgOrErr = import(D->getDefaultArg()))
3769 ToParm->setDefaultArg(*ToDefArgOrErr);
3770 else
3771 return ToDefArgOrErr.takeError();
3772 }
3773
3774 if (D->isObjCMethodParameter()) {
3775 ToParm->setObjCMethodScopeInfo(D->getFunctionScopeIndex());
3776 ToParm->setObjCDeclQualifier(D->getObjCDeclQualifier());
3777 } else {
3778 ToParm->setScopeInfo(D->getFunctionScopeDepth(),
3779 D->getFunctionScopeIndex());
3780 }
3781
3782 return ToParm;
3783}
3784
3785ExpectedDecl ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) {
3786 // Import the major distinguishing characteristics of a method.
3787 DeclContext *DC, *LexicalDC;
3788 DeclarationName Name;
3789 SourceLocation Loc;
3790 NamedDecl *ToD;
3791 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3792 return std::move(Err);
3793 if (ToD)
3794 return ToD;
3795
3796 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
3797 for (auto *FoundDecl : FoundDecls) {
3798 if (auto *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecl)) {
3799 if (FoundMethod->isInstanceMethod() != D->isInstanceMethod())
3800 continue;
3801
3802 // Check return types.
3803 if (!Importer.IsStructurallyEquivalent(D->getReturnType(),
3804 FoundMethod->getReturnType())) {
3805 Importer.ToDiag(Loc, diag::warn_odr_objc_method_result_type_inconsistent)
3806 << D->isInstanceMethod() << Name << D->getReturnType()
3807 << FoundMethod->getReturnType();
3808 Importer.ToDiag(FoundMethod->getLocation(),
3809 diag::note_odr_objc_method_here)
3810 << D->isInstanceMethod() << Name;
3811
3812 return make_error<ImportError>(ImportError::NameConflict);
3813 }
3814
3815 // Check the number of parameters.
3816 if (D->param_size() != FoundMethod->param_size()) {
3817 Importer.ToDiag(Loc, diag::warn_odr_objc_method_num_params_inconsistent)
3818 << D->isInstanceMethod() << Name
3819 << D->param_size() << FoundMethod->param_size();
3820 Importer.ToDiag(FoundMethod->getLocation(),
3821 diag::note_odr_objc_method_here)
3822 << D->isInstanceMethod() << Name;
3823
3824 return make_error<ImportError>(ImportError::NameConflict);
3825 }
3826
3827 // Check parameter types.
3828 for (ObjCMethodDecl::param_iterator P = D->param_begin(),
3829 PEnd = D->param_end(), FoundP = FoundMethod->param_begin();
3830 P != PEnd; ++P, ++FoundP) {
3831 if (!Importer.IsStructurallyEquivalent((*P)->getType(),
3832 (*FoundP)->getType())) {
3833 Importer.FromDiag((*P)->getLocation(),
3834 diag::warn_odr_objc_method_param_type_inconsistent)
3835 << D->isInstanceMethod() << Name
3836 << (*P)->getType() << (*FoundP)->getType();
3837 Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here)
3838 << (*FoundP)->getType();
3839
3840 return make_error<ImportError>(ImportError::NameConflict);
3841 }
3842 }
3843
3844 // Check variadic/non-variadic.
3845 // Check the number of parameters.
3846 if (D->isVariadic() != FoundMethod->isVariadic()) {
3847 Importer.ToDiag(Loc, diag::warn_odr_objc_method_variadic_inconsistent)
3848 << D->isInstanceMethod() << Name;
3849 Importer.ToDiag(FoundMethod->getLocation(),
3850 diag::note_odr_objc_method_here)
3851 << D->isInstanceMethod() << Name;
3852
3853 return make_error<ImportError>(ImportError::NameConflict);
3854 }
3855
3856 // FIXME: Any other bits we need to merge?
3857 return Importer.MapImported(D, FoundMethod);
3858 }
3859 }
3860
3861 SourceLocation ToEndLoc;
3862 QualType ToReturnType;
3863 TypeSourceInfo *ToReturnTypeSourceInfo;
3864 if (auto Imp = importSeq(
3865 D->getEndLoc(), D->getReturnType(), D->getReturnTypeSourceInfo()))
3866 std::tie(ToEndLoc, ToReturnType, ToReturnTypeSourceInfo) = *Imp;
3867 else
3868 return Imp.takeError();
3869
3870 ObjCMethodDecl *ToMethod;
3871 if (GetImportedOrCreateDecl(
3872 ToMethod, D, Importer.getToContext(), Loc,
3873 ToEndLoc, Name.getObjCSelector(), ToReturnType,
3874 ToReturnTypeSourceInfo, DC, D->isInstanceMethod(), D->isVariadic(),
3875 D->isPropertyAccessor(), D->isImplicit(), D->isDefined(),
3876 D->getImplementationControl(), D->hasRelatedResultType()))
3877 return ToMethod;
3878
3879 // FIXME: When we decide to merge method definitions, we'll need to
3880 // deal with implicit parameters.
3881
3882 // Import the parameters
3883 SmallVector<ParmVarDecl *, 5> ToParams;
3884 for (auto *FromP : D->parameters()) {
3885 if (Expected<ParmVarDecl *> ToPOrErr = import(FromP))
3886 ToParams.push_back(*ToPOrErr);
3887 else
3888 return ToPOrErr.takeError();
3889 }
3890
3891 // Set the parameters.
3892 for (auto *ToParam : ToParams) {
3893 ToParam->setOwningFunction(ToMethod);
3894 ToMethod->addDeclInternal(ToParam);
3895 }
3896
3897 SmallVector<SourceLocation, 12> FromSelLocs;
3898 D->getSelectorLocs(FromSelLocs);
3899 SmallVector<SourceLocation, 12> ToSelLocs(FromSelLocs.size());
3900 if (Error Err = ImportContainerChecked(FromSelLocs, ToSelLocs))
3901 return std::move(Err);
3902
3903 ToMethod->setMethodParams(Importer.getToContext(), ToParams, ToSelLocs);
3904
3905 ToMethod->setLexicalDeclContext(LexicalDC);
3906 LexicalDC->addDeclInternal(ToMethod);
3907 return ToMethod;
3908}
3909
3910ExpectedDecl ASTNodeImporter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) {
3911 // Import the major distinguishing characteristics of a category.
3912 DeclContext *DC, *LexicalDC;
3913 DeclarationName Name;
3914 SourceLocation Loc;
3915 NamedDecl *ToD;
3916 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3917 return std::move(Err);
3918 if (ToD)
3919 return ToD;
3920
3921 SourceLocation ToVarianceLoc, ToLocation, ToColonLoc;
3922 TypeSourceInfo *ToTypeSourceInfo;
3923 if (auto Imp = importSeq(
3924 D->getVarianceLoc(), D->getLocation(), D->getColonLoc(),
3925 D->getTypeSourceInfo()))
3926 std::tie(ToVarianceLoc, ToLocation, ToColonLoc, ToTypeSourceInfo) = *Imp;
3927 else
3928 return Imp.takeError();
3929
3930 ObjCTypeParamDecl *Result;
3931 if (GetImportedOrCreateDecl(
3932 Result, D, Importer.getToContext(), DC, D->getVariance(),
3933 ToVarianceLoc, D->getIndex(),
3934 ToLocation, Name.getAsIdentifierInfo(),
3935 ToColonLoc, ToTypeSourceInfo))
3936 return Result;
3937
3938 Result->setLexicalDeclContext(LexicalDC);
3939 return Result;
3940}
3941
3942ExpectedDecl ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) {
3943 // Import the major distinguishing characteristics of a category.
3944 DeclContext *DC, *LexicalDC;
3945 DeclarationName Name;
3946 SourceLocation Loc;
3947 NamedDecl *ToD;
3948 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
3949 return std::move(Err);
3950 if (ToD)
3951 return ToD;
3952
3953 ObjCInterfaceDecl *ToInterface;
3954 if (Error Err = importInto(ToInterface, D->getClassInterface()))
3955 return std::move(Err);
3956
3957 // Determine if we've already encountered this category.
3958 ObjCCategoryDecl *MergeWithCategory
3959 = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo());
3960 ObjCCategoryDecl *ToCategory = MergeWithCategory;
3961 if (!ToCategory) {
3962 SourceLocation ToAtStartLoc, ToCategoryNameLoc;
3963 SourceLocation ToIvarLBraceLoc, ToIvarRBraceLoc;
3964 if (auto Imp = importSeq(
3965 D->getAtStartLoc(), D->getCategoryNameLoc(),
3966 D->getIvarLBraceLoc(), D->getIvarRBraceLoc()))
3967 std::tie(
3968 ToAtStartLoc, ToCategoryNameLoc,
3969 ToIvarLBraceLoc, ToIvarRBraceLoc) = *Imp;
3970 else
3971 return Imp.takeError();
3972
3973 if (GetImportedOrCreateDecl(ToCategory, D, Importer.getToContext(), DC,
3974 ToAtStartLoc, Loc,
3975 ToCategoryNameLoc,
3976 Name.getAsIdentifierInfo(), ToInterface,
3977 /*TypeParamList=*/nullptr,
3978 ToIvarLBraceLoc,
3979 ToIvarRBraceLoc))
3980 return ToCategory;
3981
3982 ToCategory->setLexicalDeclContext(LexicalDC);
3983 LexicalDC->addDeclInternal(ToCategory);
3984 // Import the type parameter list after MapImported, to avoid
3985 // loops when bringing in their DeclContext.
3986 if (auto PListOrErr = ImportObjCTypeParamList(D->getTypeParamList()))
3987 ToCategory->setTypeParamList(*PListOrErr);
3988 else
3989 return PListOrErr.takeError();
3990
3991 // Import protocols
3992 SmallVector<ObjCProtocolDecl *, 4> Protocols;
3993 SmallVector<SourceLocation, 4> ProtocolLocs;
3994 ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc
3995 = D->protocol_loc_begin();
3996 for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(),
3997 FromProtoEnd = D->protocol_end();
3998 FromProto != FromProtoEnd;
3999 ++FromProto, ++FromProtoLoc) {
4000 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4001 Protocols.push_back(*ToProtoOrErr);
4002 else
4003 return ToProtoOrErr.takeError();
4004
4005 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4006 ProtocolLocs.push_back(*ToProtoLocOrErr);
4007 else
4008 return ToProtoLocOrErr.takeError();
4009 }
4010
4011 // FIXME: If we're merging, make sure that the protocol list is the same.
4012 ToCategory->setProtocolList(Protocols.data(), Protocols.size(),
4013 ProtocolLocs.data(), Importer.getToContext());
4014
4015 } else {
4016 Importer.MapImported(D, ToCategory);
4017 }
4018
4019 // Import all of the members of this category.
4020 if (Error Err = ImportDeclContext(D))
4021 return std::move(Err);
4022
4023 // If we have an implementation, import it as well.
4024 if (D->getImplementation()) {
4025 if (Expected<ObjCCategoryImplDecl *> ToImplOrErr =
4026 import(D->getImplementation()))
4027 ToCategory->setImplementation(*ToImplOrErr);
4028 else
4029 return ToImplOrErr.takeError();
4030 }
4031
4032 return ToCategory;
4033}
4034
4035Error ASTNodeImporter::ImportDefinition(
4036 ObjCProtocolDecl *From, ObjCProtocolDecl *To, ImportDefinitionKind Kind) {
4037 if (To->getDefinition()) {
4038 if (shouldForceImportDeclContext(Kind))
4039 if (Error Err = ImportDeclContext(From))
4040 return Err;
4041 return Error::success();
4042 }
4043
4044 // Start the protocol definition
4045 To->startDefinition();
4046
4047 // Import protocols
4048 SmallVector<ObjCProtocolDecl *, 4> Protocols;
4049 SmallVector<SourceLocation, 4> ProtocolLocs;
4050 ObjCProtocolDecl::protocol_loc_iterator FromProtoLoc =
4051 From->protocol_loc_begin();
4052 for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(),
4053 FromProtoEnd = From->protocol_end();
4054 FromProto != FromProtoEnd;
4055 ++FromProto, ++FromProtoLoc) {
4056 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4057 Protocols.push_back(*ToProtoOrErr);
4058 else
4059 return ToProtoOrErr.takeError();
4060
4061 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4062 ProtocolLocs.push_back(*ToProtoLocOrErr);
4063 else
4064 return ToProtoLocOrErr.takeError();
4065
4066 }
4067
4068 // FIXME: If we're merging, make sure that the protocol list is the same.
4069 To->setProtocolList(Protocols.data(), Protocols.size(),
4070 ProtocolLocs.data(), Importer.getToContext());
4071
4072 if (shouldForceImportDeclContext(Kind)) {
4073 // Import all of the members of this protocol.
4074 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
4075 return Err;
4076 }
4077 return Error::success();
4078}
4079
4080ExpectedDecl ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) {
4081 // If this protocol has a definition in the translation unit we're coming
4082 // from, but this particular declaration is not that definition, import the
4083 // definition and map to that.
4084 ObjCProtocolDecl *Definition = D->getDefinition();
4085 if (Definition && Definition != D) {
4086 if (ExpectedDecl ImportedDefOrErr = import(Definition))
4087 return Importer.MapImported(D, *ImportedDefOrErr);
4088 else
4089 return ImportedDefOrErr.takeError();
4090 }
4091
4092 // Import the major distinguishing characteristics of a protocol.
4093 DeclContext *DC, *LexicalDC;
4094 DeclarationName Name;
4095 SourceLocation Loc;
4096 NamedDecl *ToD;
4097 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4098 return std::move(Err);
4099 if (ToD)
4100 return ToD;
4101
4102 ObjCProtocolDecl *MergeWithProtocol = nullptr;
4103 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4104 for (auto *FoundDecl : FoundDecls) {
4105 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol))
4106 continue;
4107
4108 if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecl)))
4109 break;
4110 }
4111
4112 ObjCProtocolDecl *ToProto = MergeWithProtocol;
4113 if (!ToProto) {
4114 auto ToAtBeginLocOrErr = import(D->getAtStartLoc());
4115 if (!ToAtBeginLocOrErr)
4116 return ToAtBeginLocOrErr.takeError();
4117
4118 if (GetImportedOrCreateDecl(ToProto, D, Importer.getToContext(), DC,
4119 Name.getAsIdentifierInfo(), Loc,
4120 *ToAtBeginLocOrErr,
4121 /*PrevDecl=*/nullptr))
4122 return ToProto;
4123 ToProto->setLexicalDeclContext(LexicalDC);
4124 LexicalDC->addDeclInternal(ToProto);
4125 }
4126
4127 Importer.MapImported(D, ToProto);
4128
4129 if (D->isThisDeclarationADefinition())
4130 if (Error Err = ImportDefinition(D, ToProto))
4131 return std::move(Err);
4132
4133 return ToProto;
4134}
4135
4136ExpectedDecl ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) {
4137 DeclContext *DC, *LexicalDC;
4138 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4139 return std::move(Err);
4140
4141 ExpectedSLoc ExternLocOrErr = import(D->getExternLoc());
4142 if (!ExternLocOrErr)
4143 return ExternLocOrErr.takeError();
4144
4145 ExpectedSLoc LangLocOrErr = import(D->getLocation());
4146 if (!LangLocOrErr)
4147 return LangLocOrErr.takeError();
4148
4149 bool HasBraces = D->hasBraces();
4150
4151 LinkageSpecDecl *ToLinkageSpec;
4152 if (GetImportedOrCreateDecl(ToLinkageSpec, D, Importer.getToContext(), DC,
4153 *ExternLocOrErr, *LangLocOrErr,
4154 D->getLanguage(), HasBraces))
4155 return ToLinkageSpec;
4156
4157 if (HasBraces) {
4158 ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc());
4159 if (!RBraceLocOrErr)
4160 return RBraceLocOrErr.takeError();
4161 ToLinkageSpec->setRBraceLoc(*RBraceLocOrErr);
4162 }
4163
4164 ToLinkageSpec->setLexicalDeclContext(LexicalDC);
4165 LexicalDC->addDeclInternal(ToLinkageSpec);
4166
4167 return ToLinkageSpec;
4168}
4169
4170ExpectedDecl ASTNodeImporter::VisitUsingDecl(UsingDecl *D) {
4171 DeclContext *DC, *LexicalDC;
4172 DeclarationName Name;
4173 SourceLocation Loc;
4174 NamedDecl *ToD = nullptr;
4175 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4176 return std::move(Err);
4177 if (ToD)
4178 return ToD;
4179
4180 SourceLocation ToLoc, ToUsingLoc;
4181 NestedNameSpecifierLoc ToQualifierLoc;
4182 if (auto Imp = importSeq(
4183 D->getNameInfo().getLoc(), D->getUsingLoc(), D->getQualifierLoc()))
4184 std::tie(ToLoc, ToUsingLoc, ToQualifierLoc) = *Imp;
4185 else
4186 return Imp.takeError();
4187
4188 DeclarationNameInfo NameInfo(Name, ToLoc);
4189 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
4190 return std::move(Err);
4191
4192 UsingDecl *ToUsing;
4193 if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
4194 ToUsingLoc, ToQualifierLoc, NameInfo,
4195 D->hasTypename()))
4196 return ToUsing;
4197
4198 ToUsing->setLexicalDeclContext(LexicalDC);
4199 LexicalDC->addDeclInternal(ToUsing);
4200
4201 if (NamedDecl *FromPattern =
4202 Importer.getFromContext().getInstantiatedFromUsingDecl(D)) {
4203 if (Expected<NamedDecl *> ToPatternOrErr = import(FromPattern))
4204 Importer.getToContext().setInstantiatedFromUsingDecl(
4205 ToUsing, *ToPatternOrErr);
4206 else
4207 return ToPatternOrErr.takeError();
4208 }
4209
4210 for (UsingShadowDecl *FromShadow : D->shadows()) {
4211 if (Expected<UsingShadowDecl *> ToShadowOrErr = import(FromShadow))
4212 ToUsing->addShadowDecl(*ToShadowOrErr);
4213 else
4214 // FIXME: We return error here but the definition is already created
4215 // and available with lookups. How to fix this?..
4216 return ToShadowOrErr.takeError();
4217 }
4218 return ToUsing;
4219}
4220
4221ExpectedDecl ASTNodeImporter::VisitUsingShadowDecl(UsingShadowDecl *D) {
4222 DeclContext *DC, *LexicalDC;
4223 DeclarationName Name;
4224 SourceLocation Loc;
4225 NamedDecl *ToD = nullptr;
4226 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4227 return std::move(Err);
4228 if (ToD)
4229 return ToD;
4230
4231 Expected<UsingDecl *> ToUsingOrErr = import(D->getUsingDecl());
4232 if (!ToUsingOrErr)
4233 return ToUsingOrErr.takeError();
4234
4235 Expected<NamedDecl *> ToTargetOrErr = import(D->getTargetDecl());
4236 if (!ToTargetOrErr)
4237 return ToTargetOrErr.takeError();
4238
4239 UsingShadowDecl *ToShadow;
4240 if (GetImportedOrCreateDecl(ToShadow, D, Importer.getToContext(), DC, Loc,
4241 *ToUsingOrErr, *ToTargetOrErr))
4242 return ToShadow;
4243
4244 ToShadow->setLexicalDeclContext(LexicalDC);
4245 ToShadow->setAccess(D->getAccess());
4246
4247 if (UsingShadowDecl *FromPattern =
4248 Importer.getFromContext().getInstantiatedFromUsingShadowDecl(D)) {
4249 if (Expected<UsingShadowDecl *> ToPatternOrErr = import(FromPattern))
4250 Importer.getToContext().setInstantiatedFromUsingShadowDecl(
4251 ToShadow, *ToPatternOrErr);
4252 else
4253 // FIXME: We return error here but the definition is already created
4254 // and available with lookups. How to fix this?..
4255 return ToPatternOrErr.takeError();
4256 }
4257
4258 LexicalDC->addDeclInternal(ToShadow);
4259
4260 return ToShadow;
4261}
4262
4263ExpectedDecl ASTNodeImporter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) {
4264 DeclContext *DC, *LexicalDC;
4265 DeclarationName Name;
4266 SourceLocation Loc;
4267 NamedDecl *ToD = nullptr;
4268 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4269 return std::move(Err);
4270 if (ToD)
4271 return ToD;
4272
4273 auto ToComAncestorOrErr = Importer.ImportContext(D->getCommonAncestor());
4274 if (!ToComAncestorOrErr)
4275 return ToComAncestorOrErr.takeError();
4276
4277 NamespaceDecl *ToNominatedNamespace;
4278 SourceLocation ToUsingLoc, ToNamespaceKeyLocation, ToIdentLocation;
4279 NestedNameSpecifierLoc ToQualifierLoc;
4280 if (auto Imp = importSeq(
4281 D->getNominatedNamespace(), D->getUsingLoc(),
4282 D->getNamespaceKeyLocation(), D->getQualifierLoc(),
4283 D->getIdentLocation()))
4284 std::tie(
4285 ToNominatedNamespace, ToUsingLoc, ToNamespaceKeyLocation,
4286 ToQualifierLoc, ToIdentLocation) = *Imp;
4287 else
4288 return Imp.takeError();
4289
4290 UsingDirectiveDecl *ToUsingDir;
4291 if (GetImportedOrCreateDecl(ToUsingDir, D, Importer.getToContext(), DC,
4292 ToUsingLoc,
4293 ToNamespaceKeyLocation,
4294 ToQualifierLoc,
4295 ToIdentLocation,
4296 ToNominatedNamespace, *ToComAncestorOrErr))
4297 return ToUsingDir;
4298
4299 ToUsingDir->setLexicalDeclContext(LexicalDC);
4300 LexicalDC->addDeclInternal(ToUsingDir);
4301
4302 return ToUsingDir;
4303}
4304
4305ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingValueDecl(
4306 UnresolvedUsingValueDecl *D) {
4307 DeclContext *DC, *LexicalDC;
4308 DeclarationName Name;
4309 SourceLocation Loc;
4310 NamedDecl *ToD = nullptr;
4311 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4312 return std::move(Err);
4313 if (ToD)
4314 return ToD;
4315
4316 SourceLocation ToLoc, ToUsingLoc, ToEllipsisLoc;
4317 NestedNameSpecifierLoc ToQualifierLoc;
4318 if (auto Imp = importSeq(
4319 D->getNameInfo().getLoc(), D->getUsingLoc(), D->getQualifierLoc(),
4320 D->getEllipsisLoc()))
4321 std::tie(ToLoc, ToUsingLoc, ToQualifierLoc, ToEllipsisLoc) = *Imp;
4322 else
4323 return Imp.takeError();
4324
4325 DeclarationNameInfo NameInfo(Name, ToLoc);
4326 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo))
4327 return std::move(Err);
4328
4329 UnresolvedUsingValueDecl *ToUsingValue;
4330 if (GetImportedOrCreateDecl(ToUsingValue, D, Importer.getToContext(), DC,
4331 ToUsingLoc, ToQualifierLoc, NameInfo,
4332 ToEllipsisLoc))
4333 return ToUsingValue;
4334
4335 ToUsingValue->setAccess(D->getAccess());
4336 ToUsingValue->setLexicalDeclContext(LexicalDC);
4337 LexicalDC->addDeclInternal(ToUsingValue);
4338
4339 return ToUsingValue;
4340}
4341
4342ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingTypenameDecl(
4343 UnresolvedUsingTypenameDecl *D) {
4344 DeclContext *DC, *LexicalDC;
4345 DeclarationName Name;
4346 SourceLocation Loc;
4347 NamedDecl *ToD = nullptr;
4348 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4349 return std::move(Err);
4350 if (ToD)
4351 return ToD;
4352
4353 SourceLocation ToUsingLoc, ToTypenameLoc, ToEllipsisLoc;
4354 NestedNameSpecifierLoc ToQualifierLoc;
4355 if (auto Imp = importSeq(
4356 D->getUsingLoc(), D->getTypenameLoc(), D->getQualifierLoc(),
4357 D->getEllipsisLoc()))
4358 std::tie(ToUsingLoc, ToTypenameLoc, ToQualifierLoc, ToEllipsisLoc) = *Imp;
4359 else
4360 return Imp.takeError();
4361
4362 UnresolvedUsingTypenameDecl *ToUsing;
4363 if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC,
4364 ToUsingLoc, ToTypenameLoc,
4365 ToQualifierLoc, Loc, Name, ToEllipsisLoc))
4366 return ToUsing;
4367
4368 ToUsing->setAccess(D->getAccess());
4369 ToUsing->setLexicalDeclContext(LexicalDC);
4370 LexicalDC->addDeclInternal(ToUsing);
4371
4372 return ToUsing;
4373}
4374
4375
4376Error ASTNodeImporter::ImportDefinition(
4377 ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, ImportDefinitionKind Kind) {
4378 if (To->getDefinition()) {
4379 // Check consistency of superclass.
4380 ObjCInterfaceDecl *FromSuper = From->getSuperClass();
4381 if (FromSuper) {
4382 if (auto FromSuperOrErr = import(FromSuper))
4383 FromSuper = *FromSuperOrErr;
4384 else
4385 return FromSuperOrErr.takeError();
4386 }
4387
4388 ObjCInterfaceDecl *ToSuper = To->getSuperClass();
4389 if ((bool)FromSuper != (bool)ToSuper ||
4390 (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) {
4391 Importer.ToDiag(To->getLocation(),
4392 diag::warn_odr_objc_superclass_inconsistent)
4393 << To->getDeclName();
4394 if (ToSuper)
4395 Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass)
4396 << To->getSuperClass()->getDeclName();
4397 else
4398 Importer.ToDiag(To->getLocation(),
4399 diag::note_odr_objc_missing_superclass);
4400 if (From->getSuperClass())
4401 Importer.FromDiag(From->getSuperClassLoc(),
4402 diag::note_odr_objc_superclass)
4403 << From->getSuperClass()->getDeclName();
4404 else
4405 Importer.FromDiag(From->getLocation(),
4406 diag::note_odr_objc_missing_superclass);
4407 }
4408
4409 if (shouldForceImportDeclContext(Kind))
4410 if (Error Err = ImportDeclContext(From))
4411 return Err;
4412 return Error::success();
4413 }
4414
4415 // Start the definition.
4416 To->startDefinition();
4417
4418 // If this class has a superclass, import it.
4419 if (From->getSuperClass()) {
4420 if (auto SuperTInfoOrErr = import(From->getSuperClassTInfo()))
4421 To->setSuperClass(*SuperTInfoOrErr);
4422 else
4423 return SuperTInfoOrErr.takeError();
4424 }
4425
4426 // Import protocols
4427 SmallVector<ObjCProtocolDecl *, 4> Protocols;
4428 SmallVector<SourceLocation, 4> ProtocolLocs;
4429 ObjCInterfaceDecl::protocol_loc_iterator FromProtoLoc =
4430 From->protocol_loc_begin();
4431
4432 for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(),
4433 FromProtoEnd = From->protocol_end();
4434 FromProto != FromProtoEnd;
4435 ++FromProto, ++FromProtoLoc) {
4436 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto))
4437 Protocols.push_back(*ToProtoOrErr);
4438 else
4439 return ToProtoOrErr.takeError();
4440
4441 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc))
4442 ProtocolLocs.push_back(*ToProtoLocOrErr);
4443 else
4444 return ToProtoLocOrErr.takeError();
4445
4446 }
4447
4448 // FIXME: If we're merging, make sure that the protocol list is the same.
4449 To->setProtocolList(Protocols.data(), Protocols.size(),
4450 ProtocolLocs.data(), Importer.getToContext());
4451
4452 // Import categories. When the categories themselves are imported, they'll
4453 // hook themselves into this interface.
4454 for (auto *Cat : From->known_categories()) {
4455 auto ToCatOrErr = import(Cat);
4456 if (!ToCatOrErr)
4457 return ToCatOrErr.takeError();
4458 }
4459
4460 // If we have an @implementation, import it as well.
4461 if (From->getImplementation()) {
4462 if (Expected<ObjCImplementationDecl *> ToImplOrErr =
4463 import(From->getImplementation()))
4464 To->setImplementation(*ToImplOrErr);
4465 else
4466 return ToImplOrErr.takeError();
4467 }
4468
4469 if (shouldForceImportDeclContext(Kind)) {
4470 // Import all of the members of this class.
4471 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true))
4472 return Err;
4473 }
4474 return Error::success();
4475}
4476
4477Expected<ObjCTypeParamList *>
4478ASTNodeImporter::ImportObjCTypeParamList(ObjCTypeParamList *list) {
4479 if (!list)
4480 return nullptr;
4481
4482 SmallVector<ObjCTypeParamDecl *, 4> toTypeParams;
4483 for (auto *fromTypeParam : *list) {
4484 if (auto toTypeParamOrErr = import(fromTypeParam))
4485 toTypeParams.push_back(*toTypeParamOrErr);
4486 else
4487 return toTypeParamOrErr.takeError();
4488 }
4489
4490 auto LAngleLocOrErr = import(list->getLAngleLoc());
4491 if (!LAngleLocOrErr)
4492 return LAngleLocOrErr.takeError();
4493
4494 auto RAngleLocOrErr = import(list->getRAngleLoc());
4495 if (!RAngleLocOrErr)
4496 return RAngleLocOrErr.takeError();
4497
4498 return ObjCTypeParamList::create(Importer.getToContext(),
4499 *LAngleLocOrErr,
4500 toTypeParams,
4501 *RAngleLocOrErr);
4502}
4503
4504ExpectedDecl ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) {
4505 // If this class has a definition in the translation unit we're coming from,
4506 // but this particular declaration is not that definition, import the
4507 // definition and map to that.
4508 ObjCInterfaceDecl *Definition = D->getDefinition();
4509 if (Definition && Definition != D) {
4510 if (ExpectedDecl ImportedDefOrErr = import(Definition))
4511 return Importer.MapImported(D, *ImportedDefOrErr);
4512 else
4513 return ImportedDefOrErr.takeError();
4514 }
4515
4516 // Import the major distinguishing characteristics of an @interface.
4517 DeclContext *DC, *LexicalDC;
4518 DeclarationName Name;
4519 SourceLocation Loc;
4520 NamedDecl *ToD;
4521 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4522 return std::move(Err);
4523 if (ToD)
4524 return ToD;
4525
4526 // Look for an existing interface with the same name.
4527 ObjCInterfaceDecl *MergeWithIface = nullptr;
4528 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4529 for (auto *FoundDecl : FoundDecls) {
4530 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
4531 continue;
4532
4533 if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecl)))
4534 break;
4535 }
4536
4537 // Create an interface declaration, if one does not already exist.
4538 ObjCInterfaceDecl *ToIface = MergeWithIface;
4539 if (!ToIface) {
4540 ExpectedSLoc AtBeginLocOrErr = import(D->getAtStartLoc());
4541 if (!AtBeginLocOrErr)
4542 return AtBeginLocOrErr.takeError();
4543
4544 if (GetImportedOrCreateDecl(
4545 ToIface, D, Importer.getToContext(), DC,
4546 *AtBeginLocOrErr, Name.getAsIdentifierInfo(),
4547 /*TypeParamList=*/nullptr,
4548 /*PrevDecl=*/nullptr, Loc, D->isImplicitInterfaceDecl()))
4549 return ToIface;
4550 ToIface->setLexicalDeclContext(LexicalDC);
4551 LexicalDC->addDeclInternal(ToIface);
4552 }
4553 Importer.MapImported(D, ToIface);
4554 // Import the type parameter list after MapImported, to avoid
4555 // loops when bringing in their DeclContext.
4556 if (auto ToPListOrErr =
4557 ImportObjCTypeParamList(D->getTypeParamListAsWritten()))
4558 ToIface->setTypeParamList(*ToPListOrErr);
4559 else
4560 return ToPListOrErr.takeError();
4561
4562 if (D->isThisDeclarationADefinition())
4563 if (Error Err = ImportDefinition(D, ToIface))
4564 return std::move(Err);
4565
4566 return ToIface;
4567}
4568
4569ExpectedDecl
4570ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) {
4571 ObjCCategoryDecl *Category;
4572 if (Error Err = importInto(Category, D->getCategoryDecl()))
4573 return std::move(Err);
4574
4575 ObjCCategoryImplDecl *ToImpl = Category->getImplementation();
4576 if (!ToImpl) {
4577 DeclContext *DC, *LexicalDC;
4578 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4579 return std::move(Err);
4580
4581 SourceLocation ToLocation, ToAtStartLoc, ToCategoryNameLoc;
4582 if (auto Imp = importSeq(
4583 D->getLocation(), D->getAtStartLoc(), D->getCategoryNameLoc()))
4584 std::tie(ToLocation, ToAtStartLoc, ToCategoryNameLoc) = *Imp;
4585 else
4586 return Imp.takeError();
4587
4588 if (GetImportedOrCreateDecl(
4589 ToImpl, D, Importer.getToContext(), DC,
4590 Importer.Import(D->getIdentifier()), Category->getClassInterface(),
4591 ToLocation, ToAtStartLoc, ToCategoryNameLoc))
4592 return ToImpl;
4593
4594 ToImpl->setLexicalDeclContext(LexicalDC);
4595 LexicalDC->addDeclInternal(ToImpl);
4596 Category->setImplementation(ToImpl);
4597 }
4598
4599 Importer.MapImported(D, ToImpl);
4600 if (Error Err = ImportDeclContext(D))
4601 return std::move(Err);
4602
4603 return ToImpl;
4604}
4605
4606ExpectedDecl
4607ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
4608 // Find the corresponding interface.
4609 ObjCInterfaceDecl *Iface;
4610 if (Error Err = importInto(Iface, D->getClassInterface()))
4611 return std::move(Err);
4612
4613 // Import the superclass, if any.
4614 ObjCInterfaceDecl *Super;
4615 if (Error Err = importInto(Super, D->getSuperClass()))
4616 return std::move(Err);
4617
4618 ObjCImplementationDecl *Impl = Iface->getImplementation();
4619 if (!Impl) {
4620 // We haven't imported an implementation yet. Create a new @implementation
4621 // now.
4622 DeclContext *DC, *LexicalDC;
4623 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4624 return std::move(Err);
4625
4626 SourceLocation ToLocation, ToAtStartLoc, ToSuperClassLoc;
4627 SourceLocation ToIvarLBraceLoc, ToIvarRBraceLoc;
4628 if (auto Imp = importSeq(
4629 D->getLocation(), D->getAtStartLoc(), D->getSuperClassLoc(),
4630 D->getIvarLBraceLoc(), D->getIvarRBraceLoc()))
4631 std::tie(
4632 ToLocation, ToAtStartLoc, ToSuperClassLoc,
4633 ToIvarLBraceLoc, ToIvarRBraceLoc) = *Imp;
4634 else
4635 return Imp.takeError();
4636
4637 if (GetImportedOrCreateDecl(Impl, D, Importer.getToContext(),
4638 DC, Iface, Super,
4639 ToLocation,
4640 ToAtStartLoc,
4641 ToSuperClassLoc,
4642 ToIvarLBraceLoc,
4643 ToIvarRBraceLoc))
4644 return Impl;
4645
4646 Impl->setLexicalDeclContext(LexicalDC);
4647
4648 // Associate the implementation with the class it implements.
4649 Iface->setImplementation(Impl);
4650 Importer.MapImported(D, Iface->getImplementation());
4651 } else {
4652 Importer.MapImported(D, Iface->getImplementation());
4653
4654 // Verify that the existing @implementation has the same superclass.
4655 if ((Super && !Impl->getSuperClass()) ||
4656 (!Super && Impl->getSuperClass()) ||
4657 (Super && Impl->getSuperClass() &&
4658 !declaresSameEntity(Super->getCanonicalDecl(),
4659 Impl->getSuperClass()))) {
4660 Importer.ToDiag(Impl->getLocation(),
4661 diag::warn_odr_objc_superclass_inconsistent)
4662 << Iface->getDeclName();
4663 // FIXME: It would be nice to have the location of the superclass
4664 // below.
4665 if (Impl->getSuperClass())
4666 Importer.ToDiag(Impl->getLocation(),
4667 diag::note_odr_objc_superclass)
4668 << Impl->getSuperClass()->getDeclName();
4669 else
4670 Importer.ToDiag(Impl->getLocation(),
4671 diag::note_odr_objc_missing_superclass);
4672 if (D->getSuperClass())
4673 Importer.FromDiag(D->getLocation(),
4674 diag::note_odr_objc_superclass)
4675 << D->getSuperClass()->getDeclName();
4676 else
4677 Importer.FromDiag(D->getLocation(),
4678 diag::note_odr_objc_missing_superclass);
4679
4680 return make_error<ImportError>(ImportError::NameConflict);
4681 }
4682 }
4683
4684 // Import all of the members of this @implementation.
4685 if (Error Err = ImportDeclContext(D))
4686 return std::move(Err);
4687
4688 return Impl;
4689}
4690
4691ExpectedDecl ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) {
4692 // Import the major distinguishing characteristics of an @property.
4693 DeclContext *DC, *LexicalDC;
4694 DeclarationName Name;
4695 SourceLocation Loc;
4696 NamedDecl *ToD;
4697 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4698 return std::move(Err);
4699 if (ToD)
4700 return ToD;
4701
4702 // Check whether we have already imported this property.
4703 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4704 for (auto *FoundDecl : FoundDecls) {
4705 if (auto *FoundProp = dyn_cast<ObjCPropertyDecl>(FoundDecl)) {
4706 // Check property types.
4707 if (!Importer.IsStructurallyEquivalent(D->getType(),
4708 FoundProp->getType())) {
4709 Importer.ToDiag(Loc, diag::warn_odr_objc_property_type_inconsistent)
4710 << Name << D->getType() << FoundProp->getType();
4711 Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here)
4712 << FoundProp->getType();
4713
4714 return make_error<ImportError>(ImportError::NameConflict);
4715 }
4716
4717 // FIXME: Check property attributes, getters, setters, etc.?
4718
4719 // Consider these properties to be equivalent.
4720 Importer.MapImported(D, FoundProp);
4721 return FoundProp;
4722 }
4723 }
4724
4725 QualType ToType;
4726 TypeSourceInfo *ToTypeSourceInfo;
4727 SourceLocation ToAtLoc, ToLParenLoc;
4728 if (auto Imp = importSeq(
4729 D->getType(), D->getTypeSourceInfo(), D->getAtLoc(), D->getLParenLoc()))
4730 std::tie(ToType, ToTypeSourceInfo, ToAtLoc, ToLParenLoc) = *Imp;
4731 else
4732 return Imp.takeError();
4733
4734 // Create the new property.
4735 ObjCPropertyDecl *ToProperty;
4736 if (GetImportedOrCreateDecl(
4737 ToProperty, D, Importer.getToContext(), DC, Loc,
4738 Name.getAsIdentifierInfo(), ToAtLoc,
4739 ToLParenLoc, ToType,
4740 ToTypeSourceInfo, D->getPropertyImplementation()))
4741 return ToProperty;
4742
4743 Selector ToGetterName, ToSetterName;
4744 SourceLocation ToGetterNameLoc, ToSetterNameLoc;
4745 ObjCMethodDecl *ToGetterMethodDecl, *ToSetterMethodDecl;
4746 ObjCIvarDecl *ToPropertyIvarDecl;
4747 if (auto Imp = importSeq(
4748 D->getGetterName(), D->getSetterName(),
4749 D->getGetterNameLoc(), D->getSetterNameLoc(),
4750 D->getGetterMethodDecl(), D->getSetterMethodDecl(),
4751 D->getPropertyIvarDecl()))
4752 std::tie(
4753 ToGetterName, ToSetterName,
4754 ToGetterNameLoc, ToSetterNameLoc,
4755 ToGetterMethodDecl, ToSetterMethodDecl,
4756 ToPropertyIvarDecl) = *Imp;
4757 else
4758 return Imp.takeError();
4759
4760 ToProperty->setLexicalDeclContext(LexicalDC);
4761 LexicalDC->addDeclInternal(ToProperty);
4762
4763 ToProperty->setPropertyAttributes(D->getPropertyAttributes());
4764 ToProperty->setPropertyAttributesAsWritten(
4765 D->getPropertyAttributesAsWritten());
4766 ToProperty->setGetterName(ToGetterName, ToGetterNameLoc);
4767 ToProperty->setSetterName(ToSetterName, ToSetterNameLoc);
4768 ToProperty->setGetterMethodDecl(ToGetterMethodDecl);
4769 ToProperty->setSetterMethodDecl(ToSetterMethodDecl);
4770 ToProperty->setPropertyIvarDecl(ToPropertyIvarDecl);
4771 return ToProperty;
4772}
4773
4774ExpectedDecl
4775ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) {
4776 ObjCPropertyDecl *Property;
4777 if (Error Err = importInto(Property, D->getPropertyDecl()))
4778 return std::move(Err);
4779
4780 DeclContext *DC, *LexicalDC;
4781 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
4782 return std::move(Err);
4783
4784 auto *InImpl = cast<ObjCImplDecl>(LexicalDC);
4785
4786 // Import the ivar (for an @synthesize).
4787 ObjCIvarDecl *Ivar = nullptr;
4788 if (Error Err = importInto(Ivar, D->getPropertyIvarDecl()))
4789 return std::move(Err);
4790
4791 ObjCPropertyImplDecl *ToImpl
4792 = InImpl->FindPropertyImplDecl(Property->getIdentifier(),
4793 Property->getQueryKind());
4794 if (!ToImpl) {
4795 SourceLocation ToBeginLoc, ToLocation, ToPropertyIvarDeclLoc;
4796 if (auto Imp = importSeq(
4797 D->getBeginLoc(), D->getLocation(), D->getPropertyIvarDeclLoc()))
4798 std::tie(ToBeginLoc, ToLocation, ToPropertyIvarDeclLoc) = *Imp;
4799 else
4800 return Imp.takeError();
4801
4802 if (GetImportedOrCreateDecl(ToImpl, D, Importer.getToContext(), DC,
4803 ToBeginLoc,
4804 ToLocation, Property,
4805 D->getPropertyImplementation(), Ivar,
4806 ToPropertyIvarDeclLoc))
4807 return ToImpl;
4808
4809 ToImpl->setLexicalDeclContext(LexicalDC);
4810 LexicalDC->addDeclInternal(ToImpl);
4811 } else {
4812 // Check that we have the same kind of property implementation (@synthesize
4813 // vs. @dynamic).
4814 if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) {
4815 Importer.ToDiag(ToImpl->getLocation(),
4816 diag::warn_odr_objc_property_impl_kind_inconsistent)
4817 << Property->getDeclName()
4818 << (ToImpl->getPropertyImplementation()
4819 == ObjCPropertyImplDecl::Dynamic);
4820 Importer.FromDiag(D->getLocation(),
4821 diag::note_odr_objc_property_impl_kind)
4822 << D->getPropertyDecl()->getDeclName()
4823 << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic);
4824
4825 return make_error<ImportError>(ImportError::NameConflict);
4826 }
4827
4828 // For @synthesize, check that we have the same
4829 if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize &&
4830 Ivar != ToImpl->getPropertyIvarDecl()) {
4831 Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(),
4832 diag::warn_odr_objc_synthesize_ivar_inconsistent)
4833 << Property->getDeclName()
4834 << ToImpl->getPropertyIvarDecl()->getDeclName()
4835 << Ivar->getDeclName();
4836 Importer.FromDiag(D->getPropertyIvarDeclLoc(),
4837 diag::note_odr_objc_synthesize_ivar_here)
4838 << D->getPropertyIvarDecl()->getDeclName();
4839
4840 return make_error<ImportError>(ImportError::NameConflict);
4841 }
4842
4843 // Merge the existing implementation with the new implementation.
4844 Importer.MapImported(D, ToImpl);
4845 }
4846
4847 return ToImpl;
4848}
4849
4850ExpectedDecl
4851ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) {
4852 // For template arguments, we adopt the translation unit as our declaration
4853 // context. This context will be fixed when the actual template declaration
4854 // is created.
4855
4856 // FIXME: Import default argument.
4857
4858 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
4859 if (!BeginLocOrErr)
4860 return BeginLocOrErr.takeError();
4861
4862 ExpectedSLoc LocationOrErr = import(D->getLocation());
4863 if (!LocationOrErr)
4864 return LocationOrErr.takeError();
4865
4866 TemplateTypeParmDecl *ToD = nullptr;
4867 (void)GetImportedOrCreateDecl(
4868 ToD, D, Importer.getToContext(),
4869 Importer.getToContext().getTranslationUnitDecl(),
4870 *BeginLocOrErr, *LocationOrErr,
4871 D->getDepth(), D->getIndex(), Importer.Import(D->getIdentifier()),
4872 D->wasDeclaredWithTypename(), D->isParameterPack());
4873 return ToD;
4874}
4875
4876ExpectedDecl
4877ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) {
4878 DeclarationName ToDeclName;
4879 SourceLocation ToLocation, ToInnerLocStart;
4880 QualType ToType;
4881 TypeSourceInfo *ToTypeSourceInfo;
4882 if (auto Imp = importSeq(
4883 D->getDeclName(), D->getLocation(), D->getType(), D->getTypeSourceInfo(),
4884 D->getInnerLocStart()))
4885 std::tie(
4886 ToDeclName, ToLocation, ToType, ToTypeSourceInfo,
4887 ToInnerLocStart) = *Imp;
4888 else
4889 return Imp.takeError();
4890
4891 // FIXME: Import default argument.
4892
4893 NonTypeTemplateParmDecl *ToD = nullptr;
4894 (void)GetImportedOrCreateDecl(
4895 ToD, D, Importer.getToContext(),
4896 Importer.getToContext().getTranslationUnitDecl(),
4897 ToInnerLocStart, ToLocation, D->getDepth(),
4898 D->getPosition(), ToDeclName.getAsIdentifierInfo(), ToType,
4899 D->isParameterPack(), ToTypeSourceInfo);
4900 return ToD;
4901}
4902
4903ExpectedDecl
4904ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) {
4905 // Import the name of this declaration.
4906 auto NameOrErr = import(D->getDeclName());
4907 if (!NameOrErr)
4908 return NameOrErr.takeError();
4909
4910 // Import the location of this declaration.
4911 ExpectedSLoc LocationOrErr = import(D->getLocation());
4912 if (!LocationOrErr)
4913 return LocationOrErr.takeError();
4914
4915 // Import template parameters.
4916 auto TemplateParamsOrErr = import(D->getTemplateParameters());
4917 if (!TemplateParamsOrErr)
4918 return TemplateParamsOrErr.takeError();
4919
4920 // FIXME: Import default argument.
4921
4922 TemplateTemplateParmDecl *ToD = nullptr;
4923 (void)GetImportedOrCreateDecl(
4924 ToD, D, Importer.getToContext(),
4925 Importer.getToContext().getTranslationUnitDecl(), *LocationOrErr,
4926 D->getDepth(), D->getPosition(), D->isParameterPack(),
4927 (*NameOrErr).getAsIdentifierInfo(),
4928 *TemplateParamsOrErr);
4929 return ToD;
4930}
4931
4932// Returns the definition for a (forward) declaration of a TemplateDecl, if
4933// it has any definition in the redecl chain.
4934template <typename T> static auto getTemplateDefinition(T *D) -> T * {
4935 assert(D->getTemplatedDecl() && "Should be called on templates only")((D->getTemplatedDecl() && "Should be called on templates only"
) ? static_cast<void> (0) : __assert_fail ("D->getTemplatedDecl() && \"Should be called on templates only\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp"
, 4935, __PRETTY_FUNCTION__))
;
4936 auto *ToTemplatedDef = D->getTemplatedDecl()->getDefinition();
4937 if (!ToTemplatedDef)
4938 return nullptr;
4939 auto *TemplateWithDef = ToTemplatedDef->getDescribedTemplate();
4940 return cast_or_null<T>(TemplateWithDef);
4941}
4942
4943ExpectedDecl ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) {
4944 bool IsFriend = D->getFriendObjectKind() != Decl::FOK_None;
4945
4946 // Import the major distinguishing characteristics of this class template.
4947 DeclContext *DC, *LexicalDC;
4948 DeclarationName Name;
4949 SourceLocation Loc;
4950 NamedDecl *ToD;
4951 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
4952 return std::move(Err);
4953 if (ToD)
4954 return ToD;
4955
4956 ClassTemplateDecl *FoundByLookup = nullptr;
4957
4958 // We may already have a template of the same name; try to find and match it.
4959 if (!DC->isFunctionOrMethod()) {
4960 SmallVector<NamedDecl *, 4> ConflictingDecls;
4961 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
4962 for (auto *FoundDecl : FoundDecls) {
4963 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary |
4964 Decl::IDNS_TagFriend))
4965 continue;
4966
4967 Decl *Found = FoundDecl;
4968 auto *FoundTemplate = dyn_cast<ClassTemplateDecl>(Found);
4969 if (FoundTemplate) {
4970
4971 if (IsStructuralMatch(D, FoundTemplate)) {
4972 ClassTemplateDecl *TemplateWithDef =
4973 getTemplateDefinition(FoundTemplate);
4974 if (D->isThisDeclarationADefinition() && TemplateWithDef) {
4975 return Importer.MapImported(D, TemplateWithDef);
4976 }
4977 FoundByLookup = FoundTemplate;
4978 break;
4979 }
4980 }
4981
4982 ConflictingDecls.push_back(FoundDecl);
4983 }
4984
4985 if (!ConflictingDecls.empty()) {
4986 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
4987 ConflictingDecls.data(),
4988 ConflictingDecls.size());
4989 }
4990
4991 if (!Name)
4992 return make_error<ImportError>(ImportError::NameConflict);
4993 }
4994
4995 CXXRecordDecl *FromTemplated = D->getTemplatedDecl();
4996
4997 // Create the declaration that is being templated.
4998 CXXRecordDecl *ToTemplated;
4999 if (Error Err = importInto(ToTemplated, FromTemplated))
5000 return std::move(Err);
5001
5002 // Create the class template declaration itself.
5003 auto TemplateParamsOrErr = import(D->getTemplateParameters());
5004 if (!TemplateParamsOrErr)
5005 return TemplateParamsOrErr.takeError();
5006
5007 ClassTemplateDecl *D2;
5008 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, Loc, Name,
5009 *TemplateParamsOrErr, ToTemplated))
5010 return D2;
5011
5012 ToTemplated->setDescribedClassTemplate(D2);
5013
5014 D2->setAccess(D->getAccess());
5015 D2->setLexicalDeclContext(LexicalDC);
5016
5017 if (D->getDeclContext()->containsDeclAndLoad(D))
5018 DC->addDeclInternal(D2);
5019 if (DC != LexicalDC && D->getLexicalDeclContext()->containsDeclAndLoad(D))
5020 LexicalDC->addDeclInternal(D2);
5021
5022 if (FoundByLookup) {
5023 auto *Recent =
5024 const_cast<ClassTemplateDecl *>(FoundByLookup->getMostRecentDecl());
5025
5026 // It is possible that during the import of the class template definition
5027 // we start the import of a fwd friend decl of the very same class template
5028 // and we add the fwd friend decl to the lookup table. But the ToTemplated
5029 // had been created earlier and by that time the lookup could not find
5030 // anything existing, so it has no previous decl. Later, (still during the
5031 // import of the fwd friend decl) we start to import the definition again
5032 // and this time the lookup finds the previous fwd friend class template.
5033 // In this case we must set up the previous decl for the templated decl.
5034 if (!ToTemplated->getPreviousDecl()) {
5035 assert(FoundByLookup->getTemplatedDecl() &&((FoundByLookup->getTemplatedDecl() && "Found decl must have its templated decl set"
) ? static_cast<void> (0) : __assert_fail ("FoundByLookup->getTemplatedDecl() && \"Found decl must have its templated decl set\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp"
, 5036, __PRETTY_FUNCTION__))
5036 "Found decl must have its templated decl set")((FoundByLookup->getTemplatedDecl() && "Found decl must have its templated decl set"
) ? static_cast<void> (0) : __assert_fail ("FoundByLookup->getTemplatedDecl() && \"Found decl must have its templated decl set\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp"
, 5036, __PRETTY_FUNCTION__))
;
5037 CXXRecordDecl *PrevTemplated =
5038 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
5039 if (ToTemplated != PrevTemplated)
5040 ToTemplated->setPreviousDecl(PrevTemplated);
5041 }
5042
5043 D2->setPreviousDecl(Recent);
5044 }
5045
5046 if (LexicalDC != DC && IsFriend)
5047 DC->makeDeclVisibleInContext(D2);
5048
5049 if (FromTemplated->isCompleteDefinition() &&
5050 !ToTemplated->isCompleteDefinition()) {
5051 // FIXME: Import definition!
5052 }
5053
5054 return D2;
5055}
5056
5057ExpectedDecl ASTNodeImporter::VisitClassTemplateSpecializationDecl(
5058 ClassTemplateSpecializationDecl *D) {
5059 ClassTemplateDecl *ClassTemplate;
5060 if (Error Err = importInto(ClassTemplate, D->getSpecializedTemplate()))
5061 return std::move(Err);
5062
5063 // Import the context of this declaration.
5064 DeclContext *DC, *LexicalDC;
5065 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5066 return std::move(Err);
5067
5068 // Import template arguments.
5069 SmallVector<TemplateArgument, 2> TemplateArgs;
5070 if (Error Err = ImportTemplateArguments(
5071 D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs))
5072 return std::move(Err);
5073
5074 // Try to find an existing specialization with these template arguments.
5075 void *InsertPos = nullptr;
5076 ClassTemplateSpecializationDecl *PrevDecl = nullptr;
5077 ClassTemplatePartialSpecializationDecl *PartialSpec =
5078 dyn_cast<ClassTemplatePartialSpecializationDecl>(D);
5079 if (PartialSpec)
5080 PrevDecl =
5081 ClassTemplate->findPartialSpecialization(TemplateArgs, InsertPos);
5082 else
5083 PrevDecl = ClassTemplate->findSpecialization(TemplateArgs, InsertPos);
5084
5085 if (PrevDecl) {
5086 if (IsStructuralMatch(D, PrevDecl)) {
5087 if (D->isThisDeclarationADefinition() && PrevDecl->getDefinition()) {
5088 Importer.MapImported(D, PrevDecl->getDefinition());
5089 // Import those default field initializers which have been
5090 // instantiated in the "From" context, but not in the "To" context.
5091 for (auto *FromField : D->fields()) {
5092 auto ToOrErr = import(FromField);
5093 if (!ToOrErr)
5094 return ToOrErr.takeError();
5095 }
5096
5097 // Import those methods which have been instantiated in the
5098 // "From" context, but not in the "To" context.
5099 for (CXXMethodDecl *FromM : D->methods()) {
5100 auto ToOrErr = import(FromM);
5101 if (!ToOrErr)
5102 return ToOrErr.takeError();
5103 }
5104
5105 // TODO Import instantiated default arguments.
5106 // TODO Import instantiated exception specifications.
5107 //
5108 // Generally, ASTCommon.h/DeclUpdateKind enum gives a very good hint
5109 // what else could be fused during an AST merge.
5110 return PrevDecl;
5111 }
5112 } else { // ODR violation.
5113 // FIXME HandleNameConflict
5114 return nullptr;
5115 }
5116 }
5117
5118 // Import the location of this declaration.
5119 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
5120 if (!BeginLocOrErr)
5121 return BeginLocOrErr.takeError();
5122 ExpectedSLoc IdLocOrErr = import(D->getLocation());
5123 if (!IdLocOrErr)
5124 return IdLocOrErr.takeError();
5125
5126 // Create the specialization.
5127 ClassTemplateSpecializationDecl *D2 = nullptr;
5128 if (PartialSpec) {
5129 // Import TemplateArgumentListInfo.
5130 TemplateArgumentListInfo ToTAInfo;
5131 const auto &ASTTemplateArgs = *PartialSpec->getTemplateArgsAsWritten();
5132 if (Error Err = ImportTemplateArgumentListInfo(ASTTemplateArgs, ToTAInfo))
5133 return std::move(Err);
5134
5135 QualType CanonInjType;
5136 if (Error Err = importInto(
5137 CanonInjType, PartialSpec->getInjectedSpecializationType()))
5138 return std::move(Err);
5139 CanonInjType = CanonInjType.getCanonicalType();
5140
5141 auto ToTPListOrErr = import(PartialSpec->getTemplateParameters());
5142 if (!ToTPListOrErr)
5143 return ToTPListOrErr.takeError();
5144
5145 if (GetImportedOrCreateDecl<ClassTemplatePartialSpecializationDecl>(
5146 D2, D, Importer.getToContext(), D->getTagKind(), DC,
5147 *BeginLocOrErr, *IdLocOrErr, *ToTPListOrErr, ClassTemplate,
5148 llvm::makeArrayRef(TemplateArgs.data(), TemplateArgs.size()),
5149 ToTAInfo, CanonInjType,
5150 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl)))
5151 return D2;
5152
5153 // Update InsertPos, because preceding import calls may have invalidated
5154 // it by adding new specializations.
5155 if (!ClassTemplate->findPartialSpecialization(TemplateArgs, InsertPos))
5156 // Add this partial specialization to the class template.
5157 ClassTemplate->AddPartialSpecialization(
5158 cast<ClassTemplatePartialSpecializationDecl>(D2), InsertPos);
5159
5160 } else { // Not a partial specialization.
5161 if (GetImportedOrCreateDecl(
5162 D2, D, Importer.getToContext(), D->getTagKind(), DC,
5163 *BeginLocOrErr, *IdLocOrErr, ClassTemplate, TemplateArgs,
5164 PrevDecl))
5165 return D2;
5166
5167 // Update InsertPos, because preceding import calls may have invalidated
5168 // it by adding new specializations.
5169 if (!ClassTemplate->findSpecialization(TemplateArgs, InsertPos))
5170 // Add this specialization to the class template.
5171 ClassTemplate->AddSpecialization(D2, InsertPos);
5172 }
5173
5174 D2->setSpecializationKind(D->getSpecializationKind());
5175
5176 // Set the context of this specialization/instantiation.
5177 D2->setLexicalDeclContext(LexicalDC);
5178
5179 // Add to the DC only if it was an explicit specialization/instantiation.
5180 if (D2->isExplicitInstantiationOrSpecialization()) {
5181 LexicalDC->addDeclInternal(D2);
5182 }
5183
5184 // Import the qualifier, if any.
5185 if (auto LocOrErr = import(D->getQualifierLoc()))
5186 D2->setQualifierInfo(*LocOrErr);
5187 else
5188 return LocOrErr.takeError();
5189
5190 if (auto *TSI = D->getTypeAsWritten()) {
5191 if (auto TInfoOrErr = import(TSI))
5192 D2->setTypeAsWritten(*TInfoOrErr);
5193 else
5194 return TInfoOrErr.takeError();
5195
5196 if (auto LocOrErr = import(D->getTemplateKeywordLoc()))
5197 D2->setTemplateKeywordLoc(*LocOrErr);
5198 else
5199 return LocOrErr.takeError();
5200
5201 if (auto LocOrErr = import(D->getExternLoc()))
5202 D2->setExternLoc(*LocOrErr);
5203 else
5204 return LocOrErr.takeError();
5205 }
5206
5207 if (D->getPointOfInstantiation().isValid()) {
5208 if (auto POIOrErr = import(D->getPointOfInstantiation()))
5209 D2->setPointOfInstantiation(*POIOrErr);
5210 else
5211 return POIOrErr.takeError();
5212 }
5213
5214 D2->setTemplateSpecializationKind(D->getTemplateSpecializationKind());
5215
5216 if (D->isCompleteDefinition())
5217 if (Error Err = ImportDefinition(D, D2))
5218 return std::move(Err);
5219
5220 return D2;
5221}
5222
5223ExpectedDecl ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) {
5224 // If this variable has a definition in the translation unit we're coming
5225 // from,
5226 // but this particular declaration is not that definition, import the
5227 // definition and map to that.
5228 auto *Definition =
5229 cast_or_null<VarDecl>(D->getTemplatedDecl()->getDefinition());
5230 if (Definition && Definition != D->getTemplatedDecl()) {
5231 if (ExpectedDecl ImportedDefOrErr = import(
5232 Definition->getDescribedVarTemplate()))
5233 return Importer.MapImported(D, *ImportedDefOrErr);
5234 else
5235 return ImportedDefOrErr.takeError();
5236 }
5237
5238 // Import the major distinguishing characteristics of this variable template.
5239 DeclContext *DC, *LexicalDC;
5240 DeclarationName Name;
5241 SourceLocation Loc;
5242 NamedDecl *ToD;
5243 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5244 return std::move(Err);
5245 if (ToD)
5246 return ToD;
5247
5248 // We may already have a template of the same name; try to find and match it.
5249 assert(!DC->isFunctionOrMethod() &&((!DC->isFunctionOrMethod() && "Variable templates cannot be declared at function scope"
) ? static_cast<void> (0) : __assert_fail ("!DC->isFunctionOrMethod() && \"Variable templates cannot be declared at function scope\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp"
, 5250, __PRETTY_FUNCTION__))
5250 "Variable templates cannot be declared at function scope")((!DC->isFunctionOrMethod() && "Variable templates cannot be declared at function scope"
) ? static_cast<void> (0) : __assert_fail ("!DC->isFunctionOrMethod() && \"Variable templates cannot be declared at function scope\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp"
, 5250, __PRETTY_FUNCTION__))
;
5251 SmallVector<NamedDecl *, 4> ConflictingDecls;
5252 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5253 for (auto *FoundDecl : FoundDecls) {
5254 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary))
5255 continue;
5256
5257 Decl *Found = FoundDecl;
5258 if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(Found)) {
5259 if (IsStructuralMatch(D, FoundTemplate)) {
5260 // The variable templates structurally match; call it the same template.
5261 Importer.MapImported(D->getTemplatedDecl(),
5262 FoundTemplate->getTemplatedDecl());
5263 return Importer.MapImported(D, FoundTemplate);
5264 }
5265 }
5266
5267 ConflictingDecls.push_back(FoundDecl);
5268 }
5269
5270 if (!ConflictingDecls.empty()) {
5271 Name = Importer.HandleNameConflict(Name, DC, Decl::IDNS_Ordinary,
5272 ConflictingDecls.data(),
5273 ConflictingDecls.size());
5274 }
5275
5276 if (!Name)
5277 // FIXME: Is it possible to get other error than name conflict?
5278 // (Put this `if` into the previous `if`?)
5279 return make_error<ImportError>(ImportError::NameConflict);
5280
5281 VarDecl *DTemplated = D->getTemplatedDecl();
5282
5283 // Import the type.
5284 // FIXME: Value not used?
5285 ExpectedType TypeOrErr = import(DTemplated->getType());
5286 if (!TypeOrErr)
5287 return TypeOrErr.takeError();
5288
5289 // Create the declaration that is being templated.
5290 VarDecl *ToTemplated;
5291 if (Error Err = importInto(ToTemplated, DTemplated))
5292 return std::move(Err);
5293
5294 // Create the variable template declaration itself.
5295 auto TemplateParamsOrErr = import(D->getTemplateParameters());
5296 if (!TemplateParamsOrErr)
5297 return TemplateParamsOrErr.takeError();
5298
5299 VarTemplateDecl *ToVarTD;
5300 if (GetImportedOrCreateDecl(ToVarTD, D, Importer.getToContext(), DC, Loc,
5301 Name, *TemplateParamsOrErr, ToTemplated))
5302 return ToVarTD;
5303
5304 ToTemplated->setDescribedVarTemplate(ToVarTD);
5305
5306 ToVarTD->setAccess(D->getAccess());
5307 ToVarTD->setLexicalDeclContext(LexicalDC);
5308 LexicalDC->addDeclInternal(ToVarTD);
5309
5310 if (DTemplated->isThisDeclarationADefinition() &&
5311 !ToTemplated->isThisDeclarationADefinition()) {
5312 // FIXME: Import definition!
5313 }
5314
5315 return ToVarTD;
5316}
5317
5318ExpectedDecl ASTNodeImporter::VisitVarTemplateSpecializationDecl(
5319 VarTemplateSpecializationDecl *D) {
5320 // If this record has a definition in the translation unit we're coming from,
5321 // but this particular declaration is not that definition, import the
5322 // definition and map to that.
5323 VarDecl *Definition = D->getDefinition();
5324 if (Definition && Definition != D) {
5325 if (ExpectedDecl ImportedDefOrErr = import(Definition))
5326 return Importer.MapImported(D, *ImportedDefOrErr);
5327 else
5328 return ImportedDefOrErr.takeError();
5329 }
5330
5331 VarTemplateDecl *VarTemplate = nullptr;
5332 if (Error Err = importInto(VarTemplate, D->getSpecializedTemplate()))
5333 return std::move(Err);
5334
5335 // Import the context of this declaration.
5336 DeclContext *DC, *LexicalDC;
5337 if (Error Err = ImportDeclContext(D, DC, LexicalDC))
5338 return std::move(Err);
5339
5340 // Import the location of this declaration.
5341 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc());
5342 if (!BeginLocOrErr)
5343 return BeginLocOrErr.takeError();
5344
5345 auto IdLocOrErr = import(D->getLocation());
5346 if (!IdLocOrErr)
5347 return IdLocOrErr.takeError();
5348
5349 // Import template arguments.
5350 SmallVector<TemplateArgument, 2> TemplateArgs;
5351 if (Error Err = ImportTemplateArguments(
5352 D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs))
5353 return std::move(Err);
5354
5355 // Try to find an existing specialization with these template arguments.
5356 void *InsertPos = nullptr;
5357 VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization(
5358 TemplateArgs, InsertPos);
5359 if (D2) {
5360 // We already have a variable template specialization with these template
5361 // arguments.
5362
5363 // FIXME: Check for specialization vs. instantiation errors.
5364
5365 if (VarDecl *FoundDef = D2->getDefinition()) {
5366 if (!D->isThisDeclarationADefinition() ||
5367 IsStructuralMatch(D, FoundDef)) {
5368 // The record types structurally match, or the "from" translation
5369 // unit only had a forward declaration anyway; call it the same
5370 // variable.
5371 return Importer.MapImported(D, FoundDef);
5372 }
5373 }
5374 } else {
5375 // Import the type.
5376 QualType T;
5377 if (Error Err = importInto(T, D->getType()))
5378 return std::move(Err);
5379
5380 auto TInfoOrErr = import(D->getTypeSourceInfo());
5381 if (!TInfoOrErr)
5382 return TInfoOrErr.takeError();
5383
5384 TemplateArgumentListInfo ToTAInfo;
5385 if (Error Err = ImportTemplateArgumentListInfo(
5386 D->getTemplateArgsInfo(), ToTAInfo))
5387 return std::move(Err);
5388
5389 using PartVarSpecDecl = VarTemplatePartialSpecializationDecl;
5390 // Create a new specialization.
5391 if (auto *FromPartial = dyn_cast<PartVarSpecDecl>(D)) {
5392 // Import TemplateArgumentListInfo
5393 TemplateArgumentListInfo ArgInfos;
5394 const auto *FromTAArgsAsWritten = FromPartial->getTemplateArgsAsWritten();
5395 // NOTE: FromTAArgsAsWritten and template parameter list are non-null.
5396 if (Error Err = ImportTemplateArgumentListInfo(
5397 *FromTAArgsAsWritten, ArgInfos))
5398 return std::move(Err);
5399
5400 auto ToTPListOrErr = import(FromPartial->getTemplateParameters());
5401 if (!ToTPListOrErr)
5402 return ToTPListOrErr.takeError();
5403
5404 PartVarSpecDecl *ToPartial;
5405 if (GetImportedOrCreateDecl(ToPartial, D, Importer.getToContext(), DC,
5406 *BeginLocOrErr, *IdLocOrErr, *ToTPListOrErr,
5407 VarTemplate, T, *TInfoOrErr,
5408 D->getStorageClass(), TemplateArgs, ArgInfos))
5409 return ToPartial;
5410
5411 if (Expected<PartVarSpecDecl *> ToInstOrErr = import(
5412 FromPartial->getInstantiatedFromMember()))
5413 ToPartial->setInstantiatedFromMember(*ToInstOrErr);
5414 else
5415 return ToInstOrErr.takeError();
5416
5417 if (FromPartial->isMemberSpecialization())
5418 ToPartial->setMemberSpecialization();
5419
5420 D2 = ToPartial;
5421
5422 } else { // Full specialization
5423 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC,
5424 *BeginLocOrErr, *IdLocOrErr, VarTemplate,
5425 T, *TInfoOrErr,
5426 D->getStorageClass(), TemplateArgs))
5427 return D2;
5428 }
5429
5430 if (D->getPointOfInstantiation().isValid()) {
5431 if (ExpectedSLoc POIOrErr = import(D->getPointOfInstantiation()))
5432 D2->setPointOfInstantiation(*POIOrErr);
5433 else
5434 return POIOrErr.takeError();
5435 }
5436
5437 D2->setSpecializationKind(D->getSpecializationKind());
5438 D2->setTemplateArgsInfo(ToTAInfo);
5439
5440 // Add this specialization to the class template.
5441 VarTemplate->AddSpecialization(D2, InsertPos);
5442
5443 // Import the qualifier, if any.
5444 if (auto LocOrErr = import(D->getQualifierLoc()))
5445 D2->setQualifierInfo(*LocOrErr);
5446 else
5447 return LocOrErr.takeError();
5448
5449 if (D->isConstexpr())
5450 D2->setConstexpr(true);
5451
5452 // Add the specialization to this context.
5453 D2->setLexicalDeclContext(LexicalDC);
5454 LexicalDC->addDeclInternal(D2);
5455
5456 D2->setAccess(D->getAccess());
5457 }
5458
5459 if (Error Err = ImportInitializer(D, D2))
5460 return std::move(Err);
5461
5462 return D2;
5463}
5464
5465ExpectedDecl
5466ASTNodeImporter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) {
5467 DeclContext *DC, *LexicalDC;
5468 DeclarationName Name;
5469 SourceLocation Loc;
5470 NamedDecl *ToD;
5471
5472 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc))
5473 return std::move(Err);
5474
5475 if (ToD)
5476 return ToD;
5477
5478 const FunctionTemplateDecl *FoundByLookup = nullptr;
5479
5480 // Try to find a function in our own ("to") context with the same name, same
5481 // type, and in the same context as the function we're importing.
5482 // FIXME Split this into a separate function.
5483 if (!LexicalDC->isFunctionOrMethod()) {
5484 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend;
5485 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name);
5486 for (auto *FoundDecl : FoundDecls) {
5487 if (!FoundDecl->isInIdentifierNamespace(IDNS))
5488 continue;
5489
5490 if (auto *FoundTemplate = dyn_cast<FunctionTemplateDecl>(FoundDecl)) {
5491 if (FoundTemplate->hasExternalFormalLinkage() &&
5492 D->hasExternalFormalLinkage()) {
5493 if (IsStructuralMatch(D, FoundTemplate)) {
5494 FunctionTemplateDecl *TemplateWithDef =
5495 getTemplateDefinition(FoundTemplate);
5496 if (D->isThisDeclarationADefinition() && TemplateWithDef) {
5497 return Importer.MapImported(D, TemplateWithDef);
5498 }
5499 FoundByLookup = FoundTemplate;
5500 break;
5501 }
5502 // TODO: handle conflicting names
5503 }
5504 }
5505 }
5506 }
5507
5508 auto ParamsOrErr = import(D->getTemplateParameters());
5509 if (!ParamsOrErr)
5510 return ParamsOrErr.takeError();
5511
5512 FunctionDecl *TemplatedFD;
5513 if (Error Err = importInto(TemplatedFD, D->getTemplatedDecl()))
5514 return std::move(Err);
5515
5516 FunctionTemplateDecl *ToFunc;
5517 if (GetImportedOrCreateDecl(ToFunc, D, Importer.getToContext(), DC, Loc, Name,
5518 *ParamsOrErr, TemplatedFD))
5519 return ToFunc;
5520
5521 TemplatedFD->setDescribedFunctionTemplate(ToFunc);
5522
5523 ToFunc->setAccess(D->getAccess());
5524 ToFunc->setLexicalDeclContext(LexicalDC);
5525 LexicalDC->addDeclInternal(ToFunc);
5526
5527 if (FoundByLookup) {
5528 auto *Recent =
5529 const_cast<FunctionTemplateDecl *>(FoundByLookup->getMostRecentDecl());
5530 if (!TemplatedFD->getPreviousDecl()) {
5531 assert(FoundByLookup->getTemplatedDecl() &&((FoundByLookup->getTemplatedDecl() && "Found decl must have its templated decl set"
) ? static_cast<void> (0) : __assert_fail ("FoundByLookup->getTemplatedDecl() && \"Found decl must have its templated decl set\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp"
, 5532, __PRETTY_FUNCTION__))
5532 "Found decl must have its templated decl set")((FoundByLookup->getTemplatedDecl() && "Found decl must have its templated decl set"
) ? static_cast<void> (0) : __assert_fail ("FoundByLookup->getTemplatedDecl() && \"Found decl must have its templated decl set\""
, "/build/llvm-toolchain-snapshot-9~svn362543/tools/clang/lib/AST/ASTImporter.cpp"
, 5532, __PRETTY_FUNCTION__))
;
5533 auto *PrevTemplated =
5534 FoundByLookup->getTemplatedDecl()->getMostRecentDecl();
5535 if (TemplatedFD != PrevTemplated)
5536 TemplatedFD->setPreviousDecl(PrevTemplated);
5537 }
5538 ToFunc->setPreviousDecl(Recent);
5539 }
5540
5541 return ToFunc;
5542}
5543
5544//----------------------------------------------------------------------------
5545// Import Statements
5546//----------------------------------------------------------------------------
5547
5548ExpectedStmt ASTNodeImporter::VisitStmt(Stmt *S) {
5549 Importer.FromDiag(S->getBeginLoc(), diag::err_unsupported_ast_node)
5550 << S->getStmtClassName();
5551 return make_error<ImportError>(ImportError::UnsupportedConstruct);
5552}
5553
5554
5555ExpectedStmt ASTNodeImporter::VisitGCCAsmStmt(GCCAsmStmt *S) {
5556 SmallVector<IdentifierInfo *, 4> Names;
5557 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
5558 IdentifierInfo *ToII = Importer.Import(S->getOutputIdentifier(I));
5559 // ToII is nullptr when no symbolic name is given for output operand
5560 // see ParseStmtAsm::ParseAsmOperandsOpt
5561 Names.push_back(ToII);
5562 }
5563
5564 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
5565 IdentifierInfo *ToII = Importer.Import(S->getInputIdentifier(I));
5566 // ToII is nullptr when no symbolic name is given for input operand
5567 // see ParseStmtAsm::ParseAsmOperandsOpt
5568 Names.push_back(ToII);
5569 }
5570
5571 SmallVector<StringLiteral *, 4> Clobbers;
5572 for (unsigned I = 0, E = S->getNumClobbers(); I != E; I++) {
5573 if (auto ClobberOrErr = import(S->getClobberStringLiteral(I)))
5574 Clobbers.push_back(*ClobberOrErr);
5575 else
5576 return ClobberOrErr.takeError();
5577
5578 }
5579
5580 SmallVector<StringLiteral *, 4> Constraints;
5581 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) {
5582 if (auto OutputOrErr = import(S->getOutputConstraintLiteral(I)))
5583 Constraints.push_back(*OutputOrErr);
5584 else
5585 return OutputOrErr.takeError();
5586 }
5587
5588 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) {
5589 if (auto InputOrErr = import(S->getInputConstraintLiteral(I)))
5590 Constraints.push_back(*InputOrErr);
5591 else
5592 return InputOrErr.takeError();
5593 }
5594
5595 SmallVector<Expr *, 4> Exprs(S->getNumOutputs() + S->getNumInputs() +
5596 S->getNumLabels());
5597 if (Error Err = ImportContainerChecked(S->outputs(), Exprs))
5598 return std::move(Err);
5599
5600 if (Error Err =
5601 ImportArrayChecked(S->inputs(), Exprs.begin() + S->getNumOutputs()))
5602 return std::move(Err);
5603
5604 if (Error Err = ImportArrayChecked(
5605 S->labels(), Exprs.begin() + S->getNumOutputs() + S->getNumInputs()))
5606 return std::move(Err);
5607
5608 ExpectedSLoc AsmLocOrErr = import(S->getAsmLoc());
5609 if (!AsmLocOrErr)
5610 return AsmLocOrErr.takeError();
5611 auto AsmStrOrErr = import(S->getAsmString());
5612 if (!AsmStrOrErr)
5613 return AsmStrOrErr.takeError();
5614 ExpectedSLoc RParenLocOrErr = import(S->getRParenLoc());
5615 if (!RParenLocOrErr)
5616 return RParenLocOrErr.takeError();
5617
5618 return new (Importer.getToContext()) GCCAsmStmt(
5619 Importer.getToContext(),
5620 *AsmLocOrErr,
5621 S->isSimple(),
5622 S->isVolatile(),
5623 S->getNumOutputs(),
5624 S->getNumInputs(),
5625 Names.data(),
5626 Constraints.data(),
5627 Exprs.data(),
5628 *AsmStrOrErr,
5629 S->getNumClobbers(),
5630 Clobbers.data(),
5631 S->getNumLabels(),
5632 *RParenLocOrErr);
5633}
5634
5635ExpectedStmt ASTNodeImporter::VisitDeclStmt(DeclStmt *S) {
5636 auto Imp = importSeq(S->getDeclGroup(), S->getBeginLoc(), S->getEndLoc());
5637 if (!Imp)
5638 return Imp.takeError();
5639
5640 DeclGroupRef ToDG;
5641 SourceLocation ToBeginLoc, ToEndLoc;
5642 std::tie(ToDG, ToBeginLoc, ToEndLoc) = *Imp;
5643
5644 return new (Importer.getToContext()) DeclStmt(ToDG, ToBeginLoc, ToEndLoc);
5645}
5646
5647ExpectedStmt ASTNodeImporter::VisitNullStmt(NullStmt *S) {
5648 ExpectedSLoc ToSemiLocOrErr = import(S->getSemiLoc());
5649 if (!ToSemiLocOrErr)
5650 return ToSemiLocOrErr.takeError();
5651 return new (Importer.getToContext()) NullStmt(
5652 *ToSemiLocOrErr, S->hasLeadingEmptyMacro());
5653}
5654
5655ExpectedStmt ASTNodeImporter::VisitCompoundStmt(CompoundStmt *S) {
5656 SmallVector<Stmt *, 8> ToStmts(S->size());
5657
5658 if (Error Err = ImportContainerChecked(S->body(), ToStmts))
5659 return std::move(Err);
5660
5661 ExpectedSLoc ToLBracLocOrErr = import(S->getLBracLoc());
5662 if (!ToLBracLocOrErr)
5663 return ToLBracLocOrErr.takeError();
5664
5665 ExpectedSLoc ToRBracLocOrErr = import(S->getRBracLoc());
5666 if (!ToRBracLocOrErr)
5667 return ToRBracLocOrErr.takeError();
5668
5669 return CompoundStmt::Create(
5670 Importer.getToContext(), ToStmts,
5671 *ToLBracLocOrErr, *ToRBracLocOrErr);
5672}
5673
5674ExpectedStmt ASTNodeImporter::VisitCaseStmt(CaseStmt *S) {
5675 auto Imp = importSeq(
5676 S->getLHS(), S->getRHS(), S->getSubStmt(), S->getCaseLoc(),
5677 S->getEllipsisLoc(), S->getColonLoc());
5678 if (!Imp)
5679 return Imp.takeError();
5680
5681 Expr *ToLHS, *ToRHS;
5682 Stmt *ToSubStmt;
5683 SourceLocation ToCaseLoc, ToEllipsisLoc, ToColonLoc;
5684 std::tie(ToLHS, ToRHS, ToSubStmt, ToCaseLoc, ToEllipsisLoc, ToColonLoc) =
5685 *Imp;
5686
5687 auto *ToStmt = CaseStmt::Create(Importer.getToContext(), ToLHS, ToRHS,
5688 ToCaseLoc, ToEllipsisLoc, ToColonLoc);
5689 ToStmt->setSubStmt(ToSubStmt);
5690
5691 return ToStmt;
5692}
5693
5694ExpectedStmt ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) {
5695 auto Imp = importSeq(S->getDefaultLoc(), S->getColonLoc(), S->getSubStmt());
5696 if (!Imp)
5697 return Imp.takeError();
5698
5699 SourceLocation ToDefaultLoc, ToColonLoc;
5700 Stmt *ToSubStmt;
5701 std::tie(ToDefaultLoc, ToColonLoc, ToSubStmt) = *Imp;
5702
5703 return new (Importer.getToContext()) DefaultStmt(
5704 ToDefaultLoc, ToColonLoc, ToSubStmt);
5705}
5706
5707ExpectedStmt ASTNodeImporter::VisitLabelStmt(LabelStmt *S) {
5708 auto Imp = importSeq(S->getIdentLoc(), S->getDecl(), S->getSubStmt());
5709 if (!Imp)
5710 return Imp.takeError();
5711
5712 SourceLocation ToIdentLoc;
5713 LabelDecl *ToLabelDecl;
5714 Stmt *ToSubStmt;
5715 std::tie(ToIdentLoc, ToLabelDecl, ToSubStmt) = *Imp;
5716
5717 return new (Importer.getToContext()) LabelStmt(
5718 ToIdentLoc, ToLabelDecl, ToSubStmt);
5719}
5720
5721ExpectedStmt ASTNodeImporter::VisitAttributedStmt(AttributedStmt *S) {
5722 ExpectedSLoc ToAttrLocOrErr = import(S->getAttrLoc());
5723 if (!ToAttrLocOrErr)
5724 return ToAttrLocOrErr.takeError();
5725 ArrayRef<const Attr*> FromAttrs(S->getAttrs());
5726 SmallVector<const Attr *, 1> ToAttrs(FromAttrs.size());
5727 if (Error Err = ImportContainerChecked(FromAttrs, ToAttrs))
5728 return std::move(Err);
5729 ExpectedStmt ToSubStmtOrErr = import(S->getSubStmt());
5730 if (!ToSubStmtOrErr)
5731 return ToSubStmtOrErr.takeError();
5732
5733 return AttributedStmt::Create(
5734 Importer.getToContext(), *ToAttrLocOrErr, ToAttrs, *ToSubStmtOrErr);
5735}
5736
5737ExpectedStmt ASTNodeImporter::VisitIfStmt(IfStmt *S) {
5738 auto Imp = importSeq(
5739 S->getIfLoc(), S->getInit(), S->getConditionVariable(), S->getCond(),
5740 S->getThen(), S->getElseLoc(), S->getElse());
5741 if (!Imp)
5742 return Imp.takeError();
5743
5744 SourceLocation ToIfLoc, ToElseLoc;
5745 Stmt *ToInit, *ToThen, *ToElse;
5746 VarDecl *ToConditionVariable;
5747 Expr *ToCond;
5748 std::tie(
5749 ToIfLoc, ToInit, ToConditionVariable, ToCond, ToThen, ToElseLoc, ToElse) =
5750 *Imp;
5751
5752 return IfStmt::Create(Importer.getToContext(), ToIfLoc, S->isConstexpr(),
5753 ToInit, ToConditionVariable, ToCond, ToThen, ToElseLoc,
5754 ToElse);
5755}
5756
5757ExpectedStmt ASTNodeImporter::VisitSwitchStmt(SwitchStmt *S) {
5758 auto Imp = importSeq(
5759 S->getInit(), S->getConditionVariable(), S->getCond(),
5760 S->getBody(), S->getSwitchLoc());
5761 if (!Imp)
5762 return Imp.takeError();
5763
5764 Stmt *ToInit, *ToBody;
5765 VarDecl *ToConditionVariable;
5766 Expr *ToCond;
5767 SourceLocation ToSwitchLoc;
5768 std::tie(ToInit, ToConditionVariable, ToCond, ToBody, ToSwitchLoc) = *Imp;
5769
5770 auto *ToStmt = SwitchStmt::Create(Importer.getToContext(), ToInit,
5771 ToConditionVariable, ToCond);
5772 ToStmt->setBody(ToBody);
5773 ToStmt->setSwitchLoc(ToSwitchLoc);
5774
5775 // Now we have to re-chain the cases.
5776 SwitchCase *LastChainedSwitchCase = nullptr;
5777 for (SwitchCase *SC = S->getSwitchCaseList(); SC != nullptr;
5778 SC = SC->getNextSwitchCase()) {
5779 Expected<SwitchCase *> ToSCOrErr = import(SC);
5780 if (!ToSCOrErr)
5781 return ToSCOrErr.takeError();
5782 if (LastChainedSwitchCase)
5783 LastChainedSwitchCase->setNextSwitchCase(*ToSCOrErr);
5784 else
5785 ToStmt->setSwitchCaseList(*ToSCOrErr);
5786 LastChainedSwitchCase = *ToSCOrErr;
5787 }
5788
5789 return ToStmt;
5790}
5791
5792ExpectedStmt ASTNodeImporter::VisitWhileStmt(WhileStmt *S) {
5793 auto Imp = importSeq(
5794 S->getConditionVariable(), S->getCond(), S->getBody(), S->getWhileLoc());
5795 if (!Imp)
5796 return Imp.takeError();
5797
5798 VarDecl *ToConditionVariable;
5799 Expr *ToCond;
5800 Stmt *ToBody;
5801 SourceLocation ToWhileLoc;
5802 std::tie(ToConditionVariable, ToCond, ToBody, ToWhileLoc) = *Imp;
5803
5804 return WhileStmt::Create(Importer.getToContext(), ToConditionVariable, ToCond,
5805 ToBody, ToWhileLoc);
5806}
5807
5808ExpectedStmt ASTNodeImporter::VisitDoStmt(DoStmt *S) {
5809 auto Imp = importSeq(
5810 S->getBody(), S->getCond(), S->getDoLoc(), S->getWhileLoc(),
5811 S->getRParenLoc());
5812 if (!Imp)
5813 return Imp.takeError();
5814
5815 Stmt *ToBody;
5816 Expr *ToCond;
5817 SourceLocation ToDoLoc, ToWhileLoc, ToRParenLoc;
5818 std::tie(ToBody, ToCond, ToDoLoc, ToWhileLoc, ToRParenLoc) = *Imp;
5819
5820 return new (Importer.getToContext()) DoStmt(
5821 ToBody, ToCond, ToDoLoc, ToWhileLoc, ToRParenLoc);
5822}
5823
5824ExpectedStmt ASTNodeImporter::VisitForStmt(ForStmt *S) {
5825 auto Imp = importSeq(
5826 S->getInit(), S->getCond(), S->getConditionVariable(), S->getInc(),
5827 S->getBody(), S->getForLoc(), S->getLParenLoc(), S->getRParenLoc());
5828 if (!Imp)
5829 return Imp.takeError();
5830
5831 Stmt *ToInit;
5832 Expr *ToCond, *ToInc;
5833 VarDecl *ToConditionVariable;
5834 Stmt *ToBody;
5835 SourceLocation ToForLoc, ToLParenLoc, ToRParenLoc;
5836 std::tie(
5837 ToInit, ToCond, ToConditionVariable, ToInc, ToBody, ToForLoc,
5838 ToLParenLoc, ToRParenLoc) = *Imp;
5839
5840 return new (Importer.getToContext()) ForStmt(
5841 Importer.getToContext(),
5842 ToInit, ToCond, ToConditionVariable, ToInc, ToBody, ToForLoc, ToLParenLoc,
5843 ToRParenLoc);
5844}
5845
5846ExpectedStmt ASTNodeImporter::VisitGotoStmt(GotoStmt *S) {
5847 auto Imp = importSeq(S->getLabel(), S->getGotoLoc(), S->getLabelLoc());
5848 if (!Imp)
5849 return Imp.takeError();
5850
5851 LabelDecl *ToLabel;
5852 SourceLocation ToGotoLoc, ToLabelLoc;
5853 std::tie(ToLabel, ToGotoLoc, ToLabelLoc) = *Imp;
5854
5855 return new (Importer.getToContext()) GotoStmt(
5856 ToLabel, ToGotoLoc, ToLabelLoc);
5857}
5858
5859ExpectedStmt ASTNodeImporter::VisitIndirectGotoStmt(IndirectGotoStmt *S) {
5860 auto Imp = importSeq(S->getGotoLoc(), S->getStarLoc(), S->getTarget());
5861 if (!Imp)
5862 return Imp.takeError();
5863
5864 SourceLocation ToGotoLoc, ToStarLoc;
5865 Expr *ToTarget;
5866 std::tie(ToGotoLoc, ToStarLoc, ToTarget) = *Imp;
5867
5868 return new (Importer.getToContext()) IndirectGotoStmt(
5869 ToGotoLoc, ToStarLoc, ToTarget);
5870}
5871
5872ExpectedStmt ASTNodeImporter::VisitContinueStmt(ContinueStmt *S) {
5873 ExpectedSLoc ToContinueLocOrErr = import(S->getContinueLoc());
5874 if (!ToContinueLocOrErr)
5875 return ToContinueLocOrErr.takeError();
5876 return new (Importer.getToContext()) ContinueStmt(*ToContinueLocOrErr);
5877}
5878
5879ExpectedStmt ASTNodeImporter::VisitBreakStmt(BreakStmt *S) {
5880 auto ToBreakLocOrErr = import(S->getBreakLoc());
5881 if (!ToBreakLocOrErr)
5882 return ToBreakLocOrErr.takeError();
5883 return new (Importer.getToContext()) BreakStmt(*ToBreakLocOrErr);
5884}
5885
5886ExpectedStmt ASTNodeImporter::VisitReturnStmt(ReturnStmt *S) {
5887 auto Imp = importSeq(
5888 S->getReturnLoc(), S->getRetValue(), S->getNRVOCandidate());
5889 if (!Imp)
5890 return Imp.takeError();
5891
5892 SourceLocation ToReturnLoc;
5893 Expr *ToRetValue;
5894 const VarDecl *ToNRVOCandidate;
5895 std::tie(ToReturnLoc, ToRetValue, ToNRVOCandidate) = *Imp;
5896
5897 return ReturnStmt::Create(Importer.getToContext(), ToReturnLoc, ToRetValue,
5898 ToNRVOCandidate);
5899}
5900
5901ExpectedStmt ASTNodeImporter::VisitCXXCatchStmt(CXXCatchStmt *S) {
5902 auto Imp = importSeq(
5903 S->getCatchLoc(), S->getExceptionDecl(), S->getHandlerBlock());
5904 if (!Imp)
5905 return Imp.takeError();
5906
5907 SourceLocation ToCatchLoc;
5908 VarDecl *ToExceptionDecl;
5909 Stmt *ToHandlerBlock;
5910 std::tie(ToCatchLoc, ToExceptionDecl, ToHandlerBlock) = *Imp;
5911
5912 return new (Importer.getToContext()) CXXCatchStmt (
5913 ToCatchLoc, ToExceptionDecl, ToHandlerBlock);
5914}
5915
5916ExpectedStmt ASTNodeImporter::VisitCXXTryStmt(CXXTryStmt *S) {
5917 ExpectedSLoc ToTryLocOrErr = import(S->getTryLoc());
5918 if (!ToTryLocOrErr)
5919 return ToTryLocOrErr.takeError();
5920
5921 ExpectedStmt ToTryBlockOrErr = import(S->getTryBlock());
5922 if (!ToTryBlockOrErr)
5923 return ToTryBlockOrErr.takeError();
5924
5925 SmallVector<Stmt *, 1> ToHandlers(S->getNumHandlers());
5926 for (unsigned HI = 0, HE = S->getNumHandlers(); HI != HE; ++HI) {
5927 CXXCatchStmt *FromHandler = S->getHandler(HI);
5928 if (auto ToHandlerOrErr = import(FromHandler))
5929 ToHandlers[HI] = *ToHandlerOrErr;
5930 else
5931 return ToHandlerOrErr.takeError();
5932 }
5933
5934 return CXXTryStmt::Create(
5935 Importer.getToContext(), *ToTryLocOrErr,*ToTryBlockOrErr, ToHandlers);
5936}
5937
5938ExpectedStmt ASTNodeImporter::VisitCXXForRangeStmt(CXXForRangeStmt *S) {
5939 auto Imp1 = importSeq(
5940 S->getInit(), S->getRangeStmt(), S->getBeginStmt(), S->getEndStmt(),
5941 S->getCond(), S->getInc(), S->getLoopVarStmt(), S->getBody());
5942 if (!Imp1)
5943 return Imp1.takeError();
5944 auto Imp2 = importSeq(
5945 S->getForLoc(), S->getCoawaitLoc(), S->getColonLoc(), S->getRParenLoc());
5946 if (!Imp2)
5947 return Imp2.takeError();
5948
5949 DeclStmt *ToRangeStmt, *ToBeginStmt, *ToEndStmt, *ToLoopVarStmt;
5950 Expr *ToCond, *ToInc;
5951 Stmt *ToInit, *ToBody;
5952 std::tie(
5953 ToInit, ToRangeStmt, ToBeginStmt, ToEndStmt, ToCond, ToInc, ToLoopVarStmt,
5954 ToBody) = *Imp1;
5955 SourceLocation ToForLoc, ToCoawaitLoc, ToColonLoc, ToRParenLoc;
5956 std::tie(ToForLoc, ToCoawaitLoc, ToColonLoc, ToRParenLoc) = *Imp2;
5957
5958 return new (Importer.getToContext()) CXXForRangeStmt(
5959 ToInit, ToRangeStmt, ToBeginStmt, ToEndStmt, ToCond, ToInc, ToLoopVarStmt,
5960 ToBody, ToForLoc, ToCoawaitLoc, ToColonLoc, ToRParenLoc);
5961}
5962
5963ExpectedStmt
5964ASTNodeImporter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) {
5965 auto Imp = importSeq(
5966 S->getElement(), S->getCollection(), S->getBody(),
5967 S->getForLoc(), S->getRParenLoc());
5968 if (!Imp)
5969 return Imp.takeError();
5970
5971 Stmt *ToElement, *ToBody;
5972 Expr *ToCollection;
5973 SourceLocation ToForLoc, ToRParenLoc;
5974 std::tie(ToElement, ToCollection, ToBody, ToForLoc, ToRParenLoc) = *Imp;
5975
5976 return new (Importer.getToContext()) ObjCForCollectionStmt(ToElement,
5977 ToCollection,
5978 ToBody,
5979 ToForLoc,
5980 ToRParenLoc);
5981}
5982
5983ExpectedStmt ASTNodeImporter::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) {
5984 auto Imp = importSeq(
5985 S->getAtCatchLoc(), S->getRParenLoc(), S->getCatchParamDecl(),
5986 S->getCatchBody());
5987 if (!Imp)
5988 return Imp.takeError();
5989
5990 SourceLocation ToAtCatchLoc, ToRParenLoc;
5991 VarDecl *ToCatchParamDecl;
5992 Stmt *ToCatchBody;
5993 std::tie(ToAtCatchLoc, ToRParenLoc, ToCatchParamDecl, ToCatchBody) = *Imp;
5994
5995 return new (Importer.getToContext()) ObjCAtCatchStmt (
5996 ToAtCatchLoc, ToRParenLoc, ToCatchParamDecl, ToCatchBody);
5997}
5998
5999ExpectedStmt ASTNodeImporter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S) {
6000 ExpectedSLoc ToAtFinallyLocOrErr = import(S->getAtFinallyLoc());
6001 if (!ToAtFinallyLocOrErr)
6002 return ToAtFinallyLocOrErr.takeError();
6003 ExpectedStmt ToAtFinallyStmtOrErr = import(S->getFinallyBody());
6004 if (!ToAtFinallyStmtOrErr)
6005 return ToAtFinallyStmtOrErr.takeError();
6006 return new (Importer.getToContext()) ObjCAtFinallyStmt(*ToAtFinallyLocOrErr,
6007 *ToAtFinallyStmtOrErr);
6008}
6009
6010ExpectedStmt ASTNodeImporter::VisitObjCAtTryStmt(ObjCAtTryStmt *S) {
6011 auto Imp = importSeq(
6012 S->getAtTryLoc(), S->getTryBody(), S->getFinallyStmt());
6013 if (!Imp)
6014 return Imp.takeError();
6015
6016 SourceLocation ToAtTryLoc;
6017 Stmt *ToTryBody, *ToFinallyStmt;
6018 std::tie(ToAtTryLoc, ToTryBody, ToFinallyStmt) = *Imp;
6019
6020 SmallVector<Stmt *, 1> ToCatchStmts(S->getNumCatchStmts());
6021 for (unsigned CI = 0, CE = S->getNumCatchStmts(); CI != CE; ++CI) {
6022 ObjCAtCatchStmt *FromCatchStmt = S->getCatchStmt(CI);
6023 if (ExpectedStmt ToCatchStmtOrErr = import(FromCatchStmt))
6024 ToCatchStmts[CI] = *ToCatchStmtOrErr;
6025 else
6026 return ToCatchStmtOrErr.takeError();
6027 }
6028
6029 return ObjCAtTryStmt::Create(Importer.getToContext(),
6030 ToAtTryLoc, ToTryBody,
6031 ToCatchStmts.begin(), ToCatchStmts.size(),
6032 ToFinallyStmt);
6033}
6034
6035ExpectedStmt ASTNodeImporter::VisitObjCAtSynchronizedStmt
6036 (ObjCAtSynchronizedStmt *S) {
6037 auto Imp = importSeq(
6038 S->getAtSynchronizedLoc(), S->getSynchExpr(), S->getSynchBody());
6039 if (!Imp)
6040 return Imp.takeError();
6041
6042 SourceLocation ToAtSynchronizedLoc;
6043 Expr *ToSynchExpr;
6044 Stmt *ToSynchBody;
6045 std::tie(ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody) = *Imp;
6046
6047 return new (Importer.getToContext()) ObjCAtSynchronizedStmt(
6048 ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody);
6049}
6050
6051ExpectedStmt ASTNodeImporter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) {
6052 ExpectedSLoc ToThrowLocOrErr = import(S->getThrowLoc());
6053 if (!ToThrowLocOrErr)
6054 return ToThrowLocOrErr.takeError();
6055 ExpectedExpr ToThrowExprOrErr = import(S->getThrowExpr());
6056 if (!ToThrowExprOrErr)
6057 return ToThrowExprOrErr.takeError();
6058 return new (Importer.getToContext()) ObjCAtThrowStmt(
6059 *ToThrowLocOrErr, *ToThrowExprOrErr);
6060}
6061
6062ExpectedStmt ASTNodeImporter::VisitObjCAutoreleasePoolStmt(
6063 ObjCAutoreleasePoolStmt *S) {
6064 ExpectedSLoc ToAtLocOrErr = import(S->getAtLoc());
6065 if (!ToAtLocOrErr)
6066 return ToAtLocOrErr.takeError();
6067 ExpectedStmt ToSubStmtOrErr = import(S->getSubStmt());
6068 if (!ToSubStmtOrErr)
6069 return ToSubStmtOrErr.takeError();
6070 return new (Importer.getToContext()) ObjCAutoreleasePoolStmt(*ToAtLocOrErr,
6071 *ToSubStmtOrErr);
6072}
6073
6074//----------------------------------------------------------------------------
6075// Import Expressions
6076//----------------------------------------------------------------------------
6077ExpectedStmt ASTNodeImporter::VisitExpr(Expr *E) {
6078 Importer.FromDiag(E->getBeginLoc(), diag::err_unsupported_ast_node)
6079 << E->getStmtClassName();
6080 return make_error<ImportError>(ImportError::UnsupportedConstruct);
6081}
6082
6083ExpectedStmt ASTNodeImporter::VisitVAArgExpr(VAArgExpr *E) {
6084 auto Imp = importSeq(
6085 E->getBuiltinLoc(), E->getSubExpr(), E->getWrittenTypeInfo(),
6086 E->getRParenLoc(), E->getType());
6087 if (!Imp)
6088 return Imp.takeError();
6089
6090 SourceLocation ToBuiltinLoc, ToRParenLoc;
6091 Expr *ToSubExpr;
6092 TypeSourceInfo *ToWrittenTypeInfo;
6093 QualType ToType;
6094 std::tie(ToBuiltinLoc, ToSubExpr, ToWrittenTypeInfo, ToRParenLoc, ToType) =
6095 *Imp;
6096
6097 return new (Importer.getToContext()) VAArgExpr(
6098 ToBuiltinLoc, ToSubExpr, ToWrittenTypeInfo, ToRParenLoc, ToType,
6099 E->isMicrosoftABI());
6100}
6101
6102ExpectedStmt ASTNodeImporter::VisitChooseExpr(ChooseExpr *E) {
6103 auto Imp = importSeq(E->getCond(), E->getLHS(), E->getRHS(),
6104 E->getBuiltinLoc(), E->getRParenLoc(), E->getType());
6105 if (!Imp)
6106 return Imp.takeError();
6107
6108 Expr *ToCond;
6109 Expr *ToLHS;
6110 Expr *ToRHS;
6111 SourceLocation ToBuiltinLoc, ToRParenLoc;
6112 QualType ToType;
6113 std::tie(ToCond, ToLHS, ToRHS, ToBuiltinLoc, ToRParenLoc, ToType) = *Imp;
6114
6115 ExprValueKind VK = E->getValueKind();
6116 ExprObjectKind OK = E->getObjectKind();
6117
6118 bool TypeDependent = ToCond->isTypeDependent();
6119 bool ValueDependent = ToCond->isValueDependent();
6120
6121 // The value of CondIsTrue only matters if the value is not
6122 // condition-dependent.
6123 bool CondIsTrue = !E->isConditionDependent() && E->isConditionTrue();
6124
6125 return new (Importer.getToContext())
6126 ChooseExpr(ToBuiltinLoc, ToCond, ToLHS, ToRHS, ToType, VK, OK,
6127 ToRParenLoc, CondIsTrue, TypeDependent, ValueDependent);
6128}
6129
6130ExpectedStmt ASTNodeImporter::VisitGNUNullExpr(GNUNullExpr *E) {
6131 ExpectedType TypeOrErr = import(E->getType());
6132 if (!TypeOrErr)
6133 return TypeOrErr.takeError();
6134
6135 ExpectedSLoc BeginLocOrErr = import(E->getBeginLoc());
6136 if (!BeginLocOrErr)
6137 return BeginLocOrErr.takeError();
6138
6139 return new (Importer.getToContext()) GNUNullExpr(*TypeOrErr, *BeginLocOrErr);
6140}
6141
6142ExpectedStmt ASTNodeImporter::VisitPredefinedExpr(PredefinedExpr *E) {
6143 auto Imp = importSeq(
6144 E->getBeginLoc(), E->getType(), E->getFunctionName());
6145 if (!Imp)
6146 return Imp.takeError();
6147
6148 SourceLocation ToBeginLoc;
6149 QualType ToType;
6150 StringLiteral *ToFunctionName;
6151 std::tie(ToBeginLoc, ToType, ToFunctionName) = *Imp;
6152
6153 return PredefinedExpr::Create(Importer.getToContext(), ToBeginLoc, ToType,
6154 E->getIdentKind(), ToFunctionName);
6155}
6156
6157ExpectedStmt ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) {
6158 auto Imp = importSeq(
6159 E->getQualifierLoc(), E->getTemplateKeywordLoc(), E->getDecl(),
6160 E->getLocation(), E->getType());
6161 if (!Imp)
6162 return Imp.takeError();
6163
6164 NestedNameSpecifierLoc ToQualifierLoc;
6165 SourceLocation ToTemplateKeywordLoc, ToLocation;
6166 ValueDecl *ToDecl;
6167 QualType ToType;
6168 std::tie(ToQualifierLoc, ToTemplateKeywordLoc, ToDecl, ToLocation, ToType) =
6169 *Imp;
6170
6171 NamedDecl *ToFoundD = nullptr;
6172 if (E->getDecl() != E->getFoundDecl()) {
6173 auto FoundDOrErr = import(E->getFoundDecl());
6174 if (!FoundDOrErr)
6175 return FoundDOrErr.takeError();
6176 ToFoundD = *FoundDOrErr;
6177 }
6178
6179 TemplateArgumentListInfo ToTAInfo;
6180 TemplateArgumentListInfo *ToResInfo = nullptr;
6181 if (E->hasExplicitTemplateArgs()) {
6182 if (Error Err =
6183 ImportTemplateArgumentListInfo(E->template_arguments(), ToTAInfo))
6184 return std::move(Err);
6185 ToResInfo = &ToTAInfo;
6186 }
6187
6188 auto *ToE = DeclRefExpr::Create(
6189 Importer.getToContext(), ToQualifierLoc, ToTemplateKeywordLoc, ToDecl,
6190 E->refersToEnclosingVariableOrCapture(), ToLocation, ToType,
6191 E->getValueKind(), ToFoundD, ToResInfo);
6192 if (E->hadMultipleCandidates())
6193 ToE->setHadMultipleCandidates(true);
6194 return ToE;
6195}
6196
6197ExpectedStmt ASTNodeImporter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) {
6198 ExpectedType TypeOrErr = import(E->getType());
6199 if (!TypeOrErr)
6200 return TypeOrErr.takeError();
6201
6202 return new (Importer.getToContext()) ImplicitValueInitExpr(*TypeOrErr);
6203}
6204
6205ExpectedStmt ASTNodeImporter::VisitDesignatedInitExpr(DesignatedInitExpr *E) {
6206 ExpectedExpr ToInitOrErr = import(E->getInit());
6207 if (!ToInitOrErr)
6208 return ToInitOrErr.takeError();
6209
6210 ExpectedSLoc ToEqualOrColonLocOrErr = import(E->getEqualOrColonLoc());
6211 if (!ToEqualOrColonLocOrErr)
6212 return ToEqualOrColonLocOrErr.takeError();
6213
6214 SmallVector<Expr *, 4> ToIndexExprs(E->getNumSubExprs() - 1);
6215 // List elements from the second, the first is Init itself
6216 for (unsigned I = 1, N = E->getNumSubExprs(); I < N; I++) {
6217 if (ExpectedExpr ToArgOrErr = import(E->getSubExpr(I)))
6218 ToIndexExprs[I - 1] = *ToArgOrErr;
6219 else
6220 return ToArgOrErr.takeError();
6221 }
6222
6223 SmallVector<Designator, 4> ToDesignators(E->size());
6224 if (Error Err = ImportContainerChecked(E->designators(), ToDesignators))
6225 return std::move(Err);
6226
6227 return DesignatedInitExpr::Create(
6228 Importer.getToContext(), ToDesignators,
6229 ToIndexExprs, *ToEqualOrColonLocOrErr,
6230 E->usesGNUSyntax(), *ToInitOrErr);
6231}
6232
6233ExpectedStmt
6234ASTNodeImporter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E) {
6235 ExpectedType ToTypeOrErr = import(E->getType());
6236 if (!ToTypeOrErr)
6237 return ToTypeOrErr.takeError();
6238
6239 ExpectedSLoc ToLocationOrErr = import(E->getLocation());
6240 if (!ToLocationOrErr)
6241 return ToLocationOrErr.takeError();
6242
6243 return new (Importer.getToContext()) CXXNullPtrLiteralExpr(
6244 *ToTypeOrErr, *ToLocationOrErr);
6245}
6246
6247ExpectedStmt ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) {
6248 ExpectedType ToTypeOrErr = import(E->getType());
6249 if (!ToTypeOrErr)
6250 return ToTypeOrErr.takeError();
6251
6252 ExpectedSLoc ToLocationOrErr = import(E->getLocation());
6253 if (!ToLocationOrErr)
6254 return ToLocationOrErr.takeError();
6255
6256 return IntegerLiteral::Create(
6257 Importer.getToContext(), E->getValue(), *ToTypeOrErr, *ToLocationOrErr);
6258}
6259
6260
6261ExpectedStmt ASTNodeImporter::VisitFloatingLiteral(FloatingLiteral *E) {
6262 ExpectedType ToTypeOrErr = import(E->getType());
6263 if (!ToTypeOrErr)
6264 return ToTypeOrErr.takeError();
6265
6266 ExpectedSLoc ToLocationOrErr = import(E->getLocation());
6267 if (!ToLocationOrErr)
6268 return ToLocationOrErr.takeError();
6269
6270 return FloatingLiteral::Create(
6271 Importer.getToContext(), E->getValue(), E->isExact(),
6272 *ToTypeOrErr, *ToLocationOrErr);
6273}
6274
6275ExpectedStmt ASTNodeImporter::VisitImaginaryLiteral(ImaginaryLiteral *E) {
6276 auto ToTypeOrErr = import(E->getType());
6277 if (!ToTypeOrErr)
6278 return ToTypeOrErr.takeError();
6279
6280 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr());
6281 if (!ToSubExprOrErr)
6282 return ToSubExprOrErr.takeError();
6283
6284 return new (Importer.getToContext()) ImaginaryLiteral(
6285 *ToSubExprOrErr, *ToTypeOrErr);
6286}
6287
6288ExpectedStmt ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) {
6289 ExpectedType ToTypeOrErr = import(E->getType());
6290 if (!ToTypeOrErr)
6291 return ToTypeOrErr.takeError();
6292
6293 ExpectedSLoc ToLocationOrErr = import(E->getLocation());
6294 if (!ToLocationOrErr)
6295 return ToLocationOrErr.takeError();
6296
6297 return new (Importer.getToContext()) CharacterLiteral(
6298 E->getValue(), E->getKind(), *ToTypeOrErr, *ToLocationOrErr);
6299}
6300
6301ExpectedStmt ASTNodeImporter::VisitStringLiteral(StringLiteral *E) {
6302 ExpectedType ToTypeOrErr = import(E->getType());
6303 if (!ToTypeOrErr)
6304 return ToTypeOrErr.takeError();
6305
6306 SmallVector<SourceLocation, 4> ToLocations(E->getNumConcatenated());
6307 if (Error Err = ImportArrayChecked(
6308 E->tokloc_begin(), E->tokloc_end(), ToLocations.begin()))
6309 return std::move(Err);
6310
6311 return StringLiteral::Create(
6312 Importer.getToContext(), E->getBytes(), E->getKind(), E->isPascal(),
6313 *ToTypeOrErr, ToLocations.data(), ToLocations.size());
6314}
6315
6316ExpectedStmt ASTNodeImporter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) {
6317 auto Imp = importSeq(
6318 E->getLParenLoc(), E->getTypeSourceInfo(), E->getType(),
6319 E->getInitializer());
6320 if (!Imp)
6321 return Imp.takeError();
6322
6323 SourceLocation ToLParenLoc;
6324 TypeSourceInfo *ToTypeSourceInfo;
6325 QualType ToType;
6326 Expr *ToInitializer;
6327 std::tie(ToLParenLoc, ToTypeSourceInfo, ToType, ToInitializer) = *Imp;
6328
6329 return new (Importer.getToContext()) CompoundLiteralExpr(
6330 ToLParenLoc, ToTypeSourceInfo, ToType, E->getValueKind(),
6331 ToInitializer, E->isFileScope());
6332}
6333
6334ExpectedStmt ASTNodeImporter::VisitAtomicExpr(AtomicExpr *E) {
6335 auto Imp = importSeq(
6336 E->getBuiltinLoc(), E->getType(), E->getRParenLoc());
6337 if (!Imp)
6338 return Imp.takeError();
6339
6340 SourceLocation ToBuiltinLoc, ToRParenLoc;
6341 QualType ToType;
6342 std::tie(ToBuiltinLoc, ToType, ToRParenLoc) = *Imp;
6343
6344 SmallVector<Expr *, 6> ToExprs(E->getNumSubExprs());
6345 if (Error Err = ImportArrayChecked(
6346 E->getSubExprs(), E->getSubExprs() + E->getNumSubExprs(),
6347 ToExprs.begin()))
6348 return std::move(Err);
6349
6350 return new (Importer.getToContext()) AtomicExpr(
6351 ToBuiltinLoc, ToExprs, ToType, E->getOp(), ToRParenLoc);
6352}
6353
6354ExpectedStmt ASTNodeImporter::VisitAddrLabelExpr(AddrLabelExpr *E) {
6355 auto Imp = importSeq(
6356 E->getAmpAmpLoc(), E->getLabelLoc(), E->getLabel(), E->getType());
6357 if (!Imp)
6358 return Imp.takeError();
6359
6360 SourceLocation ToAmpAmpLoc, ToLabelLoc;
6361 LabelDecl *ToLabel;
6362 QualType ToType;
6363 std::tie(ToAmpAmpLoc, ToLabelLoc, ToLabel, ToType) = *Imp;
6364
6365 return new (Importer.getToContext()) AddrLabelExpr(
6366 ToAmpAmpLoc, ToLabelLoc, ToLabel, ToType);
6367}
6368
6369ExpectedStmt ASTNodeImporter::VisitConstantExpr(ConstantExpr *E) {
6370 auto Imp = importSeq(E->getSubExpr());
6371 if (!Imp)
6372 return Imp.takeError();
6373
6374 Expr *ToSubExpr;
6375 std::tie(ToSubExpr) = *Imp;
6376
6377 return ConstantExpr::Create(Importer.getToContext(), ToSubExpr);
6378}
6379
6380ExpectedStmt ASTNodeImporter::VisitParenExpr(ParenExpr *E) {
6381 auto Imp = importSeq(E->getLParen(), E->getRParen(), E->getSubExpr());
6382 if (!Imp)
6383 return Imp.takeError();
6384
6385 SourceLocation ToLParen, ToRParen;
6386 Expr *ToSubExpr;
6387 std::tie(ToLParen, ToRParen, ToSubExpr) = *Imp;
6388
6389 return new (Importer.getToContext())
6390 ParenExpr(ToLParen, ToRParen, ToSubExpr);
6391}
6392
6393ExpectedStmt ASTNodeImporter::VisitParenListExpr(ParenListExpr *E) {
6394 SmallVector<Expr *, 4> ToExprs(E->getNumExprs());
6395 if (Error Err = ImportContainerChecked(E->exprs(), ToExprs))
6396 return std::move(Err);
6397
6398 ExpectedSLoc ToLParenLocOrErr = import(E->getLParenLoc());
6399 if (!ToLParenLocOrErr)
6400 return ToLParenLocOrErr.takeError();
6401
6402 ExpectedSLoc ToRParenLocOrErr = import(E->getRParenLoc());
6403 if (!ToRParenLocOrErr)
6404 return ToRParenLocOrErr.takeError();
6405
6406 return ParenListExpr::Create(Importer.getToContext(), *ToLParenLocOrErr,
6407 ToExprs, *ToRParenLocOrErr);
6408}
6409
6410ExpectedStmt ASTNodeImporter::VisitStmtExpr(StmtExpr *E) {
6411 auto Imp = importSeq(
6412 E->getSubStmt(), E->getType(), E->getLParenLoc(), E->getRParenLoc());