Bug Summary

File:tools/clang/lib/AST/ASTImporter.cpp
Warning:line 246, column 16
2nd function call argument is an uninitialized value

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-8/lib/clang/8.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-8~svn350071/build-llvm/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/AST -I /build/llvm-toolchain-snapshot-8~svn350071/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn350071/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn350071/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/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.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-8~svn350071/build-llvm/tools/clang/lib/AST -fdebug-prefix-map=/build/llvm-toolchain-snapshot-8~svn350071=. -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-2018-12-27-042839-1215-1 -x c++ /build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/AST/ASTImporter.cpp -faddrsig

/build/llvm-toolchain-snapshot-8~svn350071/tools/clang/lib/AST/ASTImporter.cpp

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