1 //===- ASTImporter.cpp - Importing ASTs from other Contexts ---------------===// 2 // 3 // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions. 4 // See https://llvm.org/LICENSE.txt for license information. 5 // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception 6 // 7 //===----------------------------------------------------------------------===// 8 // 9 // This file defines the ASTImporter class which imports AST nodes from one 10 // context into another context. 11 // 12 //===----------------------------------------------------------------------===// 13 14 #include "clang/AST/ASTImporter.h" 15 #include "clang/AST/ASTImporterSharedState.h" 16 #include "clang/AST/ASTContext.h" 17 #include "clang/AST/ASTDiagnostic.h" 18 #include "clang/AST/ASTStructuralEquivalence.h" 19 #include "clang/AST/Attr.h" 20 #include "clang/AST/Decl.h" 21 #include "clang/AST/DeclAccessPair.h" 22 #include "clang/AST/DeclBase.h" 23 #include "clang/AST/DeclCXX.h" 24 #include "clang/AST/DeclFriend.h" 25 #include "clang/AST/DeclGroup.h" 26 #include "clang/AST/DeclObjC.h" 27 #include "clang/AST/DeclTemplate.h" 28 #include "clang/AST/DeclVisitor.h" 29 #include "clang/AST/DeclarationName.h" 30 #include "clang/AST/Expr.h" 31 #include "clang/AST/ExprCXX.h" 32 #include "clang/AST/ExprObjC.h" 33 #include "clang/AST/ExternalASTSource.h" 34 #include "clang/AST/LambdaCapture.h" 35 #include "clang/AST/NestedNameSpecifier.h" 36 #include "clang/AST/OperationKinds.h" 37 #include "clang/AST/Stmt.h" 38 #include "clang/AST/StmtCXX.h" 39 #include "clang/AST/StmtObjC.h" 40 #include "clang/AST/StmtVisitor.h" 41 #include "clang/AST/TemplateBase.h" 42 #include "clang/AST/TemplateName.h" 43 #include "clang/AST/Type.h" 44 #include "clang/AST/TypeLoc.h" 45 #include "clang/AST/TypeVisitor.h" 46 #include "clang/AST/UnresolvedSet.h" 47 #include "clang/Basic/Builtins.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/ScopeExit.h" 62 #include "llvm/ADT/STLExtras.h" 63 #include "llvm/ADT/SmallVector.h" 64 #include "llvm/Support/Casting.h" 65 #include "llvm/Support/ErrorHandling.h" 66 #include "llvm/Support/MemoryBuffer.h" 67 #include <algorithm> 68 #include <cassert> 69 #include <cstddef> 70 #include <memory> 71 #include <type_traits> 72 #include <utility> 73 74 namespace clang { 75 76 using llvm::make_error; 77 using llvm::Error; 78 using llvm::Expected; 79 using ExpectedType = llvm::Expected<QualType>; 80 using ExpectedStmt = llvm::Expected<Stmt *>; 81 using ExpectedExpr = llvm::Expected<Expr *>; 82 using ExpectedDecl = llvm::Expected<Decl *>; 83 using ExpectedSLoc = llvm::Expected<SourceLocation>; 84 using ExpectedName = llvm::Expected<DeclarationName>; 85 86 std::string ImportError::toString() const { 87 // FIXME: Improve error texts. 88 switch (Error) { 89 case NameConflict: 90 return "NameConflict"; 91 case UnsupportedConstruct: 92 return "UnsupportedConstruct"; 93 case Unknown: 94 return "Unknown error"; 95 } 96 llvm_unreachable("Invalid error code."); 97 return "Invalid error code."; 98 } 99 100 void ImportError::log(raw_ostream &OS) const { 101 OS << toString(); 102 } 103 104 std::error_code ImportError::convertToErrorCode() const { 105 llvm_unreachable("Function not implemented."); 106 } 107 108 char ImportError::ID; 109 110 template <class T> 111 SmallVector<Decl *, 2> 112 getCanonicalForwardRedeclChain(Redeclarable<T>* D) { 113 SmallVector<Decl *, 2> Redecls; 114 for (auto *R : D->getFirstDecl()->redecls()) { 115 if (R != D->getFirstDecl()) 116 Redecls.push_back(R); 117 } 118 Redecls.push_back(D->getFirstDecl()); 119 std::reverse(Redecls.begin(), Redecls.end()); 120 return Redecls; 121 } 122 123 SmallVector<Decl*, 2> getCanonicalForwardRedeclChain(Decl* D) { 124 if (auto *FD = dyn_cast<FunctionDecl>(D)) 125 return getCanonicalForwardRedeclChain<FunctionDecl>(FD); 126 if (auto *VD = dyn_cast<VarDecl>(D)) 127 return getCanonicalForwardRedeclChain<VarDecl>(VD); 128 if (auto *TD = dyn_cast<TagDecl>(D)) 129 return getCanonicalForwardRedeclChain<TagDecl>(TD); 130 llvm_unreachable("Bad declaration kind"); 131 } 132 133 void updateFlags(const Decl *From, Decl *To) { 134 // Check if some flags or attrs are new in 'From' and copy into 'To'. 135 // FIXME: Other flags or attrs? 136 if (From->isUsed(false) && !To->isUsed(false)) 137 To->setIsUsed(); 138 } 139 140 class ASTNodeImporter : public TypeVisitor<ASTNodeImporter, ExpectedType>, 141 public DeclVisitor<ASTNodeImporter, ExpectedDecl>, 142 public StmtVisitor<ASTNodeImporter, ExpectedStmt> { 143 ASTImporter &Importer; 144 145 // Use this instead of Importer.importInto . 146 template <typename ImportT> 147 LLVM_NODISCARD Error importInto(ImportT &To, const ImportT &From) { 148 return Importer.importInto(To, From); 149 } 150 151 // Use this to import pointers of specific type. 152 template <typename ImportT> 153 LLVM_NODISCARD Error importInto(ImportT *&To, ImportT *From) { 154 auto ToOrErr = Importer.Import(From); 155 if (ToOrErr) 156 To = cast_or_null<ImportT>(*ToOrErr); 157 return ToOrErr.takeError(); 158 } 159 160 // Call the import function of ASTImporter for a baseclass of type `T` and 161 // cast the return value to `T`. 162 template <typename T> 163 Expected<T *> import(T *From) { 164 auto ToOrErr = Importer.Import(From); 165 if (!ToOrErr) 166 return ToOrErr.takeError(); 167 return cast_or_null<T>(*ToOrErr); 168 } 169 170 template <typename T> 171 Expected<T *> import(const T *From) { 172 return import(const_cast<T *>(From)); 173 } 174 175 // Call the import function of ASTImporter for type `T`. 176 template <typename T> 177 Expected<T> import(const T &From) { 178 return Importer.Import(From); 179 } 180 181 // Import an Optional<T> by importing the contained T, if any. 182 template<typename T> 183 Expected<Optional<T>> import(Optional<T> From) { 184 if (!From) 185 return Optional<T>(); 186 return import(*From); 187 } 188 189 template <class T> 190 Expected<std::tuple<T>> 191 importSeq(const T &From) { 192 Expected<T> ToOrErr = import(From); 193 if (!ToOrErr) 194 return ToOrErr.takeError(); 195 return std::make_tuple<T>(std::move(*ToOrErr)); 196 } 197 198 // Import multiple objects with a single function call. 199 // This should work for every type for which a variant of `import` exists. 200 // The arguments are processed from left to right and import is stopped on 201 // first error. 202 template <class THead, class... TTail> 203 Expected<std::tuple<THead, TTail...>> 204 importSeq(const THead &FromHead, const TTail &...FromTail) { 205 Expected<std::tuple<THead>> ToHeadOrErr = importSeq(FromHead); 206 if (!ToHeadOrErr) 207 return ToHeadOrErr.takeError(); 208 Expected<std::tuple<TTail...>> ToTailOrErr = importSeq(FromTail...); 209 if (!ToTailOrErr) 210 return ToTailOrErr.takeError(); 211 return std::tuple_cat(*ToHeadOrErr, *ToTailOrErr); 212 } 213 214 // Wrapper for an overload set. 215 template <typename ToDeclT> struct CallOverloadedCreateFun { 216 template <typename... Args> 217 auto operator()(Args &&... args) 218 -> decltype(ToDeclT::Create(std::forward<Args>(args)...)) { 219 return ToDeclT::Create(std::forward<Args>(args)...); 220 } 221 }; 222 223 // Always use these functions to create a Decl during import. There are 224 // certain tasks which must be done after the Decl was created, e.g. we 225 // must immediately register that as an imported Decl. The parameter `ToD` 226 // will be set to the newly created Decl or if had been imported before 227 // then to the already imported Decl. Returns a bool value set to true if 228 // the `FromD` had been imported before. 229 template <typename ToDeclT, typename FromDeclT, typename... Args> 230 LLVM_NODISCARD bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD, 231 Args &&... args) { 232 // There may be several overloads of ToDeclT::Create. We must make sure 233 // to call the one which would be chosen by the arguments, thus we use a 234 // wrapper for the overload set. 235 CallOverloadedCreateFun<ToDeclT> OC; 236 return GetImportedOrCreateSpecialDecl(ToD, OC, FromD, 237 std::forward<Args>(args)...); 238 } 239 // Use this overload if a special Type is needed to be created. E.g if we 240 // want to create a `TypeAliasDecl` and assign that to a `TypedefNameDecl` 241 // then: 242 // TypedefNameDecl *ToTypedef; 243 // GetImportedOrCreateDecl<TypeAliasDecl>(ToTypedef, FromD, ...); 244 template <typename NewDeclT, typename ToDeclT, typename FromDeclT, 245 typename... Args> 246 LLVM_NODISCARD bool GetImportedOrCreateDecl(ToDeclT *&ToD, FromDeclT *FromD, 247 Args &&... args) { 248 CallOverloadedCreateFun<NewDeclT> OC; 249 return GetImportedOrCreateSpecialDecl(ToD, OC, FromD, 250 std::forward<Args>(args)...); 251 } 252 // Use this version if a special create function must be 253 // used, e.g. CXXRecordDecl::CreateLambda . 254 template <typename ToDeclT, typename CreateFunT, typename FromDeclT, 255 typename... Args> 256 LLVM_NODISCARD bool 257 GetImportedOrCreateSpecialDecl(ToDeclT *&ToD, CreateFunT CreateFun, 258 FromDeclT *FromD, Args &&... args) { 259 if (Importer.getImportDeclErrorIfAny(FromD)) { 260 ToD = nullptr; 261 return true; // Already imported but with error. 262 } 263 ToD = cast_or_null<ToDeclT>(Importer.GetAlreadyImportedOrNull(FromD)); 264 if (ToD) 265 return true; // Already imported. 266 ToD = CreateFun(std::forward<Args>(args)...); 267 // Keep track of imported Decls. 268 Importer.RegisterImportedDecl(FromD, ToD); 269 InitializeImportedDecl(FromD, ToD); 270 return false; // A new Decl is created. 271 } 272 273 void InitializeImportedDecl(Decl *FromD, Decl *ToD) { 274 ToD->IdentifierNamespace = FromD->IdentifierNamespace; 275 if (FromD->hasAttrs()) 276 for (const Attr *FromAttr : FromD->getAttrs()) { 277 // FIXME: Return of the error here is not possible until store of 278 // import errors is implemented. 279 auto ToAttrOrErr = import(FromAttr); 280 if (ToAttrOrErr) 281 ToD->addAttr(*ToAttrOrErr); 282 else 283 llvm::consumeError(ToAttrOrErr.takeError()); 284 } 285 if (FromD->isUsed()) 286 ToD->setIsUsed(); 287 if (FromD->isImplicit()) 288 ToD->setImplicit(); 289 } 290 291 // Check if we have found an existing definition. Returns with that 292 // definition if yes, otherwise returns null. 293 Decl *FindAndMapDefinition(FunctionDecl *D, FunctionDecl *FoundFunction) { 294 const FunctionDecl *Definition = nullptr; 295 if (D->doesThisDeclarationHaveABody() && 296 FoundFunction->hasBody(Definition)) 297 return Importer.MapImported(D, const_cast<FunctionDecl *>(Definition)); 298 return nullptr; 299 } 300 301 void addDeclToContexts(Decl *FromD, Decl *ToD) { 302 if (Importer.isMinimalImport()) { 303 // In minimal import case the decl must be added even if it is not 304 // contained in original context, for LLDB compatibility. 305 // FIXME: Check if a better solution is possible. 306 if (!FromD->getDescribedTemplate() && 307 FromD->getFriendObjectKind() == Decl::FOK_None) 308 ToD->getLexicalDeclContext()->addDeclInternal(ToD); 309 return; 310 } 311 312 DeclContext *FromDC = FromD->getDeclContext(); 313 DeclContext *FromLexicalDC = FromD->getLexicalDeclContext(); 314 DeclContext *ToDC = ToD->getDeclContext(); 315 DeclContext *ToLexicalDC = ToD->getLexicalDeclContext(); 316 317 bool Visible = false; 318 if (FromDC->containsDeclAndLoad(FromD)) { 319 ToDC->addDeclInternal(ToD); 320 Visible = true; 321 } 322 if (ToDC != ToLexicalDC && FromLexicalDC->containsDeclAndLoad(FromD)) { 323 ToLexicalDC->addDeclInternal(ToD); 324 Visible = true; 325 } 326 327 // If the Decl was added to any context, it was made already visible. 328 // Otherwise it is still possible that it should be visible. 329 if (!Visible) { 330 if (auto *FromNamed = dyn_cast<NamedDecl>(FromD)) { 331 auto *ToNamed = cast<NamedDecl>(ToD); 332 DeclContextLookupResult FromLookup = 333 FromDC->lookup(FromNamed->getDeclName()); 334 for (NamedDecl *ND : FromLookup) 335 if (ND == FromNamed) { 336 ToDC->makeDeclVisibleInContext(ToNamed); 337 break; 338 } 339 } 340 } 341 } 342 343 public: 344 explicit ASTNodeImporter(ASTImporter &Importer) : Importer(Importer) {} 345 346 using TypeVisitor<ASTNodeImporter, ExpectedType>::Visit; 347 using DeclVisitor<ASTNodeImporter, ExpectedDecl>::Visit; 348 using StmtVisitor<ASTNodeImporter, ExpectedStmt>::Visit; 349 350 // Importing types 351 ExpectedType VisitType(const Type *T); 352 ExpectedType VisitAtomicType(const AtomicType *T); 353 ExpectedType VisitBuiltinType(const BuiltinType *T); 354 ExpectedType VisitDecayedType(const DecayedType *T); 355 ExpectedType VisitComplexType(const ComplexType *T); 356 ExpectedType VisitPointerType(const PointerType *T); 357 ExpectedType VisitBlockPointerType(const BlockPointerType *T); 358 ExpectedType VisitLValueReferenceType(const LValueReferenceType *T); 359 ExpectedType VisitRValueReferenceType(const RValueReferenceType *T); 360 ExpectedType VisitMemberPointerType(const MemberPointerType *T); 361 ExpectedType VisitConstantArrayType(const ConstantArrayType *T); 362 ExpectedType VisitIncompleteArrayType(const IncompleteArrayType *T); 363 ExpectedType VisitVariableArrayType(const VariableArrayType *T); 364 ExpectedType VisitDependentSizedArrayType(const DependentSizedArrayType *T); 365 // FIXME: DependentSizedExtVectorType 366 ExpectedType VisitVectorType(const VectorType *T); 367 ExpectedType VisitExtVectorType(const ExtVectorType *T); 368 ExpectedType VisitFunctionNoProtoType(const FunctionNoProtoType *T); 369 ExpectedType VisitFunctionProtoType(const FunctionProtoType *T); 370 ExpectedType VisitUnresolvedUsingType(const UnresolvedUsingType *T); 371 ExpectedType VisitParenType(const ParenType *T); 372 ExpectedType VisitTypedefType(const TypedefType *T); 373 ExpectedType VisitTypeOfExprType(const TypeOfExprType *T); 374 // FIXME: DependentTypeOfExprType 375 ExpectedType VisitTypeOfType(const TypeOfType *T); 376 ExpectedType VisitDecltypeType(const DecltypeType *T); 377 ExpectedType VisitUnaryTransformType(const UnaryTransformType *T); 378 ExpectedType VisitAutoType(const AutoType *T); 379 ExpectedType VisitInjectedClassNameType(const InjectedClassNameType *T); 380 // FIXME: DependentDecltypeType 381 ExpectedType VisitRecordType(const RecordType *T); 382 ExpectedType VisitEnumType(const EnumType *T); 383 ExpectedType VisitAttributedType(const AttributedType *T); 384 ExpectedType VisitTemplateTypeParmType(const TemplateTypeParmType *T); 385 ExpectedType VisitSubstTemplateTypeParmType( 386 const SubstTemplateTypeParmType *T); 387 ExpectedType VisitTemplateSpecializationType( 388 const TemplateSpecializationType *T); 389 ExpectedType VisitElaboratedType(const ElaboratedType *T); 390 ExpectedType VisitDependentNameType(const DependentNameType *T); 391 ExpectedType VisitPackExpansionType(const PackExpansionType *T); 392 ExpectedType VisitDependentTemplateSpecializationType( 393 const DependentTemplateSpecializationType *T); 394 ExpectedType VisitObjCInterfaceType(const ObjCInterfaceType *T); 395 ExpectedType VisitObjCObjectType(const ObjCObjectType *T); 396 ExpectedType VisitObjCObjectPointerType(const ObjCObjectPointerType *T); 397 398 // Importing declarations 399 Error ImportDeclParts( 400 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC, 401 DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc); 402 Error ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD = nullptr); 403 Error ImportDeclarationNameLoc( 404 const DeclarationNameInfo &From, DeclarationNameInfo &To); 405 Error ImportDeclContext(DeclContext *FromDC, bool ForceImport = false); 406 Error ImportDeclContext( 407 Decl *From, DeclContext *&ToDC, DeclContext *&ToLexicalDC); 408 Error ImportImplicitMethods(const CXXRecordDecl *From, CXXRecordDecl *To); 409 410 Expected<CXXCastPath> ImportCastPath(CastExpr *E); 411 412 using Designator = DesignatedInitExpr::Designator; 413 414 /// What we should import from the definition. 415 enum ImportDefinitionKind { 416 /// Import the default subset of the definition, which might be 417 /// nothing (if minimal import is set) or might be everything (if minimal 418 /// import is not set). 419 IDK_Default, 420 /// Import everything. 421 IDK_Everything, 422 /// Import only the bare bones needed to establish a valid 423 /// DeclContext. 424 IDK_Basic 425 }; 426 427 bool shouldForceImportDeclContext(ImportDefinitionKind IDK) { 428 return IDK == IDK_Everything || 429 (IDK == IDK_Default && !Importer.isMinimalImport()); 430 } 431 432 Error ImportInitializer(VarDecl *From, VarDecl *To); 433 Error ImportDefinition( 434 RecordDecl *From, RecordDecl *To, 435 ImportDefinitionKind Kind = IDK_Default); 436 Error ImportDefinition( 437 EnumDecl *From, EnumDecl *To, 438 ImportDefinitionKind Kind = IDK_Default); 439 Error ImportDefinition( 440 ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, 441 ImportDefinitionKind Kind = IDK_Default); 442 Error ImportDefinition( 443 ObjCProtocolDecl *From, ObjCProtocolDecl *To, 444 ImportDefinitionKind Kind = IDK_Default); 445 Error ImportTemplateArguments( 446 const TemplateArgument *FromArgs, unsigned NumFromArgs, 447 SmallVectorImpl<TemplateArgument> &ToArgs); 448 Expected<TemplateArgument> 449 ImportTemplateArgument(const TemplateArgument &From); 450 451 template <typename InContainerTy> 452 Error ImportTemplateArgumentListInfo( 453 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo); 454 455 template<typename InContainerTy> 456 Error ImportTemplateArgumentListInfo( 457 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc, 458 const InContainerTy &Container, TemplateArgumentListInfo &Result); 459 460 using TemplateArgsTy = SmallVector<TemplateArgument, 8>; 461 using FunctionTemplateAndArgsTy = 462 std::tuple<FunctionTemplateDecl *, TemplateArgsTy>; 463 Expected<FunctionTemplateAndArgsTy> 464 ImportFunctionTemplateWithTemplateArgsFromSpecialization( 465 FunctionDecl *FromFD); 466 Error ImportTemplateParameterLists(const DeclaratorDecl *FromD, 467 DeclaratorDecl *ToD); 468 469 Error ImportTemplateInformation(FunctionDecl *FromFD, FunctionDecl *ToFD); 470 471 Error ImportFunctionDeclBody(FunctionDecl *FromFD, FunctionDecl *ToFD); 472 473 Error ImportDefaultArgOfParmVarDecl(const ParmVarDecl *FromParam, 474 ParmVarDecl *ToParam); 475 476 template <typename T> 477 bool hasSameVisibilityContext(T *Found, T *From); 478 479 bool IsStructuralMatch(Decl *From, Decl *To, bool Complain); 480 bool IsStructuralMatch(RecordDecl *FromRecord, RecordDecl *ToRecord, 481 bool Complain = true); 482 bool IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar, 483 bool Complain = true); 484 bool IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToRecord); 485 bool IsStructuralMatch(EnumConstantDecl *FromEC, EnumConstantDecl *ToEC); 486 bool IsStructuralMatch(FunctionTemplateDecl *From, 487 FunctionTemplateDecl *To); 488 bool IsStructuralMatch(FunctionDecl *From, FunctionDecl *To); 489 bool IsStructuralMatch(ClassTemplateDecl *From, ClassTemplateDecl *To); 490 bool IsStructuralMatch(VarTemplateDecl *From, VarTemplateDecl *To); 491 ExpectedDecl VisitDecl(Decl *D); 492 ExpectedDecl VisitImportDecl(ImportDecl *D); 493 ExpectedDecl VisitEmptyDecl(EmptyDecl *D); 494 ExpectedDecl VisitAccessSpecDecl(AccessSpecDecl *D); 495 ExpectedDecl VisitStaticAssertDecl(StaticAssertDecl *D); 496 ExpectedDecl VisitTranslationUnitDecl(TranslationUnitDecl *D); 497 ExpectedDecl VisitNamespaceDecl(NamespaceDecl *D); 498 ExpectedDecl VisitNamespaceAliasDecl(NamespaceAliasDecl *D); 499 ExpectedDecl VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias); 500 ExpectedDecl VisitTypedefDecl(TypedefDecl *D); 501 ExpectedDecl VisitTypeAliasDecl(TypeAliasDecl *D); 502 ExpectedDecl VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D); 503 ExpectedDecl VisitLabelDecl(LabelDecl *D); 504 ExpectedDecl VisitEnumDecl(EnumDecl *D); 505 ExpectedDecl VisitRecordDecl(RecordDecl *D); 506 ExpectedDecl VisitEnumConstantDecl(EnumConstantDecl *D); 507 ExpectedDecl VisitFunctionDecl(FunctionDecl *D); 508 ExpectedDecl VisitCXXMethodDecl(CXXMethodDecl *D); 509 ExpectedDecl VisitCXXConstructorDecl(CXXConstructorDecl *D); 510 ExpectedDecl VisitCXXDestructorDecl(CXXDestructorDecl *D); 511 ExpectedDecl VisitCXXConversionDecl(CXXConversionDecl *D); 512 ExpectedDecl VisitFieldDecl(FieldDecl *D); 513 ExpectedDecl VisitIndirectFieldDecl(IndirectFieldDecl *D); 514 ExpectedDecl VisitFriendDecl(FriendDecl *D); 515 ExpectedDecl VisitObjCIvarDecl(ObjCIvarDecl *D); 516 ExpectedDecl VisitVarDecl(VarDecl *D); 517 ExpectedDecl VisitImplicitParamDecl(ImplicitParamDecl *D); 518 ExpectedDecl VisitParmVarDecl(ParmVarDecl *D); 519 ExpectedDecl VisitObjCMethodDecl(ObjCMethodDecl *D); 520 ExpectedDecl VisitObjCTypeParamDecl(ObjCTypeParamDecl *D); 521 ExpectedDecl VisitObjCCategoryDecl(ObjCCategoryDecl *D); 522 ExpectedDecl VisitObjCProtocolDecl(ObjCProtocolDecl *D); 523 ExpectedDecl VisitLinkageSpecDecl(LinkageSpecDecl *D); 524 ExpectedDecl VisitUsingDecl(UsingDecl *D); 525 ExpectedDecl VisitUsingShadowDecl(UsingShadowDecl *D); 526 ExpectedDecl VisitUsingDirectiveDecl(UsingDirectiveDecl *D); 527 ExpectedDecl VisitUnresolvedUsingValueDecl(UnresolvedUsingValueDecl *D); 528 ExpectedDecl VisitUnresolvedUsingTypenameDecl(UnresolvedUsingTypenameDecl *D); 529 ExpectedDecl VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D); 530 ExpectedDecl 531 VisitLifetimeExtendedTemporaryDecl(LifetimeExtendedTemporaryDecl *D); 532 533 Expected<ObjCTypeParamList *> 534 ImportObjCTypeParamList(ObjCTypeParamList *list); 535 536 ExpectedDecl VisitObjCInterfaceDecl(ObjCInterfaceDecl *D); 537 ExpectedDecl VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D); 538 ExpectedDecl VisitObjCImplementationDecl(ObjCImplementationDecl *D); 539 ExpectedDecl VisitObjCPropertyDecl(ObjCPropertyDecl *D); 540 ExpectedDecl VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D); 541 ExpectedDecl VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D); 542 ExpectedDecl VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D); 543 ExpectedDecl VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D); 544 ExpectedDecl VisitClassTemplateDecl(ClassTemplateDecl *D); 545 ExpectedDecl VisitClassTemplateSpecializationDecl( 546 ClassTemplateSpecializationDecl *D); 547 ExpectedDecl VisitVarTemplateDecl(VarTemplateDecl *D); 548 ExpectedDecl VisitVarTemplateSpecializationDecl(VarTemplateSpecializationDecl *D); 549 ExpectedDecl VisitFunctionTemplateDecl(FunctionTemplateDecl *D); 550 551 // Importing statements 552 ExpectedStmt VisitStmt(Stmt *S); 553 ExpectedStmt VisitGCCAsmStmt(GCCAsmStmt *S); 554 ExpectedStmt VisitDeclStmt(DeclStmt *S); 555 ExpectedStmt VisitNullStmt(NullStmt *S); 556 ExpectedStmt VisitCompoundStmt(CompoundStmt *S); 557 ExpectedStmt VisitCaseStmt(CaseStmt *S); 558 ExpectedStmt VisitDefaultStmt(DefaultStmt *S); 559 ExpectedStmt VisitLabelStmt(LabelStmt *S); 560 ExpectedStmt VisitAttributedStmt(AttributedStmt *S); 561 ExpectedStmt VisitIfStmt(IfStmt *S); 562 ExpectedStmt VisitSwitchStmt(SwitchStmt *S); 563 ExpectedStmt VisitWhileStmt(WhileStmt *S); 564 ExpectedStmt VisitDoStmt(DoStmt *S); 565 ExpectedStmt VisitForStmt(ForStmt *S); 566 ExpectedStmt VisitGotoStmt(GotoStmt *S); 567 ExpectedStmt VisitIndirectGotoStmt(IndirectGotoStmt *S); 568 ExpectedStmt VisitContinueStmt(ContinueStmt *S); 569 ExpectedStmt VisitBreakStmt(BreakStmt *S); 570 ExpectedStmt VisitReturnStmt(ReturnStmt *S); 571 // FIXME: MSAsmStmt 572 // FIXME: SEHExceptStmt 573 // FIXME: SEHFinallyStmt 574 // FIXME: SEHTryStmt 575 // FIXME: SEHLeaveStmt 576 // FIXME: CapturedStmt 577 ExpectedStmt VisitCXXCatchStmt(CXXCatchStmt *S); 578 ExpectedStmt VisitCXXTryStmt(CXXTryStmt *S); 579 ExpectedStmt VisitCXXForRangeStmt(CXXForRangeStmt *S); 580 // FIXME: MSDependentExistsStmt 581 ExpectedStmt VisitObjCForCollectionStmt(ObjCForCollectionStmt *S); 582 ExpectedStmt VisitObjCAtCatchStmt(ObjCAtCatchStmt *S); 583 ExpectedStmt VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S); 584 ExpectedStmt VisitObjCAtTryStmt(ObjCAtTryStmt *S); 585 ExpectedStmt VisitObjCAtSynchronizedStmt(ObjCAtSynchronizedStmt *S); 586 ExpectedStmt VisitObjCAtThrowStmt(ObjCAtThrowStmt *S); 587 ExpectedStmt VisitObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S); 588 589 // Importing expressions 590 ExpectedStmt VisitExpr(Expr *E); 591 ExpectedStmt VisitVAArgExpr(VAArgExpr *E); 592 ExpectedStmt VisitChooseExpr(ChooseExpr *E); 593 ExpectedStmt VisitGNUNullExpr(GNUNullExpr *E); 594 ExpectedStmt VisitPredefinedExpr(PredefinedExpr *E); 595 ExpectedStmt VisitDeclRefExpr(DeclRefExpr *E); 596 ExpectedStmt VisitImplicitValueInitExpr(ImplicitValueInitExpr *E); 597 ExpectedStmt VisitDesignatedInitExpr(DesignatedInitExpr *E); 598 ExpectedStmt VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E); 599 ExpectedStmt VisitIntegerLiteral(IntegerLiteral *E); 600 ExpectedStmt VisitFloatingLiteral(FloatingLiteral *E); 601 ExpectedStmt VisitImaginaryLiteral(ImaginaryLiteral *E); 602 ExpectedStmt VisitCharacterLiteral(CharacterLiteral *E); 603 ExpectedStmt VisitStringLiteral(StringLiteral *E); 604 ExpectedStmt VisitCompoundLiteralExpr(CompoundLiteralExpr *E); 605 ExpectedStmt VisitAtomicExpr(AtomicExpr *E); 606 ExpectedStmt VisitAddrLabelExpr(AddrLabelExpr *E); 607 ExpectedStmt VisitConstantExpr(ConstantExpr *E); 608 ExpectedStmt VisitParenExpr(ParenExpr *E); 609 ExpectedStmt VisitParenListExpr(ParenListExpr *E); 610 ExpectedStmt VisitStmtExpr(StmtExpr *E); 611 ExpectedStmt VisitUnaryOperator(UnaryOperator *E); 612 ExpectedStmt VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E); 613 ExpectedStmt VisitBinaryOperator(BinaryOperator *E); 614 ExpectedStmt VisitConditionalOperator(ConditionalOperator *E); 615 ExpectedStmt VisitBinaryConditionalOperator(BinaryConditionalOperator *E); 616 ExpectedStmt VisitOpaqueValueExpr(OpaqueValueExpr *E); 617 ExpectedStmt VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E); 618 ExpectedStmt VisitExpressionTraitExpr(ExpressionTraitExpr *E); 619 ExpectedStmt VisitArraySubscriptExpr(ArraySubscriptExpr *E); 620 ExpectedStmt VisitCompoundAssignOperator(CompoundAssignOperator *E); 621 ExpectedStmt VisitImplicitCastExpr(ImplicitCastExpr *E); 622 ExpectedStmt VisitExplicitCastExpr(ExplicitCastExpr *E); 623 ExpectedStmt VisitOffsetOfExpr(OffsetOfExpr *OE); 624 ExpectedStmt VisitCXXThrowExpr(CXXThrowExpr *E); 625 ExpectedStmt VisitCXXNoexceptExpr(CXXNoexceptExpr *E); 626 ExpectedStmt VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E); 627 ExpectedStmt VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E); 628 ExpectedStmt VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E); 629 ExpectedStmt VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E); 630 ExpectedStmt VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E); 631 ExpectedStmt VisitPackExpansionExpr(PackExpansionExpr *E); 632 ExpectedStmt VisitSizeOfPackExpr(SizeOfPackExpr *E); 633 ExpectedStmt VisitCXXNewExpr(CXXNewExpr *E); 634 ExpectedStmt VisitCXXDeleteExpr(CXXDeleteExpr *E); 635 ExpectedStmt VisitCXXConstructExpr(CXXConstructExpr *E); 636 ExpectedStmt VisitCXXMemberCallExpr(CXXMemberCallExpr *E); 637 ExpectedStmt VisitCXXDependentScopeMemberExpr(CXXDependentScopeMemberExpr *E); 638 ExpectedStmt VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E); 639 ExpectedStmt VisitCXXUnresolvedConstructExpr(CXXUnresolvedConstructExpr *E); 640 ExpectedStmt VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E); 641 ExpectedStmt VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E); 642 ExpectedStmt VisitExprWithCleanups(ExprWithCleanups *E); 643 ExpectedStmt VisitCXXThisExpr(CXXThisExpr *E); 644 ExpectedStmt VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E); 645 ExpectedStmt VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E); 646 ExpectedStmt VisitMemberExpr(MemberExpr *E); 647 ExpectedStmt VisitCallExpr(CallExpr *E); 648 ExpectedStmt VisitLambdaExpr(LambdaExpr *LE); 649 ExpectedStmt VisitInitListExpr(InitListExpr *E); 650 ExpectedStmt VisitCXXStdInitializerListExpr(CXXStdInitializerListExpr *E); 651 ExpectedStmt VisitCXXInheritedCtorInitExpr(CXXInheritedCtorInitExpr *E); 652 ExpectedStmt VisitArrayInitLoopExpr(ArrayInitLoopExpr *E); 653 ExpectedStmt VisitArrayInitIndexExpr(ArrayInitIndexExpr *E); 654 ExpectedStmt VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E); 655 ExpectedStmt VisitCXXNamedCastExpr(CXXNamedCastExpr *E); 656 ExpectedStmt VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *E); 657 ExpectedStmt VisitTypeTraitExpr(TypeTraitExpr *E); 658 ExpectedStmt VisitCXXTypeidExpr(CXXTypeidExpr *E); 659 660 template<typename IIter, typename OIter> 661 Error ImportArrayChecked(IIter Ibegin, IIter Iend, OIter Obegin) { 662 using ItemT = typename std::remove_reference<decltype(*Obegin)>::type; 663 for (; Ibegin != Iend; ++Ibegin, ++Obegin) { 664 Expected<ItemT> ToOrErr = import(*Ibegin); 665 if (!ToOrErr) 666 return ToOrErr.takeError(); 667 *Obegin = *ToOrErr; 668 } 669 return Error::success(); 670 } 671 672 // Import every item from a container structure into an output container. 673 // If error occurs, stops at first error and returns the error. 674 // The output container should have space for all needed elements (it is not 675 // expanded, new items are put into from the beginning). 676 template<typename InContainerTy, typename OutContainerTy> 677 Error ImportContainerChecked( 678 const InContainerTy &InContainer, OutContainerTy &OutContainer) { 679 return ImportArrayChecked( 680 InContainer.begin(), InContainer.end(), OutContainer.begin()); 681 } 682 683 template<typename InContainerTy, typename OIter> 684 Error ImportArrayChecked(const InContainerTy &InContainer, OIter Obegin) { 685 return ImportArrayChecked(InContainer.begin(), InContainer.end(), Obegin); 686 } 687 688 Error ImportOverriddenMethods(CXXMethodDecl *ToMethod, 689 CXXMethodDecl *FromMethod); 690 691 Expected<FunctionDecl *> FindFunctionTemplateSpecialization( 692 FunctionDecl *FromFD); 693 694 // Returns true if the given function has a placeholder return type and 695 // that type is declared inside the body of the function. 696 // E.g. auto f() { struct X{}; return X(); } 697 bool hasAutoReturnTypeDeclaredInside(FunctionDecl *D); 698 }; 699 700 template <typename InContainerTy> 701 Error ASTNodeImporter::ImportTemplateArgumentListInfo( 702 SourceLocation FromLAngleLoc, SourceLocation FromRAngleLoc, 703 const InContainerTy &Container, TemplateArgumentListInfo &Result) { 704 auto ToLAngleLocOrErr = import(FromLAngleLoc); 705 if (!ToLAngleLocOrErr) 706 return ToLAngleLocOrErr.takeError(); 707 auto ToRAngleLocOrErr = import(FromRAngleLoc); 708 if (!ToRAngleLocOrErr) 709 return ToRAngleLocOrErr.takeError(); 710 711 TemplateArgumentListInfo ToTAInfo(*ToLAngleLocOrErr, *ToRAngleLocOrErr); 712 if (auto Err = ImportTemplateArgumentListInfo(Container, ToTAInfo)) 713 return Err; 714 Result = ToTAInfo; 715 return Error::success(); 716 } 717 718 template <> 719 Error ASTNodeImporter::ImportTemplateArgumentListInfo<TemplateArgumentListInfo>( 720 const TemplateArgumentListInfo &From, TemplateArgumentListInfo &Result) { 721 return ImportTemplateArgumentListInfo( 722 From.getLAngleLoc(), From.getRAngleLoc(), From.arguments(), Result); 723 } 724 725 template <> 726 Error ASTNodeImporter::ImportTemplateArgumentListInfo< 727 ASTTemplateArgumentListInfo>( 728 const ASTTemplateArgumentListInfo &From, 729 TemplateArgumentListInfo &Result) { 730 return ImportTemplateArgumentListInfo( 731 From.LAngleLoc, From.RAngleLoc, From.arguments(), Result); 732 } 733 734 Expected<ASTNodeImporter::FunctionTemplateAndArgsTy> 735 ASTNodeImporter::ImportFunctionTemplateWithTemplateArgsFromSpecialization( 736 FunctionDecl *FromFD) { 737 assert(FromFD->getTemplatedKind() == 738 FunctionDecl::TK_FunctionTemplateSpecialization); 739 740 FunctionTemplateAndArgsTy Result; 741 742 auto *FTSInfo = FromFD->getTemplateSpecializationInfo(); 743 if (Error Err = importInto(std::get<0>(Result), FTSInfo->getTemplate())) 744 return std::move(Err); 745 746 // Import template arguments. 747 auto TemplArgs = FTSInfo->TemplateArguments->asArray(); 748 if (Error Err = ImportTemplateArguments(TemplArgs.data(), TemplArgs.size(), 749 std::get<1>(Result))) 750 return std::move(Err); 751 752 return Result; 753 } 754 755 template <> 756 Expected<TemplateParameterList *> 757 ASTNodeImporter::import(TemplateParameterList *From) { 758 SmallVector<NamedDecl *, 4> To(From->size()); 759 if (Error Err = ImportContainerChecked(*From, To)) 760 return std::move(Err); 761 762 ExpectedExpr ToRequiresClause = import(From->getRequiresClause()); 763 if (!ToRequiresClause) 764 return ToRequiresClause.takeError(); 765 766 auto ToTemplateLocOrErr = import(From->getTemplateLoc()); 767 if (!ToTemplateLocOrErr) 768 return ToTemplateLocOrErr.takeError(); 769 auto ToLAngleLocOrErr = import(From->getLAngleLoc()); 770 if (!ToLAngleLocOrErr) 771 return ToLAngleLocOrErr.takeError(); 772 auto ToRAngleLocOrErr = import(From->getRAngleLoc()); 773 if (!ToRAngleLocOrErr) 774 return ToRAngleLocOrErr.takeError(); 775 776 return TemplateParameterList::Create( 777 Importer.getToContext(), 778 *ToTemplateLocOrErr, 779 *ToLAngleLocOrErr, 780 To, 781 *ToRAngleLocOrErr, 782 *ToRequiresClause); 783 } 784 785 template <> 786 Expected<TemplateArgument> 787 ASTNodeImporter::import(const TemplateArgument &From) { 788 switch (From.getKind()) { 789 case TemplateArgument::Null: 790 return TemplateArgument(); 791 792 case TemplateArgument::Type: { 793 ExpectedType ToTypeOrErr = import(From.getAsType()); 794 if (!ToTypeOrErr) 795 return ToTypeOrErr.takeError(); 796 return TemplateArgument(*ToTypeOrErr); 797 } 798 799 case TemplateArgument::Integral: { 800 ExpectedType ToTypeOrErr = import(From.getIntegralType()); 801 if (!ToTypeOrErr) 802 return ToTypeOrErr.takeError(); 803 return TemplateArgument(From, *ToTypeOrErr); 804 } 805 806 case TemplateArgument::Declaration: { 807 Expected<ValueDecl *> ToOrErr = import(From.getAsDecl()); 808 if (!ToOrErr) 809 return ToOrErr.takeError(); 810 ExpectedType ToTypeOrErr = import(From.getParamTypeForDecl()); 811 if (!ToTypeOrErr) 812 return ToTypeOrErr.takeError(); 813 return TemplateArgument(*ToOrErr, *ToTypeOrErr); 814 } 815 816 case TemplateArgument::NullPtr: { 817 ExpectedType ToTypeOrErr = import(From.getNullPtrType()); 818 if (!ToTypeOrErr) 819 return ToTypeOrErr.takeError(); 820 return TemplateArgument(*ToTypeOrErr, /*isNullPtr*/true); 821 } 822 823 case TemplateArgument::Template: { 824 Expected<TemplateName> ToTemplateOrErr = import(From.getAsTemplate()); 825 if (!ToTemplateOrErr) 826 return ToTemplateOrErr.takeError(); 827 828 return TemplateArgument(*ToTemplateOrErr); 829 } 830 831 case TemplateArgument::TemplateExpansion: { 832 Expected<TemplateName> ToTemplateOrErr = 833 import(From.getAsTemplateOrTemplatePattern()); 834 if (!ToTemplateOrErr) 835 return ToTemplateOrErr.takeError(); 836 837 return TemplateArgument( 838 *ToTemplateOrErr, From.getNumTemplateExpansions()); 839 } 840 841 case TemplateArgument::Expression: 842 if (ExpectedExpr ToExpr = import(From.getAsExpr())) 843 return TemplateArgument(*ToExpr); 844 else 845 return ToExpr.takeError(); 846 847 case TemplateArgument::Pack: { 848 SmallVector<TemplateArgument, 2> ToPack; 849 ToPack.reserve(From.pack_size()); 850 if (Error Err = ImportTemplateArguments( 851 From.pack_begin(), From.pack_size(), ToPack)) 852 return std::move(Err); 853 854 return TemplateArgument( 855 llvm::makeArrayRef(ToPack).copy(Importer.getToContext())); 856 } 857 } 858 859 llvm_unreachable("Invalid template argument kind"); 860 } 861 862 template <> 863 Expected<TemplateArgumentLoc> 864 ASTNodeImporter::import(const TemplateArgumentLoc &TALoc) { 865 Expected<TemplateArgument> ArgOrErr = import(TALoc.getArgument()); 866 if (!ArgOrErr) 867 return ArgOrErr.takeError(); 868 TemplateArgument Arg = *ArgOrErr; 869 870 TemplateArgumentLocInfo FromInfo = TALoc.getLocInfo(); 871 872 TemplateArgumentLocInfo ToInfo; 873 if (Arg.getKind() == TemplateArgument::Expression) { 874 ExpectedExpr E = import(FromInfo.getAsExpr()); 875 if (!E) 876 return E.takeError(); 877 ToInfo = TemplateArgumentLocInfo(*E); 878 } else if (Arg.getKind() == TemplateArgument::Type) { 879 if (auto TSIOrErr = import(FromInfo.getAsTypeSourceInfo())) 880 ToInfo = TemplateArgumentLocInfo(*TSIOrErr); 881 else 882 return TSIOrErr.takeError(); 883 } else { 884 auto ToTemplateQualifierLocOrErr = 885 import(FromInfo.getTemplateQualifierLoc()); 886 if (!ToTemplateQualifierLocOrErr) 887 return ToTemplateQualifierLocOrErr.takeError(); 888 auto ToTemplateNameLocOrErr = import(FromInfo.getTemplateNameLoc()); 889 if (!ToTemplateNameLocOrErr) 890 return ToTemplateNameLocOrErr.takeError(); 891 auto ToTemplateEllipsisLocOrErr = 892 import(FromInfo.getTemplateEllipsisLoc()); 893 if (!ToTemplateEllipsisLocOrErr) 894 return ToTemplateEllipsisLocOrErr.takeError(); 895 896 ToInfo = TemplateArgumentLocInfo( 897 *ToTemplateQualifierLocOrErr, 898 *ToTemplateNameLocOrErr, 899 *ToTemplateEllipsisLocOrErr); 900 } 901 902 return TemplateArgumentLoc(Arg, ToInfo); 903 } 904 905 template <> 906 Expected<DeclGroupRef> ASTNodeImporter::import(const DeclGroupRef &DG) { 907 if (DG.isNull()) 908 return DeclGroupRef::Create(Importer.getToContext(), nullptr, 0); 909 size_t NumDecls = DG.end() - DG.begin(); 910 SmallVector<Decl *, 1> ToDecls; 911 ToDecls.reserve(NumDecls); 912 for (Decl *FromD : DG) { 913 if (auto ToDOrErr = import(FromD)) 914 ToDecls.push_back(*ToDOrErr); 915 else 916 return ToDOrErr.takeError(); 917 } 918 return DeclGroupRef::Create(Importer.getToContext(), 919 ToDecls.begin(), 920 NumDecls); 921 } 922 923 template <> 924 Expected<ASTNodeImporter::Designator> 925 ASTNodeImporter::import(const Designator &D) { 926 if (D.isFieldDesignator()) { 927 IdentifierInfo *ToFieldName = Importer.Import(D.getFieldName()); 928 929 ExpectedSLoc ToDotLocOrErr = import(D.getDotLoc()); 930 if (!ToDotLocOrErr) 931 return ToDotLocOrErr.takeError(); 932 933 ExpectedSLoc ToFieldLocOrErr = import(D.getFieldLoc()); 934 if (!ToFieldLocOrErr) 935 return ToFieldLocOrErr.takeError(); 936 937 return Designator(ToFieldName, *ToDotLocOrErr, *ToFieldLocOrErr); 938 } 939 940 ExpectedSLoc ToLBracketLocOrErr = import(D.getLBracketLoc()); 941 if (!ToLBracketLocOrErr) 942 return ToLBracketLocOrErr.takeError(); 943 944 ExpectedSLoc ToRBracketLocOrErr = import(D.getRBracketLoc()); 945 if (!ToRBracketLocOrErr) 946 return ToRBracketLocOrErr.takeError(); 947 948 if (D.isArrayDesignator()) 949 return Designator(D.getFirstExprIndex(), 950 *ToLBracketLocOrErr, *ToRBracketLocOrErr); 951 952 ExpectedSLoc ToEllipsisLocOrErr = import(D.getEllipsisLoc()); 953 if (!ToEllipsisLocOrErr) 954 return ToEllipsisLocOrErr.takeError(); 955 956 assert(D.isArrayRangeDesignator()); 957 return Designator( 958 D.getFirstExprIndex(), *ToLBracketLocOrErr, *ToEllipsisLocOrErr, 959 *ToRBracketLocOrErr); 960 } 961 962 template <> 963 Expected<LambdaCapture> ASTNodeImporter::import(const LambdaCapture &From) { 964 VarDecl *Var = nullptr; 965 if (From.capturesVariable()) { 966 if (auto VarOrErr = import(From.getCapturedVar())) 967 Var = *VarOrErr; 968 else 969 return VarOrErr.takeError(); 970 } 971 972 auto LocationOrErr = import(From.getLocation()); 973 if (!LocationOrErr) 974 return LocationOrErr.takeError(); 975 976 SourceLocation EllipsisLoc; 977 if (From.isPackExpansion()) 978 if (Error Err = importInto(EllipsisLoc, From.getEllipsisLoc())) 979 return std::move(Err); 980 981 return LambdaCapture( 982 *LocationOrErr, From.isImplicit(), From.getCaptureKind(), Var, 983 EllipsisLoc); 984 } 985 986 template <typename T> 987 bool ASTNodeImporter::hasSameVisibilityContext(T *Found, T *From) { 988 if (From->hasExternalFormalLinkage()) 989 return Found->hasExternalFormalLinkage(); 990 if (Importer.GetFromTU(Found) != From->getTranslationUnitDecl()) 991 return false; 992 if (From->isInAnonymousNamespace()) 993 return Found->isInAnonymousNamespace(); 994 else 995 return !Found->isInAnonymousNamespace() && 996 !Found->hasExternalFormalLinkage(); 997 } 998 999 template <> 1000 bool ASTNodeImporter::hasSameVisibilityContext(TypedefNameDecl *Found, 1001 TypedefNameDecl *From) { 1002 if (From->isInAnonymousNamespace() && Found->isInAnonymousNamespace()) 1003 return Importer.GetFromTU(Found) == From->getTranslationUnitDecl(); 1004 return From->isInAnonymousNamespace() == Found->isInAnonymousNamespace(); 1005 } 1006 1007 } // namespace clang 1008 1009 //---------------------------------------------------------------------------- 1010 // Import Types 1011 //---------------------------------------------------------------------------- 1012 1013 using namespace clang; 1014 1015 ExpectedType ASTNodeImporter::VisitType(const Type *T) { 1016 Importer.FromDiag(SourceLocation(), diag::err_unsupported_ast_node) 1017 << T->getTypeClassName(); 1018 return make_error<ImportError>(ImportError::UnsupportedConstruct); 1019 } 1020 1021 ExpectedType ASTNodeImporter::VisitAtomicType(const AtomicType *T){ 1022 ExpectedType UnderlyingTypeOrErr = import(T->getValueType()); 1023 if (!UnderlyingTypeOrErr) 1024 return UnderlyingTypeOrErr.takeError(); 1025 1026 return Importer.getToContext().getAtomicType(*UnderlyingTypeOrErr); 1027 } 1028 1029 ExpectedType ASTNodeImporter::VisitBuiltinType(const BuiltinType *T) { 1030 switch (T->getKind()) { 1031 #define IMAGE_TYPE(ImgType, Id, SingletonId, Access, Suffix) \ 1032 case BuiltinType::Id: \ 1033 return Importer.getToContext().SingletonId; 1034 #include "clang/Basic/OpenCLImageTypes.def" 1035 #define EXT_OPAQUE_TYPE(ExtType, Id, Ext) \ 1036 case BuiltinType::Id: \ 1037 return Importer.getToContext().Id##Ty; 1038 #include "clang/Basic/OpenCLExtensionTypes.def" 1039 #define SVE_TYPE(Name, Id, SingletonId) \ 1040 case BuiltinType::Id: \ 1041 return Importer.getToContext().SingletonId; 1042 #include "clang/Basic/AArch64SVEACLETypes.def" 1043 #define SHARED_SINGLETON_TYPE(Expansion) 1044 #define BUILTIN_TYPE(Id, SingletonId) \ 1045 case BuiltinType::Id: return Importer.getToContext().SingletonId; 1046 #include "clang/AST/BuiltinTypes.def" 1047 1048 // FIXME: for Char16, Char32, and NullPtr, make sure that the "to" 1049 // context supports C++. 1050 1051 // FIXME: for ObjCId, ObjCClass, and ObjCSel, make sure that the "to" 1052 // context supports ObjC. 1053 1054 case BuiltinType::Char_U: 1055 // The context we're importing from has an unsigned 'char'. If we're 1056 // importing into a context with a signed 'char', translate to 1057 // 'unsigned char' instead. 1058 if (Importer.getToContext().getLangOpts().CharIsSigned) 1059 return Importer.getToContext().UnsignedCharTy; 1060 1061 return Importer.getToContext().CharTy; 1062 1063 case BuiltinType::Char_S: 1064 // The context we're importing from has an unsigned 'char'. If we're 1065 // importing into a context with a signed 'char', translate to 1066 // 'unsigned char' instead. 1067 if (!Importer.getToContext().getLangOpts().CharIsSigned) 1068 return Importer.getToContext().SignedCharTy; 1069 1070 return Importer.getToContext().CharTy; 1071 1072 case BuiltinType::WChar_S: 1073 case BuiltinType::WChar_U: 1074 // FIXME: If not in C++, shall we translate to the C equivalent of 1075 // wchar_t? 1076 return Importer.getToContext().WCharTy; 1077 } 1078 1079 llvm_unreachable("Invalid BuiltinType Kind!"); 1080 } 1081 1082 ExpectedType ASTNodeImporter::VisitDecayedType(const DecayedType *T) { 1083 ExpectedType ToOriginalTypeOrErr = import(T->getOriginalType()); 1084 if (!ToOriginalTypeOrErr) 1085 return ToOriginalTypeOrErr.takeError(); 1086 1087 return Importer.getToContext().getDecayedType(*ToOriginalTypeOrErr); 1088 } 1089 1090 ExpectedType ASTNodeImporter::VisitComplexType(const ComplexType *T) { 1091 ExpectedType ToElementTypeOrErr = import(T->getElementType()); 1092 if (!ToElementTypeOrErr) 1093 return ToElementTypeOrErr.takeError(); 1094 1095 return Importer.getToContext().getComplexType(*ToElementTypeOrErr); 1096 } 1097 1098 ExpectedType ASTNodeImporter::VisitPointerType(const PointerType *T) { 1099 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType()); 1100 if (!ToPointeeTypeOrErr) 1101 return ToPointeeTypeOrErr.takeError(); 1102 1103 return Importer.getToContext().getPointerType(*ToPointeeTypeOrErr); 1104 } 1105 1106 ExpectedType ASTNodeImporter::VisitBlockPointerType(const BlockPointerType *T) { 1107 // FIXME: Check for blocks support in "to" context. 1108 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType()); 1109 if (!ToPointeeTypeOrErr) 1110 return ToPointeeTypeOrErr.takeError(); 1111 1112 return Importer.getToContext().getBlockPointerType(*ToPointeeTypeOrErr); 1113 } 1114 1115 ExpectedType 1116 ASTNodeImporter::VisitLValueReferenceType(const LValueReferenceType *T) { 1117 // FIXME: Check for C++ support in "to" context. 1118 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten()); 1119 if (!ToPointeeTypeOrErr) 1120 return ToPointeeTypeOrErr.takeError(); 1121 1122 return Importer.getToContext().getLValueReferenceType(*ToPointeeTypeOrErr); 1123 } 1124 1125 ExpectedType 1126 ASTNodeImporter::VisitRValueReferenceType(const RValueReferenceType *T) { 1127 // FIXME: Check for C++0x support in "to" context. 1128 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeTypeAsWritten()); 1129 if (!ToPointeeTypeOrErr) 1130 return ToPointeeTypeOrErr.takeError(); 1131 1132 return Importer.getToContext().getRValueReferenceType(*ToPointeeTypeOrErr); 1133 } 1134 1135 ExpectedType 1136 ASTNodeImporter::VisitMemberPointerType(const MemberPointerType *T) { 1137 // FIXME: Check for C++ support in "to" context. 1138 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType()); 1139 if (!ToPointeeTypeOrErr) 1140 return ToPointeeTypeOrErr.takeError(); 1141 1142 ExpectedType ClassTypeOrErr = import(QualType(T->getClass(), 0)); 1143 if (!ClassTypeOrErr) 1144 return ClassTypeOrErr.takeError(); 1145 1146 return Importer.getToContext().getMemberPointerType( 1147 *ToPointeeTypeOrErr, (*ClassTypeOrErr).getTypePtr()); 1148 } 1149 1150 ExpectedType 1151 ASTNodeImporter::VisitConstantArrayType(const ConstantArrayType *T) { 1152 QualType ToElementType; 1153 const Expr *ToSizeExpr; 1154 if (auto Imp = importSeq(T->getElementType(), T->getSizeExpr())) 1155 std::tie(ToElementType, ToSizeExpr) = *Imp; 1156 else 1157 return Imp.takeError(); 1158 1159 return Importer.getToContext().getConstantArrayType( 1160 ToElementType, T->getSize(), ToSizeExpr, T->getSizeModifier(), 1161 T->getIndexTypeCVRQualifiers()); 1162 } 1163 1164 ExpectedType 1165 ASTNodeImporter::VisitIncompleteArrayType(const IncompleteArrayType *T) { 1166 ExpectedType ToElementTypeOrErr = import(T->getElementType()); 1167 if (!ToElementTypeOrErr) 1168 return ToElementTypeOrErr.takeError(); 1169 1170 return Importer.getToContext().getIncompleteArrayType(*ToElementTypeOrErr, 1171 T->getSizeModifier(), 1172 T->getIndexTypeCVRQualifiers()); 1173 } 1174 1175 ExpectedType 1176 ASTNodeImporter::VisitVariableArrayType(const VariableArrayType *T) { 1177 QualType ToElementType; 1178 Expr *ToSizeExpr; 1179 SourceRange ToBracketsRange; 1180 if (auto Imp = importSeq( 1181 T->getElementType(), T->getSizeExpr(), T->getBracketsRange())) 1182 std::tie(ToElementType, ToSizeExpr, ToBracketsRange) = *Imp; 1183 else 1184 return Imp.takeError(); 1185 1186 return Importer.getToContext().getVariableArrayType( 1187 ToElementType, ToSizeExpr, T->getSizeModifier(), 1188 T->getIndexTypeCVRQualifiers(), ToBracketsRange); 1189 } 1190 1191 ExpectedType ASTNodeImporter::VisitDependentSizedArrayType( 1192 const DependentSizedArrayType *T) { 1193 QualType ToElementType; 1194 Expr *ToSizeExpr; 1195 SourceRange ToBracketsRange; 1196 if (auto Imp = importSeq( 1197 T->getElementType(), T->getSizeExpr(), T->getBracketsRange())) 1198 std::tie(ToElementType, ToSizeExpr, ToBracketsRange) = *Imp; 1199 else 1200 return Imp.takeError(); 1201 // SizeExpr may be null if size is not specified directly. 1202 // For example, 'int a[]'. 1203 1204 return Importer.getToContext().getDependentSizedArrayType( 1205 ToElementType, ToSizeExpr, T->getSizeModifier(), 1206 T->getIndexTypeCVRQualifiers(), ToBracketsRange); 1207 } 1208 1209 ExpectedType ASTNodeImporter::VisitVectorType(const VectorType *T) { 1210 ExpectedType ToElementTypeOrErr = import(T->getElementType()); 1211 if (!ToElementTypeOrErr) 1212 return ToElementTypeOrErr.takeError(); 1213 1214 return Importer.getToContext().getVectorType(*ToElementTypeOrErr, 1215 T->getNumElements(), 1216 T->getVectorKind()); 1217 } 1218 1219 ExpectedType ASTNodeImporter::VisitExtVectorType(const ExtVectorType *T) { 1220 ExpectedType ToElementTypeOrErr = import(T->getElementType()); 1221 if (!ToElementTypeOrErr) 1222 return ToElementTypeOrErr.takeError(); 1223 1224 return Importer.getToContext().getExtVectorType(*ToElementTypeOrErr, 1225 T->getNumElements()); 1226 } 1227 1228 ExpectedType 1229 ASTNodeImporter::VisitFunctionNoProtoType(const FunctionNoProtoType *T) { 1230 // FIXME: What happens if we're importing a function without a prototype 1231 // into C++? Should we make it variadic? 1232 ExpectedType ToReturnTypeOrErr = import(T->getReturnType()); 1233 if (!ToReturnTypeOrErr) 1234 return ToReturnTypeOrErr.takeError(); 1235 1236 return Importer.getToContext().getFunctionNoProtoType(*ToReturnTypeOrErr, 1237 T->getExtInfo()); 1238 } 1239 1240 ExpectedType 1241 ASTNodeImporter::VisitFunctionProtoType(const FunctionProtoType *T) { 1242 ExpectedType ToReturnTypeOrErr = import(T->getReturnType()); 1243 if (!ToReturnTypeOrErr) 1244 return ToReturnTypeOrErr.takeError(); 1245 1246 // Import argument types 1247 SmallVector<QualType, 4> ArgTypes; 1248 for (const auto &A : T->param_types()) { 1249 ExpectedType TyOrErr = import(A); 1250 if (!TyOrErr) 1251 return TyOrErr.takeError(); 1252 ArgTypes.push_back(*TyOrErr); 1253 } 1254 1255 // Import exception types 1256 SmallVector<QualType, 4> ExceptionTypes; 1257 for (const auto &E : T->exceptions()) { 1258 ExpectedType TyOrErr = import(E); 1259 if (!TyOrErr) 1260 return TyOrErr.takeError(); 1261 ExceptionTypes.push_back(*TyOrErr); 1262 } 1263 1264 FunctionProtoType::ExtProtoInfo FromEPI = T->getExtProtoInfo(); 1265 FunctionProtoType::ExtProtoInfo ToEPI; 1266 1267 auto Imp = importSeq( 1268 FromEPI.ExceptionSpec.NoexceptExpr, 1269 FromEPI.ExceptionSpec.SourceDecl, 1270 FromEPI.ExceptionSpec.SourceTemplate); 1271 if (!Imp) 1272 return Imp.takeError(); 1273 1274 ToEPI.ExtInfo = FromEPI.ExtInfo; 1275 ToEPI.Variadic = FromEPI.Variadic; 1276 ToEPI.HasTrailingReturn = FromEPI.HasTrailingReturn; 1277 ToEPI.TypeQuals = FromEPI.TypeQuals; 1278 ToEPI.RefQualifier = FromEPI.RefQualifier; 1279 ToEPI.ExceptionSpec.Type = FromEPI.ExceptionSpec.Type; 1280 ToEPI.ExceptionSpec.Exceptions = ExceptionTypes; 1281 std::tie( 1282 ToEPI.ExceptionSpec.NoexceptExpr, 1283 ToEPI.ExceptionSpec.SourceDecl, 1284 ToEPI.ExceptionSpec.SourceTemplate) = *Imp; 1285 1286 return Importer.getToContext().getFunctionType( 1287 *ToReturnTypeOrErr, ArgTypes, ToEPI); 1288 } 1289 1290 ExpectedType ASTNodeImporter::VisitUnresolvedUsingType( 1291 const UnresolvedUsingType *T) { 1292 UnresolvedUsingTypenameDecl *ToD; 1293 Decl *ToPrevD; 1294 if (auto Imp = importSeq(T->getDecl(), T->getDecl()->getPreviousDecl())) 1295 std::tie(ToD, ToPrevD) = *Imp; 1296 else 1297 return Imp.takeError(); 1298 1299 return Importer.getToContext().getTypeDeclType( 1300 ToD, cast_or_null<TypeDecl>(ToPrevD)); 1301 } 1302 1303 ExpectedType ASTNodeImporter::VisitParenType(const ParenType *T) { 1304 ExpectedType ToInnerTypeOrErr = import(T->getInnerType()); 1305 if (!ToInnerTypeOrErr) 1306 return ToInnerTypeOrErr.takeError(); 1307 1308 return Importer.getToContext().getParenType(*ToInnerTypeOrErr); 1309 } 1310 1311 ExpectedType ASTNodeImporter::VisitTypedefType(const TypedefType *T) { 1312 Expected<TypedefNameDecl *> ToDeclOrErr = import(T->getDecl()); 1313 if (!ToDeclOrErr) 1314 return ToDeclOrErr.takeError(); 1315 1316 return Importer.getToContext().getTypeDeclType(*ToDeclOrErr); 1317 } 1318 1319 ExpectedType ASTNodeImporter::VisitTypeOfExprType(const TypeOfExprType *T) { 1320 ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr()); 1321 if (!ToExprOrErr) 1322 return ToExprOrErr.takeError(); 1323 1324 return Importer.getToContext().getTypeOfExprType(*ToExprOrErr); 1325 } 1326 1327 ExpectedType ASTNodeImporter::VisitTypeOfType(const TypeOfType *T) { 1328 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType()); 1329 if (!ToUnderlyingTypeOrErr) 1330 return ToUnderlyingTypeOrErr.takeError(); 1331 1332 return Importer.getToContext().getTypeOfType(*ToUnderlyingTypeOrErr); 1333 } 1334 1335 ExpectedType ASTNodeImporter::VisitDecltypeType(const DecltypeType *T) { 1336 // FIXME: Make sure that the "to" context supports C++0x! 1337 ExpectedExpr ToExprOrErr = import(T->getUnderlyingExpr()); 1338 if (!ToExprOrErr) 1339 return ToExprOrErr.takeError(); 1340 1341 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType()); 1342 if (!ToUnderlyingTypeOrErr) 1343 return ToUnderlyingTypeOrErr.takeError(); 1344 1345 return Importer.getToContext().getDecltypeType( 1346 *ToExprOrErr, *ToUnderlyingTypeOrErr); 1347 } 1348 1349 ExpectedType 1350 ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) { 1351 ExpectedType ToBaseTypeOrErr = import(T->getBaseType()); 1352 if (!ToBaseTypeOrErr) 1353 return ToBaseTypeOrErr.takeError(); 1354 1355 ExpectedType ToUnderlyingTypeOrErr = import(T->getUnderlyingType()); 1356 if (!ToUnderlyingTypeOrErr) 1357 return ToUnderlyingTypeOrErr.takeError(); 1358 1359 return Importer.getToContext().getUnaryTransformType( 1360 *ToBaseTypeOrErr, *ToUnderlyingTypeOrErr, T->getUTTKind()); 1361 } 1362 1363 ExpectedType ASTNodeImporter::VisitAutoType(const AutoType *T) { 1364 // FIXME: Make sure that the "to" context supports C++11! 1365 ExpectedType ToDeducedTypeOrErr = import(T->getDeducedType()); 1366 if (!ToDeducedTypeOrErr) 1367 return ToDeducedTypeOrErr.takeError(); 1368 1369 ExpectedDecl ToTypeConstraintConcept = import(T->getTypeConstraintConcept()); 1370 if (!ToTypeConstraintConcept) 1371 return ToTypeConstraintConcept.takeError(); 1372 1373 SmallVector<TemplateArgument, 2> ToTemplateArgs; 1374 ArrayRef<TemplateArgument> FromTemplateArgs = T->getTypeConstraintArguments(); 1375 if (Error Err = ImportTemplateArguments(FromTemplateArgs.data(), 1376 FromTemplateArgs.size(), 1377 ToTemplateArgs)) 1378 return std::move(Err); 1379 1380 return Importer.getToContext().getAutoType( 1381 *ToDeducedTypeOrErr, T->getKeyword(), /*IsDependent*/false, 1382 /*IsPack=*/false, cast_or_null<ConceptDecl>(*ToTypeConstraintConcept), 1383 ToTemplateArgs); 1384 } 1385 1386 ExpectedType ASTNodeImporter::VisitInjectedClassNameType( 1387 const InjectedClassNameType *T) { 1388 Expected<CXXRecordDecl *> ToDeclOrErr = import(T->getDecl()); 1389 if (!ToDeclOrErr) 1390 return ToDeclOrErr.takeError(); 1391 1392 ExpectedType ToInjTypeOrErr = import(T->getInjectedSpecializationType()); 1393 if (!ToInjTypeOrErr) 1394 return ToInjTypeOrErr.takeError(); 1395 1396 // FIXME: ASTContext::getInjectedClassNameType is not suitable for AST reading 1397 // See comments in InjectedClassNameType definition for details 1398 // return Importer.getToContext().getInjectedClassNameType(D, InjType); 1399 enum { 1400 TypeAlignmentInBits = 4, 1401 TypeAlignment = 1 << TypeAlignmentInBits 1402 }; 1403 1404 return QualType(new (Importer.getToContext(), TypeAlignment) 1405 InjectedClassNameType(*ToDeclOrErr, *ToInjTypeOrErr), 0); 1406 } 1407 1408 ExpectedType ASTNodeImporter::VisitRecordType(const RecordType *T) { 1409 Expected<RecordDecl *> ToDeclOrErr = import(T->getDecl()); 1410 if (!ToDeclOrErr) 1411 return ToDeclOrErr.takeError(); 1412 1413 return Importer.getToContext().getTagDeclType(*ToDeclOrErr); 1414 } 1415 1416 ExpectedType ASTNodeImporter::VisitEnumType(const EnumType *T) { 1417 Expected<EnumDecl *> ToDeclOrErr = import(T->getDecl()); 1418 if (!ToDeclOrErr) 1419 return ToDeclOrErr.takeError(); 1420 1421 return Importer.getToContext().getTagDeclType(*ToDeclOrErr); 1422 } 1423 1424 ExpectedType ASTNodeImporter::VisitAttributedType(const AttributedType *T) { 1425 ExpectedType ToModifiedTypeOrErr = import(T->getModifiedType()); 1426 if (!ToModifiedTypeOrErr) 1427 return ToModifiedTypeOrErr.takeError(); 1428 ExpectedType ToEquivalentTypeOrErr = import(T->getEquivalentType()); 1429 if (!ToEquivalentTypeOrErr) 1430 return ToEquivalentTypeOrErr.takeError(); 1431 1432 return Importer.getToContext().getAttributedType(T->getAttrKind(), 1433 *ToModifiedTypeOrErr, *ToEquivalentTypeOrErr); 1434 } 1435 1436 ExpectedType ASTNodeImporter::VisitTemplateTypeParmType( 1437 const TemplateTypeParmType *T) { 1438 Expected<TemplateTypeParmDecl *> ToDeclOrErr = import(T->getDecl()); 1439 if (!ToDeclOrErr) 1440 return ToDeclOrErr.takeError(); 1441 1442 return Importer.getToContext().getTemplateTypeParmType( 1443 T->getDepth(), T->getIndex(), T->isParameterPack(), *ToDeclOrErr); 1444 } 1445 1446 ExpectedType ASTNodeImporter::VisitSubstTemplateTypeParmType( 1447 const SubstTemplateTypeParmType *T) { 1448 ExpectedType ReplacedOrErr = import(QualType(T->getReplacedParameter(), 0)); 1449 if (!ReplacedOrErr) 1450 return ReplacedOrErr.takeError(); 1451 const TemplateTypeParmType *Replaced = 1452 cast<TemplateTypeParmType>((*ReplacedOrErr).getTypePtr()); 1453 1454 ExpectedType ToReplacementTypeOrErr = import(T->getReplacementType()); 1455 if (!ToReplacementTypeOrErr) 1456 return ToReplacementTypeOrErr.takeError(); 1457 1458 return Importer.getToContext().getSubstTemplateTypeParmType( 1459 Replaced, (*ToReplacementTypeOrErr).getCanonicalType()); 1460 } 1461 1462 ExpectedType ASTNodeImporter::VisitTemplateSpecializationType( 1463 const TemplateSpecializationType *T) { 1464 auto ToTemplateOrErr = import(T->getTemplateName()); 1465 if (!ToTemplateOrErr) 1466 return ToTemplateOrErr.takeError(); 1467 1468 SmallVector<TemplateArgument, 2> ToTemplateArgs; 1469 if (Error Err = ImportTemplateArguments( 1470 T->getArgs(), T->getNumArgs(), ToTemplateArgs)) 1471 return std::move(Err); 1472 1473 QualType ToCanonType; 1474 if (!QualType(T, 0).isCanonical()) { 1475 QualType FromCanonType 1476 = Importer.getFromContext().getCanonicalType(QualType(T, 0)); 1477 if (ExpectedType TyOrErr = import(FromCanonType)) 1478 ToCanonType = *TyOrErr; 1479 else 1480 return TyOrErr.takeError(); 1481 } 1482 return Importer.getToContext().getTemplateSpecializationType(*ToTemplateOrErr, 1483 ToTemplateArgs, 1484 ToCanonType); 1485 } 1486 1487 ExpectedType ASTNodeImporter::VisitElaboratedType(const ElaboratedType *T) { 1488 // Note: the qualifier in an ElaboratedType is optional. 1489 auto ToQualifierOrErr = import(T->getQualifier()); 1490 if (!ToQualifierOrErr) 1491 return ToQualifierOrErr.takeError(); 1492 1493 ExpectedType ToNamedTypeOrErr = import(T->getNamedType()); 1494 if (!ToNamedTypeOrErr) 1495 return ToNamedTypeOrErr.takeError(); 1496 1497 Expected<TagDecl *> ToOwnedTagDeclOrErr = import(T->getOwnedTagDecl()); 1498 if (!ToOwnedTagDeclOrErr) 1499 return ToOwnedTagDeclOrErr.takeError(); 1500 1501 return Importer.getToContext().getElaboratedType(T->getKeyword(), 1502 *ToQualifierOrErr, 1503 *ToNamedTypeOrErr, 1504 *ToOwnedTagDeclOrErr); 1505 } 1506 1507 ExpectedType 1508 ASTNodeImporter::VisitPackExpansionType(const PackExpansionType *T) { 1509 ExpectedType ToPatternOrErr = import(T->getPattern()); 1510 if (!ToPatternOrErr) 1511 return ToPatternOrErr.takeError(); 1512 1513 return Importer.getToContext().getPackExpansionType(*ToPatternOrErr, 1514 T->getNumExpansions()); 1515 } 1516 1517 ExpectedType ASTNodeImporter::VisitDependentTemplateSpecializationType( 1518 const DependentTemplateSpecializationType *T) { 1519 auto ToQualifierOrErr = import(T->getQualifier()); 1520 if (!ToQualifierOrErr) 1521 return ToQualifierOrErr.takeError(); 1522 1523 IdentifierInfo *ToName = Importer.Import(T->getIdentifier()); 1524 1525 SmallVector<TemplateArgument, 2> ToPack; 1526 ToPack.reserve(T->getNumArgs()); 1527 if (Error Err = ImportTemplateArguments( 1528 T->getArgs(), T->getNumArgs(), ToPack)) 1529 return std::move(Err); 1530 1531 return Importer.getToContext().getDependentTemplateSpecializationType( 1532 T->getKeyword(), *ToQualifierOrErr, ToName, ToPack); 1533 } 1534 1535 ExpectedType 1536 ASTNodeImporter::VisitDependentNameType(const DependentNameType *T) { 1537 auto ToQualifierOrErr = import(T->getQualifier()); 1538 if (!ToQualifierOrErr) 1539 return ToQualifierOrErr.takeError(); 1540 1541 IdentifierInfo *Name = Importer.Import(T->getIdentifier()); 1542 1543 QualType Canon; 1544 if (T != T->getCanonicalTypeInternal().getTypePtr()) { 1545 if (ExpectedType TyOrErr = import(T->getCanonicalTypeInternal())) 1546 Canon = (*TyOrErr).getCanonicalType(); 1547 else 1548 return TyOrErr.takeError(); 1549 } 1550 1551 return Importer.getToContext().getDependentNameType(T->getKeyword(), 1552 *ToQualifierOrErr, 1553 Name, Canon); 1554 } 1555 1556 ExpectedType 1557 ASTNodeImporter::VisitObjCInterfaceType(const ObjCInterfaceType *T) { 1558 Expected<ObjCInterfaceDecl *> ToDeclOrErr = import(T->getDecl()); 1559 if (!ToDeclOrErr) 1560 return ToDeclOrErr.takeError(); 1561 1562 return Importer.getToContext().getObjCInterfaceType(*ToDeclOrErr); 1563 } 1564 1565 ExpectedType ASTNodeImporter::VisitObjCObjectType(const ObjCObjectType *T) { 1566 ExpectedType ToBaseTypeOrErr = import(T->getBaseType()); 1567 if (!ToBaseTypeOrErr) 1568 return ToBaseTypeOrErr.takeError(); 1569 1570 SmallVector<QualType, 4> TypeArgs; 1571 for (auto TypeArg : T->getTypeArgsAsWritten()) { 1572 if (ExpectedType TyOrErr = import(TypeArg)) 1573 TypeArgs.push_back(*TyOrErr); 1574 else 1575 return TyOrErr.takeError(); 1576 } 1577 1578 SmallVector<ObjCProtocolDecl *, 4> Protocols; 1579 for (auto *P : T->quals()) { 1580 if (Expected<ObjCProtocolDecl *> ProtocolOrErr = import(P)) 1581 Protocols.push_back(*ProtocolOrErr); 1582 else 1583 return ProtocolOrErr.takeError(); 1584 1585 } 1586 1587 return Importer.getToContext().getObjCObjectType(*ToBaseTypeOrErr, TypeArgs, 1588 Protocols, 1589 T->isKindOfTypeAsWritten()); 1590 } 1591 1592 ExpectedType 1593 ASTNodeImporter::VisitObjCObjectPointerType(const ObjCObjectPointerType *T) { 1594 ExpectedType ToPointeeTypeOrErr = import(T->getPointeeType()); 1595 if (!ToPointeeTypeOrErr) 1596 return ToPointeeTypeOrErr.takeError(); 1597 1598 return Importer.getToContext().getObjCObjectPointerType(*ToPointeeTypeOrErr); 1599 } 1600 1601 //---------------------------------------------------------------------------- 1602 // Import Declarations 1603 //---------------------------------------------------------------------------- 1604 Error ASTNodeImporter::ImportDeclParts( 1605 NamedDecl *D, DeclContext *&DC, DeclContext *&LexicalDC, 1606 DeclarationName &Name, NamedDecl *&ToD, SourceLocation &Loc) { 1607 // Check if RecordDecl is in FunctionDecl parameters to avoid infinite loop. 1608 // example: int struct_in_proto(struct data_t{int a;int b;} *d); 1609 // FIXME: We could support these constructs by importing a different type of 1610 // this parameter and by importing the original type of the parameter only 1611 // after the FunctionDecl is created. See 1612 // VisitFunctionDecl::UsedDifferentProtoType. 1613 DeclContext *OrigDC = D->getDeclContext(); 1614 FunctionDecl *FunDecl; 1615 if (isa<RecordDecl>(D) && (FunDecl = dyn_cast<FunctionDecl>(OrigDC)) && 1616 FunDecl->hasBody()) { 1617 auto getLeafPointeeType = [](const Type *T) { 1618 while (T->isPointerType() || T->isArrayType()) { 1619 T = T->getPointeeOrArrayElementType(); 1620 } 1621 return T; 1622 }; 1623 for (const ParmVarDecl *P : FunDecl->parameters()) { 1624 const Type *LeafT = 1625 getLeafPointeeType(P->getType().getCanonicalType().getTypePtr()); 1626 auto *RT = dyn_cast<RecordType>(LeafT); 1627 if (RT && RT->getDecl() == D) { 1628 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node) 1629 << D->getDeclKindName(); 1630 return make_error<ImportError>(ImportError::UnsupportedConstruct); 1631 } 1632 } 1633 } 1634 1635 // Import the context of this declaration. 1636 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 1637 return Err; 1638 1639 // Import the name of this declaration. 1640 if (Error Err = importInto(Name, D->getDeclName())) 1641 return Err; 1642 1643 // Import the location of this declaration. 1644 if (Error Err = importInto(Loc, D->getLocation())) 1645 return Err; 1646 1647 ToD = cast_or_null<NamedDecl>(Importer.GetAlreadyImportedOrNull(D)); 1648 if (ToD) 1649 if (Error Err = ASTNodeImporter(*this).ImportDefinitionIfNeeded(D, ToD)) 1650 return Err; 1651 1652 return Error::success(); 1653 } 1654 1655 Error ASTNodeImporter::ImportDefinitionIfNeeded(Decl *FromD, Decl *ToD) { 1656 if (!FromD) 1657 return Error::success(); 1658 1659 if (!ToD) 1660 if (Error Err = importInto(ToD, FromD)) 1661 return Err; 1662 1663 if (RecordDecl *FromRecord = dyn_cast<RecordDecl>(FromD)) { 1664 if (RecordDecl *ToRecord = cast<RecordDecl>(ToD)) { 1665 if (FromRecord->getDefinition() && FromRecord->isCompleteDefinition() && 1666 !ToRecord->getDefinition()) { 1667 if (Error Err = ImportDefinition(FromRecord, ToRecord)) 1668 return Err; 1669 } 1670 } 1671 return Error::success(); 1672 } 1673 1674 if (EnumDecl *FromEnum = dyn_cast<EnumDecl>(FromD)) { 1675 if (EnumDecl *ToEnum = cast<EnumDecl>(ToD)) { 1676 if (FromEnum->getDefinition() && !ToEnum->getDefinition()) { 1677 if (Error Err = ImportDefinition(FromEnum, ToEnum)) 1678 return Err; 1679 } 1680 } 1681 return Error::success(); 1682 } 1683 1684 return Error::success(); 1685 } 1686 1687 Error 1688 ASTNodeImporter::ImportDeclarationNameLoc( 1689 const DeclarationNameInfo &From, DeclarationNameInfo& To) { 1690 // NOTE: To.Name and To.Loc are already imported. 1691 // We only have to import To.LocInfo. 1692 switch (To.getName().getNameKind()) { 1693 case DeclarationName::Identifier: 1694 case DeclarationName::ObjCZeroArgSelector: 1695 case DeclarationName::ObjCOneArgSelector: 1696 case DeclarationName::ObjCMultiArgSelector: 1697 case DeclarationName::CXXUsingDirective: 1698 case DeclarationName::CXXDeductionGuideName: 1699 return Error::success(); 1700 1701 case DeclarationName::CXXOperatorName: { 1702 if (auto ToRangeOrErr = import(From.getCXXOperatorNameRange())) 1703 To.setCXXOperatorNameRange(*ToRangeOrErr); 1704 else 1705 return ToRangeOrErr.takeError(); 1706 return Error::success(); 1707 } 1708 case DeclarationName::CXXLiteralOperatorName: { 1709 if (ExpectedSLoc LocOrErr = import(From.getCXXLiteralOperatorNameLoc())) 1710 To.setCXXLiteralOperatorNameLoc(*LocOrErr); 1711 else 1712 return LocOrErr.takeError(); 1713 return Error::success(); 1714 } 1715 case DeclarationName::CXXConstructorName: 1716 case DeclarationName::CXXDestructorName: 1717 case DeclarationName::CXXConversionFunctionName: { 1718 if (auto ToTInfoOrErr = import(From.getNamedTypeInfo())) 1719 To.setNamedTypeInfo(*ToTInfoOrErr); 1720 else 1721 return ToTInfoOrErr.takeError(); 1722 return Error::success(); 1723 } 1724 } 1725 llvm_unreachable("Unknown name kind."); 1726 } 1727 1728 Error 1729 ASTNodeImporter::ImportDeclContext(DeclContext *FromDC, bool ForceImport) { 1730 if (Importer.isMinimalImport() && !ForceImport) { 1731 auto ToDCOrErr = Importer.ImportContext(FromDC); 1732 return ToDCOrErr.takeError(); 1733 } 1734 1735 // We use strict error handling in case of records and enums, but not 1736 // with e.g. namespaces. 1737 // 1738 // FIXME Clients of the ASTImporter should be able to choose an 1739 // appropriate error handling strategy for their needs. For instance, 1740 // they may not want to mark an entire namespace as erroneous merely 1741 // because there is an ODR error with two typedefs. As another example, 1742 // the client may allow EnumConstantDecls with same names but with 1743 // different values in two distinct translation units. 1744 bool AccumulateChildErrors = isa<TagDecl>(FromDC); 1745 1746 Error ChildErrors = Error::success(); 1747 for (auto *From : FromDC->decls()) { 1748 ExpectedDecl ImportedOrErr = import(From); 1749 1750 // If we are in the process of ImportDefinition(...) for a RecordDecl we 1751 // want to make sure that we are also completing each FieldDecl. There 1752 // are currently cases where this does not happen and this is correctness 1753 // fix since operations such as code generation will expect this to be so. 1754 if (ImportedOrErr) { 1755 FieldDecl *FieldFrom = dyn_cast_or_null<FieldDecl>(From); 1756 Decl *ImportedDecl = (Decl*)*ImportedOrErr; 1757 FieldDecl *FieldTo = dyn_cast_or_null<FieldDecl>(ImportedDecl); 1758 if (FieldFrom && FieldTo) { 1759 const RecordType *RecordFrom = FieldFrom->getType()->getAs<RecordType>(); 1760 const RecordType *RecordTo = FieldTo->getType()->getAs<RecordType>(); 1761 if (RecordFrom && RecordTo) { 1762 RecordDecl *FromRecordDecl = RecordFrom->getDecl(); 1763 RecordDecl *ToRecordDecl = RecordTo->getDecl(); 1764 1765 if (FromRecordDecl->isCompleteDefinition() && 1766 !ToRecordDecl->isCompleteDefinition()) { 1767 Error Err = ImportDefinition(FromRecordDecl, ToRecordDecl); 1768 1769 if (Err && AccumulateChildErrors) 1770 ChildErrors = joinErrors(std::move(ChildErrors), std::move(Err)); 1771 else 1772 consumeError(std::move(Err)); 1773 } 1774 } 1775 } 1776 } else { 1777 if (AccumulateChildErrors) 1778 ChildErrors = 1779 joinErrors(std::move(ChildErrors), ImportedOrErr.takeError()); 1780 else 1781 consumeError(ImportedOrErr.takeError()); 1782 } 1783 } 1784 1785 // We reorder declarations in RecordDecls because they may have another order 1786 // in the "to" context than they have in the "from" context. This may happen 1787 // e.g when we import a class like this: 1788 // struct declToImport { 1789 // int a = c + b; 1790 // int b = 1; 1791 // int c = 2; 1792 // }; 1793 // During the import of `a` we import first the dependencies in sequence, 1794 // thus the order would be `c`, `b`, `a`. We will get the normal order by 1795 // first removing the already imported members and then adding them in the 1796 // order as they apper in the "from" context. 1797 // 1798 // Keeping field order is vital because it determines structure layout. 1799 // 1800 // Here and below, we cannot call field_begin() method and its callers on 1801 // ToDC if it has an external storage. Calling field_begin() will 1802 // automatically load all the fields by calling 1803 // LoadFieldsFromExternalStorage(). LoadFieldsFromExternalStorage() would 1804 // call ASTImporter::Import(). This is because the ExternalASTSource 1805 // interface in LLDB is implemented by the means of the ASTImporter. However, 1806 // calling an import at this point would result in an uncontrolled import, we 1807 // must avoid that. 1808 const auto *FromRD = dyn_cast<RecordDecl>(FromDC); 1809 if (!FromRD) 1810 return ChildErrors; 1811 1812 auto ToDCOrErr = Importer.ImportContext(FromDC); 1813 if (!ToDCOrErr) { 1814 consumeError(std::move(ChildErrors)); 1815 return ToDCOrErr.takeError(); 1816 } 1817 1818 DeclContext *ToDC = *ToDCOrErr; 1819 // Remove all declarations, which may be in wrong order in the 1820 // lexical DeclContext and then add them in the proper order. 1821 for (auto *D : FromRD->decls()) { 1822 if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<FriendDecl>(D)) { 1823 assert(D && "DC contains a null decl"); 1824 Decl *ToD = Importer.GetAlreadyImportedOrNull(D); 1825 // Remove only the decls which we successfully imported. 1826 if (ToD) { 1827 assert(ToDC == ToD->getLexicalDeclContext() && ToDC->containsDecl(ToD)); 1828 // Remove the decl from its wrong place in the linked list. 1829 ToDC->removeDecl(ToD); 1830 // Add the decl to the end of the linked list. 1831 // This time it will be at the proper place because the enclosing for 1832 // loop iterates in the original (good) order of the decls. 1833 ToDC->addDeclInternal(ToD); 1834 } 1835 } 1836 } 1837 1838 return ChildErrors; 1839 } 1840 1841 Error ASTNodeImporter::ImportDeclContext( 1842 Decl *FromD, DeclContext *&ToDC, DeclContext *&ToLexicalDC) { 1843 auto ToDCOrErr = Importer.ImportContext(FromD->getDeclContext()); 1844 if (!ToDCOrErr) 1845 return ToDCOrErr.takeError(); 1846 ToDC = *ToDCOrErr; 1847 1848 if (FromD->getDeclContext() != FromD->getLexicalDeclContext()) { 1849 auto ToLexicalDCOrErr = Importer.ImportContext( 1850 FromD->getLexicalDeclContext()); 1851 if (!ToLexicalDCOrErr) 1852 return ToLexicalDCOrErr.takeError(); 1853 ToLexicalDC = *ToLexicalDCOrErr; 1854 } else 1855 ToLexicalDC = ToDC; 1856 1857 return Error::success(); 1858 } 1859 1860 Error ASTNodeImporter::ImportImplicitMethods( 1861 const CXXRecordDecl *From, CXXRecordDecl *To) { 1862 assert(From->isCompleteDefinition() && To->getDefinition() == To && 1863 "Import implicit methods to or from non-definition"); 1864 1865 for (CXXMethodDecl *FromM : From->methods()) 1866 if (FromM->isImplicit()) { 1867 Expected<CXXMethodDecl *> ToMOrErr = import(FromM); 1868 if (!ToMOrErr) 1869 return ToMOrErr.takeError(); 1870 } 1871 1872 return Error::success(); 1873 } 1874 1875 static Error setTypedefNameForAnonDecl(TagDecl *From, TagDecl *To, 1876 ASTImporter &Importer) { 1877 if (TypedefNameDecl *FromTypedef = From->getTypedefNameForAnonDecl()) { 1878 if (ExpectedDecl ToTypedefOrErr = Importer.Import(FromTypedef)) 1879 To->setTypedefNameForAnonDecl(cast<TypedefNameDecl>(*ToTypedefOrErr)); 1880 else 1881 return ToTypedefOrErr.takeError(); 1882 } 1883 return Error::success(); 1884 } 1885 1886 Error ASTNodeImporter::ImportDefinition( 1887 RecordDecl *From, RecordDecl *To, ImportDefinitionKind Kind) { 1888 auto DefinitionCompleter = [To]() { 1889 // There are cases in LLDB when we first import a class without its 1890 // members. The class will have DefinitionData, but no members. Then, 1891 // importDefinition is called from LLDB, which tries to get the members, so 1892 // when we get here, the class already has the DefinitionData set, so we 1893 // must unset the CompleteDefinition here to be able to complete again the 1894 // definition. 1895 To->setCompleteDefinition(false); 1896 To->completeDefinition(); 1897 }; 1898 1899 if (To->getDefinition() || To->isBeingDefined()) { 1900 if (Kind == IDK_Everything || 1901 // In case of lambdas, the class already has a definition ptr set, but 1902 // the contained decls are not imported yet. Also, isBeingDefined was 1903 // set in CXXRecordDecl::CreateLambda. We must import the contained 1904 // decls here and finish the definition. 1905 (To->isLambda() && shouldForceImportDeclContext(Kind))) { 1906 Error Result = ImportDeclContext(From, /*ForceImport=*/true); 1907 // Finish the definition of the lambda, set isBeingDefined to false. 1908 if (To->isLambda()) 1909 DefinitionCompleter(); 1910 return Result; 1911 } 1912 1913 return Error::success(); 1914 } 1915 1916 To->startDefinition(); 1917 // Complete the definition even if error is returned. 1918 // The RecordDecl may be already part of the AST so it is better to 1919 // have it in complete state even if something is wrong with it. 1920 auto DefinitionCompleterScopeExit = 1921 llvm::make_scope_exit(DefinitionCompleter); 1922 1923 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer)) 1924 return Err; 1925 1926 // Add base classes. 1927 auto *ToCXX = dyn_cast<CXXRecordDecl>(To); 1928 auto *FromCXX = dyn_cast<CXXRecordDecl>(From); 1929 if (ToCXX && FromCXX && ToCXX->dataPtr() && FromCXX->dataPtr()) { 1930 1931 struct CXXRecordDecl::DefinitionData &ToData = ToCXX->data(); 1932 struct CXXRecordDecl::DefinitionData &FromData = FromCXX->data(); 1933 1934 #define FIELD(Name, Width, Merge) \ 1935 ToData.Name = FromData.Name; 1936 #include "clang/AST/CXXRecordDeclDefinitionBits.def" 1937 1938 // Copy over the data stored in RecordDeclBits 1939 ToCXX->setArgPassingRestrictions(FromCXX->getArgPassingRestrictions()); 1940 1941 SmallVector<CXXBaseSpecifier *, 4> Bases; 1942 for (const auto &Base1 : FromCXX->bases()) { 1943 ExpectedType TyOrErr = import(Base1.getType()); 1944 if (!TyOrErr) 1945 return TyOrErr.takeError(); 1946 1947 SourceLocation EllipsisLoc; 1948 if (Base1.isPackExpansion()) { 1949 if (ExpectedSLoc LocOrErr = import(Base1.getEllipsisLoc())) 1950 EllipsisLoc = *LocOrErr; 1951 else 1952 return LocOrErr.takeError(); 1953 } 1954 1955 // Ensure that we have a definition for the base. 1956 if (Error Err = 1957 ImportDefinitionIfNeeded(Base1.getType()->getAsCXXRecordDecl())) 1958 return Err; 1959 1960 auto RangeOrErr = import(Base1.getSourceRange()); 1961 if (!RangeOrErr) 1962 return RangeOrErr.takeError(); 1963 1964 auto TSIOrErr = import(Base1.getTypeSourceInfo()); 1965 if (!TSIOrErr) 1966 return TSIOrErr.takeError(); 1967 1968 Bases.push_back( 1969 new (Importer.getToContext()) CXXBaseSpecifier( 1970 *RangeOrErr, 1971 Base1.isVirtual(), 1972 Base1.isBaseOfClass(), 1973 Base1.getAccessSpecifierAsWritten(), 1974 *TSIOrErr, 1975 EllipsisLoc)); 1976 } 1977 if (!Bases.empty()) 1978 ToCXX->setBases(Bases.data(), Bases.size()); 1979 } 1980 1981 if (shouldForceImportDeclContext(Kind)) 1982 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true)) 1983 return Err; 1984 1985 return Error::success(); 1986 } 1987 1988 Error ASTNodeImporter::ImportInitializer(VarDecl *From, VarDecl *To) { 1989 if (To->getAnyInitializer()) 1990 return Error::success(); 1991 1992 Expr *FromInit = From->getInit(); 1993 if (!FromInit) 1994 return Error::success(); 1995 1996 ExpectedExpr ToInitOrErr = import(FromInit); 1997 if (!ToInitOrErr) 1998 return ToInitOrErr.takeError(); 1999 2000 To->setInit(*ToInitOrErr); 2001 if (From->isInitKnownICE()) { 2002 EvaluatedStmt *Eval = To->ensureEvaluatedStmt(); 2003 Eval->CheckedICE = true; 2004 Eval->IsICE = From->isInitICE(); 2005 } 2006 2007 // FIXME: Other bits to merge? 2008 return Error::success(); 2009 } 2010 2011 Error ASTNodeImporter::ImportDefinition( 2012 EnumDecl *From, EnumDecl *To, ImportDefinitionKind Kind) { 2013 if (To->getDefinition() || To->isBeingDefined()) { 2014 if (Kind == IDK_Everything) 2015 return ImportDeclContext(From, /*ForceImport=*/true); 2016 return Error::success(); 2017 } 2018 2019 To->startDefinition(); 2020 2021 if (Error Err = setTypedefNameForAnonDecl(From, To, Importer)) 2022 return Err; 2023 2024 ExpectedType ToTypeOrErr = 2025 import(Importer.getFromContext().getTypeDeclType(From)); 2026 if (!ToTypeOrErr) 2027 return ToTypeOrErr.takeError(); 2028 2029 ExpectedType ToPromotionTypeOrErr = import(From->getPromotionType()); 2030 if (!ToPromotionTypeOrErr) 2031 return ToPromotionTypeOrErr.takeError(); 2032 2033 if (shouldForceImportDeclContext(Kind)) 2034 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true)) 2035 return Err; 2036 2037 // FIXME: we might need to merge the number of positive or negative bits 2038 // if the enumerator lists don't match. 2039 To->completeDefinition(*ToTypeOrErr, *ToPromotionTypeOrErr, 2040 From->getNumPositiveBits(), 2041 From->getNumNegativeBits()); 2042 return Error::success(); 2043 } 2044 2045 Error ASTNodeImporter::ImportTemplateArguments( 2046 const TemplateArgument *FromArgs, unsigned NumFromArgs, 2047 SmallVectorImpl<TemplateArgument> &ToArgs) { 2048 for (unsigned I = 0; I != NumFromArgs; ++I) { 2049 if (auto ToOrErr = import(FromArgs[I])) 2050 ToArgs.push_back(*ToOrErr); 2051 else 2052 return ToOrErr.takeError(); 2053 } 2054 2055 return Error::success(); 2056 } 2057 2058 // FIXME: Do not forget to remove this and use only 'import'. 2059 Expected<TemplateArgument> 2060 ASTNodeImporter::ImportTemplateArgument(const TemplateArgument &From) { 2061 return import(From); 2062 } 2063 2064 template <typename InContainerTy> 2065 Error ASTNodeImporter::ImportTemplateArgumentListInfo( 2066 const InContainerTy &Container, TemplateArgumentListInfo &ToTAInfo) { 2067 for (const auto &FromLoc : Container) { 2068 if (auto ToLocOrErr = import(FromLoc)) 2069 ToTAInfo.addArgument(*ToLocOrErr); 2070 else 2071 return ToLocOrErr.takeError(); 2072 } 2073 return Error::success(); 2074 } 2075 2076 static StructuralEquivalenceKind 2077 getStructuralEquivalenceKind(const ASTImporter &Importer) { 2078 return Importer.isMinimalImport() ? StructuralEquivalenceKind::Minimal 2079 : StructuralEquivalenceKind::Default; 2080 } 2081 2082 bool ASTNodeImporter::IsStructuralMatch(Decl *From, Decl *To, bool Complain) { 2083 StructuralEquivalenceContext Ctx( 2084 Importer.getFromContext(), Importer.getToContext(), 2085 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer), 2086 false, Complain); 2087 return Ctx.IsEquivalent(From, To); 2088 } 2089 2090 bool ASTNodeImporter::IsStructuralMatch(RecordDecl *FromRecord, 2091 RecordDecl *ToRecord, bool Complain) { 2092 // Eliminate a potential failure point where we attempt to re-import 2093 // something we're trying to import while completing ToRecord. 2094 Decl *ToOrigin = Importer.GetOriginalDecl(ToRecord); 2095 if (ToOrigin) { 2096 auto *ToOriginRecord = dyn_cast<RecordDecl>(ToOrigin); 2097 if (ToOriginRecord) 2098 ToRecord = ToOriginRecord; 2099 } 2100 2101 StructuralEquivalenceContext Ctx(Importer.getFromContext(), 2102 ToRecord->getASTContext(), 2103 Importer.getNonEquivalentDecls(), 2104 getStructuralEquivalenceKind(Importer), 2105 false, Complain); 2106 return Ctx.IsEquivalent(FromRecord, ToRecord); 2107 } 2108 2109 bool ASTNodeImporter::IsStructuralMatch(VarDecl *FromVar, VarDecl *ToVar, 2110 bool Complain) { 2111 StructuralEquivalenceContext Ctx( 2112 Importer.getFromContext(), Importer.getToContext(), 2113 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer), 2114 false, Complain); 2115 return Ctx.IsEquivalent(FromVar, ToVar); 2116 } 2117 2118 bool ASTNodeImporter::IsStructuralMatch(EnumDecl *FromEnum, EnumDecl *ToEnum) { 2119 // Eliminate a potential failure point where we attempt to re-import 2120 // something we're trying to import while completing ToEnum. 2121 if (Decl *ToOrigin = Importer.GetOriginalDecl(ToEnum)) 2122 if (auto *ToOriginEnum = dyn_cast<EnumDecl>(ToOrigin)) 2123 ToEnum = ToOriginEnum; 2124 2125 StructuralEquivalenceContext Ctx( 2126 Importer.getFromContext(), Importer.getToContext(), 2127 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer)); 2128 return Ctx.IsEquivalent(FromEnum, ToEnum); 2129 } 2130 2131 bool ASTNodeImporter::IsStructuralMatch(FunctionTemplateDecl *From, 2132 FunctionTemplateDecl *To) { 2133 StructuralEquivalenceContext Ctx( 2134 Importer.getFromContext(), Importer.getToContext(), 2135 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer), 2136 false, false); 2137 return Ctx.IsEquivalent(From, To); 2138 } 2139 2140 bool ASTNodeImporter::IsStructuralMatch(FunctionDecl *From, FunctionDecl *To) { 2141 StructuralEquivalenceContext Ctx( 2142 Importer.getFromContext(), Importer.getToContext(), 2143 Importer.getNonEquivalentDecls(), getStructuralEquivalenceKind(Importer), 2144 false, false); 2145 return Ctx.IsEquivalent(From, To); 2146 } 2147 2148 bool ASTNodeImporter::IsStructuralMatch(EnumConstantDecl *FromEC, 2149 EnumConstantDecl *ToEC) { 2150 const llvm::APSInt &FromVal = FromEC->getInitVal(); 2151 const llvm::APSInt &ToVal = ToEC->getInitVal(); 2152 2153 return FromVal.isSigned() == ToVal.isSigned() && 2154 FromVal.getBitWidth() == ToVal.getBitWidth() && 2155 FromVal == ToVal; 2156 } 2157 2158 bool ASTNodeImporter::IsStructuralMatch(ClassTemplateDecl *From, 2159 ClassTemplateDecl *To) { 2160 StructuralEquivalenceContext Ctx(Importer.getFromContext(), 2161 Importer.getToContext(), 2162 Importer.getNonEquivalentDecls(), 2163 getStructuralEquivalenceKind(Importer)); 2164 return Ctx.IsEquivalent(From, To); 2165 } 2166 2167 bool ASTNodeImporter::IsStructuralMatch(VarTemplateDecl *From, 2168 VarTemplateDecl *To) { 2169 StructuralEquivalenceContext Ctx(Importer.getFromContext(), 2170 Importer.getToContext(), 2171 Importer.getNonEquivalentDecls(), 2172 getStructuralEquivalenceKind(Importer)); 2173 return Ctx.IsEquivalent(From, To); 2174 } 2175 2176 ExpectedDecl ASTNodeImporter::VisitDecl(Decl *D) { 2177 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node) 2178 << D->getDeclKindName(); 2179 return make_error<ImportError>(ImportError::UnsupportedConstruct); 2180 } 2181 2182 ExpectedDecl ASTNodeImporter::VisitImportDecl(ImportDecl *D) { 2183 Importer.FromDiag(D->getLocation(), diag::err_unsupported_ast_node) 2184 << D->getDeclKindName(); 2185 return make_error<ImportError>(ImportError::UnsupportedConstruct); 2186 } 2187 2188 ExpectedDecl ASTNodeImporter::VisitEmptyDecl(EmptyDecl *D) { 2189 // Import the context of this declaration. 2190 DeclContext *DC, *LexicalDC; 2191 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 2192 return std::move(Err); 2193 2194 // Import the location of this declaration. 2195 ExpectedSLoc LocOrErr = import(D->getLocation()); 2196 if (!LocOrErr) 2197 return LocOrErr.takeError(); 2198 2199 EmptyDecl *ToD; 2200 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), DC, *LocOrErr)) 2201 return ToD; 2202 2203 ToD->setLexicalDeclContext(LexicalDC); 2204 LexicalDC->addDeclInternal(ToD); 2205 return ToD; 2206 } 2207 2208 ExpectedDecl ASTNodeImporter::VisitTranslationUnitDecl(TranslationUnitDecl *D) { 2209 TranslationUnitDecl *ToD = 2210 Importer.getToContext().getTranslationUnitDecl(); 2211 2212 Importer.MapImported(D, ToD); 2213 2214 return ToD; 2215 } 2216 2217 ExpectedDecl ASTNodeImporter::VisitAccessSpecDecl(AccessSpecDecl *D) { 2218 ExpectedSLoc LocOrErr = import(D->getLocation()); 2219 if (!LocOrErr) 2220 return LocOrErr.takeError(); 2221 auto ColonLocOrErr = import(D->getColonLoc()); 2222 if (!ColonLocOrErr) 2223 return ColonLocOrErr.takeError(); 2224 2225 // Import the context of this declaration. 2226 auto DCOrErr = Importer.ImportContext(D->getDeclContext()); 2227 if (!DCOrErr) 2228 return DCOrErr.takeError(); 2229 DeclContext *DC = *DCOrErr; 2230 2231 AccessSpecDecl *ToD; 2232 if (GetImportedOrCreateDecl(ToD, D, Importer.getToContext(), D->getAccess(), 2233 DC, *LocOrErr, *ColonLocOrErr)) 2234 return ToD; 2235 2236 // Lexical DeclContext and Semantic DeclContext 2237 // is always the same for the accessSpec. 2238 ToD->setLexicalDeclContext(DC); 2239 DC->addDeclInternal(ToD); 2240 2241 return ToD; 2242 } 2243 2244 ExpectedDecl ASTNodeImporter::VisitStaticAssertDecl(StaticAssertDecl *D) { 2245 auto DCOrErr = Importer.ImportContext(D->getDeclContext()); 2246 if (!DCOrErr) 2247 return DCOrErr.takeError(); 2248 DeclContext *DC = *DCOrErr; 2249 DeclContext *LexicalDC = DC; 2250 2251 SourceLocation ToLocation, ToRParenLoc; 2252 Expr *ToAssertExpr; 2253 StringLiteral *ToMessage; 2254 if (auto Imp = importSeq( 2255 D->getLocation(), D->getAssertExpr(), D->getMessage(), D->getRParenLoc())) 2256 std::tie(ToLocation, ToAssertExpr, ToMessage, ToRParenLoc) = *Imp; 2257 else 2258 return Imp.takeError(); 2259 2260 StaticAssertDecl *ToD; 2261 if (GetImportedOrCreateDecl( 2262 ToD, D, Importer.getToContext(), DC, ToLocation, ToAssertExpr, ToMessage, 2263 ToRParenLoc, D->isFailed())) 2264 return ToD; 2265 2266 ToD->setLexicalDeclContext(LexicalDC); 2267 LexicalDC->addDeclInternal(ToD); 2268 return ToD; 2269 } 2270 2271 ExpectedDecl ASTNodeImporter::VisitNamespaceDecl(NamespaceDecl *D) { 2272 // Import the major distinguishing characteristics of this namespace. 2273 DeclContext *DC, *LexicalDC; 2274 DeclarationName Name; 2275 SourceLocation Loc; 2276 NamedDecl *ToD; 2277 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 2278 return std::move(Err); 2279 if (ToD) 2280 return ToD; 2281 2282 NamespaceDecl *MergeWithNamespace = nullptr; 2283 if (!Name) { 2284 // This is an anonymous namespace. Adopt an existing anonymous 2285 // namespace if we can. 2286 // FIXME: Not testable. 2287 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC)) 2288 MergeWithNamespace = TU->getAnonymousNamespace(); 2289 else 2290 MergeWithNamespace = cast<NamespaceDecl>(DC)->getAnonymousNamespace(); 2291 } else { 2292 SmallVector<NamedDecl *, 4> ConflictingDecls; 2293 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 2294 for (auto *FoundDecl : FoundDecls) { 2295 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Namespace)) 2296 continue; 2297 2298 if (auto *FoundNS = dyn_cast<NamespaceDecl>(FoundDecl)) { 2299 MergeWithNamespace = FoundNS; 2300 ConflictingDecls.clear(); 2301 break; 2302 } 2303 2304 ConflictingDecls.push_back(FoundDecl); 2305 } 2306 2307 if (!ConflictingDecls.empty()) { 2308 ExpectedName NameOrErr = Importer.HandleNameConflict( 2309 Name, DC, Decl::IDNS_Namespace, ConflictingDecls.data(), 2310 ConflictingDecls.size()); 2311 if (NameOrErr) 2312 Name = NameOrErr.get(); 2313 else 2314 return NameOrErr.takeError(); 2315 } 2316 } 2317 2318 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc()); 2319 if (!BeginLocOrErr) 2320 return BeginLocOrErr.takeError(); 2321 ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc()); 2322 if (!RBraceLocOrErr) 2323 return RBraceLocOrErr.takeError(); 2324 2325 // Create the "to" namespace, if needed. 2326 NamespaceDecl *ToNamespace = MergeWithNamespace; 2327 if (!ToNamespace) { 2328 if (GetImportedOrCreateDecl( 2329 ToNamespace, D, Importer.getToContext(), DC, D->isInline(), 2330 *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(), 2331 /*PrevDecl=*/nullptr)) 2332 return ToNamespace; 2333 ToNamespace->setRBraceLoc(*RBraceLocOrErr); 2334 ToNamespace->setLexicalDeclContext(LexicalDC); 2335 LexicalDC->addDeclInternal(ToNamespace); 2336 2337 // If this is an anonymous namespace, register it as the anonymous 2338 // namespace within its context. 2339 if (!Name) { 2340 if (auto *TU = dyn_cast<TranslationUnitDecl>(DC)) 2341 TU->setAnonymousNamespace(ToNamespace); 2342 else 2343 cast<NamespaceDecl>(DC)->setAnonymousNamespace(ToNamespace); 2344 } 2345 } 2346 Importer.MapImported(D, ToNamespace); 2347 2348 if (Error Err = ImportDeclContext(D)) 2349 return std::move(Err); 2350 2351 return ToNamespace; 2352 } 2353 2354 ExpectedDecl ASTNodeImporter::VisitNamespaceAliasDecl(NamespaceAliasDecl *D) { 2355 // Import the major distinguishing characteristics of this namespace. 2356 DeclContext *DC, *LexicalDC; 2357 DeclarationName Name; 2358 SourceLocation Loc; 2359 NamedDecl *LookupD; 2360 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, LookupD, Loc)) 2361 return std::move(Err); 2362 if (LookupD) 2363 return LookupD; 2364 2365 // NOTE: No conflict resolution is done for namespace aliases now. 2366 2367 SourceLocation ToNamespaceLoc, ToAliasLoc, ToTargetNameLoc; 2368 NestedNameSpecifierLoc ToQualifierLoc; 2369 NamespaceDecl *ToNamespace; 2370 if (auto Imp = importSeq( 2371 D->getNamespaceLoc(), D->getAliasLoc(), D->getQualifierLoc(), 2372 D->getTargetNameLoc(), D->getNamespace())) 2373 std::tie( 2374 ToNamespaceLoc, ToAliasLoc, ToQualifierLoc, ToTargetNameLoc, 2375 ToNamespace) = *Imp; 2376 else 2377 return Imp.takeError(); 2378 IdentifierInfo *ToIdentifier = Importer.Import(D->getIdentifier()); 2379 2380 NamespaceAliasDecl *ToD; 2381 if (GetImportedOrCreateDecl( 2382 ToD, D, Importer.getToContext(), DC, ToNamespaceLoc, ToAliasLoc, 2383 ToIdentifier, ToQualifierLoc, ToTargetNameLoc, ToNamespace)) 2384 return ToD; 2385 2386 ToD->setLexicalDeclContext(LexicalDC); 2387 LexicalDC->addDeclInternal(ToD); 2388 2389 return ToD; 2390 } 2391 2392 ExpectedDecl 2393 ASTNodeImporter::VisitTypedefNameDecl(TypedefNameDecl *D, bool IsAlias) { 2394 // Import the major distinguishing characteristics of this typedef. 2395 DeclContext *DC, *LexicalDC; 2396 DeclarationName Name; 2397 SourceLocation Loc; 2398 NamedDecl *ToD; 2399 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 2400 return std::move(Err); 2401 if (ToD) 2402 return ToD; 2403 2404 // If this typedef is not in block scope, determine whether we've 2405 // seen a typedef with the same name (that we can merge with) or any 2406 // other entity by that name (which name lookup could conflict with). 2407 // Note: Repeated typedefs are not valid in C99: 2408 // 'typedef int T; typedef int T;' is invalid 2409 // We do not care about this now. 2410 if (!DC->isFunctionOrMethod()) { 2411 SmallVector<NamedDecl *, 4> ConflictingDecls; 2412 unsigned IDNS = Decl::IDNS_Ordinary; 2413 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 2414 for (auto *FoundDecl : FoundDecls) { 2415 if (!FoundDecl->isInIdentifierNamespace(IDNS)) 2416 continue; 2417 if (auto *FoundTypedef = dyn_cast<TypedefNameDecl>(FoundDecl)) { 2418 if (!hasSameVisibilityContext(FoundTypedef, D)) 2419 continue; 2420 2421 QualType FromUT = D->getUnderlyingType(); 2422 QualType FoundUT = FoundTypedef->getUnderlyingType(); 2423 if (Importer.IsStructurallyEquivalent(FromUT, FoundUT)) { 2424 // If the "From" context has a complete underlying type but we 2425 // already have a complete underlying type then return with that. 2426 if (!FromUT->isIncompleteType() && !FoundUT->isIncompleteType()) 2427 return Importer.MapImported(D, FoundTypedef); 2428 // FIXME Handle redecl chain. When you do that make consistent changes 2429 // in ASTImporterLookupTable too. 2430 } else { 2431 ConflictingDecls.push_back(FoundDecl); 2432 } 2433 } 2434 } 2435 2436 if (!ConflictingDecls.empty()) { 2437 ExpectedName NameOrErr = Importer.HandleNameConflict( 2438 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size()); 2439 if (NameOrErr) 2440 Name = NameOrErr.get(); 2441 else 2442 return NameOrErr.takeError(); 2443 } 2444 } 2445 2446 QualType ToUnderlyingType; 2447 TypeSourceInfo *ToTypeSourceInfo; 2448 SourceLocation ToBeginLoc; 2449 if (auto Imp = importSeq( 2450 D->getUnderlyingType(), D->getTypeSourceInfo(), D->getBeginLoc())) 2451 std::tie(ToUnderlyingType, ToTypeSourceInfo, ToBeginLoc) = *Imp; 2452 else 2453 return Imp.takeError(); 2454 2455 // Create the new typedef node. 2456 // FIXME: ToUnderlyingType is not used. 2457 TypedefNameDecl *ToTypedef; 2458 if (IsAlias) { 2459 if (GetImportedOrCreateDecl<TypeAliasDecl>( 2460 ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc, 2461 Name.getAsIdentifierInfo(), ToTypeSourceInfo)) 2462 return ToTypedef; 2463 } else if (GetImportedOrCreateDecl<TypedefDecl>( 2464 ToTypedef, D, Importer.getToContext(), DC, ToBeginLoc, Loc, 2465 Name.getAsIdentifierInfo(), ToTypeSourceInfo)) 2466 return ToTypedef; 2467 2468 ToTypedef->setAccess(D->getAccess()); 2469 ToTypedef->setLexicalDeclContext(LexicalDC); 2470 2471 // Templated declarations should not appear in DeclContext. 2472 TypeAliasDecl *FromAlias = IsAlias ? cast<TypeAliasDecl>(D) : nullptr; 2473 if (!FromAlias || !FromAlias->getDescribedAliasTemplate()) 2474 LexicalDC->addDeclInternal(ToTypedef); 2475 2476 return ToTypedef; 2477 } 2478 2479 ExpectedDecl ASTNodeImporter::VisitTypedefDecl(TypedefDecl *D) { 2480 return VisitTypedefNameDecl(D, /*IsAlias=*/false); 2481 } 2482 2483 ExpectedDecl ASTNodeImporter::VisitTypeAliasDecl(TypeAliasDecl *D) { 2484 return VisitTypedefNameDecl(D, /*IsAlias=*/true); 2485 } 2486 2487 ExpectedDecl 2488 ASTNodeImporter::VisitTypeAliasTemplateDecl(TypeAliasTemplateDecl *D) { 2489 // Import the major distinguishing characteristics of this typedef. 2490 DeclContext *DC, *LexicalDC; 2491 DeclarationName Name; 2492 SourceLocation Loc; 2493 NamedDecl *FoundD; 2494 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, FoundD, Loc)) 2495 return std::move(Err); 2496 if (FoundD) 2497 return FoundD; 2498 2499 // If this typedef is not in block scope, determine whether we've 2500 // seen a typedef with the same name (that we can merge with) or any 2501 // other entity by that name (which name lookup could conflict with). 2502 if (!DC->isFunctionOrMethod()) { 2503 SmallVector<NamedDecl *, 4> ConflictingDecls; 2504 unsigned IDNS = Decl::IDNS_Ordinary; 2505 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 2506 for (auto *FoundDecl : FoundDecls) { 2507 if (!FoundDecl->isInIdentifierNamespace(IDNS)) 2508 continue; 2509 if (auto *FoundAlias = dyn_cast<TypeAliasTemplateDecl>(FoundDecl)) 2510 return Importer.MapImported(D, FoundAlias); 2511 ConflictingDecls.push_back(FoundDecl); 2512 } 2513 2514 if (!ConflictingDecls.empty()) { 2515 ExpectedName NameOrErr = Importer.HandleNameConflict( 2516 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size()); 2517 if (NameOrErr) 2518 Name = NameOrErr.get(); 2519 else 2520 return NameOrErr.takeError(); 2521 } 2522 } 2523 2524 TemplateParameterList *ToTemplateParameters; 2525 TypeAliasDecl *ToTemplatedDecl; 2526 if (auto Imp = importSeq(D->getTemplateParameters(), D->getTemplatedDecl())) 2527 std::tie(ToTemplateParameters, ToTemplatedDecl) = *Imp; 2528 else 2529 return Imp.takeError(); 2530 2531 TypeAliasTemplateDecl *ToAlias; 2532 if (GetImportedOrCreateDecl(ToAlias, D, Importer.getToContext(), DC, Loc, 2533 Name, ToTemplateParameters, ToTemplatedDecl)) 2534 return ToAlias; 2535 2536 ToTemplatedDecl->setDescribedAliasTemplate(ToAlias); 2537 2538 ToAlias->setAccess(D->getAccess()); 2539 ToAlias->setLexicalDeclContext(LexicalDC); 2540 LexicalDC->addDeclInternal(ToAlias); 2541 return ToAlias; 2542 } 2543 2544 ExpectedDecl ASTNodeImporter::VisitLabelDecl(LabelDecl *D) { 2545 // Import the major distinguishing characteristics of this label. 2546 DeclContext *DC, *LexicalDC; 2547 DeclarationName Name; 2548 SourceLocation Loc; 2549 NamedDecl *ToD; 2550 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 2551 return std::move(Err); 2552 if (ToD) 2553 return ToD; 2554 2555 assert(LexicalDC->isFunctionOrMethod()); 2556 2557 LabelDecl *ToLabel; 2558 if (D->isGnuLocal()) { 2559 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc()); 2560 if (!BeginLocOrErr) 2561 return BeginLocOrErr.takeError(); 2562 if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc, 2563 Name.getAsIdentifierInfo(), *BeginLocOrErr)) 2564 return ToLabel; 2565 2566 } else { 2567 if (GetImportedOrCreateDecl(ToLabel, D, Importer.getToContext(), DC, Loc, 2568 Name.getAsIdentifierInfo())) 2569 return ToLabel; 2570 2571 } 2572 2573 Expected<LabelStmt *> ToStmtOrErr = import(D->getStmt()); 2574 if (!ToStmtOrErr) 2575 return ToStmtOrErr.takeError(); 2576 2577 ToLabel->setStmt(*ToStmtOrErr); 2578 ToLabel->setLexicalDeclContext(LexicalDC); 2579 LexicalDC->addDeclInternal(ToLabel); 2580 return ToLabel; 2581 } 2582 2583 ExpectedDecl ASTNodeImporter::VisitEnumDecl(EnumDecl *D) { 2584 // Import the major distinguishing characteristics of this enum. 2585 DeclContext *DC, *LexicalDC; 2586 DeclarationName Name; 2587 SourceLocation Loc; 2588 NamedDecl *ToD; 2589 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 2590 return std::move(Err); 2591 if (ToD) 2592 return ToD; 2593 2594 // Figure out what enum name we're looking for. 2595 unsigned IDNS = Decl::IDNS_Tag; 2596 DeclarationName SearchName = Name; 2597 if (!SearchName && D->getTypedefNameForAnonDecl()) { 2598 if (Error Err = importInto( 2599 SearchName, D->getTypedefNameForAnonDecl()->getDeclName())) 2600 return std::move(Err); 2601 IDNS = Decl::IDNS_Ordinary; 2602 } else if (Importer.getToContext().getLangOpts().CPlusPlus) 2603 IDNS |= Decl::IDNS_Ordinary; 2604 2605 // We may already have an enum of the same name; try to find and match it. 2606 if (!DC->isFunctionOrMethod() && SearchName) { 2607 SmallVector<NamedDecl *, 4> ConflictingDecls; 2608 auto FoundDecls = 2609 Importer.findDeclsInToCtx(DC, SearchName); 2610 for (auto *FoundDecl : FoundDecls) { 2611 if (!FoundDecl->isInIdentifierNamespace(IDNS)) 2612 continue; 2613 2614 if (auto *Typedef = dyn_cast<TypedefNameDecl>(FoundDecl)) { 2615 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>()) 2616 FoundDecl = Tag->getDecl(); 2617 } 2618 2619 if (auto *FoundEnum = dyn_cast<EnumDecl>(FoundDecl)) { 2620 if (!hasSameVisibilityContext(FoundEnum, D)) 2621 continue; 2622 if (IsStructuralMatch(D, FoundEnum)) 2623 return Importer.MapImported(D, FoundEnum); 2624 ConflictingDecls.push_back(FoundDecl); 2625 } 2626 } 2627 2628 if (!ConflictingDecls.empty()) { 2629 ExpectedName NameOrErr = Importer.HandleNameConflict( 2630 SearchName, DC, IDNS, ConflictingDecls.data(), 2631 ConflictingDecls.size()); 2632 if (NameOrErr) 2633 Name = NameOrErr.get(); 2634 else 2635 return NameOrErr.takeError(); 2636 } 2637 } 2638 2639 SourceLocation ToBeginLoc; 2640 NestedNameSpecifierLoc ToQualifierLoc; 2641 QualType ToIntegerType; 2642 SourceRange ToBraceRange; 2643 if (auto Imp = importSeq(D->getBeginLoc(), D->getQualifierLoc(), 2644 D->getIntegerType(), D->getBraceRange())) 2645 std::tie(ToBeginLoc, ToQualifierLoc, ToIntegerType, ToBraceRange) = *Imp; 2646 else 2647 return Imp.takeError(); 2648 2649 // Create the enum declaration. 2650 EnumDecl *D2; 2651 if (GetImportedOrCreateDecl( 2652 D2, D, Importer.getToContext(), DC, ToBeginLoc, 2653 Loc, Name.getAsIdentifierInfo(), nullptr, D->isScoped(), 2654 D->isScopedUsingClassTag(), D->isFixed())) 2655 return D2; 2656 2657 D2->setQualifierInfo(ToQualifierLoc); 2658 D2->setIntegerType(ToIntegerType); 2659 D2->setBraceRange(ToBraceRange); 2660 D2->setAccess(D->getAccess()); 2661 D2->setLexicalDeclContext(LexicalDC); 2662 LexicalDC->addDeclInternal(D2); 2663 2664 // Import the definition 2665 if (D->isCompleteDefinition()) 2666 if (Error Err = ImportDefinition(D, D2)) 2667 return std::move(Err); 2668 2669 return D2; 2670 } 2671 2672 ExpectedDecl ASTNodeImporter::VisitRecordDecl(RecordDecl *D) { 2673 bool IsFriendTemplate = false; 2674 if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) { 2675 IsFriendTemplate = 2676 DCXX->getDescribedClassTemplate() && 2677 DCXX->getDescribedClassTemplate()->getFriendObjectKind() != 2678 Decl::FOK_None; 2679 } 2680 2681 // Import the major distinguishing characteristics of this record. 2682 DeclContext *DC = nullptr, *LexicalDC = nullptr; 2683 DeclarationName Name; 2684 SourceLocation Loc; 2685 NamedDecl *ToD = nullptr; 2686 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 2687 return std::move(Err); 2688 if (ToD) 2689 return ToD; 2690 2691 // Figure out what structure name we're looking for. 2692 unsigned IDNS = Decl::IDNS_Tag; 2693 DeclarationName SearchName = Name; 2694 if (!SearchName && D->getTypedefNameForAnonDecl()) { 2695 if (Error Err = importInto( 2696 SearchName, D->getTypedefNameForAnonDecl()->getDeclName())) 2697 return std::move(Err); 2698 IDNS = Decl::IDNS_Ordinary; 2699 } else if (Importer.getToContext().getLangOpts().CPlusPlus) 2700 IDNS |= Decl::IDNS_Ordinary | Decl::IDNS_TagFriend; 2701 2702 // We may already have a record of the same name; try to find and match it. 2703 RecordDecl *PrevDecl = nullptr; 2704 if (!DC->isFunctionOrMethod() && !D->isLambda()) { 2705 SmallVector<NamedDecl *, 4> ConflictingDecls; 2706 auto FoundDecls = 2707 Importer.findDeclsInToCtx(DC, SearchName); 2708 if (!FoundDecls.empty()) { 2709 // We're going to have to compare D against potentially conflicting Decls, 2710 // so complete it. 2711 if (D->hasExternalLexicalStorage() && !D->isCompleteDefinition()) 2712 D->getASTContext().getExternalSource()->CompleteType(D); 2713 } 2714 2715 for (auto *FoundDecl : FoundDecls) { 2716 if (!FoundDecl->isInIdentifierNamespace(IDNS)) 2717 continue; 2718 2719 Decl *Found = FoundDecl; 2720 if (auto *Typedef = dyn_cast<TypedefNameDecl>(Found)) { 2721 if (const auto *Tag = Typedef->getUnderlyingType()->getAs<TagType>()) 2722 Found = Tag->getDecl(); 2723 } 2724 2725 if (auto *FoundRecord = dyn_cast<RecordDecl>(Found)) { 2726 // Do not emit false positive diagnostic in case of unnamed 2727 // struct/union and in case of anonymous structs. Would be false 2728 // because there may be several anonymous/unnamed structs in a class. 2729 // E.g. these are both valid: 2730 // struct A { // unnamed structs 2731 // struct { struct A *next; } entry0; 2732 // struct { struct A *next; } entry1; 2733 // }; 2734 // struct X { struct { int a; }; struct { int b; }; }; // anon structs 2735 if (!SearchName) 2736 if (!IsStructuralMatch(D, FoundRecord, false)) 2737 continue; 2738 2739 if (!hasSameVisibilityContext(FoundRecord, D)) 2740 continue; 2741 2742 if (IsStructuralMatch(D, FoundRecord)) { 2743 RecordDecl *FoundDef = FoundRecord->getDefinition(); 2744 if (D->isThisDeclarationADefinition() && FoundDef) { 2745 // FIXME: Structural equivalence check should check for same 2746 // user-defined methods. 2747 Importer.MapImported(D, FoundDef); 2748 if (const auto *DCXX = dyn_cast<CXXRecordDecl>(D)) { 2749 auto *FoundCXX = dyn_cast<CXXRecordDecl>(FoundDef); 2750 assert(FoundCXX && "Record type mismatch"); 2751 2752 if (!Importer.isMinimalImport()) 2753 // FoundDef may not have every implicit method that D has 2754 // because implicit methods are created only if they are used. 2755 if (Error Err = ImportImplicitMethods(DCXX, FoundCXX)) 2756 return std::move(Err); 2757 } 2758 } 2759 PrevDecl = FoundRecord->getMostRecentDecl(); 2760 break; 2761 } 2762 ConflictingDecls.push_back(FoundDecl); 2763 } // kind is RecordDecl 2764 } // for 2765 2766 if (!ConflictingDecls.empty() && SearchName) { 2767 ExpectedName NameOrErr = Importer.HandleNameConflict( 2768 SearchName, DC, IDNS, ConflictingDecls.data(), 2769 ConflictingDecls.size()); 2770 if (NameOrErr) 2771 Name = NameOrErr.get(); 2772 else 2773 return NameOrErr.takeError(); 2774 } 2775 } 2776 2777 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc()); 2778 if (!BeginLocOrErr) 2779 return BeginLocOrErr.takeError(); 2780 2781 // Create the record declaration. 2782 RecordDecl *D2 = nullptr; 2783 CXXRecordDecl *D2CXX = nullptr; 2784 if (auto *DCXX = dyn_cast<CXXRecordDecl>(D)) { 2785 if (DCXX->isLambda()) { 2786 auto TInfoOrErr = import(DCXX->getLambdaTypeInfo()); 2787 if (!TInfoOrErr) 2788 return TInfoOrErr.takeError(); 2789 if (GetImportedOrCreateSpecialDecl( 2790 D2CXX, CXXRecordDecl::CreateLambda, D, Importer.getToContext(), 2791 DC, *TInfoOrErr, Loc, DCXX->isDependentLambda(), 2792 DCXX->isGenericLambda(), DCXX->getLambdaCaptureDefault())) 2793 return D2CXX; 2794 ExpectedDecl CDeclOrErr = import(DCXX->getLambdaContextDecl()); 2795 if (!CDeclOrErr) 2796 return CDeclOrErr.takeError(); 2797 D2CXX->setLambdaMangling(DCXX->getLambdaManglingNumber(), *CDeclOrErr, 2798 DCXX->hasKnownLambdaInternalLinkage()); 2799 } else if (DCXX->isInjectedClassName()) { 2800 // We have to be careful to do a similar dance to the one in 2801 // Sema::ActOnStartCXXMemberDeclarations 2802 const bool DelayTypeCreation = true; 2803 if (GetImportedOrCreateDecl( 2804 D2CXX, D, Importer.getToContext(), D->getTagKind(), DC, 2805 *BeginLocOrErr, Loc, Name.getAsIdentifierInfo(), 2806 cast_or_null<CXXRecordDecl>(PrevDecl), DelayTypeCreation)) 2807 return D2CXX; 2808 Importer.getToContext().getTypeDeclType( 2809 D2CXX, dyn_cast<CXXRecordDecl>(DC)); 2810 } else { 2811 if (GetImportedOrCreateDecl(D2CXX, D, Importer.getToContext(), 2812 D->getTagKind(), DC, *BeginLocOrErr, Loc, 2813 Name.getAsIdentifierInfo(), 2814 cast_or_null<CXXRecordDecl>(PrevDecl))) 2815 return D2CXX; 2816 } 2817 2818 D2 = D2CXX; 2819 D2->setAccess(D->getAccess()); 2820 D2->setLexicalDeclContext(LexicalDC); 2821 addDeclToContexts(D, D2); 2822 2823 if (ClassTemplateDecl *FromDescribed = 2824 DCXX->getDescribedClassTemplate()) { 2825 ClassTemplateDecl *ToDescribed; 2826 if (Error Err = importInto(ToDescribed, FromDescribed)) 2827 return std::move(Err); 2828 D2CXX->setDescribedClassTemplate(ToDescribed); 2829 if (!DCXX->isInjectedClassName() && !IsFriendTemplate) { 2830 // In a record describing a template the type should be an 2831 // InjectedClassNameType (see Sema::CheckClassTemplate). Update the 2832 // previously set type to the correct value here (ToDescribed is not 2833 // available at record create). 2834 // FIXME: The previous type is cleared but not removed from 2835 // ASTContext's internal storage. 2836 CXXRecordDecl *Injected = nullptr; 2837 for (NamedDecl *Found : D2CXX->noload_lookup(Name)) { 2838 auto *Record = dyn_cast<CXXRecordDecl>(Found); 2839 if (Record && Record->isInjectedClassName()) { 2840 Injected = Record; 2841 break; 2842 } 2843 } 2844 // Create an injected type for the whole redecl chain. 2845 SmallVector<Decl *, 2> Redecls = 2846 getCanonicalForwardRedeclChain(D2CXX); 2847 for (auto *R : Redecls) { 2848 auto *RI = cast<CXXRecordDecl>(R); 2849 RI->setTypeForDecl(nullptr); 2850 // Below we create a new injected type and assign that to the 2851 // canonical decl, subsequent declarations in the chain will reuse 2852 // that type. 2853 Importer.getToContext().getInjectedClassNameType( 2854 RI, ToDescribed->getInjectedClassNameSpecialization()); 2855 } 2856 // Set the new type for the previous injected decl too. 2857 if (Injected) { 2858 Injected->setTypeForDecl(nullptr); 2859 Importer.getToContext().getTypeDeclType(Injected, D2CXX); 2860 } 2861 } 2862 } else if (MemberSpecializationInfo *MemberInfo = 2863 DCXX->getMemberSpecializationInfo()) { 2864 TemplateSpecializationKind SK = 2865 MemberInfo->getTemplateSpecializationKind(); 2866 CXXRecordDecl *FromInst = DCXX->getInstantiatedFromMemberClass(); 2867 2868 if (Expected<CXXRecordDecl *> ToInstOrErr = import(FromInst)) 2869 D2CXX->setInstantiationOfMemberClass(*ToInstOrErr, SK); 2870 else 2871 return ToInstOrErr.takeError(); 2872 2873 if (ExpectedSLoc POIOrErr = 2874 import(MemberInfo->getPointOfInstantiation())) 2875 D2CXX->getMemberSpecializationInfo()->setPointOfInstantiation( 2876 *POIOrErr); 2877 else 2878 return POIOrErr.takeError(); 2879 } 2880 2881 } else { 2882 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), 2883 D->getTagKind(), DC, *BeginLocOrErr, Loc, 2884 Name.getAsIdentifierInfo(), PrevDecl)) 2885 return D2; 2886 D2->setLexicalDeclContext(LexicalDC); 2887 addDeclToContexts(D, D2); 2888 } 2889 2890 if (auto BraceRangeOrErr = import(D->getBraceRange())) 2891 D2->setBraceRange(*BraceRangeOrErr); 2892 else 2893 return BraceRangeOrErr.takeError(); 2894 if (auto QualifierLocOrErr = import(D->getQualifierLoc())) 2895 D2->setQualifierInfo(*QualifierLocOrErr); 2896 else 2897 return QualifierLocOrErr.takeError(); 2898 2899 if (D->isAnonymousStructOrUnion()) 2900 D2->setAnonymousStructOrUnion(true); 2901 2902 if (D->isCompleteDefinition()) 2903 if (Error Err = ImportDefinition(D, D2, IDK_Default)) 2904 return std::move(Err); 2905 2906 return D2; 2907 } 2908 2909 ExpectedDecl ASTNodeImporter::VisitEnumConstantDecl(EnumConstantDecl *D) { 2910 // Import the major distinguishing characteristics of this enumerator. 2911 DeclContext *DC, *LexicalDC; 2912 DeclarationName Name; 2913 SourceLocation Loc; 2914 NamedDecl *ToD; 2915 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 2916 return std::move(Err); 2917 if (ToD) 2918 return ToD; 2919 2920 // Determine whether there are any other declarations with the same name and 2921 // in the same context. 2922 if (!LexicalDC->isFunctionOrMethod()) { 2923 SmallVector<NamedDecl *, 4> ConflictingDecls; 2924 unsigned IDNS = Decl::IDNS_Ordinary; 2925 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 2926 for (auto *FoundDecl : FoundDecls) { 2927 if (!FoundDecl->isInIdentifierNamespace(IDNS)) 2928 continue; 2929 2930 if (auto *FoundEnumConstant = dyn_cast<EnumConstantDecl>(FoundDecl)) { 2931 if (IsStructuralMatch(D, FoundEnumConstant)) 2932 return Importer.MapImported(D, FoundEnumConstant); 2933 ConflictingDecls.push_back(FoundDecl); 2934 } 2935 } 2936 2937 if (!ConflictingDecls.empty()) { 2938 ExpectedName NameOrErr = Importer.HandleNameConflict( 2939 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size()); 2940 if (NameOrErr) 2941 Name = NameOrErr.get(); 2942 else 2943 return NameOrErr.takeError(); 2944 } 2945 } 2946 2947 ExpectedType TypeOrErr = import(D->getType()); 2948 if (!TypeOrErr) 2949 return TypeOrErr.takeError(); 2950 2951 ExpectedExpr InitOrErr = import(D->getInitExpr()); 2952 if (!InitOrErr) 2953 return InitOrErr.takeError(); 2954 2955 EnumConstantDecl *ToEnumerator; 2956 if (GetImportedOrCreateDecl( 2957 ToEnumerator, D, Importer.getToContext(), cast<EnumDecl>(DC), Loc, 2958 Name.getAsIdentifierInfo(), *TypeOrErr, *InitOrErr, D->getInitVal())) 2959 return ToEnumerator; 2960 2961 ToEnumerator->setAccess(D->getAccess()); 2962 ToEnumerator->setLexicalDeclContext(LexicalDC); 2963 LexicalDC->addDeclInternal(ToEnumerator); 2964 return ToEnumerator; 2965 } 2966 2967 Error ASTNodeImporter::ImportTemplateParameterLists(const DeclaratorDecl *FromD, 2968 DeclaratorDecl *ToD) { 2969 unsigned int Num = FromD->getNumTemplateParameterLists(); 2970 if (Num == 0) 2971 return Error::success(); 2972 SmallVector<TemplateParameterList *, 2> ToTPLists(Num); 2973 for (unsigned int I = 0; I < Num; ++I) 2974 if (Expected<TemplateParameterList *> ToTPListOrErr = 2975 import(FromD->getTemplateParameterList(I))) 2976 ToTPLists[I] = *ToTPListOrErr; 2977 else 2978 return ToTPListOrErr.takeError(); 2979 ToD->setTemplateParameterListsInfo(Importer.ToContext, ToTPLists); 2980 return Error::success(); 2981 } 2982 2983 Error ASTNodeImporter::ImportTemplateInformation( 2984 FunctionDecl *FromFD, FunctionDecl *ToFD) { 2985 switch (FromFD->getTemplatedKind()) { 2986 case FunctionDecl::TK_NonTemplate: 2987 case FunctionDecl::TK_FunctionTemplate: 2988 return Error::success(); 2989 2990 case FunctionDecl::TK_MemberSpecialization: { 2991 TemplateSpecializationKind TSK = FromFD->getTemplateSpecializationKind(); 2992 2993 if (Expected<FunctionDecl *> InstFDOrErr = 2994 import(FromFD->getInstantiatedFromMemberFunction())) 2995 ToFD->setInstantiationOfMemberFunction(*InstFDOrErr, TSK); 2996 else 2997 return InstFDOrErr.takeError(); 2998 2999 if (ExpectedSLoc POIOrErr = import( 3000 FromFD->getMemberSpecializationInfo()->getPointOfInstantiation())) 3001 ToFD->getMemberSpecializationInfo()->setPointOfInstantiation(*POIOrErr); 3002 else 3003 return POIOrErr.takeError(); 3004 3005 return Error::success(); 3006 } 3007 3008 case FunctionDecl::TK_FunctionTemplateSpecialization: { 3009 auto FunctionAndArgsOrErr = 3010 ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD); 3011 if (!FunctionAndArgsOrErr) 3012 return FunctionAndArgsOrErr.takeError(); 3013 3014 TemplateArgumentList *ToTAList = TemplateArgumentList::CreateCopy( 3015 Importer.getToContext(), std::get<1>(*FunctionAndArgsOrErr)); 3016 3017 auto *FTSInfo = FromFD->getTemplateSpecializationInfo(); 3018 TemplateArgumentListInfo ToTAInfo; 3019 const auto *FromTAArgsAsWritten = FTSInfo->TemplateArgumentsAsWritten; 3020 if (FromTAArgsAsWritten) 3021 if (Error Err = ImportTemplateArgumentListInfo( 3022 *FromTAArgsAsWritten, ToTAInfo)) 3023 return Err; 3024 3025 ExpectedSLoc POIOrErr = import(FTSInfo->getPointOfInstantiation()); 3026 if (!POIOrErr) 3027 return POIOrErr.takeError(); 3028 3029 if (Error Err = ImportTemplateParameterLists(FromFD, ToFD)) 3030 return Err; 3031 3032 TemplateSpecializationKind TSK = FTSInfo->getTemplateSpecializationKind(); 3033 ToFD->setFunctionTemplateSpecialization( 3034 std::get<0>(*FunctionAndArgsOrErr), ToTAList, /* InsertPos= */ nullptr, 3035 TSK, FromTAArgsAsWritten ? &ToTAInfo : nullptr, *POIOrErr); 3036 return Error::success(); 3037 } 3038 3039 case FunctionDecl::TK_DependentFunctionTemplateSpecialization: { 3040 auto *FromInfo = FromFD->getDependentSpecializationInfo(); 3041 UnresolvedSet<8> TemplDecls; 3042 unsigned NumTemplates = FromInfo->getNumTemplates(); 3043 for (unsigned I = 0; I < NumTemplates; I++) { 3044 if (Expected<FunctionTemplateDecl *> ToFTDOrErr = 3045 import(FromInfo->getTemplate(I))) 3046 TemplDecls.addDecl(*ToFTDOrErr); 3047 else 3048 return ToFTDOrErr.takeError(); 3049 } 3050 3051 // Import TemplateArgumentListInfo. 3052 TemplateArgumentListInfo ToTAInfo; 3053 if (Error Err = ImportTemplateArgumentListInfo( 3054 FromInfo->getLAngleLoc(), FromInfo->getRAngleLoc(), 3055 llvm::makeArrayRef( 3056 FromInfo->getTemplateArgs(), FromInfo->getNumTemplateArgs()), 3057 ToTAInfo)) 3058 return Err; 3059 3060 ToFD->setDependentTemplateSpecialization(Importer.getToContext(), 3061 TemplDecls, ToTAInfo); 3062 return Error::success(); 3063 } 3064 } 3065 llvm_unreachable("All cases should be covered!"); 3066 } 3067 3068 Expected<FunctionDecl *> 3069 ASTNodeImporter::FindFunctionTemplateSpecialization(FunctionDecl *FromFD) { 3070 auto FunctionAndArgsOrErr = 3071 ImportFunctionTemplateWithTemplateArgsFromSpecialization(FromFD); 3072 if (!FunctionAndArgsOrErr) 3073 return FunctionAndArgsOrErr.takeError(); 3074 3075 FunctionTemplateDecl *Template; 3076 TemplateArgsTy ToTemplArgs; 3077 std::tie(Template, ToTemplArgs) = *FunctionAndArgsOrErr; 3078 void *InsertPos = nullptr; 3079 auto *FoundSpec = Template->findSpecialization(ToTemplArgs, InsertPos); 3080 return FoundSpec; 3081 } 3082 3083 Error ASTNodeImporter::ImportFunctionDeclBody(FunctionDecl *FromFD, 3084 FunctionDecl *ToFD) { 3085 if (Stmt *FromBody = FromFD->getBody()) { 3086 if (ExpectedStmt ToBodyOrErr = import(FromBody)) 3087 ToFD->setBody(*ToBodyOrErr); 3088 else 3089 return ToBodyOrErr.takeError(); 3090 } 3091 return Error::success(); 3092 } 3093 3094 // Returns true if the given D has a DeclContext up to the TranslationUnitDecl 3095 // which is equal to the given DC. 3096 static bool isAncestorDeclContextOf(const DeclContext *DC, const Decl *D) { 3097 const DeclContext *DCi = D->getDeclContext(); 3098 while (DCi != D->getTranslationUnitDecl()) { 3099 if (DCi == DC) 3100 return true; 3101 DCi = DCi->getParent(); 3102 } 3103 return false; 3104 } 3105 3106 bool ASTNodeImporter::hasAutoReturnTypeDeclaredInside(FunctionDecl *D) { 3107 QualType FromTy = D->getType(); 3108 const FunctionProtoType *FromFPT = FromTy->getAs<FunctionProtoType>(); 3109 assert(FromFPT && "Must be called on FunctionProtoType"); 3110 if (AutoType *AutoT = FromFPT->getReturnType()->getContainedAutoType()) { 3111 QualType DeducedT = AutoT->getDeducedType(); 3112 if (const RecordType *RecordT = 3113 DeducedT.isNull() ? nullptr : dyn_cast<RecordType>(DeducedT)) { 3114 RecordDecl *RD = RecordT->getDecl(); 3115 assert(RD); 3116 if (isAncestorDeclContextOf(D, RD)) { 3117 assert(RD->getLexicalDeclContext() == RD->getDeclContext()); 3118 return true; 3119 } 3120 } 3121 } 3122 if (const TypedefType *TypedefT = 3123 dyn_cast<TypedefType>(FromFPT->getReturnType())) { 3124 TypedefNameDecl *TD = TypedefT->getDecl(); 3125 assert(TD); 3126 if (isAncestorDeclContextOf(D, TD)) { 3127 assert(TD->getLexicalDeclContext() == TD->getDeclContext()); 3128 return true; 3129 } 3130 } 3131 return false; 3132 } 3133 3134 ExpectedDecl ASTNodeImporter::VisitFunctionDecl(FunctionDecl *D) { 3135 3136 SmallVector<Decl *, 2> Redecls = getCanonicalForwardRedeclChain(D); 3137 auto RedeclIt = Redecls.begin(); 3138 // Import the first part of the decl chain. I.e. import all previous 3139 // declarations starting from the canonical decl. 3140 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) { 3141 ExpectedDecl ToRedeclOrErr = import(*RedeclIt); 3142 if (!ToRedeclOrErr) 3143 return ToRedeclOrErr.takeError(); 3144 } 3145 assert(*RedeclIt == D); 3146 3147 // Import the major distinguishing characteristics of this function. 3148 DeclContext *DC, *LexicalDC; 3149 DeclarationName Name; 3150 SourceLocation Loc; 3151 NamedDecl *ToD; 3152 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 3153 return std::move(Err); 3154 if (ToD) 3155 return ToD; 3156 3157 FunctionDecl *FoundByLookup = nullptr; 3158 FunctionTemplateDecl *FromFT = D->getDescribedFunctionTemplate(); 3159 3160 // If this is a function template specialization, then try to find the same 3161 // existing specialization in the "to" context. The lookup below will not 3162 // find any specialization, but would find the primary template; thus, we 3163 // have to skip normal lookup in case of specializations. 3164 // FIXME handle member function templates (TK_MemberSpecialization) similarly? 3165 if (D->getTemplatedKind() == 3166 FunctionDecl::TK_FunctionTemplateSpecialization) { 3167 auto FoundFunctionOrErr = FindFunctionTemplateSpecialization(D); 3168 if (!FoundFunctionOrErr) 3169 return FoundFunctionOrErr.takeError(); 3170 if (FunctionDecl *FoundFunction = *FoundFunctionOrErr) { 3171 if (Decl *Def = FindAndMapDefinition(D, FoundFunction)) 3172 return Def; 3173 FoundByLookup = FoundFunction; 3174 } 3175 } 3176 // Try to find a function in our own ("to") context with the same name, same 3177 // type, and in the same context as the function we're importing. 3178 else if (!LexicalDC->isFunctionOrMethod()) { 3179 SmallVector<NamedDecl *, 4> ConflictingDecls; 3180 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend; 3181 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 3182 for (auto *FoundDecl : FoundDecls) { 3183 if (!FoundDecl->isInIdentifierNamespace(IDNS)) 3184 continue; 3185 3186 if (auto *FoundFunction = dyn_cast<FunctionDecl>(FoundDecl)) { 3187 if (!hasSameVisibilityContext(FoundFunction, D)) 3188 continue; 3189 3190 if (IsStructuralMatch(D, FoundFunction)) { 3191 if (Decl *Def = FindAndMapDefinition(D, FoundFunction)) 3192 return Def; 3193 FoundByLookup = FoundFunction; 3194 break; 3195 } 3196 // FIXME: Check for overloading more carefully, e.g., by boosting 3197 // Sema::IsOverload out to the AST library. 3198 3199 // Function overloading is okay in C++. 3200 if (Importer.getToContext().getLangOpts().CPlusPlus) 3201 continue; 3202 3203 // Complain about inconsistent function types. 3204 Importer.ToDiag(Loc, diag::warn_odr_function_type_inconsistent) 3205 << Name << D->getType() << FoundFunction->getType(); 3206 Importer.ToDiag(FoundFunction->getLocation(), diag::note_odr_value_here) 3207 << FoundFunction->getType(); 3208 ConflictingDecls.push_back(FoundDecl); 3209 } 3210 } 3211 3212 if (!ConflictingDecls.empty()) { 3213 ExpectedName NameOrErr = Importer.HandleNameConflict( 3214 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size()); 3215 if (NameOrErr) 3216 Name = NameOrErr.get(); 3217 else 3218 return NameOrErr.takeError(); 3219 } 3220 } 3221 3222 // We do not allow more than one in-class declaration of a function. This is 3223 // because AST clients like VTableBuilder asserts on this. VTableBuilder 3224 // assumes there is only one in-class declaration. Building a redecl 3225 // chain would result in more than one in-class declaration for 3226 // overrides (even if they are part of the same redecl chain inside the 3227 // derived class.) 3228 if (FoundByLookup) { 3229 if (isa<CXXMethodDecl>(FoundByLookup)) { 3230 if (D->getLexicalDeclContext() == D->getDeclContext()) { 3231 if (!D->doesThisDeclarationHaveABody()) { 3232 if (FunctionTemplateDecl *DescribedD = 3233 D->getDescribedFunctionTemplate()) { 3234 // Handle a "templated" function together with its described 3235 // template. This avoids need for a similar check at import of the 3236 // described template. 3237 assert(FoundByLookup->getDescribedFunctionTemplate() && 3238 "Templated function mapped to non-templated?"); 3239 Importer.MapImported(DescribedD, 3240 FoundByLookup->getDescribedFunctionTemplate()); 3241 } 3242 return Importer.MapImported(D, FoundByLookup); 3243 } else { 3244 // Let's continue and build up the redecl chain in this case. 3245 // FIXME Merge the functions into one decl. 3246 } 3247 } 3248 } 3249 } 3250 3251 DeclarationNameInfo NameInfo(Name, Loc); 3252 // Import additional name location/type info. 3253 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo)) 3254 return std::move(Err); 3255 3256 QualType FromTy = D->getType(); 3257 // Set to true if we do not import the type of the function as is. There are 3258 // cases when the original type would result in an infinite recursion during 3259 // the import. To avoid an infinite recursion when importing, we create the 3260 // FunctionDecl with a simplified function type and update it only after the 3261 // relevant AST nodes are already imported. 3262 bool UsedDifferentProtoType = false; 3263 if (const auto *FromFPT = FromTy->getAs<FunctionProtoType>()) { 3264 QualType FromReturnTy = FromFPT->getReturnType(); 3265 // Functions with auto return type may define a struct inside their body 3266 // and the return type could refer to that struct. 3267 // E.g.: auto foo() { struct X{}; return X(); } 3268 // To avoid an infinite recursion when importing, create the FunctionDecl 3269 // with a simplified return type. 3270 if (hasAutoReturnTypeDeclaredInside(D)) { 3271 FromReturnTy = Importer.getFromContext().VoidTy; 3272 UsedDifferentProtoType = true; 3273 } 3274 FunctionProtoType::ExtProtoInfo FromEPI = FromFPT->getExtProtoInfo(); 3275 // FunctionProtoType::ExtProtoInfo's ExceptionSpecDecl can point to the 3276 // FunctionDecl that we are importing the FunctionProtoType for. 3277 // To avoid an infinite recursion when importing, create the FunctionDecl 3278 // with a simplified function type. 3279 if (FromEPI.ExceptionSpec.SourceDecl || 3280 FromEPI.ExceptionSpec.SourceTemplate || 3281 FromEPI.ExceptionSpec.NoexceptExpr) { 3282 FunctionProtoType::ExtProtoInfo DefaultEPI; 3283 FromEPI = DefaultEPI; 3284 UsedDifferentProtoType = true; 3285 } 3286 FromTy = Importer.getFromContext().getFunctionType( 3287 FromReturnTy, FromFPT->getParamTypes(), FromEPI); 3288 } 3289 3290 QualType T; 3291 TypeSourceInfo *TInfo; 3292 SourceLocation ToInnerLocStart, ToEndLoc; 3293 NestedNameSpecifierLoc ToQualifierLoc; 3294 Expr *TrailingRequiresClause; 3295 if (auto Imp = importSeq( 3296 FromTy, D->getTypeSourceInfo(), D->getInnerLocStart(), 3297 D->getQualifierLoc(), D->getEndLoc(), D->getTrailingRequiresClause())) 3298 std::tie(T, TInfo, ToInnerLocStart, ToQualifierLoc, ToEndLoc, 3299 TrailingRequiresClause) = *Imp; 3300 else 3301 return Imp.takeError(); 3302 3303 // Import the function parameters. 3304 SmallVector<ParmVarDecl *, 8> Parameters; 3305 for (auto P : D->parameters()) { 3306 if (Expected<ParmVarDecl *> ToPOrErr = import(P)) 3307 Parameters.push_back(*ToPOrErr); 3308 else 3309 return ToPOrErr.takeError(); 3310 } 3311 3312 // Create the imported function. 3313 FunctionDecl *ToFunction = nullptr; 3314 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) { 3315 Expr *ExplicitExpr = nullptr; 3316 if (FromConstructor->getExplicitSpecifier().getExpr()) { 3317 auto Imp = importSeq(FromConstructor->getExplicitSpecifier().getExpr()); 3318 if (!Imp) 3319 return Imp.takeError(); 3320 std::tie(ExplicitExpr) = *Imp; 3321 } 3322 if (GetImportedOrCreateDecl<CXXConstructorDecl>( 3323 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC), 3324 ToInnerLocStart, NameInfo, T, TInfo, 3325 ExplicitSpecifier( 3326 ExplicitExpr, 3327 FromConstructor->getExplicitSpecifier().getKind()), 3328 D->isInlineSpecified(), D->isImplicit(), D->getConstexprKind(), 3329 InheritedConstructor(), // FIXME: Properly import inherited 3330 // constructor info 3331 TrailingRequiresClause)) 3332 return ToFunction; 3333 } else if (CXXDestructorDecl *FromDtor = dyn_cast<CXXDestructorDecl>(D)) { 3334 3335 auto Imp = 3336 importSeq(const_cast<FunctionDecl *>(FromDtor->getOperatorDelete()), 3337 FromDtor->getOperatorDeleteThisArg()); 3338 3339 if (!Imp) 3340 return Imp.takeError(); 3341 3342 FunctionDecl *ToOperatorDelete; 3343 Expr *ToThisArg; 3344 std::tie(ToOperatorDelete, ToThisArg) = *Imp; 3345 3346 if (GetImportedOrCreateDecl<CXXDestructorDecl>( 3347 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC), 3348 ToInnerLocStart, NameInfo, T, TInfo, D->isInlineSpecified(), 3349 D->isImplicit(), D->getConstexprKind(), TrailingRequiresClause)) 3350 return ToFunction; 3351 3352 CXXDestructorDecl *ToDtor = cast<CXXDestructorDecl>(ToFunction); 3353 3354 ToDtor->setOperatorDelete(ToOperatorDelete, ToThisArg); 3355 } else if (CXXConversionDecl *FromConversion = 3356 dyn_cast<CXXConversionDecl>(D)) { 3357 Expr *ExplicitExpr = nullptr; 3358 if (FromConversion->getExplicitSpecifier().getExpr()) { 3359 auto Imp = importSeq(FromConversion->getExplicitSpecifier().getExpr()); 3360 if (!Imp) 3361 return Imp.takeError(); 3362 std::tie(ExplicitExpr) = *Imp; 3363 } 3364 if (GetImportedOrCreateDecl<CXXConversionDecl>( 3365 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC), 3366 ToInnerLocStart, NameInfo, T, TInfo, D->isInlineSpecified(), 3367 ExplicitSpecifier(ExplicitExpr, 3368 FromConversion->getExplicitSpecifier().getKind()), 3369 D->getConstexprKind(), SourceLocation(), TrailingRequiresClause)) 3370 return ToFunction; 3371 } else if (auto *Method = dyn_cast<CXXMethodDecl>(D)) { 3372 if (GetImportedOrCreateDecl<CXXMethodDecl>( 3373 ToFunction, D, Importer.getToContext(), cast<CXXRecordDecl>(DC), 3374 ToInnerLocStart, NameInfo, T, TInfo, Method->getStorageClass(), 3375 Method->isInlineSpecified(), D->getConstexprKind(), 3376 SourceLocation(), TrailingRequiresClause)) 3377 return ToFunction; 3378 } else { 3379 if (GetImportedOrCreateDecl( 3380 ToFunction, D, Importer.getToContext(), DC, ToInnerLocStart, 3381 NameInfo, T, TInfo, D->getStorageClass(), D->isInlineSpecified(), 3382 D->hasWrittenPrototype(), D->getConstexprKind(), 3383 TrailingRequiresClause)) 3384 return ToFunction; 3385 } 3386 3387 // Connect the redecl chain. 3388 if (FoundByLookup) { 3389 auto *Recent = const_cast<FunctionDecl *>( 3390 FoundByLookup->getMostRecentDecl()); 3391 ToFunction->setPreviousDecl(Recent); 3392 // FIXME Probably we should merge exception specifications. E.g. In the 3393 // "To" context the existing function may have exception specification with 3394 // noexcept-unevaluated, while the newly imported function may have an 3395 // evaluated noexcept. A call to adjustExceptionSpec() on the imported 3396 // decl and its redeclarations may be required. 3397 } 3398 3399 ToFunction->setQualifierInfo(ToQualifierLoc); 3400 ToFunction->setAccess(D->getAccess()); 3401 ToFunction->setLexicalDeclContext(LexicalDC); 3402 ToFunction->setVirtualAsWritten(D->isVirtualAsWritten()); 3403 ToFunction->setTrivial(D->isTrivial()); 3404 ToFunction->setPure(D->isPure()); 3405 ToFunction->setDefaulted(D->isDefaulted()); 3406 ToFunction->setExplicitlyDefaulted(D->isExplicitlyDefaulted()); 3407 ToFunction->setDeletedAsWritten(D->isDeletedAsWritten()); 3408 ToFunction->setRangeEnd(ToEndLoc); 3409 3410 // Set the parameters. 3411 for (auto *Param : Parameters) { 3412 Param->setOwningFunction(ToFunction); 3413 ToFunction->addDeclInternal(Param); 3414 } 3415 ToFunction->setParams(Parameters); 3416 3417 // We need to complete creation of FunctionProtoTypeLoc manually with setting 3418 // params it refers to. 3419 if (TInfo) { 3420 if (auto ProtoLoc = 3421 TInfo->getTypeLoc().IgnoreParens().getAs<FunctionProtoTypeLoc>()) { 3422 for (unsigned I = 0, N = Parameters.size(); I != N; ++I) 3423 ProtoLoc.setParam(I, Parameters[I]); 3424 } 3425 } 3426 3427 // Import the describing template function, if any. 3428 if (FromFT) { 3429 auto ToFTOrErr = import(FromFT); 3430 if (!ToFTOrErr) 3431 return ToFTOrErr.takeError(); 3432 } 3433 3434 // Import Ctor initializers. 3435 if (auto *FromConstructor = dyn_cast<CXXConstructorDecl>(D)) { 3436 if (unsigned NumInitializers = FromConstructor->getNumCtorInitializers()) { 3437 SmallVector<CXXCtorInitializer *, 4> CtorInitializers(NumInitializers); 3438 // Import first, then allocate memory and copy if there was no error. 3439 if (Error Err = ImportContainerChecked( 3440 FromConstructor->inits(), CtorInitializers)) 3441 return std::move(Err); 3442 auto **Memory = 3443 new (Importer.getToContext()) CXXCtorInitializer *[NumInitializers]; 3444 std::copy(CtorInitializers.begin(), CtorInitializers.end(), Memory); 3445 auto *ToCtor = cast<CXXConstructorDecl>(ToFunction); 3446 ToCtor->setCtorInitializers(Memory); 3447 ToCtor->setNumCtorInitializers(NumInitializers); 3448 } 3449 } 3450 3451 if (D->doesThisDeclarationHaveABody()) { 3452 Error Err = ImportFunctionDeclBody(D, ToFunction); 3453 3454 if (Err) 3455 return std::move(Err); 3456 } 3457 3458 // Import and set the original type in case we used another type. 3459 if (UsedDifferentProtoType) { 3460 if (ExpectedType TyOrErr = import(D->getType())) 3461 ToFunction->setType(*TyOrErr); 3462 else 3463 return TyOrErr.takeError(); 3464 } 3465 3466 // FIXME: Other bits to merge? 3467 3468 // If it is a template, import all related things. 3469 if (Error Err = ImportTemplateInformation(D, ToFunction)) 3470 return std::move(Err); 3471 3472 addDeclToContexts(D, ToFunction); 3473 3474 if (auto *FromCXXMethod = dyn_cast<CXXMethodDecl>(D)) 3475 if (Error Err = ImportOverriddenMethods(cast<CXXMethodDecl>(ToFunction), 3476 FromCXXMethod)) 3477 return std::move(Err); 3478 3479 // Import the rest of the chain. I.e. import all subsequent declarations. 3480 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) { 3481 ExpectedDecl ToRedeclOrErr = import(*RedeclIt); 3482 if (!ToRedeclOrErr) 3483 return ToRedeclOrErr.takeError(); 3484 } 3485 3486 return ToFunction; 3487 } 3488 3489 ExpectedDecl ASTNodeImporter::VisitCXXMethodDecl(CXXMethodDecl *D) { 3490 return VisitFunctionDecl(D); 3491 } 3492 3493 ExpectedDecl ASTNodeImporter::VisitCXXConstructorDecl(CXXConstructorDecl *D) { 3494 return VisitCXXMethodDecl(D); 3495 } 3496 3497 ExpectedDecl ASTNodeImporter::VisitCXXDestructorDecl(CXXDestructorDecl *D) { 3498 return VisitCXXMethodDecl(D); 3499 } 3500 3501 ExpectedDecl ASTNodeImporter::VisitCXXConversionDecl(CXXConversionDecl *D) { 3502 return VisitCXXMethodDecl(D); 3503 } 3504 3505 ExpectedDecl ASTNodeImporter::VisitFieldDecl(FieldDecl *D) { 3506 // Import the major distinguishing characteristics of a variable. 3507 DeclContext *DC, *LexicalDC; 3508 DeclarationName Name; 3509 SourceLocation Loc; 3510 NamedDecl *ToD; 3511 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 3512 return std::move(Err); 3513 if (ToD) 3514 return ToD; 3515 3516 // Determine whether we've already imported this field. 3517 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 3518 for (auto *FoundDecl : FoundDecls) { 3519 if (FieldDecl *FoundField = dyn_cast<FieldDecl>(FoundDecl)) { 3520 // For anonymous fields, match up by index. 3521 if (!Name && 3522 ASTImporter::getFieldIndex(D) != 3523 ASTImporter::getFieldIndex(FoundField)) 3524 continue; 3525 3526 if (Importer.IsStructurallyEquivalent(D->getType(), 3527 FoundField->getType())) { 3528 Importer.MapImported(D, FoundField); 3529 // In case of a FieldDecl of a ClassTemplateSpecializationDecl, the 3530 // initializer of a FieldDecl might not had been instantiated in the 3531 // "To" context. However, the "From" context might instantiated that, 3532 // thus we have to merge that. 3533 if (Expr *FromInitializer = D->getInClassInitializer()) { 3534 // We don't have yet the initializer set. 3535 if (FoundField->hasInClassInitializer() && 3536 !FoundField->getInClassInitializer()) { 3537 if (ExpectedExpr ToInitializerOrErr = import(FromInitializer)) 3538 FoundField->setInClassInitializer(*ToInitializerOrErr); 3539 else { 3540 // We can't return error here, 3541 // since we already mapped D as imported. 3542 // FIXME: warning message? 3543 consumeError(ToInitializerOrErr.takeError()); 3544 return FoundField; 3545 } 3546 } 3547 } 3548 return FoundField; 3549 } 3550 3551 // FIXME: Why is this case not handled with calling HandleNameConflict? 3552 Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent) 3553 << Name << D->getType() << FoundField->getType(); 3554 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here) 3555 << FoundField->getType(); 3556 3557 return make_error<ImportError>(ImportError::NameConflict); 3558 } 3559 } 3560 3561 QualType ToType; 3562 TypeSourceInfo *ToTInfo; 3563 Expr *ToBitWidth; 3564 SourceLocation ToInnerLocStart; 3565 Expr *ToInitializer; 3566 if (auto Imp = importSeq( 3567 D->getType(), D->getTypeSourceInfo(), D->getBitWidth(), 3568 D->getInnerLocStart(), D->getInClassInitializer())) 3569 std::tie( 3570 ToType, ToTInfo, ToBitWidth, ToInnerLocStart, ToInitializer) = *Imp; 3571 else 3572 return Imp.takeError(); 3573 3574 FieldDecl *ToField; 3575 if (GetImportedOrCreateDecl(ToField, D, Importer.getToContext(), DC, 3576 ToInnerLocStart, Loc, Name.getAsIdentifierInfo(), 3577 ToType, ToTInfo, ToBitWidth, D->isMutable(), 3578 D->getInClassInitStyle())) 3579 return ToField; 3580 3581 ToField->setAccess(D->getAccess()); 3582 ToField->setLexicalDeclContext(LexicalDC); 3583 if (ToInitializer) 3584 ToField->setInClassInitializer(ToInitializer); 3585 ToField->setImplicit(D->isImplicit()); 3586 LexicalDC->addDeclInternal(ToField); 3587 return ToField; 3588 } 3589 3590 ExpectedDecl ASTNodeImporter::VisitIndirectFieldDecl(IndirectFieldDecl *D) { 3591 // Import the major distinguishing characteristics of a variable. 3592 DeclContext *DC, *LexicalDC; 3593 DeclarationName Name; 3594 SourceLocation Loc; 3595 NamedDecl *ToD; 3596 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 3597 return std::move(Err); 3598 if (ToD) 3599 return ToD; 3600 3601 // Determine whether we've already imported this field. 3602 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 3603 for (unsigned I = 0, N = FoundDecls.size(); I != N; ++I) { 3604 if (auto *FoundField = dyn_cast<IndirectFieldDecl>(FoundDecls[I])) { 3605 // For anonymous indirect fields, match up by index. 3606 if (!Name && 3607 ASTImporter::getFieldIndex(D) != 3608 ASTImporter::getFieldIndex(FoundField)) 3609 continue; 3610 3611 if (Importer.IsStructurallyEquivalent(D->getType(), 3612 FoundField->getType(), 3613 !Name.isEmpty())) { 3614 Importer.MapImported(D, FoundField); 3615 return FoundField; 3616 } 3617 3618 // If there are more anonymous fields to check, continue. 3619 if (!Name && I < N-1) 3620 continue; 3621 3622 // FIXME: Why is this case not handled with calling HandleNameConflict? 3623 Importer.ToDiag(Loc, diag::warn_odr_field_type_inconsistent) 3624 << Name << D->getType() << FoundField->getType(); 3625 Importer.ToDiag(FoundField->getLocation(), diag::note_odr_value_here) 3626 << FoundField->getType(); 3627 3628 return make_error<ImportError>(ImportError::NameConflict); 3629 } 3630 } 3631 3632 // Import the type. 3633 auto TypeOrErr = import(D->getType()); 3634 if (!TypeOrErr) 3635 return TypeOrErr.takeError(); 3636 3637 auto **NamedChain = 3638 new (Importer.getToContext()) NamedDecl*[D->getChainingSize()]; 3639 3640 unsigned i = 0; 3641 for (auto *PI : D->chain()) 3642 if (Expected<NamedDecl *> ToD = import(PI)) 3643 NamedChain[i++] = *ToD; 3644 else 3645 return ToD.takeError(); 3646 3647 llvm::MutableArrayRef<NamedDecl *> CH = {NamedChain, D->getChainingSize()}; 3648 IndirectFieldDecl *ToIndirectField; 3649 if (GetImportedOrCreateDecl(ToIndirectField, D, Importer.getToContext(), DC, 3650 Loc, Name.getAsIdentifierInfo(), *TypeOrErr, CH)) 3651 // FIXME here we leak `NamedChain` which is allocated before 3652 return ToIndirectField; 3653 3654 ToIndirectField->setAccess(D->getAccess()); 3655 ToIndirectField->setLexicalDeclContext(LexicalDC); 3656 LexicalDC->addDeclInternal(ToIndirectField); 3657 return ToIndirectField; 3658 } 3659 3660 ExpectedDecl ASTNodeImporter::VisitFriendDecl(FriendDecl *D) { 3661 // Import the major distinguishing characteristics of a declaration. 3662 DeclContext *DC, *LexicalDC; 3663 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 3664 return std::move(Err); 3665 3666 // Determine whether we've already imported this decl. 3667 // FriendDecl is not a NamedDecl so we cannot use lookup. 3668 auto *RD = cast<CXXRecordDecl>(DC); 3669 FriendDecl *ImportedFriend = RD->getFirstFriend(); 3670 3671 while (ImportedFriend) { 3672 if (D->getFriendDecl() && ImportedFriend->getFriendDecl()) { 3673 if (IsStructuralMatch(D->getFriendDecl(), ImportedFriend->getFriendDecl(), 3674 /*Complain=*/false)) 3675 return Importer.MapImported(D, ImportedFriend); 3676 3677 } else if (D->getFriendType() && ImportedFriend->getFriendType()) { 3678 if (Importer.IsStructurallyEquivalent( 3679 D->getFriendType()->getType(), 3680 ImportedFriend->getFriendType()->getType(), true)) 3681 return Importer.MapImported(D, ImportedFriend); 3682 } 3683 ImportedFriend = ImportedFriend->getNextFriend(); 3684 } 3685 3686 // Not found. Create it. 3687 FriendDecl::FriendUnion ToFU; 3688 if (NamedDecl *FriendD = D->getFriendDecl()) { 3689 NamedDecl *ToFriendD; 3690 if (Error Err = importInto(ToFriendD, FriendD)) 3691 return std::move(Err); 3692 3693 if (FriendD->getFriendObjectKind() != Decl::FOK_None && 3694 !(FriendD->isInIdentifierNamespace(Decl::IDNS_NonMemberOperator))) 3695 ToFriendD->setObjectOfFriendDecl(false); 3696 3697 ToFU = ToFriendD; 3698 } else { // The friend is a type, not a decl. 3699 if (auto TSIOrErr = import(D->getFriendType())) 3700 ToFU = *TSIOrErr; 3701 else 3702 return TSIOrErr.takeError(); 3703 } 3704 3705 SmallVector<TemplateParameterList *, 1> ToTPLists(D->NumTPLists); 3706 auto **FromTPLists = D->getTrailingObjects<TemplateParameterList *>(); 3707 for (unsigned I = 0; I < D->NumTPLists; I++) { 3708 if (auto ListOrErr = import(FromTPLists[I])) 3709 ToTPLists[I] = *ListOrErr; 3710 else 3711 return ListOrErr.takeError(); 3712 } 3713 3714 auto LocationOrErr = import(D->getLocation()); 3715 if (!LocationOrErr) 3716 return LocationOrErr.takeError(); 3717 auto FriendLocOrErr = import(D->getFriendLoc()); 3718 if (!FriendLocOrErr) 3719 return FriendLocOrErr.takeError(); 3720 3721 FriendDecl *FrD; 3722 if (GetImportedOrCreateDecl(FrD, D, Importer.getToContext(), DC, 3723 *LocationOrErr, ToFU, 3724 *FriendLocOrErr, ToTPLists)) 3725 return FrD; 3726 3727 FrD->setAccess(D->getAccess()); 3728 FrD->setLexicalDeclContext(LexicalDC); 3729 LexicalDC->addDeclInternal(FrD); 3730 return FrD; 3731 } 3732 3733 ExpectedDecl ASTNodeImporter::VisitObjCIvarDecl(ObjCIvarDecl *D) { 3734 // Import the major distinguishing characteristics of an ivar. 3735 DeclContext *DC, *LexicalDC; 3736 DeclarationName Name; 3737 SourceLocation Loc; 3738 NamedDecl *ToD; 3739 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 3740 return std::move(Err); 3741 if (ToD) 3742 return ToD; 3743 3744 // Determine whether we've already imported this ivar 3745 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 3746 for (auto *FoundDecl : FoundDecls) { 3747 if (ObjCIvarDecl *FoundIvar = dyn_cast<ObjCIvarDecl>(FoundDecl)) { 3748 if (Importer.IsStructurallyEquivalent(D->getType(), 3749 FoundIvar->getType())) { 3750 Importer.MapImported(D, FoundIvar); 3751 return FoundIvar; 3752 } 3753 3754 Importer.ToDiag(Loc, diag::warn_odr_ivar_type_inconsistent) 3755 << Name << D->getType() << FoundIvar->getType(); 3756 Importer.ToDiag(FoundIvar->getLocation(), diag::note_odr_value_here) 3757 << FoundIvar->getType(); 3758 3759 return make_error<ImportError>(ImportError::NameConflict); 3760 } 3761 } 3762 3763 QualType ToType; 3764 TypeSourceInfo *ToTypeSourceInfo; 3765 Expr *ToBitWidth; 3766 SourceLocation ToInnerLocStart; 3767 if (auto Imp = importSeq( 3768 D->getType(), D->getTypeSourceInfo(), D->getBitWidth(), D->getInnerLocStart())) 3769 std::tie(ToType, ToTypeSourceInfo, ToBitWidth, ToInnerLocStart) = *Imp; 3770 else 3771 return Imp.takeError(); 3772 3773 ObjCIvarDecl *ToIvar; 3774 if (GetImportedOrCreateDecl( 3775 ToIvar, D, Importer.getToContext(), cast<ObjCContainerDecl>(DC), 3776 ToInnerLocStart, Loc, Name.getAsIdentifierInfo(), 3777 ToType, ToTypeSourceInfo, 3778 D->getAccessControl(),ToBitWidth, D->getSynthesize())) 3779 return ToIvar; 3780 3781 ToIvar->setLexicalDeclContext(LexicalDC); 3782 LexicalDC->addDeclInternal(ToIvar); 3783 return ToIvar; 3784 } 3785 3786 ExpectedDecl ASTNodeImporter::VisitVarDecl(VarDecl *D) { 3787 3788 SmallVector<Decl*, 2> Redecls = getCanonicalForwardRedeclChain(D); 3789 auto RedeclIt = Redecls.begin(); 3790 // Import the first part of the decl chain. I.e. import all previous 3791 // declarations starting from the canonical decl. 3792 for (; RedeclIt != Redecls.end() && *RedeclIt != D; ++RedeclIt) { 3793 ExpectedDecl RedeclOrErr = import(*RedeclIt); 3794 if (!RedeclOrErr) 3795 return RedeclOrErr.takeError(); 3796 } 3797 assert(*RedeclIt == D); 3798 3799 // Import the major distinguishing characteristics of a variable. 3800 DeclContext *DC, *LexicalDC; 3801 DeclarationName Name; 3802 SourceLocation Loc; 3803 NamedDecl *ToD; 3804 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 3805 return std::move(Err); 3806 if (ToD) 3807 return ToD; 3808 3809 // Try to find a variable in our own ("to") context with the same name and 3810 // in the same context as the variable we're importing. 3811 VarDecl *FoundByLookup = nullptr; 3812 if (D->isFileVarDecl()) { 3813 SmallVector<NamedDecl *, 4> ConflictingDecls; 3814 unsigned IDNS = Decl::IDNS_Ordinary; 3815 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 3816 for (auto *FoundDecl : FoundDecls) { 3817 if (!FoundDecl->isInIdentifierNamespace(IDNS)) 3818 continue; 3819 3820 if (auto *FoundVar = dyn_cast<VarDecl>(FoundDecl)) { 3821 if (!hasSameVisibilityContext(FoundVar, D)) 3822 continue; 3823 if (Importer.IsStructurallyEquivalent(D->getType(), 3824 FoundVar->getType())) { 3825 3826 // The VarDecl in the "From" context has a definition, but in the 3827 // "To" context we already have a definition. 3828 VarDecl *FoundDef = FoundVar->getDefinition(); 3829 if (D->isThisDeclarationADefinition() && FoundDef) 3830 // FIXME Check for ODR error if the two definitions have 3831 // different initializers? 3832 return Importer.MapImported(D, FoundDef); 3833 3834 // The VarDecl in the "From" context has an initializer, but in the 3835 // "To" context we already have an initializer. 3836 const VarDecl *FoundDInit = nullptr; 3837 if (D->getInit() && FoundVar->getAnyInitializer(FoundDInit)) 3838 // FIXME Diagnose ODR error if the two initializers are different? 3839 return Importer.MapImported(D, const_cast<VarDecl*>(FoundDInit)); 3840 3841 FoundByLookup = FoundVar; 3842 break; 3843 } 3844 3845 const ArrayType *FoundArray 3846 = Importer.getToContext().getAsArrayType(FoundVar->getType()); 3847 const ArrayType *TArray 3848 = Importer.getToContext().getAsArrayType(D->getType()); 3849 if (FoundArray && TArray) { 3850 if (isa<IncompleteArrayType>(FoundArray) && 3851 isa<ConstantArrayType>(TArray)) { 3852 // Import the type. 3853 if (auto TyOrErr = import(D->getType())) 3854 FoundVar->setType(*TyOrErr); 3855 else 3856 return TyOrErr.takeError(); 3857 3858 FoundByLookup = FoundVar; 3859 break; 3860 } else if (isa<IncompleteArrayType>(TArray) && 3861 isa<ConstantArrayType>(FoundArray)) { 3862 FoundByLookup = FoundVar; 3863 break; 3864 } 3865 } 3866 3867 Importer.ToDiag(Loc, diag::warn_odr_variable_type_inconsistent) 3868 << Name << D->getType() << FoundVar->getType(); 3869 Importer.ToDiag(FoundVar->getLocation(), diag::note_odr_value_here) 3870 << FoundVar->getType(); 3871 ConflictingDecls.push_back(FoundDecl); 3872 } 3873 } 3874 3875 if (!ConflictingDecls.empty()) { 3876 ExpectedName NameOrErr = Importer.HandleNameConflict( 3877 Name, DC, IDNS, ConflictingDecls.data(), ConflictingDecls.size()); 3878 if (NameOrErr) 3879 Name = NameOrErr.get(); 3880 else 3881 return NameOrErr.takeError(); 3882 } 3883 } 3884 3885 QualType ToType; 3886 TypeSourceInfo *ToTypeSourceInfo; 3887 SourceLocation ToInnerLocStart; 3888 NestedNameSpecifierLoc ToQualifierLoc; 3889 if (auto Imp = importSeq( 3890 D->getType(), D->getTypeSourceInfo(), D->getInnerLocStart(), 3891 D->getQualifierLoc())) 3892 std::tie(ToType, ToTypeSourceInfo, ToInnerLocStart, ToQualifierLoc) = *Imp; 3893 else 3894 return Imp.takeError(); 3895 3896 // Create the imported variable. 3897 VarDecl *ToVar; 3898 if (GetImportedOrCreateDecl(ToVar, D, Importer.getToContext(), DC, 3899 ToInnerLocStart, Loc, 3900 Name.getAsIdentifierInfo(), 3901 ToType, ToTypeSourceInfo, 3902 D->getStorageClass())) 3903 return ToVar; 3904 3905 ToVar->setQualifierInfo(ToQualifierLoc); 3906 ToVar->setAccess(D->getAccess()); 3907 ToVar->setLexicalDeclContext(LexicalDC); 3908 3909 if (FoundByLookup) { 3910 auto *Recent = const_cast<VarDecl *>(FoundByLookup->getMostRecentDecl()); 3911 ToVar->setPreviousDecl(Recent); 3912 } 3913 3914 if (Error Err = ImportInitializer(D, ToVar)) 3915 return std::move(Err); 3916 3917 if (D->isConstexpr()) 3918 ToVar->setConstexpr(true); 3919 3920 addDeclToContexts(D, ToVar); 3921 3922 // Import the rest of the chain. I.e. import all subsequent declarations. 3923 for (++RedeclIt; RedeclIt != Redecls.end(); ++RedeclIt) { 3924 ExpectedDecl RedeclOrErr = import(*RedeclIt); 3925 if (!RedeclOrErr) 3926 return RedeclOrErr.takeError(); 3927 } 3928 3929 return ToVar; 3930 } 3931 3932 ExpectedDecl ASTNodeImporter::VisitImplicitParamDecl(ImplicitParamDecl *D) { 3933 // Parameters are created in the translation unit's context, then moved 3934 // into the function declaration's context afterward. 3935 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl(); 3936 3937 DeclarationName ToDeclName; 3938 SourceLocation ToLocation; 3939 QualType ToType; 3940 if (auto Imp = importSeq(D->getDeclName(), D->getLocation(), D->getType())) 3941 std::tie(ToDeclName, ToLocation, ToType) = *Imp; 3942 else 3943 return Imp.takeError(); 3944 3945 // Create the imported parameter. 3946 ImplicitParamDecl *ToParm = nullptr; 3947 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC, 3948 ToLocation, ToDeclName.getAsIdentifierInfo(), 3949 ToType, D->getParameterKind())) 3950 return ToParm; 3951 return ToParm; 3952 } 3953 3954 Error ASTNodeImporter::ImportDefaultArgOfParmVarDecl( 3955 const ParmVarDecl *FromParam, ParmVarDecl *ToParam) { 3956 ToParam->setHasInheritedDefaultArg(FromParam->hasInheritedDefaultArg()); 3957 ToParam->setKNRPromoted(FromParam->isKNRPromoted()); 3958 3959 if (FromParam->hasUninstantiatedDefaultArg()) { 3960 if (auto ToDefArgOrErr = import(FromParam->getUninstantiatedDefaultArg())) 3961 ToParam->setUninstantiatedDefaultArg(*ToDefArgOrErr); 3962 else 3963 return ToDefArgOrErr.takeError(); 3964 } else if (FromParam->hasUnparsedDefaultArg()) { 3965 ToParam->setUnparsedDefaultArg(); 3966 } else if (FromParam->hasDefaultArg()) { 3967 if (auto ToDefArgOrErr = import(FromParam->getDefaultArg())) 3968 ToParam->setDefaultArg(*ToDefArgOrErr); 3969 else 3970 return ToDefArgOrErr.takeError(); 3971 } 3972 3973 return Error::success(); 3974 } 3975 3976 ExpectedDecl ASTNodeImporter::VisitParmVarDecl(ParmVarDecl *D) { 3977 // Parameters are created in the translation unit's context, then moved 3978 // into the function declaration's context afterward. 3979 DeclContext *DC = Importer.getToContext().getTranslationUnitDecl(); 3980 3981 DeclarationName ToDeclName; 3982 SourceLocation ToLocation, ToInnerLocStart; 3983 QualType ToType; 3984 TypeSourceInfo *ToTypeSourceInfo; 3985 if (auto Imp = importSeq( 3986 D->getDeclName(), D->getLocation(), D->getType(), D->getInnerLocStart(), 3987 D->getTypeSourceInfo())) 3988 std::tie( 3989 ToDeclName, ToLocation, ToType, ToInnerLocStart, 3990 ToTypeSourceInfo) = *Imp; 3991 else 3992 return Imp.takeError(); 3993 3994 ParmVarDecl *ToParm; 3995 if (GetImportedOrCreateDecl(ToParm, D, Importer.getToContext(), DC, 3996 ToInnerLocStart, ToLocation, 3997 ToDeclName.getAsIdentifierInfo(), ToType, 3998 ToTypeSourceInfo, D->getStorageClass(), 3999 /*DefaultArg*/ nullptr)) 4000 return ToParm; 4001 4002 // Set the default argument. It should be no problem if it was already done. 4003 // Do not import the default expression before GetImportedOrCreateDecl call 4004 // to avoid possible infinite import loop because circular dependency. 4005 if (Error Err = ImportDefaultArgOfParmVarDecl(D, ToParm)) 4006 return std::move(Err); 4007 4008 if (D->isObjCMethodParameter()) { 4009 ToParm->setObjCMethodScopeInfo(D->getFunctionScopeIndex()); 4010 ToParm->setObjCDeclQualifier(D->getObjCDeclQualifier()); 4011 } else { 4012 ToParm->setScopeInfo(D->getFunctionScopeDepth(), 4013 D->getFunctionScopeIndex()); 4014 } 4015 4016 return ToParm; 4017 } 4018 4019 ExpectedDecl ASTNodeImporter::VisitObjCMethodDecl(ObjCMethodDecl *D) { 4020 // Import the major distinguishing characteristics of a method. 4021 DeclContext *DC, *LexicalDC; 4022 DeclarationName Name; 4023 SourceLocation Loc; 4024 NamedDecl *ToD; 4025 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4026 return std::move(Err); 4027 if (ToD) 4028 return ToD; 4029 4030 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 4031 for (auto *FoundDecl : FoundDecls) { 4032 if (auto *FoundMethod = dyn_cast<ObjCMethodDecl>(FoundDecl)) { 4033 if (FoundMethod->isInstanceMethod() != D->isInstanceMethod()) 4034 continue; 4035 4036 // Check return types. 4037 if (!Importer.IsStructurallyEquivalent(D->getReturnType(), 4038 FoundMethod->getReturnType())) { 4039 Importer.ToDiag(Loc, diag::warn_odr_objc_method_result_type_inconsistent) 4040 << D->isInstanceMethod() << Name << D->getReturnType() 4041 << FoundMethod->getReturnType(); 4042 Importer.ToDiag(FoundMethod->getLocation(), 4043 diag::note_odr_objc_method_here) 4044 << D->isInstanceMethod() << Name; 4045 4046 return make_error<ImportError>(ImportError::NameConflict); 4047 } 4048 4049 // Check the number of parameters. 4050 if (D->param_size() != FoundMethod->param_size()) { 4051 Importer.ToDiag(Loc, diag::warn_odr_objc_method_num_params_inconsistent) 4052 << D->isInstanceMethod() << Name 4053 << D->param_size() << FoundMethod->param_size(); 4054 Importer.ToDiag(FoundMethod->getLocation(), 4055 diag::note_odr_objc_method_here) 4056 << D->isInstanceMethod() << Name; 4057 4058 return make_error<ImportError>(ImportError::NameConflict); 4059 } 4060 4061 // Check parameter types. 4062 for (ObjCMethodDecl::param_iterator P = D->param_begin(), 4063 PEnd = D->param_end(), FoundP = FoundMethod->param_begin(); 4064 P != PEnd; ++P, ++FoundP) { 4065 if (!Importer.IsStructurallyEquivalent((*P)->getType(), 4066 (*FoundP)->getType())) { 4067 Importer.FromDiag((*P)->getLocation(), 4068 diag::warn_odr_objc_method_param_type_inconsistent) 4069 << D->isInstanceMethod() << Name 4070 << (*P)->getType() << (*FoundP)->getType(); 4071 Importer.ToDiag((*FoundP)->getLocation(), diag::note_odr_value_here) 4072 << (*FoundP)->getType(); 4073 4074 return make_error<ImportError>(ImportError::NameConflict); 4075 } 4076 } 4077 4078 // Check variadic/non-variadic. 4079 // Check the number of parameters. 4080 if (D->isVariadic() != FoundMethod->isVariadic()) { 4081 Importer.ToDiag(Loc, diag::warn_odr_objc_method_variadic_inconsistent) 4082 << D->isInstanceMethod() << Name; 4083 Importer.ToDiag(FoundMethod->getLocation(), 4084 diag::note_odr_objc_method_here) 4085 << D->isInstanceMethod() << Name; 4086 4087 return make_error<ImportError>(ImportError::NameConflict); 4088 } 4089 4090 // FIXME: Any other bits we need to merge? 4091 return Importer.MapImported(D, FoundMethod); 4092 } 4093 } 4094 4095 SourceLocation ToEndLoc; 4096 QualType ToReturnType; 4097 TypeSourceInfo *ToReturnTypeSourceInfo; 4098 if (auto Imp = importSeq( 4099 D->getEndLoc(), D->getReturnType(), D->getReturnTypeSourceInfo())) 4100 std::tie(ToEndLoc, ToReturnType, ToReturnTypeSourceInfo) = *Imp; 4101 else 4102 return Imp.takeError(); 4103 4104 ObjCMethodDecl *ToMethod; 4105 if (GetImportedOrCreateDecl( 4106 ToMethod, D, Importer.getToContext(), Loc, ToEndLoc, 4107 Name.getObjCSelector(), ToReturnType, ToReturnTypeSourceInfo, DC, 4108 D->isInstanceMethod(), D->isVariadic(), D->isPropertyAccessor(), 4109 D->isSynthesizedAccessorStub(), D->isImplicit(), D->isDefined(), 4110 D->getImplementationControl(), D->hasRelatedResultType())) 4111 return ToMethod; 4112 4113 // FIXME: When we decide to merge method definitions, we'll need to 4114 // deal with implicit parameters. 4115 4116 // Import the parameters 4117 SmallVector<ParmVarDecl *, 5> ToParams; 4118 for (auto *FromP : D->parameters()) { 4119 if (Expected<ParmVarDecl *> ToPOrErr = import(FromP)) 4120 ToParams.push_back(*ToPOrErr); 4121 else 4122 return ToPOrErr.takeError(); 4123 } 4124 4125 // Set the parameters. 4126 for (auto *ToParam : ToParams) { 4127 ToParam->setOwningFunction(ToMethod); 4128 ToMethod->addDeclInternal(ToParam); 4129 } 4130 4131 SmallVector<SourceLocation, 12> FromSelLocs; 4132 D->getSelectorLocs(FromSelLocs); 4133 SmallVector<SourceLocation, 12> ToSelLocs(FromSelLocs.size()); 4134 if (Error Err = ImportContainerChecked(FromSelLocs, ToSelLocs)) 4135 return std::move(Err); 4136 4137 ToMethod->setMethodParams(Importer.getToContext(), ToParams, ToSelLocs); 4138 4139 ToMethod->setLexicalDeclContext(LexicalDC); 4140 LexicalDC->addDeclInternal(ToMethod); 4141 4142 // Implicit params are declared when Sema encounters the definition but this 4143 // never happens when the method is imported. Manually declare the implicit 4144 // params now that the MethodDecl knows its class interface. 4145 if (D->getSelfDecl()) 4146 ToMethod->createImplicitParams(Importer.getToContext(), 4147 ToMethod->getClassInterface()); 4148 4149 return ToMethod; 4150 } 4151 4152 ExpectedDecl ASTNodeImporter::VisitObjCTypeParamDecl(ObjCTypeParamDecl *D) { 4153 // Import the major distinguishing characteristics of a category. 4154 DeclContext *DC, *LexicalDC; 4155 DeclarationName Name; 4156 SourceLocation Loc; 4157 NamedDecl *ToD; 4158 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4159 return std::move(Err); 4160 if (ToD) 4161 return ToD; 4162 4163 SourceLocation ToVarianceLoc, ToLocation, ToColonLoc; 4164 TypeSourceInfo *ToTypeSourceInfo; 4165 if (auto Imp = importSeq( 4166 D->getVarianceLoc(), D->getLocation(), D->getColonLoc(), 4167 D->getTypeSourceInfo())) 4168 std::tie(ToVarianceLoc, ToLocation, ToColonLoc, ToTypeSourceInfo) = *Imp; 4169 else 4170 return Imp.takeError(); 4171 4172 ObjCTypeParamDecl *Result; 4173 if (GetImportedOrCreateDecl( 4174 Result, D, Importer.getToContext(), DC, D->getVariance(), 4175 ToVarianceLoc, D->getIndex(), 4176 ToLocation, Name.getAsIdentifierInfo(), 4177 ToColonLoc, ToTypeSourceInfo)) 4178 return Result; 4179 4180 Result->setLexicalDeclContext(LexicalDC); 4181 return Result; 4182 } 4183 4184 ExpectedDecl ASTNodeImporter::VisitObjCCategoryDecl(ObjCCategoryDecl *D) { 4185 // Import the major distinguishing characteristics of a category. 4186 DeclContext *DC, *LexicalDC; 4187 DeclarationName Name; 4188 SourceLocation Loc; 4189 NamedDecl *ToD; 4190 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4191 return std::move(Err); 4192 if (ToD) 4193 return ToD; 4194 4195 ObjCInterfaceDecl *ToInterface; 4196 if (Error Err = importInto(ToInterface, D->getClassInterface())) 4197 return std::move(Err); 4198 4199 // Determine if we've already encountered this category. 4200 ObjCCategoryDecl *MergeWithCategory 4201 = ToInterface->FindCategoryDeclaration(Name.getAsIdentifierInfo()); 4202 ObjCCategoryDecl *ToCategory = MergeWithCategory; 4203 if (!ToCategory) { 4204 SourceLocation ToAtStartLoc, ToCategoryNameLoc; 4205 SourceLocation ToIvarLBraceLoc, ToIvarRBraceLoc; 4206 if (auto Imp = importSeq( 4207 D->getAtStartLoc(), D->getCategoryNameLoc(), 4208 D->getIvarLBraceLoc(), D->getIvarRBraceLoc())) 4209 std::tie( 4210 ToAtStartLoc, ToCategoryNameLoc, 4211 ToIvarLBraceLoc, ToIvarRBraceLoc) = *Imp; 4212 else 4213 return Imp.takeError(); 4214 4215 if (GetImportedOrCreateDecl(ToCategory, D, Importer.getToContext(), DC, 4216 ToAtStartLoc, Loc, 4217 ToCategoryNameLoc, 4218 Name.getAsIdentifierInfo(), ToInterface, 4219 /*TypeParamList=*/nullptr, 4220 ToIvarLBraceLoc, 4221 ToIvarRBraceLoc)) 4222 return ToCategory; 4223 4224 ToCategory->setLexicalDeclContext(LexicalDC); 4225 LexicalDC->addDeclInternal(ToCategory); 4226 // Import the type parameter list after MapImported, to avoid 4227 // loops when bringing in their DeclContext. 4228 if (auto PListOrErr = ImportObjCTypeParamList(D->getTypeParamList())) 4229 ToCategory->setTypeParamList(*PListOrErr); 4230 else 4231 return PListOrErr.takeError(); 4232 4233 // Import protocols 4234 SmallVector<ObjCProtocolDecl *, 4> Protocols; 4235 SmallVector<SourceLocation, 4> ProtocolLocs; 4236 ObjCCategoryDecl::protocol_loc_iterator FromProtoLoc 4237 = D->protocol_loc_begin(); 4238 for (ObjCCategoryDecl::protocol_iterator FromProto = D->protocol_begin(), 4239 FromProtoEnd = D->protocol_end(); 4240 FromProto != FromProtoEnd; 4241 ++FromProto, ++FromProtoLoc) { 4242 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto)) 4243 Protocols.push_back(*ToProtoOrErr); 4244 else 4245 return ToProtoOrErr.takeError(); 4246 4247 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc)) 4248 ProtocolLocs.push_back(*ToProtoLocOrErr); 4249 else 4250 return ToProtoLocOrErr.takeError(); 4251 } 4252 4253 // FIXME: If we're merging, make sure that the protocol list is the same. 4254 ToCategory->setProtocolList(Protocols.data(), Protocols.size(), 4255 ProtocolLocs.data(), Importer.getToContext()); 4256 4257 } else { 4258 Importer.MapImported(D, ToCategory); 4259 } 4260 4261 // Import all of the members of this category. 4262 if (Error Err = ImportDeclContext(D)) 4263 return std::move(Err); 4264 4265 // If we have an implementation, import it as well. 4266 if (D->getImplementation()) { 4267 if (Expected<ObjCCategoryImplDecl *> ToImplOrErr = 4268 import(D->getImplementation())) 4269 ToCategory->setImplementation(*ToImplOrErr); 4270 else 4271 return ToImplOrErr.takeError(); 4272 } 4273 4274 return ToCategory; 4275 } 4276 4277 Error ASTNodeImporter::ImportDefinition( 4278 ObjCProtocolDecl *From, ObjCProtocolDecl *To, ImportDefinitionKind Kind) { 4279 if (To->getDefinition()) { 4280 if (shouldForceImportDeclContext(Kind)) 4281 if (Error Err = ImportDeclContext(From)) 4282 return Err; 4283 return Error::success(); 4284 } 4285 4286 // Start the protocol definition 4287 To->startDefinition(); 4288 4289 // Import protocols 4290 SmallVector<ObjCProtocolDecl *, 4> Protocols; 4291 SmallVector<SourceLocation, 4> ProtocolLocs; 4292 ObjCProtocolDecl::protocol_loc_iterator FromProtoLoc = 4293 From->protocol_loc_begin(); 4294 for (ObjCProtocolDecl::protocol_iterator FromProto = From->protocol_begin(), 4295 FromProtoEnd = From->protocol_end(); 4296 FromProto != FromProtoEnd; 4297 ++FromProto, ++FromProtoLoc) { 4298 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto)) 4299 Protocols.push_back(*ToProtoOrErr); 4300 else 4301 return ToProtoOrErr.takeError(); 4302 4303 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc)) 4304 ProtocolLocs.push_back(*ToProtoLocOrErr); 4305 else 4306 return ToProtoLocOrErr.takeError(); 4307 4308 } 4309 4310 // FIXME: If we're merging, make sure that the protocol list is the same. 4311 To->setProtocolList(Protocols.data(), Protocols.size(), 4312 ProtocolLocs.data(), Importer.getToContext()); 4313 4314 if (shouldForceImportDeclContext(Kind)) { 4315 // Import all of the members of this protocol. 4316 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true)) 4317 return Err; 4318 } 4319 return Error::success(); 4320 } 4321 4322 ExpectedDecl ASTNodeImporter::VisitObjCProtocolDecl(ObjCProtocolDecl *D) { 4323 // If this protocol has a definition in the translation unit we're coming 4324 // from, but this particular declaration is not that definition, import the 4325 // definition and map to that. 4326 ObjCProtocolDecl *Definition = D->getDefinition(); 4327 if (Definition && Definition != D) { 4328 if (ExpectedDecl ImportedDefOrErr = import(Definition)) 4329 return Importer.MapImported(D, *ImportedDefOrErr); 4330 else 4331 return ImportedDefOrErr.takeError(); 4332 } 4333 4334 // Import the major distinguishing characteristics of a protocol. 4335 DeclContext *DC, *LexicalDC; 4336 DeclarationName Name; 4337 SourceLocation Loc; 4338 NamedDecl *ToD; 4339 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4340 return std::move(Err); 4341 if (ToD) 4342 return ToD; 4343 4344 ObjCProtocolDecl *MergeWithProtocol = nullptr; 4345 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 4346 for (auto *FoundDecl : FoundDecls) { 4347 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_ObjCProtocol)) 4348 continue; 4349 4350 if ((MergeWithProtocol = dyn_cast<ObjCProtocolDecl>(FoundDecl))) 4351 break; 4352 } 4353 4354 ObjCProtocolDecl *ToProto = MergeWithProtocol; 4355 if (!ToProto) { 4356 auto ToAtBeginLocOrErr = import(D->getAtStartLoc()); 4357 if (!ToAtBeginLocOrErr) 4358 return ToAtBeginLocOrErr.takeError(); 4359 4360 if (GetImportedOrCreateDecl(ToProto, D, Importer.getToContext(), DC, 4361 Name.getAsIdentifierInfo(), Loc, 4362 *ToAtBeginLocOrErr, 4363 /*PrevDecl=*/nullptr)) 4364 return ToProto; 4365 ToProto->setLexicalDeclContext(LexicalDC); 4366 LexicalDC->addDeclInternal(ToProto); 4367 } 4368 4369 Importer.MapImported(D, ToProto); 4370 4371 if (D->isThisDeclarationADefinition()) 4372 if (Error Err = ImportDefinition(D, ToProto)) 4373 return std::move(Err); 4374 4375 return ToProto; 4376 } 4377 4378 ExpectedDecl ASTNodeImporter::VisitLinkageSpecDecl(LinkageSpecDecl *D) { 4379 DeclContext *DC, *LexicalDC; 4380 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 4381 return std::move(Err); 4382 4383 ExpectedSLoc ExternLocOrErr = import(D->getExternLoc()); 4384 if (!ExternLocOrErr) 4385 return ExternLocOrErr.takeError(); 4386 4387 ExpectedSLoc LangLocOrErr = import(D->getLocation()); 4388 if (!LangLocOrErr) 4389 return LangLocOrErr.takeError(); 4390 4391 bool HasBraces = D->hasBraces(); 4392 4393 LinkageSpecDecl *ToLinkageSpec; 4394 if (GetImportedOrCreateDecl(ToLinkageSpec, D, Importer.getToContext(), DC, 4395 *ExternLocOrErr, *LangLocOrErr, 4396 D->getLanguage(), HasBraces)) 4397 return ToLinkageSpec; 4398 4399 if (HasBraces) { 4400 ExpectedSLoc RBraceLocOrErr = import(D->getRBraceLoc()); 4401 if (!RBraceLocOrErr) 4402 return RBraceLocOrErr.takeError(); 4403 ToLinkageSpec->setRBraceLoc(*RBraceLocOrErr); 4404 } 4405 4406 ToLinkageSpec->setLexicalDeclContext(LexicalDC); 4407 LexicalDC->addDeclInternal(ToLinkageSpec); 4408 4409 return ToLinkageSpec; 4410 } 4411 4412 ExpectedDecl ASTNodeImporter::VisitUsingDecl(UsingDecl *D) { 4413 DeclContext *DC, *LexicalDC; 4414 DeclarationName Name; 4415 SourceLocation Loc; 4416 NamedDecl *ToD = nullptr; 4417 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4418 return std::move(Err); 4419 if (ToD) 4420 return ToD; 4421 4422 SourceLocation ToLoc, ToUsingLoc; 4423 NestedNameSpecifierLoc ToQualifierLoc; 4424 if (auto Imp = importSeq( 4425 D->getNameInfo().getLoc(), D->getUsingLoc(), D->getQualifierLoc())) 4426 std::tie(ToLoc, ToUsingLoc, ToQualifierLoc) = *Imp; 4427 else 4428 return Imp.takeError(); 4429 4430 DeclarationNameInfo NameInfo(Name, ToLoc); 4431 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo)) 4432 return std::move(Err); 4433 4434 UsingDecl *ToUsing; 4435 if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC, 4436 ToUsingLoc, ToQualifierLoc, NameInfo, 4437 D->hasTypename())) 4438 return ToUsing; 4439 4440 ToUsing->setLexicalDeclContext(LexicalDC); 4441 LexicalDC->addDeclInternal(ToUsing); 4442 4443 if (NamedDecl *FromPattern = 4444 Importer.getFromContext().getInstantiatedFromUsingDecl(D)) { 4445 if (Expected<NamedDecl *> ToPatternOrErr = import(FromPattern)) 4446 Importer.getToContext().setInstantiatedFromUsingDecl( 4447 ToUsing, *ToPatternOrErr); 4448 else 4449 return ToPatternOrErr.takeError(); 4450 } 4451 4452 for (UsingShadowDecl *FromShadow : D->shadows()) { 4453 if (Expected<UsingShadowDecl *> ToShadowOrErr = import(FromShadow)) 4454 ToUsing->addShadowDecl(*ToShadowOrErr); 4455 else 4456 // FIXME: We return error here but the definition is already created 4457 // and available with lookups. How to fix this?.. 4458 return ToShadowOrErr.takeError(); 4459 } 4460 return ToUsing; 4461 } 4462 4463 ExpectedDecl ASTNodeImporter::VisitUsingShadowDecl(UsingShadowDecl *D) { 4464 DeclContext *DC, *LexicalDC; 4465 DeclarationName Name; 4466 SourceLocation Loc; 4467 NamedDecl *ToD = nullptr; 4468 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4469 return std::move(Err); 4470 if (ToD) 4471 return ToD; 4472 4473 Expected<UsingDecl *> ToUsingOrErr = import(D->getUsingDecl()); 4474 if (!ToUsingOrErr) 4475 return ToUsingOrErr.takeError(); 4476 4477 Expected<NamedDecl *> ToTargetOrErr = import(D->getTargetDecl()); 4478 if (!ToTargetOrErr) 4479 return ToTargetOrErr.takeError(); 4480 4481 UsingShadowDecl *ToShadow; 4482 if (GetImportedOrCreateDecl(ToShadow, D, Importer.getToContext(), DC, Loc, 4483 *ToUsingOrErr, *ToTargetOrErr)) 4484 return ToShadow; 4485 4486 ToShadow->setLexicalDeclContext(LexicalDC); 4487 ToShadow->setAccess(D->getAccess()); 4488 4489 if (UsingShadowDecl *FromPattern = 4490 Importer.getFromContext().getInstantiatedFromUsingShadowDecl(D)) { 4491 if (Expected<UsingShadowDecl *> ToPatternOrErr = import(FromPattern)) 4492 Importer.getToContext().setInstantiatedFromUsingShadowDecl( 4493 ToShadow, *ToPatternOrErr); 4494 else 4495 // FIXME: We return error here but the definition is already created 4496 // and available with lookups. How to fix this?.. 4497 return ToPatternOrErr.takeError(); 4498 } 4499 4500 LexicalDC->addDeclInternal(ToShadow); 4501 4502 return ToShadow; 4503 } 4504 4505 ExpectedDecl ASTNodeImporter::VisitUsingDirectiveDecl(UsingDirectiveDecl *D) { 4506 DeclContext *DC, *LexicalDC; 4507 DeclarationName Name; 4508 SourceLocation Loc; 4509 NamedDecl *ToD = nullptr; 4510 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4511 return std::move(Err); 4512 if (ToD) 4513 return ToD; 4514 4515 auto ToComAncestorOrErr = Importer.ImportContext(D->getCommonAncestor()); 4516 if (!ToComAncestorOrErr) 4517 return ToComAncestorOrErr.takeError(); 4518 4519 NamespaceDecl *ToNominatedNamespace; 4520 SourceLocation ToUsingLoc, ToNamespaceKeyLocation, ToIdentLocation; 4521 NestedNameSpecifierLoc ToQualifierLoc; 4522 if (auto Imp = importSeq( 4523 D->getNominatedNamespace(), D->getUsingLoc(), 4524 D->getNamespaceKeyLocation(), D->getQualifierLoc(), 4525 D->getIdentLocation())) 4526 std::tie( 4527 ToNominatedNamespace, ToUsingLoc, ToNamespaceKeyLocation, 4528 ToQualifierLoc, ToIdentLocation) = *Imp; 4529 else 4530 return Imp.takeError(); 4531 4532 UsingDirectiveDecl *ToUsingDir; 4533 if (GetImportedOrCreateDecl(ToUsingDir, D, Importer.getToContext(), DC, 4534 ToUsingLoc, 4535 ToNamespaceKeyLocation, 4536 ToQualifierLoc, 4537 ToIdentLocation, 4538 ToNominatedNamespace, *ToComAncestorOrErr)) 4539 return ToUsingDir; 4540 4541 ToUsingDir->setLexicalDeclContext(LexicalDC); 4542 LexicalDC->addDeclInternal(ToUsingDir); 4543 4544 return ToUsingDir; 4545 } 4546 4547 ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingValueDecl( 4548 UnresolvedUsingValueDecl *D) { 4549 DeclContext *DC, *LexicalDC; 4550 DeclarationName Name; 4551 SourceLocation Loc; 4552 NamedDecl *ToD = nullptr; 4553 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4554 return std::move(Err); 4555 if (ToD) 4556 return ToD; 4557 4558 SourceLocation ToLoc, ToUsingLoc, ToEllipsisLoc; 4559 NestedNameSpecifierLoc ToQualifierLoc; 4560 if (auto Imp = importSeq( 4561 D->getNameInfo().getLoc(), D->getUsingLoc(), D->getQualifierLoc(), 4562 D->getEllipsisLoc())) 4563 std::tie(ToLoc, ToUsingLoc, ToQualifierLoc, ToEllipsisLoc) = *Imp; 4564 else 4565 return Imp.takeError(); 4566 4567 DeclarationNameInfo NameInfo(Name, ToLoc); 4568 if (Error Err = ImportDeclarationNameLoc(D->getNameInfo(), NameInfo)) 4569 return std::move(Err); 4570 4571 UnresolvedUsingValueDecl *ToUsingValue; 4572 if (GetImportedOrCreateDecl(ToUsingValue, D, Importer.getToContext(), DC, 4573 ToUsingLoc, ToQualifierLoc, NameInfo, 4574 ToEllipsisLoc)) 4575 return ToUsingValue; 4576 4577 ToUsingValue->setAccess(D->getAccess()); 4578 ToUsingValue->setLexicalDeclContext(LexicalDC); 4579 LexicalDC->addDeclInternal(ToUsingValue); 4580 4581 return ToUsingValue; 4582 } 4583 4584 ExpectedDecl ASTNodeImporter::VisitUnresolvedUsingTypenameDecl( 4585 UnresolvedUsingTypenameDecl *D) { 4586 DeclContext *DC, *LexicalDC; 4587 DeclarationName Name; 4588 SourceLocation Loc; 4589 NamedDecl *ToD = nullptr; 4590 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4591 return std::move(Err); 4592 if (ToD) 4593 return ToD; 4594 4595 SourceLocation ToUsingLoc, ToTypenameLoc, ToEllipsisLoc; 4596 NestedNameSpecifierLoc ToQualifierLoc; 4597 if (auto Imp = importSeq( 4598 D->getUsingLoc(), D->getTypenameLoc(), D->getQualifierLoc(), 4599 D->getEllipsisLoc())) 4600 std::tie(ToUsingLoc, ToTypenameLoc, ToQualifierLoc, ToEllipsisLoc) = *Imp; 4601 else 4602 return Imp.takeError(); 4603 4604 UnresolvedUsingTypenameDecl *ToUsing; 4605 if (GetImportedOrCreateDecl(ToUsing, D, Importer.getToContext(), DC, 4606 ToUsingLoc, ToTypenameLoc, 4607 ToQualifierLoc, Loc, Name, ToEllipsisLoc)) 4608 return ToUsing; 4609 4610 ToUsing->setAccess(D->getAccess()); 4611 ToUsing->setLexicalDeclContext(LexicalDC); 4612 LexicalDC->addDeclInternal(ToUsing); 4613 4614 return ToUsing; 4615 } 4616 4617 ExpectedDecl ASTNodeImporter::VisitBuiltinTemplateDecl(BuiltinTemplateDecl *D) { 4618 Decl* ToD = nullptr; 4619 switch (D->getBuiltinTemplateKind()) { 4620 case BuiltinTemplateKind::BTK__make_integer_seq: 4621 ToD = Importer.getToContext().getMakeIntegerSeqDecl(); 4622 break; 4623 case BuiltinTemplateKind::BTK__type_pack_element: 4624 ToD = Importer.getToContext().getTypePackElementDecl(); 4625 break; 4626 } 4627 assert(ToD && "BuiltinTemplateDecl of unsupported kind!"); 4628 Importer.MapImported(D, ToD); 4629 return ToD; 4630 } 4631 4632 Error ASTNodeImporter::ImportDefinition( 4633 ObjCInterfaceDecl *From, ObjCInterfaceDecl *To, ImportDefinitionKind Kind) { 4634 if (To->getDefinition()) { 4635 // Check consistency of superclass. 4636 ObjCInterfaceDecl *FromSuper = From->getSuperClass(); 4637 if (FromSuper) { 4638 if (auto FromSuperOrErr = import(FromSuper)) 4639 FromSuper = *FromSuperOrErr; 4640 else 4641 return FromSuperOrErr.takeError(); 4642 } 4643 4644 ObjCInterfaceDecl *ToSuper = To->getSuperClass(); 4645 if ((bool)FromSuper != (bool)ToSuper || 4646 (FromSuper && !declaresSameEntity(FromSuper, ToSuper))) { 4647 Importer.ToDiag(To->getLocation(), 4648 diag::warn_odr_objc_superclass_inconsistent) 4649 << To->getDeclName(); 4650 if (ToSuper) 4651 Importer.ToDiag(To->getSuperClassLoc(), diag::note_odr_objc_superclass) 4652 << To->getSuperClass()->getDeclName(); 4653 else 4654 Importer.ToDiag(To->getLocation(), 4655 diag::note_odr_objc_missing_superclass); 4656 if (From->getSuperClass()) 4657 Importer.FromDiag(From->getSuperClassLoc(), 4658 diag::note_odr_objc_superclass) 4659 << From->getSuperClass()->getDeclName(); 4660 else 4661 Importer.FromDiag(From->getLocation(), 4662 diag::note_odr_objc_missing_superclass); 4663 } 4664 4665 if (shouldForceImportDeclContext(Kind)) 4666 if (Error Err = ImportDeclContext(From)) 4667 return Err; 4668 return Error::success(); 4669 } 4670 4671 // Start the definition. 4672 To->startDefinition(); 4673 4674 // If this class has a superclass, import it. 4675 if (From->getSuperClass()) { 4676 if (auto SuperTInfoOrErr = import(From->getSuperClassTInfo())) 4677 To->setSuperClass(*SuperTInfoOrErr); 4678 else 4679 return SuperTInfoOrErr.takeError(); 4680 } 4681 4682 // Import protocols 4683 SmallVector<ObjCProtocolDecl *, 4> Protocols; 4684 SmallVector<SourceLocation, 4> ProtocolLocs; 4685 ObjCInterfaceDecl::protocol_loc_iterator FromProtoLoc = 4686 From->protocol_loc_begin(); 4687 4688 for (ObjCInterfaceDecl::protocol_iterator FromProto = From->protocol_begin(), 4689 FromProtoEnd = From->protocol_end(); 4690 FromProto != FromProtoEnd; 4691 ++FromProto, ++FromProtoLoc) { 4692 if (Expected<ObjCProtocolDecl *> ToProtoOrErr = import(*FromProto)) 4693 Protocols.push_back(*ToProtoOrErr); 4694 else 4695 return ToProtoOrErr.takeError(); 4696 4697 if (ExpectedSLoc ToProtoLocOrErr = import(*FromProtoLoc)) 4698 ProtocolLocs.push_back(*ToProtoLocOrErr); 4699 else 4700 return ToProtoLocOrErr.takeError(); 4701 4702 } 4703 4704 // FIXME: If we're merging, make sure that the protocol list is the same. 4705 To->setProtocolList(Protocols.data(), Protocols.size(), 4706 ProtocolLocs.data(), Importer.getToContext()); 4707 4708 // Import categories. When the categories themselves are imported, they'll 4709 // hook themselves into this interface. 4710 for (auto *Cat : From->known_categories()) { 4711 auto ToCatOrErr = import(Cat); 4712 if (!ToCatOrErr) 4713 return ToCatOrErr.takeError(); 4714 } 4715 4716 // If we have an @implementation, import it as well. 4717 if (From->getImplementation()) { 4718 if (Expected<ObjCImplementationDecl *> ToImplOrErr = 4719 import(From->getImplementation())) 4720 To->setImplementation(*ToImplOrErr); 4721 else 4722 return ToImplOrErr.takeError(); 4723 } 4724 4725 if (shouldForceImportDeclContext(Kind)) { 4726 // Import all of the members of this class. 4727 if (Error Err = ImportDeclContext(From, /*ForceImport=*/true)) 4728 return Err; 4729 } 4730 return Error::success(); 4731 } 4732 4733 Expected<ObjCTypeParamList *> 4734 ASTNodeImporter::ImportObjCTypeParamList(ObjCTypeParamList *list) { 4735 if (!list) 4736 return nullptr; 4737 4738 SmallVector<ObjCTypeParamDecl *, 4> toTypeParams; 4739 for (auto *fromTypeParam : *list) { 4740 if (auto toTypeParamOrErr = import(fromTypeParam)) 4741 toTypeParams.push_back(*toTypeParamOrErr); 4742 else 4743 return toTypeParamOrErr.takeError(); 4744 } 4745 4746 auto LAngleLocOrErr = import(list->getLAngleLoc()); 4747 if (!LAngleLocOrErr) 4748 return LAngleLocOrErr.takeError(); 4749 4750 auto RAngleLocOrErr = import(list->getRAngleLoc()); 4751 if (!RAngleLocOrErr) 4752 return RAngleLocOrErr.takeError(); 4753 4754 return ObjCTypeParamList::create(Importer.getToContext(), 4755 *LAngleLocOrErr, 4756 toTypeParams, 4757 *RAngleLocOrErr); 4758 } 4759 4760 ExpectedDecl ASTNodeImporter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *D) { 4761 // If this class has a definition in the translation unit we're coming from, 4762 // but this particular declaration is not that definition, import the 4763 // definition and map to that. 4764 ObjCInterfaceDecl *Definition = D->getDefinition(); 4765 if (Definition && Definition != D) { 4766 if (ExpectedDecl ImportedDefOrErr = import(Definition)) 4767 return Importer.MapImported(D, *ImportedDefOrErr); 4768 else 4769 return ImportedDefOrErr.takeError(); 4770 } 4771 4772 // Import the major distinguishing characteristics of an @interface. 4773 DeclContext *DC, *LexicalDC; 4774 DeclarationName Name; 4775 SourceLocation Loc; 4776 NamedDecl *ToD; 4777 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4778 return std::move(Err); 4779 if (ToD) 4780 return ToD; 4781 4782 // Look for an existing interface with the same name. 4783 ObjCInterfaceDecl *MergeWithIface = nullptr; 4784 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 4785 for (auto *FoundDecl : FoundDecls) { 4786 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 4787 continue; 4788 4789 if ((MergeWithIface = dyn_cast<ObjCInterfaceDecl>(FoundDecl))) 4790 break; 4791 } 4792 4793 // Create an interface declaration, if one does not already exist. 4794 ObjCInterfaceDecl *ToIface = MergeWithIface; 4795 if (!ToIface) { 4796 ExpectedSLoc AtBeginLocOrErr = import(D->getAtStartLoc()); 4797 if (!AtBeginLocOrErr) 4798 return AtBeginLocOrErr.takeError(); 4799 4800 if (GetImportedOrCreateDecl( 4801 ToIface, D, Importer.getToContext(), DC, 4802 *AtBeginLocOrErr, Name.getAsIdentifierInfo(), 4803 /*TypeParamList=*/nullptr, 4804 /*PrevDecl=*/nullptr, Loc, D->isImplicitInterfaceDecl())) 4805 return ToIface; 4806 ToIface->setLexicalDeclContext(LexicalDC); 4807 LexicalDC->addDeclInternal(ToIface); 4808 } 4809 Importer.MapImported(D, ToIface); 4810 // Import the type parameter list after MapImported, to avoid 4811 // loops when bringing in their DeclContext. 4812 if (auto ToPListOrErr = 4813 ImportObjCTypeParamList(D->getTypeParamListAsWritten())) 4814 ToIface->setTypeParamList(*ToPListOrErr); 4815 else 4816 return ToPListOrErr.takeError(); 4817 4818 if (D->isThisDeclarationADefinition()) 4819 if (Error Err = ImportDefinition(D, ToIface)) 4820 return std::move(Err); 4821 4822 return ToIface; 4823 } 4824 4825 ExpectedDecl 4826 ASTNodeImporter::VisitObjCCategoryImplDecl(ObjCCategoryImplDecl *D) { 4827 ObjCCategoryDecl *Category; 4828 if (Error Err = importInto(Category, D->getCategoryDecl())) 4829 return std::move(Err); 4830 4831 ObjCCategoryImplDecl *ToImpl = Category->getImplementation(); 4832 if (!ToImpl) { 4833 DeclContext *DC, *LexicalDC; 4834 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 4835 return std::move(Err); 4836 4837 SourceLocation ToLocation, ToAtStartLoc, ToCategoryNameLoc; 4838 if (auto Imp = importSeq( 4839 D->getLocation(), D->getAtStartLoc(), D->getCategoryNameLoc())) 4840 std::tie(ToLocation, ToAtStartLoc, ToCategoryNameLoc) = *Imp; 4841 else 4842 return Imp.takeError(); 4843 4844 if (GetImportedOrCreateDecl( 4845 ToImpl, D, Importer.getToContext(), DC, 4846 Importer.Import(D->getIdentifier()), Category->getClassInterface(), 4847 ToLocation, ToAtStartLoc, ToCategoryNameLoc)) 4848 return ToImpl; 4849 4850 ToImpl->setLexicalDeclContext(LexicalDC); 4851 LexicalDC->addDeclInternal(ToImpl); 4852 Category->setImplementation(ToImpl); 4853 } 4854 4855 Importer.MapImported(D, ToImpl); 4856 if (Error Err = ImportDeclContext(D)) 4857 return std::move(Err); 4858 4859 return ToImpl; 4860 } 4861 4862 ExpectedDecl 4863 ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) { 4864 // Find the corresponding interface. 4865 ObjCInterfaceDecl *Iface; 4866 if (Error Err = importInto(Iface, D->getClassInterface())) 4867 return std::move(Err); 4868 4869 // Import the superclass, if any. 4870 ObjCInterfaceDecl *Super; 4871 if (Error Err = importInto(Super, D->getSuperClass())) 4872 return std::move(Err); 4873 4874 ObjCImplementationDecl *Impl = Iface->getImplementation(); 4875 if (!Impl) { 4876 // We haven't imported an implementation yet. Create a new @implementation 4877 // now. 4878 DeclContext *DC, *LexicalDC; 4879 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 4880 return std::move(Err); 4881 4882 SourceLocation ToLocation, ToAtStartLoc, ToSuperClassLoc; 4883 SourceLocation ToIvarLBraceLoc, ToIvarRBraceLoc; 4884 if (auto Imp = importSeq( 4885 D->getLocation(), D->getAtStartLoc(), D->getSuperClassLoc(), 4886 D->getIvarLBraceLoc(), D->getIvarRBraceLoc())) 4887 std::tie( 4888 ToLocation, ToAtStartLoc, ToSuperClassLoc, 4889 ToIvarLBraceLoc, ToIvarRBraceLoc) = *Imp; 4890 else 4891 return Imp.takeError(); 4892 4893 if (GetImportedOrCreateDecl(Impl, D, Importer.getToContext(), 4894 DC, Iface, Super, 4895 ToLocation, 4896 ToAtStartLoc, 4897 ToSuperClassLoc, 4898 ToIvarLBraceLoc, 4899 ToIvarRBraceLoc)) 4900 return Impl; 4901 4902 Impl->setLexicalDeclContext(LexicalDC); 4903 4904 // Associate the implementation with the class it implements. 4905 Iface->setImplementation(Impl); 4906 Importer.MapImported(D, Iface->getImplementation()); 4907 } else { 4908 Importer.MapImported(D, Iface->getImplementation()); 4909 4910 // Verify that the existing @implementation has the same superclass. 4911 if ((Super && !Impl->getSuperClass()) || 4912 (!Super && Impl->getSuperClass()) || 4913 (Super && Impl->getSuperClass() && 4914 !declaresSameEntity(Super->getCanonicalDecl(), 4915 Impl->getSuperClass()))) { 4916 Importer.ToDiag(Impl->getLocation(), 4917 diag::warn_odr_objc_superclass_inconsistent) 4918 << Iface->getDeclName(); 4919 // FIXME: It would be nice to have the location of the superclass 4920 // below. 4921 if (Impl->getSuperClass()) 4922 Importer.ToDiag(Impl->getLocation(), 4923 diag::note_odr_objc_superclass) 4924 << Impl->getSuperClass()->getDeclName(); 4925 else 4926 Importer.ToDiag(Impl->getLocation(), 4927 diag::note_odr_objc_missing_superclass); 4928 if (D->getSuperClass()) 4929 Importer.FromDiag(D->getLocation(), 4930 diag::note_odr_objc_superclass) 4931 << D->getSuperClass()->getDeclName(); 4932 else 4933 Importer.FromDiag(D->getLocation(), 4934 diag::note_odr_objc_missing_superclass); 4935 4936 return make_error<ImportError>(ImportError::NameConflict); 4937 } 4938 } 4939 4940 // Import all of the members of this @implementation. 4941 if (Error Err = ImportDeclContext(D)) 4942 return std::move(Err); 4943 4944 return Impl; 4945 } 4946 4947 ExpectedDecl ASTNodeImporter::VisitObjCPropertyDecl(ObjCPropertyDecl *D) { 4948 // Import the major distinguishing characteristics of an @property. 4949 DeclContext *DC, *LexicalDC; 4950 DeclarationName Name; 4951 SourceLocation Loc; 4952 NamedDecl *ToD; 4953 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 4954 return std::move(Err); 4955 if (ToD) 4956 return ToD; 4957 4958 // Check whether we have already imported this property. 4959 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 4960 for (auto *FoundDecl : FoundDecls) { 4961 if (auto *FoundProp = dyn_cast<ObjCPropertyDecl>(FoundDecl)) { 4962 // Check property types. 4963 if (!Importer.IsStructurallyEquivalent(D->getType(), 4964 FoundProp->getType())) { 4965 Importer.ToDiag(Loc, diag::warn_odr_objc_property_type_inconsistent) 4966 << Name << D->getType() << FoundProp->getType(); 4967 Importer.ToDiag(FoundProp->getLocation(), diag::note_odr_value_here) 4968 << FoundProp->getType(); 4969 4970 return make_error<ImportError>(ImportError::NameConflict); 4971 } 4972 4973 // FIXME: Check property attributes, getters, setters, etc.? 4974 4975 // Consider these properties to be equivalent. 4976 Importer.MapImported(D, FoundProp); 4977 return FoundProp; 4978 } 4979 } 4980 4981 QualType ToType; 4982 TypeSourceInfo *ToTypeSourceInfo; 4983 SourceLocation ToAtLoc, ToLParenLoc; 4984 if (auto Imp = importSeq( 4985 D->getType(), D->getTypeSourceInfo(), D->getAtLoc(), D->getLParenLoc())) 4986 std::tie(ToType, ToTypeSourceInfo, ToAtLoc, ToLParenLoc) = *Imp; 4987 else 4988 return Imp.takeError(); 4989 4990 // Create the new property. 4991 ObjCPropertyDecl *ToProperty; 4992 if (GetImportedOrCreateDecl( 4993 ToProperty, D, Importer.getToContext(), DC, Loc, 4994 Name.getAsIdentifierInfo(), ToAtLoc, 4995 ToLParenLoc, ToType, 4996 ToTypeSourceInfo, D->getPropertyImplementation())) 4997 return ToProperty; 4998 4999 Selector ToGetterName, ToSetterName; 5000 SourceLocation ToGetterNameLoc, ToSetterNameLoc; 5001 ObjCMethodDecl *ToGetterMethodDecl, *ToSetterMethodDecl; 5002 ObjCIvarDecl *ToPropertyIvarDecl; 5003 if (auto Imp = importSeq( 5004 D->getGetterName(), D->getSetterName(), 5005 D->getGetterNameLoc(), D->getSetterNameLoc(), 5006 D->getGetterMethodDecl(), D->getSetterMethodDecl(), 5007 D->getPropertyIvarDecl())) 5008 std::tie( 5009 ToGetterName, ToSetterName, 5010 ToGetterNameLoc, ToSetterNameLoc, 5011 ToGetterMethodDecl, ToSetterMethodDecl, 5012 ToPropertyIvarDecl) = *Imp; 5013 else 5014 return Imp.takeError(); 5015 5016 ToProperty->setLexicalDeclContext(LexicalDC); 5017 LexicalDC->addDeclInternal(ToProperty); 5018 5019 ToProperty->setPropertyAttributes(D->getPropertyAttributes()); 5020 ToProperty->setPropertyAttributesAsWritten( 5021 D->getPropertyAttributesAsWritten()); 5022 ToProperty->setGetterName(ToGetterName, ToGetterNameLoc); 5023 ToProperty->setSetterName(ToSetterName, ToSetterNameLoc); 5024 ToProperty->setGetterMethodDecl(ToGetterMethodDecl); 5025 ToProperty->setSetterMethodDecl(ToSetterMethodDecl); 5026 ToProperty->setPropertyIvarDecl(ToPropertyIvarDecl); 5027 return ToProperty; 5028 } 5029 5030 ExpectedDecl 5031 ASTNodeImporter::VisitObjCPropertyImplDecl(ObjCPropertyImplDecl *D) { 5032 ObjCPropertyDecl *Property; 5033 if (Error Err = importInto(Property, D->getPropertyDecl())) 5034 return std::move(Err); 5035 5036 DeclContext *DC, *LexicalDC; 5037 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 5038 return std::move(Err); 5039 5040 auto *InImpl = cast<ObjCImplDecl>(LexicalDC); 5041 5042 // Import the ivar (for an @synthesize). 5043 ObjCIvarDecl *Ivar = nullptr; 5044 if (Error Err = importInto(Ivar, D->getPropertyIvarDecl())) 5045 return std::move(Err); 5046 5047 ObjCPropertyImplDecl *ToImpl 5048 = InImpl->FindPropertyImplDecl(Property->getIdentifier(), 5049 Property->getQueryKind()); 5050 if (!ToImpl) { 5051 SourceLocation ToBeginLoc, ToLocation, ToPropertyIvarDeclLoc; 5052 if (auto Imp = importSeq( 5053 D->getBeginLoc(), D->getLocation(), D->getPropertyIvarDeclLoc())) 5054 std::tie(ToBeginLoc, ToLocation, ToPropertyIvarDeclLoc) = *Imp; 5055 else 5056 return Imp.takeError(); 5057 5058 if (GetImportedOrCreateDecl(ToImpl, D, Importer.getToContext(), DC, 5059 ToBeginLoc, 5060 ToLocation, Property, 5061 D->getPropertyImplementation(), Ivar, 5062 ToPropertyIvarDeclLoc)) 5063 return ToImpl; 5064 5065 ToImpl->setLexicalDeclContext(LexicalDC); 5066 LexicalDC->addDeclInternal(ToImpl); 5067 } else { 5068 // Check that we have the same kind of property implementation (@synthesize 5069 // vs. @dynamic). 5070 if (D->getPropertyImplementation() != ToImpl->getPropertyImplementation()) { 5071 Importer.ToDiag(ToImpl->getLocation(), 5072 diag::warn_odr_objc_property_impl_kind_inconsistent) 5073 << Property->getDeclName() 5074 << (ToImpl->getPropertyImplementation() 5075 == ObjCPropertyImplDecl::Dynamic); 5076 Importer.FromDiag(D->getLocation(), 5077 diag::note_odr_objc_property_impl_kind) 5078 << D->getPropertyDecl()->getDeclName() 5079 << (D->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic); 5080 5081 return make_error<ImportError>(ImportError::NameConflict); 5082 } 5083 5084 // For @synthesize, check that we have the same 5085 if (D->getPropertyImplementation() == ObjCPropertyImplDecl::Synthesize && 5086 Ivar != ToImpl->getPropertyIvarDecl()) { 5087 Importer.ToDiag(ToImpl->getPropertyIvarDeclLoc(), 5088 diag::warn_odr_objc_synthesize_ivar_inconsistent) 5089 << Property->getDeclName() 5090 << ToImpl->getPropertyIvarDecl()->getDeclName() 5091 << Ivar->getDeclName(); 5092 Importer.FromDiag(D->getPropertyIvarDeclLoc(), 5093 diag::note_odr_objc_synthesize_ivar_here) 5094 << D->getPropertyIvarDecl()->getDeclName(); 5095 5096 return make_error<ImportError>(ImportError::NameConflict); 5097 } 5098 5099 // Merge the existing implementation with the new implementation. 5100 Importer.MapImported(D, ToImpl); 5101 } 5102 5103 return ToImpl; 5104 } 5105 5106 ExpectedDecl 5107 ASTNodeImporter::VisitTemplateTypeParmDecl(TemplateTypeParmDecl *D) { 5108 // For template arguments, we adopt the translation unit as our declaration 5109 // context. This context will be fixed when the actual template declaration 5110 // is created. 5111 5112 // FIXME: Import default argument and constraint expression. 5113 5114 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc()); 5115 if (!BeginLocOrErr) 5116 return BeginLocOrErr.takeError(); 5117 5118 ExpectedSLoc LocationOrErr = import(D->getLocation()); 5119 if (!LocationOrErr) 5120 return LocationOrErr.takeError(); 5121 5122 TemplateTypeParmDecl *ToD = nullptr; 5123 if (GetImportedOrCreateDecl( 5124 ToD, D, Importer.getToContext(), 5125 Importer.getToContext().getTranslationUnitDecl(), 5126 *BeginLocOrErr, *LocationOrErr, 5127 D->getDepth(), D->getIndex(), Importer.Import(D->getIdentifier()), 5128 D->wasDeclaredWithTypename(), D->isParameterPack(), 5129 D->hasTypeConstraint())) 5130 return ToD; 5131 5132 // Import the type-constraint 5133 if (const TypeConstraint *TC = D->getTypeConstraint()) { 5134 NestedNameSpecifierLoc ToNNS; 5135 DeclarationName ToName; 5136 SourceLocation ToNameLoc; 5137 NamedDecl *ToFoundDecl; 5138 ConceptDecl *ToNamedConcept; 5139 Expr *ToIDC; 5140 if (auto Imp = importSeq(TC->getNestedNameSpecifierLoc(), 5141 TC->getConceptNameInfo().getName(), TC->getConceptNameInfo().getLoc(), 5142 TC->getFoundDecl(), TC->getNamedConcept(), 5143 TC->getImmediatelyDeclaredConstraint())) 5144 std::tie(ToNNS, ToName, ToNameLoc, ToFoundDecl, ToNamedConcept, 5145 ToIDC) = *Imp; 5146 else 5147 return Imp.takeError(); 5148 5149 TemplateArgumentListInfo ToTAInfo; 5150 const auto *ASTTemplateArgs = TC->getTemplateArgsAsWritten(); 5151 if (ASTTemplateArgs) 5152 if (Error Err = ImportTemplateArgumentListInfo(*ASTTemplateArgs, 5153 ToTAInfo)) 5154 return std::move(Err); 5155 5156 ToD->setTypeConstraint(ToNNS, DeclarationNameInfo(ToName, ToNameLoc), 5157 ToFoundDecl, ToNamedConcept, 5158 ASTTemplateArgs ? 5159 ASTTemplateArgumentListInfo::Create(Importer.getToContext(), 5160 ToTAInfo) : nullptr, 5161 ToIDC); 5162 } 5163 5164 return ToD; 5165 } 5166 5167 ExpectedDecl 5168 ASTNodeImporter::VisitNonTypeTemplateParmDecl(NonTypeTemplateParmDecl *D) { 5169 DeclarationName ToDeclName; 5170 SourceLocation ToLocation, ToInnerLocStart; 5171 QualType ToType; 5172 TypeSourceInfo *ToTypeSourceInfo; 5173 if (auto Imp = importSeq( 5174 D->getDeclName(), D->getLocation(), D->getType(), D->getTypeSourceInfo(), 5175 D->getInnerLocStart())) 5176 std::tie( 5177 ToDeclName, ToLocation, ToType, ToTypeSourceInfo, 5178 ToInnerLocStart) = *Imp; 5179 else 5180 return Imp.takeError(); 5181 5182 // FIXME: Import default argument. 5183 5184 NonTypeTemplateParmDecl *ToD = nullptr; 5185 (void)GetImportedOrCreateDecl( 5186 ToD, D, Importer.getToContext(), 5187 Importer.getToContext().getTranslationUnitDecl(), 5188 ToInnerLocStart, ToLocation, D->getDepth(), 5189 D->getPosition(), ToDeclName.getAsIdentifierInfo(), ToType, 5190 D->isParameterPack(), ToTypeSourceInfo); 5191 return ToD; 5192 } 5193 5194 ExpectedDecl 5195 ASTNodeImporter::VisitTemplateTemplateParmDecl(TemplateTemplateParmDecl *D) { 5196 // Import the name of this declaration. 5197 auto NameOrErr = import(D->getDeclName()); 5198 if (!NameOrErr) 5199 return NameOrErr.takeError(); 5200 5201 // Import the location of this declaration. 5202 ExpectedSLoc LocationOrErr = import(D->getLocation()); 5203 if (!LocationOrErr) 5204 return LocationOrErr.takeError(); 5205 5206 // Import template parameters. 5207 auto TemplateParamsOrErr = import(D->getTemplateParameters()); 5208 if (!TemplateParamsOrErr) 5209 return TemplateParamsOrErr.takeError(); 5210 5211 // FIXME: Import default argument. 5212 5213 TemplateTemplateParmDecl *ToD = nullptr; 5214 (void)GetImportedOrCreateDecl( 5215 ToD, D, Importer.getToContext(), 5216 Importer.getToContext().getTranslationUnitDecl(), *LocationOrErr, 5217 D->getDepth(), D->getPosition(), D->isParameterPack(), 5218 (*NameOrErr).getAsIdentifierInfo(), 5219 *TemplateParamsOrErr); 5220 return ToD; 5221 } 5222 5223 // Returns the definition for a (forward) declaration of a TemplateDecl, if 5224 // it has any definition in the redecl chain. 5225 template <typename T> static auto getTemplateDefinition(T *D) -> T * { 5226 assert(D->getTemplatedDecl() && "Should be called on templates only"); 5227 auto *ToTemplatedDef = D->getTemplatedDecl()->getDefinition(); 5228 if (!ToTemplatedDef) 5229 return nullptr; 5230 auto *TemplateWithDef = ToTemplatedDef->getDescribedTemplate(); 5231 return cast_or_null<T>(TemplateWithDef); 5232 } 5233 5234 ExpectedDecl ASTNodeImporter::VisitClassTemplateDecl(ClassTemplateDecl *D) { 5235 5236 // Import the major distinguishing characteristics of this class template. 5237 DeclContext *DC, *LexicalDC; 5238 DeclarationName Name; 5239 SourceLocation Loc; 5240 NamedDecl *ToD; 5241 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 5242 return std::move(Err); 5243 if (ToD) 5244 return ToD; 5245 5246 ClassTemplateDecl *FoundByLookup = nullptr; 5247 5248 // We may already have a template of the same name; try to find and match it. 5249 if (!DC->isFunctionOrMethod()) { 5250 SmallVector<NamedDecl *, 4> ConflictingDecls; 5251 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 5252 for (auto *FoundDecl : FoundDecls) { 5253 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary | 5254 Decl::IDNS_TagFriend)) 5255 continue; 5256 5257 Decl *Found = FoundDecl; 5258 auto *FoundTemplate = dyn_cast<ClassTemplateDecl>(Found); 5259 if (FoundTemplate) { 5260 if (!hasSameVisibilityContext(FoundTemplate, D)) 5261 continue; 5262 5263 if (IsStructuralMatch(D, FoundTemplate)) { 5264 ClassTemplateDecl *TemplateWithDef = 5265 getTemplateDefinition(FoundTemplate); 5266 if (D->isThisDeclarationADefinition() && TemplateWithDef) 5267 return Importer.MapImported(D, TemplateWithDef); 5268 if (!FoundByLookup) 5269 FoundByLookup = FoundTemplate; 5270 // Search in all matches because there may be multiple decl chains, 5271 // see ASTTests test ImportExistingFriendClassTemplateDef. 5272 continue; 5273 } 5274 ConflictingDecls.push_back(FoundDecl); 5275 } 5276 } 5277 5278 if (!ConflictingDecls.empty()) { 5279 ExpectedName NameOrErr = Importer.HandleNameConflict( 5280 Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(), 5281 ConflictingDecls.size()); 5282 if (NameOrErr) 5283 Name = NameOrErr.get(); 5284 else 5285 return NameOrErr.takeError(); 5286 } 5287 } 5288 5289 CXXRecordDecl *FromTemplated = D->getTemplatedDecl(); 5290 5291 // Create the declaration that is being templated. 5292 CXXRecordDecl *ToTemplated; 5293 if (Error Err = importInto(ToTemplated, FromTemplated)) 5294 return std::move(Err); 5295 5296 // Create the class template declaration itself. 5297 auto TemplateParamsOrErr = import(D->getTemplateParameters()); 5298 if (!TemplateParamsOrErr) 5299 return TemplateParamsOrErr.takeError(); 5300 5301 ClassTemplateDecl *D2; 5302 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, Loc, Name, 5303 *TemplateParamsOrErr, ToTemplated)) 5304 return D2; 5305 5306 ToTemplated->setDescribedClassTemplate(D2); 5307 5308 D2->setAccess(D->getAccess()); 5309 D2->setLexicalDeclContext(LexicalDC); 5310 5311 addDeclToContexts(D, D2); 5312 5313 if (FoundByLookup) { 5314 auto *Recent = 5315 const_cast<ClassTemplateDecl *>(FoundByLookup->getMostRecentDecl()); 5316 5317 // It is possible that during the import of the class template definition 5318 // we start the import of a fwd friend decl of the very same class template 5319 // and we add the fwd friend decl to the lookup table. But the ToTemplated 5320 // had been created earlier and by that time the lookup could not find 5321 // anything existing, so it has no previous decl. Later, (still during the 5322 // import of the fwd friend decl) we start to import the definition again 5323 // and this time the lookup finds the previous fwd friend class template. 5324 // In this case we must set up the previous decl for the templated decl. 5325 if (!ToTemplated->getPreviousDecl()) { 5326 assert(FoundByLookup->getTemplatedDecl() && 5327 "Found decl must have its templated decl set"); 5328 CXXRecordDecl *PrevTemplated = 5329 FoundByLookup->getTemplatedDecl()->getMostRecentDecl(); 5330 if (ToTemplated != PrevTemplated) 5331 ToTemplated->setPreviousDecl(PrevTemplated); 5332 } 5333 5334 D2->setPreviousDecl(Recent); 5335 } 5336 5337 if (FromTemplated->isCompleteDefinition() && 5338 !ToTemplated->isCompleteDefinition()) { 5339 // FIXME: Import definition! 5340 } 5341 5342 return D2; 5343 } 5344 5345 ExpectedDecl ASTNodeImporter::VisitClassTemplateSpecializationDecl( 5346 ClassTemplateSpecializationDecl *D) { 5347 ClassTemplateDecl *ClassTemplate; 5348 if (Error Err = importInto(ClassTemplate, D->getSpecializedTemplate())) 5349 return std::move(Err); 5350 5351 // Import the context of this declaration. 5352 DeclContext *DC, *LexicalDC; 5353 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 5354 return std::move(Err); 5355 5356 // Import template arguments. 5357 SmallVector<TemplateArgument, 2> TemplateArgs; 5358 if (Error Err = ImportTemplateArguments( 5359 D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs)) 5360 return std::move(Err); 5361 // Try to find an existing specialization with these template arguments and 5362 // template parameter list. 5363 void *InsertPos = nullptr; 5364 ClassTemplateSpecializationDecl *PrevDecl = nullptr; 5365 ClassTemplatePartialSpecializationDecl *PartialSpec = 5366 dyn_cast<ClassTemplatePartialSpecializationDecl>(D); 5367 5368 // Import template parameters. 5369 TemplateParameterList *ToTPList = nullptr; 5370 5371 if (PartialSpec) { 5372 auto ToTPListOrErr = import(PartialSpec->getTemplateParameters()); 5373 if (!ToTPListOrErr) 5374 return ToTPListOrErr.takeError(); 5375 ToTPList = *ToTPListOrErr; 5376 PrevDecl = ClassTemplate->findPartialSpecialization(TemplateArgs, 5377 *ToTPListOrErr, 5378 InsertPos); 5379 } else 5380 PrevDecl = ClassTemplate->findSpecialization(TemplateArgs, InsertPos); 5381 5382 if (PrevDecl) { 5383 if (IsStructuralMatch(D, PrevDecl)) { 5384 if (D->isThisDeclarationADefinition() && PrevDecl->getDefinition()) { 5385 Importer.MapImported(D, PrevDecl->getDefinition()); 5386 // Import those default field initializers which have been 5387 // instantiated in the "From" context, but not in the "To" context. 5388 for (auto *FromField : D->fields()) { 5389 auto ToOrErr = import(FromField); 5390 if (!ToOrErr) 5391 return ToOrErr.takeError(); 5392 } 5393 5394 // Import those methods which have been instantiated in the 5395 // "From" context, but not in the "To" context. 5396 for (CXXMethodDecl *FromM : D->methods()) { 5397 auto ToOrErr = import(FromM); 5398 if (!ToOrErr) 5399 return ToOrErr.takeError(); 5400 } 5401 5402 // TODO Import instantiated default arguments. 5403 // TODO Import instantiated exception specifications. 5404 // 5405 // Generally, ASTCommon.h/DeclUpdateKind enum gives a very good hint 5406 // what else could be fused during an AST merge. 5407 return PrevDecl; 5408 } 5409 } else { // ODR violation. 5410 // FIXME HandleNameConflict 5411 return make_error<ImportError>(ImportError::NameConflict); 5412 } 5413 } 5414 5415 // Import the location of this declaration. 5416 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc()); 5417 if (!BeginLocOrErr) 5418 return BeginLocOrErr.takeError(); 5419 ExpectedSLoc IdLocOrErr = import(D->getLocation()); 5420 if (!IdLocOrErr) 5421 return IdLocOrErr.takeError(); 5422 5423 // Create the specialization. 5424 ClassTemplateSpecializationDecl *D2 = nullptr; 5425 if (PartialSpec) { 5426 // Import TemplateArgumentListInfo. 5427 TemplateArgumentListInfo ToTAInfo; 5428 const auto &ASTTemplateArgs = *PartialSpec->getTemplateArgsAsWritten(); 5429 if (Error Err = ImportTemplateArgumentListInfo(ASTTemplateArgs, ToTAInfo)) 5430 return std::move(Err); 5431 5432 QualType CanonInjType; 5433 if (Error Err = importInto( 5434 CanonInjType, PartialSpec->getInjectedSpecializationType())) 5435 return std::move(Err); 5436 CanonInjType = CanonInjType.getCanonicalType(); 5437 5438 if (GetImportedOrCreateDecl<ClassTemplatePartialSpecializationDecl>( 5439 D2, D, Importer.getToContext(), D->getTagKind(), DC, 5440 *BeginLocOrErr, *IdLocOrErr, ToTPList, ClassTemplate, 5441 llvm::makeArrayRef(TemplateArgs.data(), TemplateArgs.size()), 5442 ToTAInfo, CanonInjType, 5443 cast_or_null<ClassTemplatePartialSpecializationDecl>(PrevDecl))) 5444 return D2; 5445 5446 // Update InsertPos, because preceding import calls may have invalidated 5447 // it by adding new specializations. 5448 auto *PartSpec2 = cast<ClassTemplatePartialSpecializationDecl>(D2); 5449 if (!ClassTemplate->findPartialSpecialization(TemplateArgs, ToTPList, 5450 InsertPos)) 5451 // Add this partial specialization to the class template. 5452 ClassTemplate->AddPartialSpecialization(PartSpec2, InsertPos); 5453 5454 } else { // Not a partial specialization. 5455 if (GetImportedOrCreateDecl( 5456 D2, D, Importer.getToContext(), D->getTagKind(), DC, 5457 *BeginLocOrErr, *IdLocOrErr, ClassTemplate, TemplateArgs, 5458 PrevDecl)) 5459 return D2; 5460 5461 // Update InsertPos, because preceding import calls may have invalidated 5462 // it by adding new specializations. 5463 if (!ClassTemplate->findSpecialization(TemplateArgs, InsertPos)) 5464 // Add this specialization to the class template. 5465 ClassTemplate->AddSpecialization(D2, InsertPos); 5466 } 5467 5468 D2->setSpecializationKind(D->getSpecializationKind()); 5469 5470 // Set the context of this specialization/instantiation. 5471 D2->setLexicalDeclContext(LexicalDC); 5472 5473 // Add to the DC only if it was an explicit specialization/instantiation. 5474 if (D2->isExplicitInstantiationOrSpecialization()) { 5475 LexicalDC->addDeclInternal(D2); 5476 } 5477 5478 if (auto BraceRangeOrErr = import(D->getBraceRange())) 5479 D2->setBraceRange(*BraceRangeOrErr); 5480 else 5481 return BraceRangeOrErr.takeError(); 5482 5483 // Import the qualifier, if any. 5484 if (auto LocOrErr = import(D->getQualifierLoc())) 5485 D2->setQualifierInfo(*LocOrErr); 5486 else 5487 return LocOrErr.takeError(); 5488 5489 if (auto *TSI = D->getTypeAsWritten()) { 5490 if (auto TInfoOrErr = import(TSI)) 5491 D2->setTypeAsWritten(*TInfoOrErr); 5492 else 5493 return TInfoOrErr.takeError(); 5494 5495 if (auto LocOrErr = import(D->getTemplateKeywordLoc())) 5496 D2->setTemplateKeywordLoc(*LocOrErr); 5497 else 5498 return LocOrErr.takeError(); 5499 5500 if (auto LocOrErr = import(D->getExternLoc())) 5501 D2->setExternLoc(*LocOrErr); 5502 else 5503 return LocOrErr.takeError(); 5504 } 5505 5506 if (D->getPointOfInstantiation().isValid()) { 5507 if (auto POIOrErr = import(D->getPointOfInstantiation())) 5508 D2->setPointOfInstantiation(*POIOrErr); 5509 else 5510 return POIOrErr.takeError(); 5511 } 5512 5513 D2->setTemplateSpecializationKind(D->getTemplateSpecializationKind()); 5514 5515 if (D->isCompleteDefinition()) 5516 if (Error Err = ImportDefinition(D, D2)) 5517 return std::move(Err); 5518 5519 return D2; 5520 } 5521 5522 ExpectedDecl ASTNodeImporter::VisitVarTemplateDecl(VarTemplateDecl *D) { 5523 // If this variable has a definition in the translation unit we're coming 5524 // from, 5525 // but this particular declaration is not that definition, import the 5526 // definition and map to that. 5527 auto *Definition = 5528 cast_or_null<VarDecl>(D->getTemplatedDecl()->getDefinition()); 5529 if (Definition && Definition != D->getTemplatedDecl()) { 5530 if (ExpectedDecl ImportedDefOrErr = import( 5531 Definition->getDescribedVarTemplate())) 5532 return Importer.MapImported(D, *ImportedDefOrErr); 5533 else 5534 return ImportedDefOrErr.takeError(); 5535 } 5536 5537 // Import the major distinguishing characteristics of this variable template. 5538 DeclContext *DC, *LexicalDC; 5539 DeclarationName Name; 5540 SourceLocation Loc; 5541 NamedDecl *ToD; 5542 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 5543 return std::move(Err); 5544 if (ToD) 5545 return ToD; 5546 5547 // We may already have a template of the same name; try to find and match it. 5548 assert(!DC->isFunctionOrMethod() && 5549 "Variable templates cannot be declared at function scope"); 5550 SmallVector<NamedDecl *, 4> ConflictingDecls; 5551 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 5552 for (auto *FoundDecl : FoundDecls) { 5553 if (!FoundDecl->isInIdentifierNamespace(Decl::IDNS_Ordinary)) 5554 continue; 5555 5556 Decl *Found = FoundDecl; 5557 if (VarTemplateDecl *FoundTemplate = dyn_cast<VarTemplateDecl>(Found)) { 5558 if (IsStructuralMatch(D, FoundTemplate)) { 5559 // The variable templates structurally match; call it the same template. 5560 Importer.MapImported(D->getTemplatedDecl(), 5561 FoundTemplate->getTemplatedDecl()); 5562 return Importer.MapImported(D, FoundTemplate); 5563 } 5564 ConflictingDecls.push_back(FoundDecl); 5565 } 5566 } 5567 5568 if (!ConflictingDecls.empty()) { 5569 ExpectedName NameOrErr = Importer.HandleNameConflict( 5570 Name, DC, Decl::IDNS_Ordinary, ConflictingDecls.data(), 5571 ConflictingDecls.size()); 5572 if (NameOrErr) 5573 Name = NameOrErr.get(); 5574 else 5575 return NameOrErr.takeError(); 5576 } 5577 5578 VarDecl *DTemplated = D->getTemplatedDecl(); 5579 5580 // Import the type. 5581 // FIXME: Value not used? 5582 ExpectedType TypeOrErr = import(DTemplated->getType()); 5583 if (!TypeOrErr) 5584 return TypeOrErr.takeError(); 5585 5586 // Create the declaration that is being templated. 5587 VarDecl *ToTemplated; 5588 if (Error Err = importInto(ToTemplated, DTemplated)) 5589 return std::move(Err); 5590 5591 // Create the variable template declaration itself. 5592 auto TemplateParamsOrErr = import(D->getTemplateParameters()); 5593 if (!TemplateParamsOrErr) 5594 return TemplateParamsOrErr.takeError(); 5595 5596 VarTemplateDecl *ToVarTD; 5597 if (GetImportedOrCreateDecl(ToVarTD, D, Importer.getToContext(), DC, Loc, 5598 Name, *TemplateParamsOrErr, ToTemplated)) 5599 return ToVarTD; 5600 5601 ToTemplated->setDescribedVarTemplate(ToVarTD); 5602 5603 ToVarTD->setAccess(D->getAccess()); 5604 ToVarTD->setLexicalDeclContext(LexicalDC); 5605 LexicalDC->addDeclInternal(ToVarTD); 5606 5607 if (DTemplated->isThisDeclarationADefinition() && 5608 !ToTemplated->isThisDeclarationADefinition()) { 5609 // FIXME: Import definition! 5610 } 5611 5612 return ToVarTD; 5613 } 5614 5615 ExpectedDecl ASTNodeImporter::VisitVarTemplateSpecializationDecl( 5616 VarTemplateSpecializationDecl *D) { 5617 // If this record has a definition in the translation unit we're coming from, 5618 // but this particular declaration is not that definition, import the 5619 // definition and map to that. 5620 VarDecl *Definition = D->getDefinition(); 5621 if (Definition && Definition != D) { 5622 if (ExpectedDecl ImportedDefOrErr = import(Definition)) 5623 return Importer.MapImported(D, *ImportedDefOrErr); 5624 else 5625 return ImportedDefOrErr.takeError(); 5626 } 5627 5628 VarTemplateDecl *VarTemplate = nullptr; 5629 if (Error Err = importInto(VarTemplate, D->getSpecializedTemplate())) 5630 return std::move(Err); 5631 5632 // Import the context of this declaration. 5633 DeclContext *DC, *LexicalDC; 5634 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 5635 return std::move(Err); 5636 5637 // Import the location of this declaration. 5638 ExpectedSLoc BeginLocOrErr = import(D->getBeginLoc()); 5639 if (!BeginLocOrErr) 5640 return BeginLocOrErr.takeError(); 5641 5642 auto IdLocOrErr = import(D->getLocation()); 5643 if (!IdLocOrErr) 5644 return IdLocOrErr.takeError(); 5645 5646 // Import template arguments. 5647 SmallVector<TemplateArgument, 2> TemplateArgs; 5648 if (Error Err = ImportTemplateArguments( 5649 D->getTemplateArgs().data(), D->getTemplateArgs().size(), TemplateArgs)) 5650 return std::move(Err); 5651 5652 // Try to find an existing specialization with these template arguments. 5653 void *InsertPos = nullptr; 5654 VarTemplateSpecializationDecl *D2 = VarTemplate->findSpecialization( 5655 TemplateArgs, InsertPos); 5656 if (D2) { 5657 // We already have a variable template specialization with these template 5658 // arguments. 5659 5660 // FIXME: Check for specialization vs. instantiation errors. 5661 5662 if (VarDecl *FoundDef = D2->getDefinition()) { 5663 if (!D->isThisDeclarationADefinition() || 5664 IsStructuralMatch(D, FoundDef)) { 5665 // The record types structurally match, or the "from" translation 5666 // unit only had a forward declaration anyway; call it the same 5667 // variable. 5668 return Importer.MapImported(D, FoundDef); 5669 } 5670 } 5671 } else { 5672 // Import the type. 5673 QualType T; 5674 if (Error Err = importInto(T, D->getType())) 5675 return std::move(Err); 5676 5677 auto TInfoOrErr = import(D->getTypeSourceInfo()); 5678 if (!TInfoOrErr) 5679 return TInfoOrErr.takeError(); 5680 5681 TemplateArgumentListInfo ToTAInfo; 5682 if (Error Err = ImportTemplateArgumentListInfo( 5683 D->getTemplateArgsInfo(), ToTAInfo)) 5684 return std::move(Err); 5685 5686 using PartVarSpecDecl = VarTemplatePartialSpecializationDecl; 5687 // Create a new specialization. 5688 if (auto *FromPartial = dyn_cast<PartVarSpecDecl>(D)) { 5689 // Import TemplateArgumentListInfo 5690 TemplateArgumentListInfo ArgInfos; 5691 const auto *FromTAArgsAsWritten = FromPartial->getTemplateArgsAsWritten(); 5692 // NOTE: FromTAArgsAsWritten and template parameter list are non-null. 5693 if (Error Err = ImportTemplateArgumentListInfo( 5694 *FromTAArgsAsWritten, ArgInfos)) 5695 return std::move(Err); 5696 5697 auto ToTPListOrErr = import(FromPartial->getTemplateParameters()); 5698 if (!ToTPListOrErr) 5699 return ToTPListOrErr.takeError(); 5700 5701 PartVarSpecDecl *ToPartial; 5702 if (GetImportedOrCreateDecl(ToPartial, D, Importer.getToContext(), DC, 5703 *BeginLocOrErr, *IdLocOrErr, *ToTPListOrErr, 5704 VarTemplate, T, *TInfoOrErr, 5705 D->getStorageClass(), TemplateArgs, ArgInfos)) 5706 return ToPartial; 5707 5708 if (Expected<PartVarSpecDecl *> ToInstOrErr = import( 5709 FromPartial->getInstantiatedFromMember())) 5710 ToPartial->setInstantiatedFromMember(*ToInstOrErr); 5711 else 5712 return ToInstOrErr.takeError(); 5713 5714 if (FromPartial->isMemberSpecialization()) 5715 ToPartial->setMemberSpecialization(); 5716 5717 D2 = ToPartial; 5718 5719 } else { // Full specialization 5720 if (GetImportedOrCreateDecl(D2, D, Importer.getToContext(), DC, 5721 *BeginLocOrErr, *IdLocOrErr, VarTemplate, 5722 T, *TInfoOrErr, 5723 D->getStorageClass(), TemplateArgs)) 5724 return D2; 5725 } 5726 5727 if (D->getPointOfInstantiation().isValid()) { 5728 if (ExpectedSLoc POIOrErr = import(D->getPointOfInstantiation())) 5729 D2->setPointOfInstantiation(*POIOrErr); 5730 else 5731 return POIOrErr.takeError(); 5732 } 5733 5734 D2->setSpecializationKind(D->getSpecializationKind()); 5735 D2->setTemplateArgsInfo(ToTAInfo); 5736 5737 // Add this specialization to the class template. 5738 VarTemplate->AddSpecialization(D2, InsertPos); 5739 5740 // Import the qualifier, if any. 5741 if (auto LocOrErr = import(D->getQualifierLoc())) 5742 D2->setQualifierInfo(*LocOrErr); 5743 else 5744 return LocOrErr.takeError(); 5745 5746 if (D->isConstexpr()) 5747 D2->setConstexpr(true); 5748 5749 // Add the specialization to this context. 5750 D2->setLexicalDeclContext(LexicalDC); 5751 LexicalDC->addDeclInternal(D2); 5752 5753 D2->setAccess(D->getAccess()); 5754 } 5755 5756 if (Error Err = ImportInitializer(D, D2)) 5757 return std::move(Err); 5758 5759 return D2; 5760 } 5761 5762 ExpectedDecl 5763 ASTNodeImporter::VisitFunctionTemplateDecl(FunctionTemplateDecl *D) { 5764 DeclContext *DC, *LexicalDC; 5765 DeclarationName Name; 5766 SourceLocation Loc; 5767 NamedDecl *ToD; 5768 5769 if (Error Err = ImportDeclParts(D, DC, LexicalDC, Name, ToD, Loc)) 5770 return std::move(Err); 5771 5772 if (ToD) 5773 return ToD; 5774 5775 const FunctionTemplateDecl *FoundByLookup = nullptr; 5776 5777 // Try to find a function in our own ("to") context with the same name, same 5778 // type, and in the same context as the function we're importing. 5779 // FIXME Split this into a separate function. 5780 if (!LexicalDC->isFunctionOrMethod()) { 5781 unsigned IDNS = Decl::IDNS_Ordinary | Decl::IDNS_OrdinaryFriend; 5782 auto FoundDecls = Importer.findDeclsInToCtx(DC, Name); 5783 for (auto *FoundDecl : FoundDecls) { 5784 if (!FoundDecl->isInIdentifierNamespace(IDNS)) 5785 continue; 5786 5787 if (auto *FoundTemplate = dyn_cast<FunctionTemplateDecl>(FoundDecl)) { 5788 if (!hasSameVisibilityContext(FoundTemplate, D)) 5789 continue; 5790 if (IsStructuralMatch(D, FoundTemplate)) { 5791 FunctionTemplateDecl *TemplateWithDef = 5792 getTemplateDefinition(FoundTemplate); 5793 if (D->isThisDeclarationADefinition() && TemplateWithDef) 5794 return Importer.MapImported(D, TemplateWithDef); 5795 5796 FoundByLookup = FoundTemplate; 5797 break; 5798 // TODO: handle conflicting names 5799 } 5800 } 5801 } 5802 } 5803 5804 auto ParamsOrErr = import(D->getTemplateParameters()); 5805 if (!ParamsOrErr) 5806 return ParamsOrErr.takeError(); 5807 5808 FunctionDecl *TemplatedFD; 5809 if (Error Err = importInto(TemplatedFD, D->getTemplatedDecl())) 5810 return std::move(Err); 5811 5812 FunctionTemplateDecl *ToFunc; 5813 if (GetImportedOrCreateDecl(ToFunc, D, Importer.getToContext(), DC, Loc, Name, 5814 *ParamsOrErr, TemplatedFD)) 5815 return ToFunc; 5816 5817 TemplatedFD->setDescribedFunctionTemplate(ToFunc); 5818 5819 ToFunc->setAccess(D->getAccess()); 5820 ToFunc->setLexicalDeclContext(LexicalDC); 5821 LexicalDC->addDeclInternal(ToFunc); 5822 5823 if (FoundByLookup) { 5824 auto *Recent = 5825 const_cast<FunctionTemplateDecl *>(FoundByLookup->getMostRecentDecl()); 5826 if (!TemplatedFD->getPreviousDecl()) { 5827 assert(FoundByLookup->getTemplatedDecl() && 5828 "Found decl must have its templated decl set"); 5829 auto *PrevTemplated = 5830 FoundByLookup->getTemplatedDecl()->getMostRecentDecl(); 5831 if (TemplatedFD != PrevTemplated) 5832 TemplatedFD->setPreviousDecl(PrevTemplated); 5833 } 5834 ToFunc->setPreviousDecl(Recent); 5835 } 5836 5837 return ToFunc; 5838 } 5839 5840 //---------------------------------------------------------------------------- 5841 // Import Statements 5842 //---------------------------------------------------------------------------- 5843 5844 ExpectedStmt ASTNodeImporter::VisitStmt(Stmt *S) { 5845 Importer.FromDiag(S->getBeginLoc(), diag::err_unsupported_ast_node) 5846 << S->getStmtClassName(); 5847 return make_error<ImportError>(ImportError::UnsupportedConstruct); 5848 } 5849 5850 5851 ExpectedStmt ASTNodeImporter::VisitGCCAsmStmt(GCCAsmStmt *S) { 5852 if (Importer.returnWithErrorInTest()) 5853 return make_error<ImportError>(ImportError::UnsupportedConstruct); 5854 SmallVector<IdentifierInfo *, 4> Names; 5855 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) { 5856 IdentifierInfo *ToII = Importer.Import(S->getOutputIdentifier(I)); 5857 // ToII is nullptr when no symbolic name is given for output operand 5858 // see ParseStmtAsm::ParseAsmOperandsOpt 5859 Names.push_back(ToII); 5860 } 5861 5862 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) { 5863 IdentifierInfo *ToII = Importer.Import(S->getInputIdentifier(I)); 5864 // ToII is nullptr when no symbolic name is given for input operand 5865 // see ParseStmtAsm::ParseAsmOperandsOpt 5866 Names.push_back(ToII); 5867 } 5868 5869 SmallVector<StringLiteral *, 4> Clobbers; 5870 for (unsigned I = 0, E = S->getNumClobbers(); I != E; I++) { 5871 if (auto ClobberOrErr = import(S->getClobberStringLiteral(I))) 5872 Clobbers.push_back(*ClobberOrErr); 5873 else 5874 return ClobberOrErr.takeError(); 5875 5876 } 5877 5878 SmallVector<StringLiteral *, 4> Constraints; 5879 for (unsigned I = 0, E = S->getNumOutputs(); I != E; I++) { 5880 if (auto OutputOrErr = import(S->getOutputConstraintLiteral(I))) 5881 Constraints.push_back(*OutputOrErr); 5882 else 5883 return OutputOrErr.takeError(); 5884 } 5885 5886 for (unsigned I = 0, E = S->getNumInputs(); I != E; I++) { 5887 if (auto InputOrErr = import(S->getInputConstraintLiteral(I))) 5888 Constraints.push_back(*InputOrErr); 5889 else 5890 return InputOrErr.takeError(); 5891 } 5892 5893 SmallVector<Expr *, 4> Exprs(S->getNumOutputs() + S->getNumInputs() + 5894 S->getNumLabels()); 5895 if (Error Err = ImportContainerChecked(S->outputs(), Exprs)) 5896 return std::move(Err); 5897 5898 if (Error Err = 5899 ImportArrayChecked(S->inputs(), Exprs.begin() + S->getNumOutputs())) 5900 return std::move(Err); 5901 5902 if (Error Err = ImportArrayChecked( 5903 S->labels(), Exprs.begin() + S->getNumOutputs() + S->getNumInputs())) 5904 return std::move(Err); 5905 5906 ExpectedSLoc AsmLocOrErr = import(S->getAsmLoc()); 5907 if (!AsmLocOrErr) 5908 return AsmLocOrErr.takeError(); 5909 auto AsmStrOrErr = import(S->getAsmString()); 5910 if (!AsmStrOrErr) 5911 return AsmStrOrErr.takeError(); 5912 ExpectedSLoc RParenLocOrErr = import(S->getRParenLoc()); 5913 if (!RParenLocOrErr) 5914 return RParenLocOrErr.takeError(); 5915 5916 return new (Importer.getToContext()) GCCAsmStmt( 5917 Importer.getToContext(), 5918 *AsmLocOrErr, 5919 S->isSimple(), 5920 S->isVolatile(), 5921 S->getNumOutputs(), 5922 S->getNumInputs(), 5923 Names.data(), 5924 Constraints.data(), 5925 Exprs.data(), 5926 *AsmStrOrErr, 5927 S->getNumClobbers(), 5928 Clobbers.data(), 5929 S->getNumLabels(), 5930 *RParenLocOrErr); 5931 } 5932 5933 ExpectedStmt ASTNodeImporter::VisitDeclStmt(DeclStmt *S) { 5934 auto Imp = importSeq(S->getDeclGroup(), S->getBeginLoc(), S->getEndLoc()); 5935 if (!Imp) 5936 return Imp.takeError(); 5937 5938 DeclGroupRef ToDG; 5939 SourceLocation ToBeginLoc, ToEndLoc; 5940 std::tie(ToDG, ToBeginLoc, ToEndLoc) = *Imp; 5941 5942 return new (Importer.getToContext()) DeclStmt(ToDG, ToBeginLoc, ToEndLoc); 5943 } 5944 5945 ExpectedStmt ASTNodeImporter::VisitNullStmt(NullStmt *S) { 5946 ExpectedSLoc ToSemiLocOrErr = import(S->getSemiLoc()); 5947 if (!ToSemiLocOrErr) 5948 return ToSemiLocOrErr.takeError(); 5949 return new (Importer.getToContext()) NullStmt( 5950 *ToSemiLocOrErr, S->hasLeadingEmptyMacro()); 5951 } 5952 5953 ExpectedStmt ASTNodeImporter::VisitCompoundStmt(CompoundStmt *S) { 5954 SmallVector<Stmt *, 8> ToStmts(S->size()); 5955 5956 if (Error Err = ImportContainerChecked(S->body(), ToStmts)) 5957 return std::move(Err); 5958 5959 ExpectedSLoc ToLBracLocOrErr = import(S->getLBracLoc()); 5960 if (!ToLBracLocOrErr) 5961 return ToLBracLocOrErr.takeError(); 5962 5963 ExpectedSLoc ToRBracLocOrErr = import(S->getRBracLoc()); 5964 if (!ToRBracLocOrErr) 5965 return ToRBracLocOrErr.takeError(); 5966 5967 return CompoundStmt::Create( 5968 Importer.getToContext(), ToStmts, 5969 *ToLBracLocOrErr, *ToRBracLocOrErr); 5970 } 5971 5972 ExpectedStmt ASTNodeImporter::VisitCaseStmt(CaseStmt *S) { 5973 auto Imp = importSeq( 5974 S->getLHS(), S->getRHS(), S->getSubStmt(), S->getCaseLoc(), 5975 S->getEllipsisLoc(), S->getColonLoc()); 5976 if (!Imp) 5977 return Imp.takeError(); 5978 5979 Expr *ToLHS, *ToRHS; 5980 Stmt *ToSubStmt; 5981 SourceLocation ToCaseLoc, ToEllipsisLoc, ToColonLoc; 5982 std::tie(ToLHS, ToRHS, ToSubStmt, ToCaseLoc, ToEllipsisLoc, ToColonLoc) = 5983 *Imp; 5984 5985 auto *ToStmt = CaseStmt::Create(Importer.getToContext(), ToLHS, ToRHS, 5986 ToCaseLoc, ToEllipsisLoc, ToColonLoc); 5987 ToStmt->setSubStmt(ToSubStmt); 5988 5989 return ToStmt; 5990 } 5991 5992 ExpectedStmt ASTNodeImporter::VisitDefaultStmt(DefaultStmt *S) { 5993 auto Imp = importSeq(S->getDefaultLoc(), S->getColonLoc(), S->getSubStmt()); 5994 if (!Imp) 5995 return Imp.takeError(); 5996 5997 SourceLocation ToDefaultLoc, ToColonLoc; 5998 Stmt *ToSubStmt; 5999 std::tie(ToDefaultLoc, ToColonLoc, ToSubStmt) = *Imp; 6000 6001 return new (Importer.getToContext()) DefaultStmt( 6002 ToDefaultLoc, ToColonLoc, ToSubStmt); 6003 } 6004 6005 ExpectedStmt ASTNodeImporter::VisitLabelStmt(LabelStmt *S) { 6006 auto Imp = importSeq(S->getIdentLoc(), S->getDecl(), S->getSubStmt()); 6007 if (!Imp) 6008 return Imp.takeError(); 6009 6010 SourceLocation ToIdentLoc; 6011 LabelDecl *ToLabelDecl; 6012 Stmt *ToSubStmt; 6013 std::tie(ToIdentLoc, ToLabelDecl, ToSubStmt) = *Imp; 6014 6015 return new (Importer.getToContext()) LabelStmt( 6016 ToIdentLoc, ToLabelDecl, ToSubStmt); 6017 } 6018 6019 ExpectedStmt ASTNodeImporter::VisitAttributedStmt(AttributedStmt *S) { 6020 ExpectedSLoc ToAttrLocOrErr = import(S->getAttrLoc()); 6021 if (!ToAttrLocOrErr) 6022 return ToAttrLocOrErr.takeError(); 6023 ArrayRef<const Attr*> FromAttrs(S->getAttrs()); 6024 SmallVector<const Attr *, 1> ToAttrs(FromAttrs.size()); 6025 if (Error Err = ImportContainerChecked(FromAttrs, ToAttrs)) 6026 return std::move(Err); 6027 ExpectedStmt ToSubStmtOrErr = import(S->getSubStmt()); 6028 if (!ToSubStmtOrErr) 6029 return ToSubStmtOrErr.takeError(); 6030 6031 return AttributedStmt::Create( 6032 Importer.getToContext(), *ToAttrLocOrErr, ToAttrs, *ToSubStmtOrErr); 6033 } 6034 6035 ExpectedStmt ASTNodeImporter::VisitIfStmt(IfStmt *S) { 6036 auto Imp = importSeq( 6037 S->getIfLoc(), S->getInit(), S->getConditionVariable(), S->getCond(), 6038 S->getThen(), S->getElseLoc(), S->getElse()); 6039 if (!Imp) 6040 return Imp.takeError(); 6041 6042 SourceLocation ToIfLoc, ToElseLoc; 6043 Stmt *ToInit, *ToThen, *ToElse; 6044 VarDecl *ToConditionVariable; 6045 Expr *ToCond; 6046 std::tie( 6047 ToIfLoc, ToInit, ToConditionVariable, ToCond, ToThen, ToElseLoc, ToElse) = 6048 *Imp; 6049 6050 return IfStmt::Create(Importer.getToContext(), ToIfLoc, S->isConstexpr(), 6051 ToInit, ToConditionVariable, ToCond, ToThen, ToElseLoc, 6052 ToElse); 6053 } 6054 6055 ExpectedStmt ASTNodeImporter::VisitSwitchStmt(SwitchStmt *S) { 6056 auto Imp = importSeq( 6057 S->getInit(), S->getConditionVariable(), S->getCond(), 6058 S->getBody(), S->getSwitchLoc()); 6059 if (!Imp) 6060 return Imp.takeError(); 6061 6062 Stmt *ToInit, *ToBody; 6063 VarDecl *ToConditionVariable; 6064 Expr *ToCond; 6065 SourceLocation ToSwitchLoc; 6066 std::tie(ToInit, ToConditionVariable, ToCond, ToBody, ToSwitchLoc) = *Imp; 6067 6068 auto *ToStmt = SwitchStmt::Create(Importer.getToContext(), ToInit, 6069 ToConditionVariable, ToCond); 6070 ToStmt->setBody(ToBody); 6071 ToStmt->setSwitchLoc(ToSwitchLoc); 6072 6073 // Now we have to re-chain the cases. 6074 SwitchCase *LastChainedSwitchCase = nullptr; 6075 for (SwitchCase *SC = S->getSwitchCaseList(); SC != nullptr; 6076 SC = SC->getNextSwitchCase()) { 6077 Expected<SwitchCase *> ToSCOrErr = import(SC); 6078 if (!ToSCOrErr) 6079 return ToSCOrErr.takeError(); 6080 if (LastChainedSwitchCase) 6081 LastChainedSwitchCase->setNextSwitchCase(*ToSCOrErr); 6082 else 6083 ToStmt->setSwitchCaseList(*ToSCOrErr); 6084 LastChainedSwitchCase = *ToSCOrErr; 6085 } 6086 6087 return ToStmt; 6088 } 6089 6090 ExpectedStmt ASTNodeImporter::VisitWhileStmt(WhileStmt *S) { 6091 auto Imp = importSeq( 6092 S->getConditionVariable(), S->getCond(), S->getBody(), S->getWhileLoc()); 6093 if (!Imp) 6094 return Imp.takeError(); 6095 6096 VarDecl *ToConditionVariable; 6097 Expr *ToCond; 6098 Stmt *ToBody; 6099 SourceLocation ToWhileLoc; 6100 std::tie(ToConditionVariable, ToCond, ToBody, ToWhileLoc) = *Imp; 6101 6102 return WhileStmt::Create(Importer.getToContext(), ToConditionVariable, ToCond, 6103 ToBody, ToWhileLoc); 6104 } 6105 6106 ExpectedStmt ASTNodeImporter::VisitDoStmt(DoStmt *S) { 6107 auto Imp = importSeq( 6108 S->getBody(), S->getCond(), S->getDoLoc(), S->getWhileLoc(), 6109 S->getRParenLoc()); 6110 if (!Imp) 6111 return Imp.takeError(); 6112 6113 Stmt *ToBody; 6114 Expr *ToCond; 6115 SourceLocation ToDoLoc, ToWhileLoc, ToRParenLoc; 6116 std::tie(ToBody, ToCond, ToDoLoc, ToWhileLoc, ToRParenLoc) = *Imp; 6117 6118 return new (Importer.getToContext()) DoStmt( 6119 ToBody, ToCond, ToDoLoc, ToWhileLoc, ToRParenLoc); 6120 } 6121 6122 ExpectedStmt ASTNodeImporter::VisitForStmt(ForStmt *S) { 6123 auto Imp = importSeq( 6124 S->getInit(), S->getCond(), S->getConditionVariable(), S->getInc(), 6125 S->getBody(), S->getForLoc(), S->getLParenLoc(), S->getRParenLoc()); 6126 if (!Imp) 6127 return Imp.takeError(); 6128 6129 Stmt *ToInit; 6130 Expr *ToCond, *ToInc; 6131 VarDecl *ToConditionVariable; 6132 Stmt *ToBody; 6133 SourceLocation ToForLoc, ToLParenLoc, ToRParenLoc; 6134 std::tie( 6135 ToInit, ToCond, ToConditionVariable, ToInc, ToBody, ToForLoc, 6136 ToLParenLoc, ToRParenLoc) = *Imp; 6137 6138 return new (Importer.getToContext()) ForStmt( 6139 Importer.getToContext(), 6140 ToInit, ToCond, ToConditionVariable, ToInc, ToBody, ToForLoc, ToLParenLoc, 6141 ToRParenLoc); 6142 } 6143 6144 ExpectedStmt ASTNodeImporter::VisitGotoStmt(GotoStmt *S) { 6145 auto Imp = importSeq(S->getLabel(), S->getGotoLoc(), S->getLabelLoc()); 6146 if (!Imp) 6147 return Imp.takeError(); 6148 6149 LabelDecl *ToLabel; 6150 SourceLocation ToGotoLoc, ToLabelLoc; 6151 std::tie(ToLabel, ToGotoLoc, ToLabelLoc) = *Imp; 6152 6153 return new (Importer.getToContext()) GotoStmt( 6154 ToLabel, ToGotoLoc, ToLabelLoc); 6155 } 6156 6157 ExpectedStmt ASTNodeImporter::VisitIndirectGotoStmt(IndirectGotoStmt *S) { 6158 auto Imp = importSeq(S->getGotoLoc(), S->getStarLoc(), S->getTarget()); 6159 if (!Imp) 6160 return Imp.takeError(); 6161 6162 SourceLocation ToGotoLoc, ToStarLoc; 6163 Expr *ToTarget; 6164 std::tie(ToGotoLoc, ToStarLoc, ToTarget) = *Imp; 6165 6166 return new (Importer.getToContext()) IndirectGotoStmt( 6167 ToGotoLoc, ToStarLoc, ToTarget); 6168 } 6169 6170 ExpectedStmt ASTNodeImporter::VisitContinueStmt(ContinueStmt *S) { 6171 ExpectedSLoc ToContinueLocOrErr = import(S->getContinueLoc()); 6172 if (!ToContinueLocOrErr) 6173 return ToContinueLocOrErr.takeError(); 6174 return new (Importer.getToContext()) ContinueStmt(*ToContinueLocOrErr); 6175 } 6176 6177 ExpectedStmt ASTNodeImporter::VisitBreakStmt(BreakStmt *S) { 6178 auto ToBreakLocOrErr = import(S->getBreakLoc()); 6179 if (!ToBreakLocOrErr) 6180 return ToBreakLocOrErr.takeError(); 6181 return new (Importer.getToContext()) BreakStmt(*ToBreakLocOrErr); 6182 } 6183 6184 ExpectedStmt ASTNodeImporter::VisitReturnStmt(ReturnStmt *S) { 6185 auto Imp = importSeq( 6186 S->getReturnLoc(), S->getRetValue(), S->getNRVOCandidate()); 6187 if (!Imp) 6188 return Imp.takeError(); 6189 6190 SourceLocation ToReturnLoc; 6191 Expr *ToRetValue; 6192 const VarDecl *ToNRVOCandidate; 6193 std::tie(ToReturnLoc, ToRetValue, ToNRVOCandidate) = *Imp; 6194 6195 return ReturnStmt::Create(Importer.getToContext(), ToReturnLoc, ToRetValue, 6196 ToNRVOCandidate); 6197 } 6198 6199 ExpectedStmt ASTNodeImporter::VisitCXXCatchStmt(CXXCatchStmt *S) { 6200 auto Imp = importSeq( 6201 S->getCatchLoc(), S->getExceptionDecl(), S->getHandlerBlock()); 6202 if (!Imp) 6203 return Imp.takeError(); 6204 6205 SourceLocation ToCatchLoc; 6206 VarDecl *ToExceptionDecl; 6207 Stmt *ToHandlerBlock; 6208 std::tie(ToCatchLoc, ToExceptionDecl, ToHandlerBlock) = *Imp; 6209 6210 return new (Importer.getToContext()) CXXCatchStmt ( 6211 ToCatchLoc, ToExceptionDecl, ToHandlerBlock); 6212 } 6213 6214 ExpectedStmt ASTNodeImporter::VisitCXXTryStmt(CXXTryStmt *S) { 6215 ExpectedSLoc ToTryLocOrErr = import(S->getTryLoc()); 6216 if (!ToTryLocOrErr) 6217 return ToTryLocOrErr.takeError(); 6218 6219 ExpectedStmt ToTryBlockOrErr = import(S->getTryBlock()); 6220 if (!ToTryBlockOrErr) 6221 return ToTryBlockOrErr.takeError(); 6222 6223 SmallVector<Stmt *, 1> ToHandlers(S->getNumHandlers()); 6224 for (unsigned HI = 0, HE = S->getNumHandlers(); HI != HE; ++HI) { 6225 CXXCatchStmt *FromHandler = S->getHandler(HI); 6226 if (auto ToHandlerOrErr = import(FromHandler)) 6227 ToHandlers[HI] = *ToHandlerOrErr; 6228 else 6229 return ToHandlerOrErr.takeError(); 6230 } 6231 6232 return CXXTryStmt::Create( 6233 Importer.getToContext(), *ToTryLocOrErr,*ToTryBlockOrErr, ToHandlers); 6234 } 6235 6236 ExpectedStmt ASTNodeImporter::VisitCXXForRangeStmt(CXXForRangeStmt *S) { 6237 auto Imp1 = importSeq( 6238 S->getInit(), S->getRangeStmt(), S->getBeginStmt(), S->getEndStmt(), 6239 S->getCond(), S->getInc(), S->getLoopVarStmt(), S->getBody()); 6240 if (!Imp1) 6241 return Imp1.takeError(); 6242 auto Imp2 = importSeq( 6243 S->getForLoc(), S->getCoawaitLoc(), S->getColonLoc(), S->getRParenLoc()); 6244 if (!Imp2) 6245 return Imp2.takeError(); 6246 6247 DeclStmt *ToRangeStmt, *ToBeginStmt, *ToEndStmt, *ToLoopVarStmt; 6248 Expr *ToCond, *ToInc; 6249 Stmt *ToInit, *ToBody; 6250 std::tie( 6251 ToInit, ToRangeStmt, ToBeginStmt, ToEndStmt, ToCond, ToInc, ToLoopVarStmt, 6252 ToBody) = *Imp1; 6253 SourceLocation ToForLoc, ToCoawaitLoc, ToColonLoc, ToRParenLoc; 6254 std::tie(ToForLoc, ToCoawaitLoc, ToColonLoc, ToRParenLoc) = *Imp2; 6255 6256 return new (Importer.getToContext()) CXXForRangeStmt( 6257 ToInit, ToRangeStmt, ToBeginStmt, ToEndStmt, ToCond, ToInc, ToLoopVarStmt, 6258 ToBody, ToForLoc, ToCoawaitLoc, ToColonLoc, ToRParenLoc); 6259 } 6260 6261 ExpectedStmt 6262 ASTNodeImporter::VisitObjCForCollectionStmt(ObjCForCollectionStmt *S) { 6263 auto Imp = importSeq( 6264 S->getElement(), S->getCollection(), S->getBody(), 6265 S->getForLoc(), S->getRParenLoc()); 6266 if (!Imp) 6267 return Imp.takeError(); 6268 6269 Stmt *ToElement, *ToBody; 6270 Expr *ToCollection; 6271 SourceLocation ToForLoc, ToRParenLoc; 6272 std::tie(ToElement, ToCollection, ToBody, ToForLoc, ToRParenLoc) = *Imp; 6273 6274 return new (Importer.getToContext()) ObjCForCollectionStmt(ToElement, 6275 ToCollection, 6276 ToBody, 6277 ToForLoc, 6278 ToRParenLoc); 6279 } 6280 6281 ExpectedStmt ASTNodeImporter::VisitObjCAtCatchStmt(ObjCAtCatchStmt *S) { 6282 auto Imp = importSeq( 6283 S->getAtCatchLoc(), S->getRParenLoc(), S->getCatchParamDecl(), 6284 S->getCatchBody()); 6285 if (!Imp) 6286 return Imp.takeError(); 6287 6288 SourceLocation ToAtCatchLoc, ToRParenLoc; 6289 VarDecl *ToCatchParamDecl; 6290 Stmt *ToCatchBody; 6291 std::tie(ToAtCatchLoc, ToRParenLoc, ToCatchParamDecl, ToCatchBody) = *Imp; 6292 6293 return new (Importer.getToContext()) ObjCAtCatchStmt ( 6294 ToAtCatchLoc, ToRParenLoc, ToCatchParamDecl, ToCatchBody); 6295 } 6296 6297 ExpectedStmt ASTNodeImporter::VisitObjCAtFinallyStmt(ObjCAtFinallyStmt *S) { 6298 ExpectedSLoc ToAtFinallyLocOrErr = import(S->getAtFinallyLoc()); 6299 if (!ToAtFinallyLocOrErr) 6300 return ToAtFinallyLocOrErr.takeError(); 6301 ExpectedStmt ToAtFinallyStmtOrErr = import(S->getFinallyBody()); 6302 if (!ToAtFinallyStmtOrErr) 6303 return ToAtFinallyStmtOrErr.takeError(); 6304 return new (Importer.getToContext()) ObjCAtFinallyStmt(*ToAtFinallyLocOrErr, 6305 *ToAtFinallyStmtOrErr); 6306 } 6307 6308 ExpectedStmt ASTNodeImporter::VisitObjCAtTryStmt(ObjCAtTryStmt *S) { 6309 auto Imp = importSeq( 6310 S->getAtTryLoc(), S->getTryBody(), S->getFinallyStmt()); 6311 if (!Imp) 6312 return Imp.takeError(); 6313 6314 SourceLocation ToAtTryLoc; 6315 Stmt *ToTryBody, *ToFinallyStmt; 6316 std::tie(ToAtTryLoc, ToTryBody, ToFinallyStmt) = *Imp; 6317 6318 SmallVector<Stmt *, 1> ToCatchStmts(S->getNumCatchStmts()); 6319 for (unsigned CI = 0, CE = S->getNumCatchStmts(); CI != CE; ++CI) { 6320 ObjCAtCatchStmt *FromCatchStmt = S->getCatchStmt(CI); 6321 if (ExpectedStmt ToCatchStmtOrErr = import(FromCatchStmt)) 6322 ToCatchStmts[CI] = *ToCatchStmtOrErr; 6323 else 6324 return ToCatchStmtOrErr.takeError(); 6325 } 6326 6327 return ObjCAtTryStmt::Create(Importer.getToContext(), 6328 ToAtTryLoc, ToTryBody, 6329 ToCatchStmts.begin(), ToCatchStmts.size(), 6330 ToFinallyStmt); 6331 } 6332 6333 ExpectedStmt ASTNodeImporter::VisitObjCAtSynchronizedStmt 6334 (ObjCAtSynchronizedStmt *S) { 6335 auto Imp = importSeq( 6336 S->getAtSynchronizedLoc(), S->getSynchExpr(), S->getSynchBody()); 6337 if (!Imp) 6338 return Imp.takeError(); 6339 6340 SourceLocation ToAtSynchronizedLoc; 6341 Expr *ToSynchExpr; 6342 Stmt *ToSynchBody; 6343 std::tie(ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody) = *Imp; 6344 6345 return new (Importer.getToContext()) ObjCAtSynchronizedStmt( 6346 ToAtSynchronizedLoc, ToSynchExpr, ToSynchBody); 6347 } 6348 6349 ExpectedStmt ASTNodeImporter::VisitObjCAtThrowStmt(ObjCAtThrowStmt *S) { 6350 ExpectedSLoc ToThrowLocOrErr = import(S->getThrowLoc()); 6351 if (!ToThrowLocOrErr) 6352 return ToThrowLocOrErr.takeError(); 6353 ExpectedExpr ToThrowExprOrErr = import(S->getThrowExpr()); 6354 if (!ToThrowExprOrErr) 6355 return ToThrowExprOrErr.takeError(); 6356 return new (Importer.getToContext()) ObjCAtThrowStmt( 6357 *ToThrowLocOrErr, *ToThrowExprOrErr); 6358 } 6359 6360 ExpectedStmt ASTNodeImporter::VisitObjCAutoreleasePoolStmt( 6361 ObjCAutoreleasePoolStmt *S) { 6362 ExpectedSLoc ToAtLocOrErr = import(S->getAtLoc()); 6363 if (!ToAtLocOrErr) 6364 return ToAtLocOrErr.takeError(); 6365 ExpectedStmt ToSubStmtOrErr = import(S->getSubStmt()); 6366 if (!ToSubStmtOrErr) 6367 return ToSubStmtOrErr.takeError(); 6368 return new (Importer.getToContext()) ObjCAutoreleasePoolStmt(*ToAtLocOrErr, 6369 *ToSubStmtOrErr); 6370 } 6371 6372 //---------------------------------------------------------------------------- 6373 // Import Expressions 6374 //---------------------------------------------------------------------------- 6375 ExpectedStmt ASTNodeImporter::VisitExpr(Expr *E) { 6376 Importer.FromDiag(E->getBeginLoc(), diag::err_unsupported_ast_node) 6377 << E->getStmtClassName(); 6378 return make_error<ImportError>(ImportError::UnsupportedConstruct); 6379 } 6380 6381 ExpectedStmt ASTNodeImporter::VisitVAArgExpr(VAArgExpr *E) { 6382 auto Imp = importSeq( 6383 E->getBuiltinLoc(), E->getSubExpr(), E->getWrittenTypeInfo(), 6384 E->getRParenLoc(), E->getType()); 6385 if (!Imp) 6386 return Imp.takeError(); 6387 6388 SourceLocation ToBuiltinLoc, ToRParenLoc; 6389 Expr *ToSubExpr; 6390 TypeSourceInfo *ToWrittenTypeInfo; 6391 QualType ToType; 6392 std::tie(ToBuiltinLoc, ToSubExpr, ToWrittenTypeInfo, ToRParenLoc, ToType) = 6393 *Imp; 6394 6395 return new (Importer.getToContext()) VAArgExpr( 6396 ToBuiltinLoc, ToSubExpr, ToWrittenTypeInfo, ToRParenLoc, ToType, 6397 E->isMicrosoftABI()); 6398 } 6399 6400 ExpectedStmt ASTNodeImporter::VisitChooseExpr(ChooseExpr *E) { 6401 auto Imp = importSeq(E->getCond(), E->getLHS(), E->getRHS(), 6402 E->getBuiltinLoc(), E->getRParenLoc(), E->getType()); 6403 if (!Imp) 6404 return Imp.takeError(); 6405 6406 Expr *ToCond; 6407 Expr *ToLHS; 6408 Expr *ToRHS; 6409 SourceLocation ToBuiltinLoc, ToRParenLoc; 6410 QualType ToType; 6411 std::tie(ToCond, ToLHS, ToRHS, ToBuiltinLoc, ToRParenLoc, ToType) = *Imp; 6412 6413 ExprValueKind VK = E->getValueKind(); 6414 ExprObjectKind OK = E->getObjectKind(); 6415 6416 bool TypeDependent = ToCond->isTypeDependent(); 6417 bool ValueDependent = ToCond->isValueDependent(); 6418 6419 // The value of CondIsTrue only matters if the value is not 6420 // condition-dependent. 6421 bool CondIsTrue = !E->isConditionDependent() && E->isConditionTrue(); 6422 6423 return new (Importer.getToContext()) 6424 ChooseExpr(ToBuiltinLoc, ToCond, ToLHS, ToRHS, ToType, VK, OK, 6425 ToRParenLoc, CondIsTrue, TypeDependent, ValueDependent); 6426 } 6427 6428 ExpectedStmt ASTNodeImporter::VisitGNUNullExpr(GNUNullExpr *E) { 6429 ExpectedType TypeOrErr = import(E->getType()); 6430 if (!TypeOrErr) 6431 return TypeOrErr.takeError(); 6432 6433 ExpectedSLoc BeginLocOrErr = import(E->getBeginLoc()); 6434 if (!BeginLocOrErr) 6435 return BeginLocOrErr.takeError(); 6436 6437 return new (Importer.getToContext()) GNUNullExpr(*TypeOrErr, *BeginLocOrErr); 6438 } 6439 6440 ExpectedStmt ASTNodeImporter::VisitPredefinedExpr(PredefinedExpr *E) { 6441 auto Imp = importSeq( 6442 E->getBeginLoc(), E->getType(), E->getFunctionName()); 6443 if (!Imp) 6444 return Imp.takeError(); 6445 6446 SourceLocation ToBeginLoc; 6447 QualType ToType; 6448 StringLiteral *ToFunctionName; 6449 std::tie(ToBeginLoc, ToType, ToFunctionName) = *Imp; 6450 6451 return PredefinedExpr::Create(Importer.getToContext(), ToBeginLoc, ToType, 6452 E->getIdentKind(), ToFunctionName); 6453 } 6454 6455 ExpectedStmt ASTNodeImporter::VisitDeclRefExpr(DeclRefExpr *E) { 6456 auto Imp = importSeq( 6457 E->getQualifierLoc(), E->getTemplateKeywordLoc(), E->getDecl(), 6458 E->getLocation(), E->getType()); 6459 if (!Imp) 6460 return Imp.takeError(); 6461 6462 NestedNameSpecifierLoc ToQualifierLoc; 6463 SourceLocation ToTemplateKeywordLoc, ToLocation; 6464 ValueDecl *ToDecl; 6465 QualType ToType; 6466 std::tie(ToQualifierLoc, ToTemplateKeywordLoc, ToDecl, ToLocation, ToType) = 6467 *Imp; 6468 6469 NamedDecl *ToFoundD = nullptr; 6470 if (E->getDecl() != E->getFoundDecl()) { 6471 auto FoundDOrErr = import(E->getFoundDecl()); 6472 if (!FoundDOrErr) 6473 return FoundDOrErr.takeError(); 6474 ToFoundD = *FoundDOrErr; 6475 } 6476 6477 TemplateArgumentListInfo ToTAInfo; 6478 TemplateArgumentListInfo *ToResInfo = nullptr; 6479 if (E->hasExplicitTemplateArgs()) { 6480 if (Error Err = 6481 ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(), 6482 E->template_arguments(), ToTAInfo)) 6483 return std::move(Err); 6484 ToResInfo = &ToTAInfo; 6485 } 6486 6487 auto *ToE = DeclRefExpr::Create( 6488 Importer.getToContext(), ToQualifierLoc, ToTemplateKeywordLoc, ToDecl, 6489 E->refersToEnclosingVariableOrCapture(), ToLocation, ToType, 6490 E->getValueKind(), ToFoundD, ToResInfo, E->isNonOdrUse()); 6491 if (E->hadMultipleCandidates()) 6492 ToE->setHadMultipleCandidates(true); 6493 return ToE; 6494 } 6495 6496 ExpectedStmt ASTNodeImporter::VisitImplicitValueInitExpr(ImplicitValueInitExpr *E) { 6497 ExpectedType TypeOrErr = import(E->getType()); 6498 if (!TypeOrErr) 6499 return TypeOrErr.takeError(); 6500 6501 return new (Importer.getToContext()) ImplicitValueInitExpr(*TypeOrErr); 6502 } 6503 6504 ExpectedStmt ASTNodeImporter::VisitDesignatedInitExpr(DesignatedInitExpr *E) { 6505 ExpectedExpr ToInitOrErr = import(E->getInit()); 6506 if (!ToInitOrErr) 6507 return ToInitOrErr.takeError(); 6508 6509 ExpectedSLoc ToEqualOrColonLocOrErr = import(E->getEqualOrColonLoc()); 6510 if (!ToEqualOrColonLocOrErr) 6511 return ToEqualOrColonLocOrErr.takeError(); 6512 6513 SmallVector<Expr *, 4> ToIndexExprs(E->getNumSubExprs() - 1); 6514 // List elements from the second, the first is Init itself 6515 for (unsigned I = 1, N = E->getNumSubExprs(); I < N; I++) { 6516 if (ExpectedExpr ToArgOrErr = import(E->getSubExpr(I))) 6517 ToIndexExprs[I - 1] = *ToArgOrErr; 6518 else 6519 return ToArgOrErr.takeError(); 6520 } 6521 6522 SmallVector<Designator, 4> ToDesignators(E->size()); 6523 if (Error Err = ImportContainerChecked(E->designators(), ToDesignators)) 6524 return std::move(Err); 6525 6526 return DesignatedInitExpr::Create( 6527 Importer.getToContext(), ToDesignators, 6528 ToIndexExprs, *ToEqualOrColonLocOrErr, 6529 E->usesGNUSyntax(), *ToInitOrErr); 6530 } 6531 6532 ExpectedStmt 6533 ASTNodeImporter::VisitCXXNullPtrLiteralExpr(CXXNullPtrLiteralExpr *E) { 6534 ExpectedType ToTypeOrErr = import(E->getType()); 6535 if (!ToTypeOrErr) 6536 return ToTypeOrErr.takeError(); 6537 6538 ExpectedSLoc ToLocationOrErr = import(E->getLocation()); 6539 if (!ToLocationOrErr) 6540 return ToLocationOrErr.takeError(); 6541 6542 return new (Importer.getToContext()) CXXNullPtrLiteralExpr( 6543 *ToTypeOrErr, *ToLocationOrErr); 6544 } 6545 6546 ExpectedStmt ASTNodeImporter::VisitIntegerLiteral(IntegerLiteral *E) { 6547 ExpectedType ToTypeOrErr = import(E->getType()); 6548 if (!ToTypeOrErr) 6549 return ToTypeOrErr.takeError(); 6550 6551 ExpectedSLoc ToLocationOrErr = import(E->getLocation()); 6552 if (!ToLocationOrErr) 6553 return ToLocationOrErr.takeError(); 6554 6555 return IntegerLiteral::Create( 6556 Importer.getToContext(), E->getValue(), *ToTypeOrErr, *ToLocationOrErr); 6557 } 6558 6559 6560 ExpectedStmt ASTNodeImporter::VisitFloatingLiteral(FloatingLiteral *E) { 6561 ExpectedType ToTypeOrErr = import(E->getType()); 6562 if (!ToTypeOrErr) 6563 return ToTypeOrErr.takeError(); 6564 6565 ExpectedSLoc ToLocationOrErr = import(E->getLocation()); 6566 if (!ToLocationOrErr) 6567 return ToLocationOrErr.takeError(); 6568 6569 return FloatingLiteral::Create( 6570 Importer.getToContext(), E->getValue(), E->isExact(), 6571 *ToTypeOrErr, *ToLocationOrErr); 6572 } 6573 6574 ExpectedStmt ASTNodeImporter::VisitImaginaryLiteral(ImaginaryLiteral *E) { 6575 auto ToTypeOrErr = import(E->getType()); 6576 if (!ToTypeOrErr) 6577 return ToTypeOrErr.takeError(); 6578 6579 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr()); 6580 if (!ToSubExprOrErr) 6581 return ToSubExprOrErr.takeError(); 6582 6583 return new (Importer.getToContext()) ImaginaryLiteral( 6584 *ToSubExprOrErr, *ToTypeOrErr); 6585 } 6586 6587 ExpectedStmt ASTNodeImporter::VisitCharacterLiteral(CharacterLiteral *E) { 6588 ExpectedType ToTypeOrErr = import(E->getType()); 6589 if (!ToTypeOrErr) 6590 return ToTypeOrErr.takeError(); 6591 6592 ExpectedSLoc ToLocationOrErr = import(E->getLocation()); 6593 if (!ToLocationOrErr) 6594 return ToLocationOrErr.takeError(); 6595 6596 return new (Importer.getToContext()) CharacterLiteral( 6597 E->getValue(), E->getKind(), *ToTypeOrErr, *ToLocationOrErr); 6598 } 6599 6600 ExpectedStmt ASTNodeImporter::VisitStringLiteral(StringLiteral *E) { 6601 ExpectedType ToTypeOrErr = import(E->getType()); 6602 if (!ToTypeOrErr) 6603 return ToTypeOrErr.takeError(); 6604 6605 SmallVector<SourceLocation, 4> ToLocations(E->getNumConcatenated()); 6606 if (Error Err = ImportArrayChecked( 6607 E->tokloc_begin(), E->tokloc_end(), ToLocations.begin())) 6608 return std::move(Err); 6609 6610 return StringLiteral::Create( 6611 Importer.getToContext(), E->getBytes(), E->getKind(), E->isPascal(), 6612 *ToTypeOrErr, ToLocations.data(), ToLocations.size()); 6613 } 6614 6615 ExpectedStmt ASTNodeImporter::VisitCompoundLiteralExpr(CompoundLiteralExpr *E) { 6616 auto Imp = importSeq( 6617 E->getLParenLoc(), E->getTypeSourceInfo(), E->getType(), 6618 E->getInitializer()); 6619 if (!Imp) 6620 return Imp.takeError(); 6621 6622 SourceLocation ToLParenLoc; 6623 TypeSourceInfo *ToTypeSourceInfo; 6624 QualType ToType; 6625 Expr *ToInitializer; 6626 std::tie(ToLParenLoc, ToTypeSourceInfo, ToType, ToInitializer) = *Imp; 6627 6628 return new (Importer.getToContext()) CompoundLiteralExpr( 6629 ToLParenLoc, ToTypeSourceInfo, ToType, E->getValueKind(), 6630 ToInitializer, E->isFileScope()); 6631 } 6632 6633 ExpectedStmt ASTNodeImporter::VisitAtomicExpr(AtomicExpr *E) { 6634 auto Imp = importSeq( 6635 E->getBuiltinLoc(), E->getType(), E->getRParenLoc()); 6636 if (!Imp) 6637 return Imp.takeError(); 6638 6639 SourceLocation ToBuiltinLoc, ToRParenLoc; 6640 QualType ToType; 6641 std::tie(ToBuiltinLoc, ToType, ToRParenLoc) = *Imp; 6642 6643 SmallVector<Expr *, 6> ToExprs(E->getNumSubExprs()); 6644 if (Error Err = ImportArrayChecked( 6645 E->getSubExprs(), E->getSubExprs() + E->getNumSubExprs(), 6646 ToExprs.begin())) 6647 return std::move(Err); 6648 6649 return new (Importer.getToContext()) AtomicExpr( 6650 ToBuiltinLoc, ToExprs, ToType, E->getOp(), ToRParenLoc); 6651 } 6652 6653 ExpectedStmt ASTNodeImporter::VisitAddrLabelExpr(AddrLabelExpr *E) { 6654 auto Imp = importSeq( 6655 E->getAmpAmpLoc(), E->getLabelLoc(), E->getLabel(), E->getType()); 6656 if (!Imp) 6657 return Imp.takeError(); 6658 6659 SourceLocation ToAmpAmpLoc, ToLabelLoc; 6660 LabelDecl *ToLabel; 6661 QualType ToType; 6662 std::tie(ToAmpAmpLoc, ToLabelLoc, ToLabel, ToType) = *Imp; 6663 6664 return new (Importer.getToContext()) AddrLabelExpr( 6665 ToAmpAmpLoc, ToLabelLoc, ToLabel, ToType); 6666 } 6667 6668 ExpectedStmt ASTNodeImporter::VisitConstantExpr(ConstantExpr *E) { 6669 auto Imp = importSeq(E->getSubExpr()); 6670 if (!Imp) 6671 return Imp.takeError(); 6672 6673 Expr *ToSubExpr; 6674 std::tie(ToSubExpr) = *Imp; 6675 6676 // TODO : Handle APValue::ValueKind that require importing. 6677 APValue::ValueKind Kind = E->getResultAPValueKind(); 6678 if (Kind == APValue::Int || Kind == APValue::Float || 6679 Kind == APValue::FixedPoint || Kind == APValue::ComplexFloat || 6680 Kind == APValue::ComplexInt) 6681 return ConstantExpr::Create(Importer.getToContext(), ToSubExpr, 6682 E->getAPValueResult()); 6683 return ConstantExpr::Create(Importer.getToContext(), ToSubExpr); 6684 } 6685 6686 ExpectedStmt ASTNodeImporter::VisitParenExpr(ParenExpr *E) { 6687 auto Imp = importSeq(E->getLParen(), E->getRParen(), E->getSubExpr()); 6688 if (!Imp) 6689 return Imp.takeError(); 6690 6691 SourceLocation ToLParen, ToRParen; 6692 Expr *ToSubExpr; 6693 std::tie(ToLParen, ToRParen, ToSubExpr) = *Imp; 6694 6695 return new (Importer.getToContext()) 6696 ParenExpr(ToLParen, ToRParen, ToSubExpr); 6697 } 6698 6699 ExpectedStmt ASTNodeImporter::VisitParenListExpr(ParenListExpr *E) { 6700 SmallVector<Expr *, 4> ToExprs(E->getNumExprs()); 6701 if (Error Err = ImportContainerChecked(E->exprs(), ToExprs)) 6702 return std::move(Err); 6703 6704 ExpectedSLoc ToLParenLocOrErr = import(E->getLParenLoc()); 6705 if (!ToLParenLocOrErr) 6706 return ToLParenLocOrErr.takeError(); 6707 6708 ExpectedSLoc ToRParenLocOrErr = import(E->getRParenLoc()); 6709 if (!ToRParenLocOrErr) 6710 return ToRParenLocOrErr.takeError(); 6711 6712 return ParenListExpr::Create(Importer.getToContext(), *ToLParenLocOrErr, 6713 ToExprs, *ToRParenLocOrErr); 6714 } 6715 6716 ExpectedStmt ASTNodeImporter::VisitStmtExpr(StmtExpr *E) { 6717 auto Imp = importSeq( 6718 E->getSubStmt(), E->getType(), E->getLParenLoc(), E->getRParenLoc()); 6719 if (!Imp) 6720 return Imp.takeError(); 6721 6722 CompoundStmt *ToSubStmt; 6723 QualType ToType; 6724 SourceLocation ToLParenLoc, ToRParenLoc; 6725 std::tie(ToSubStmt, ToType, ToLParenLoc, ToRParenLoc) = *Imp; 6726 6727 return new (Importer.getToContext()) StmtExpr( 6728 ToSubStmt, ToType, ToLParenLoc, ToRParenLoc); 6729 } 6730 6731 ExpectedStmt ASTNodeImporter::VisitUnaryOperator(UnaryOperator *E) { 6732 auto Imp = importSeq( 6733 E->getSubExpr(), E->getType(), E->getOperatorLoc()); 6734 if (!Imp) 6735 return Imp.takeError(); 6736 6737 Expr *ToSubExpr; 6738 QualType ToType; 6739 SourceLocation ToOperatorLoc; 6740 std::tie(ToSubExpr, ToType, ToOperatorLoc) = *Imp; 6741 6742 return new (Importer.getToContext()) UnaryOperator( 6743 ToSubExpr, E->getOpcode(), ToType, E->getValueKind(), E->getObjectKind(), 6744 ToOperatorLoc, E->canOverflow()); 6745 } 6746 6747 ExpectedStmt 6748 ASTNodeImporter::VisitUnaryExprOrTypeTraitExpr(UnaryExprOrTypeTraitExpr *E) { 6749 auto Imp = importSeq(E->getType(), E->getOperatorLoc(), E->getRParenLoc()); 6750 if (!Imp) 6751 return Imp.takeError(); 6752 6753 QualType ToType; 6754 SourceLocation ToOperatorLoc, ToRParenLoc; 6755 std::tie(ToType, ToOperatorLoc, ToRParenLoc) = *Imp; 6756 6757 if (E->isArgumentType()) { 6758 Expected<TypeSourceInfo *> ToArgumentTypeInfoOrErr = 6759 import(E->getArgumentTypeInfo()); 6760 if (!ToArgumentTypeInfoOrErr) 6761 return ToArgumentTypeInfoOrErr.takeError(); 6762 6763 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr( 6764 E->getKind(), *ToArgumentTypeInfoOrErr, ToType, ToOperatorLoc, 6765 ToRParenLoc); 6766 } 6767 6768 ExpectedExpr ToArgumentExprOrErr = import(E->getArgumentExpr()); 6769 if (!ToArgumentExprOrErr) 6770 return ToArgumentExprOrErr.takeError(); 6771 6772 return new (Importer.getToContext()) UnaryExprOrTypeTraitExpr( 6773 E->getKind(), *ToArgumentExprOrErr, ToType, ToOperatorLoc, ToRParenLoc); 6774 } 6775 6776 ExpectedStmt ASTNodeImporter::VisitBinaryOperator(BinaryOperator *E) { 6777 auto Imp = importSeq( 6778 E->getLHS(), E->getRHS(), E->getType(), E->getOperatorLoc()); 6779 if (!Imp) 6780 return Imp.takeError(); 6781 6782 Expr *ToLHS, *ToRHS; 6783 QualType ToType; 6784 SourceLocation ToOperatorLoc; 6785 std::tie(ToLHS, ToRHS, ToType, ToOperatorLoc) = *Imp; 6786 6787 return new (Importer.getToContext()) BinaryOperator( 6788 ToLHS, ToRHS, E->getOpcode(), ToType, E->getValueKind(), 6789 E->getObjectKind(), ToOperatorLoc, E->getFPFeatures()); 6790 } 6791 6792 ExpectedStmt ASTNodeImporter::VisitConditionalOperator(ConditionalOperator *E) { 6793 auto Imp = importSeq( 6794 E->getCond(), E->getQuestionLoc(), E->getLHS(), E->getColonLoc(), 6795 E->getRHS(), E->getType()); 6796 if (!Imp) 6797 return Imp.takeError(); 6798 6799 Expr *ToCond, *ToLHS, *ToRHS; 6800 SourceLocation ToQuestionLoc, ToColonLoc; 6801 QualType ToType; 6802 std::tie(ToCond, ToQuestionLoc, ToLHS, ToColonLoc, ToRHS, ToType) = *Imp; 6803 6804 return new (Importer.getToContext()) ConditionalOperator( 6805 ToCond, ToQuestionLoc, ToLHS, ToColonLoc, ToRHS, ToType, 6806 E->getValueKind(), E->getObjectKind()); 6807 } 6808 6809 ExpectedStmt ASTNodeImporter::VisitBinaryConditionalOperator( 6810 BinaryConditionalOperator *E) { 6811 auto Imp = importSeq( 6812 E->getCommon(), E->getOpaqueValue(), E->getCond(), E->getTrueExpr(), 6813 E->getFalseExpr(), E->getQuestionLoc(), E->getColonLoc(), E->getType()); 6814 if (!Imp) 6815 return Imp.takeError(); 6816 6817 Expr *ToCommon, *ToCond, *ToTrueExpr, *ToFalseExpr; 6818 OpaqueValueExpr *ToOpaqueValue; 6819 SourceLocation ToQuestionLoc, ToColonLoc; 6820 QualType ToType; 6821 std::tie( 6822 ToCommon, ToOpaqueValue, ToCond, ToTrueExpr, ToFalseExpr, ToQuestionLoc, 6823 ToColonLoc, ToType) = *Imp; 6824 6825 return new (Importer.getToContext()) BinaryConditionalOperator( 6826 ToCommon, ToOpaqueValue, ToCond, ToTrueExpr, ToFalseExpr, 6827 ToQuestionLoc, ToColonLoc, ToType, E->getValueKind(), 6828 E->getObjectKind()); 6829 } 6830 6831 ExpectedStmt ASTNodeImporter::VisitArrayTypeTraitExpr(ArrayTypeTraitExpr *E) { 6832 auto Imp = importSeq( 6833 E->getBeginLoc(), E->getQueriedTypeSourceInfo(), 6834 E->getDimensionExpression(), E->getEndLoc(), E->getType()); 6835 if (!Imp) 6836 return Imp.takeError(); 6837 6838 SourceLocation ToBeginLoc, ToEndLoc; 6839 TypeSourceInfo *ToQueriedTypeSourceInfo; 6840 Expr *ToDimensionExpression; 6841 QualType ToType; 6842 std::tie( 6843 ToBeginLoc, ToQueriedTypeSourceInfo, ToDimensionExpression, ToEndLoc, 6844 ToType) = *Imp; 6845 6846 return new (Importer.getToContext()) ArrayTypeTraitExpr( 6847 ToBeginLoc, E->getTrait(), ToQueriedTypeSourceInfo, E->getValue(), 6848 ToDimensionExpression, ToEndLoc, ToType); 6849 } 6850 6851 ExpectedStmt ASTNodeImporter::VisitExpressionTraitExpr(ExpressionTraitExpr *E) { 6852 auto Imp = importSeq( 6853 E->getBeginLoc(), E->getQueriedExpression(), E->getEndLoc(), E->getType()); 6854 if (!Imp) 6855 return Imp.takeError(); 6856 6857 SourceLocation ToBeginLoc, ToEndLoc; 6858 Expr *ToQueriedExpression; 6859 QualType ToType; 6860 std::tie(ToBeginLoc, ToQueriedExpression, ToEndLoc, ToType) = *Imp; 6861 6862 return new (Importer.getToContext()) ExpressionTraitExpr( 6863 ToBeginLoc, E->getTrait(), ToQueriedExpression, E->getValue(), 6864 ToEndLoc, ToType); 6865 } 6866 6867 ExpectedStmt ASTNodeImporter::VisitOpaqueValueExpr(OpaqueValueExpr *E) { 6868 auto Imp = importSeq( 6869 E->getLocation(), E->getType(), E->getSourceExpr()); 6870 if (!Imp) 6871 return Imp.takeError(); 6872 6873 SourceLocation ToLocation; 6874 QualType ToType; 6875 Expr *ToSourceExpr; 6876 std::tie(ToLocation, ToType, ToSourceExpr) = *Imp; 6877 6878 return new (Importer.getToContext()) OpaqueValueExpr( 6879 ToLocation, ToType, E->getValueKind(), E->getObjectKind(), ToSourceExpr); 6880 } 6881 6882 ExpectedStmt ASTNodeImporter::VisitArraySubscriptExpr(ArraySubscriptExpr *E) { 6883 auto Imp = importSeq( 6884 E->getLHS(), E->getRHS(), E->getType(), E->getRBracketLoc()); 6885 if (!Imp) 6886 return Imp.takeError(); 6887 6888 Expr *ToLHS, *ToRHS; 6889 SourceLocation ToRBracketLoc; 6890 QualType ToType; 6891 std::tie(ToLHS, ToRHS, ToType, ToRBracketLoc) = *Imp; 6892 6893 return new (Importer.getToContext()) ArraySubscriptExpr( 6894 ToLHS, ToRHS, ToType, E->getValueKind(), E->getObjectKind(), 6895 ToRBracketLoc); 6896 } 6897 6898 ExpectedStmt 6899 ASTNodeImporter::VisitCompoundAssignOperator(CompoundAssignOperator *E) { 6900 auto Imp = importSeq( 6901 E->getLHS(), E->getRHS(), E->getType(), E->getComputationLHSType(), 6902 E->getComputationResultType(), E->getOperatorLoc()); 6903 if (!Imp) 6904 return Imp.takeError(); 6905 6906 Expr *ToLHS, *ToRHS; 6907 QualType ToType, ToComputationLHSType, ToComputationResultType; 6908 SourceLocation ToOperatorLoc; 6909 std::tie(ToLHS, ToRHS, ToType, ToComputationLHSType, ToComputationResultType, 6910 ToOperatorLoc) = *Imp; 6911 6912 return new (Importer.getToContext()) CompoundAssignOperator( 6913 ToLHS, ToRHS, E->getOpcode(), ToType, E->getValueKind(), 6914 E->getObjectKind(), ToComputationLHSType, ToComputationResultType, 6915 ToOperatorLoc, E->getFPFeatures()); 6916 } 6917 6918 Expected<CXXCastPath> 6919 ASTNodeImporter::ImportCastPath(CastExpr *CE) { 6920 CXXCastPath Path; 6921 for (auto I = CE->path_begin(), E = CE->path_end(); I != E; ++I) { 6922 if (auto SpecOrErr = import(*I)) 6923 Path.push_back(*SpecOrErr); 6924 else 6925 return SpecOrErr.takeError(); 6926 } 6927 return Path; 6928 } 6929 6930 ExpectedStmt ASTNodeImporter::VisitImplicitCastExpr(ImplicitCastExpr *E) { 6931 ExpectedType ToTypeOrErr = import(E->getType()); 6932 if (!ToTypeOrErr) 6933 return ToTypeOrErr.takeError(); 6934 6935 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr()); 6936 if (!ToSubExprOrErr) 6937 return ToSubExprOrErr.takeError(); 6938 6939 Expected<CXXCastPath> ToBasePathOrErr = ImportCastPath(E); 6940 if (!ToBasePathOrErr) 6941 return ToBasePathOrErr.takeError(); 6942 6943 return ImplicitCastExpr::Create( 6944 Importer.getToContext(), *ToTypeOrErr, E->getCastKind(), *ToSubExprOrErr, 6945 &(*ToBasePathOrErr), E->getValueKind()); 6946 } 6947 6948 ExpectedStmt ASTNodeImporter::VisitExplicitCastExpr(ExplicitCastExpr *E) { 6949 auto Imp1 = importSeq( 6950 E->getType(), E->getSubExpr(), E->getTypeInfoAsWritten()); 6951 if (!Imp1) 6952 return Imp1.takeError(); 6953 6954 QualType ToType; 6955 Expr *ToSubExpr; 6956 TypeSourceInfo *ToTypeInfoAsWritten; 6957 std::tie(ToType, ToSubExpr, ToTypeInfoAsWritten) = *Imp1; 6958 6959 Expected<CXXCastPath> ToBasePathOrErr = ImportCastPath(E); 6960 if (!ToBasePathOrErr) 6961 return ToBasePathOrErr.takeError(); 6962 CXXCastPath *ToBasePath = &(*ToBasePathOrErr); 6963 6964 switch (E->getStmtClass()) { 6965 case Stmt::CStyleCastExprClass: { 6966 auto *CCE = cast<CStyleCastExpr>(E); 6967 ExpectedSLoc ToLParenLocOrErr = import(CCE->getLParenLoc()); 6968 if (!ToLParenLocOrErr) 6969 return ToLParenLocOrErr.takeError(); 6970 ExpectedSLoc ToRParenLocOrErr = import(CCE->getRParenLoc()); 6971 if (!ToRParenLocOrErr) 6972 return ToRParenLocOrErr.takeError(); 6973 return CStyleCastExpr::Create( 6974 Importer.getToContext(), ToType, E->getValueKind(), E->getCastKind(), 6975 ToSubExpr, ToBasePath, ToTypeInfoAsWritten, *ToLParenLocOrErr, 6976 *ToRParenLocOrErr); 6977 } 6978 6979 case Stmt::CXXFunctionalCastExprClass: { 6980 auto *FCE = cast<CXXFunctionalCastExpr>(E); 6981 ExpectedSLoc ToLParenLocOrErr = import(FCE->getLParenLoc()); 6982 if (!ToLParenLocOrErr) 6983 return ToLParenLocOrErr.takeError(); 6984 ExpectedSLoc ToRParenLocOrErr = import(FCE->getRParenLoc()); 6985 if (!ToRParenLocOrErr) 6986 return ToRParenLocOrErr.takeError(); 6987 return CXXFunctionalCastExpr::Create( 6988 Importer.getToContext(), ToType, E->getValueKind(), ToTypeInfoAsWritten, 6989 E->getCastKind(), ToSubExpr, ToBasePath, *ToLParenLocOrErr, 6990 *ToRParenLocOrErr); 6991 } 6992 6993 case Stmt::ObjCBridgedCastExprClass: { 6994 auto *OCE = cast<ObjCBridgedCastExpr>(E); 6995 ExpectedSLoc ToLParenLocOrErr = import(OCE->getLParenLoc()); 6996 if (!ToLParenLocOrErr) 6997 return ToLParenLocOrErr.takeError(); 6998 ExpectedSLoc ToBridgeKeywordLocOrErr = import(OCE->getBridgeKeywordLoc()); 6999 if (!ToBridgeKeywordLocOrErr) 7000 return ToBridgeKeywordLocOrErr.takeError(); 7001 return new (Importer.getToContext()) ObjCBridgedCastExpr( 7002 *ToLParenLocOrErr, OCE->getBridgeKind(), E->getCastKind(), 7003 *ToBridgeKeywordLocOrErr, ToTypeInfoAsWritten, ToSubExpr); 7004 } 7005 default: 7006 llvm_unreachable("Cast expression of unsupported type!"); 7007 return make_error<ImportError>(ImportError::UnsupportedConstruct); 7008 } 7009 } 7010 7011 ExpectedStmt ASTNodeImporter::VisitOffsetOfExpr(OffsetOfExpr *E) { 7012 SmallVector<OffsetOfNode, 4> ToNodes; 7013 for (int I = 0, N = E->getNumComponents(); I < N; ++I) { 7014 const OffsetOfNode &FromNode = E->getComponent(I); 7015 7016 SourceLocation ToBeginLoc, ToEndLoc; 7017 if (FromNode.getKind() != OffsetOfNode::Base) { 7018 auto Imp = importSeq(FromNode.getBeginLoc(), FromNode.getEndLoc()); 7019 if (!Imp) 7020 return Imp.takeError(); 7021 std::tie(ToBeginLoc, ToEndLoc) = *Imp; 7022 } 7023 7024 switch (FromNode.getKind()) { 7025 case OffsetOfNode::Array: 7026 ToNodes.push_back( 7027 OffsetOfNode(ToBeginLoc, FromNode.getArrayExprIndex(), ToEndLoc)); 7028 break; 7029 case OffsetOfNode::Base: { 7030 auto ToBSOrErr = import(FromNode.getBase()); 7031 if (!ToBSOrErr) 7032 return ToBSOrErr.takeError(); 7033 ToNodes.push_back(OffsetOfNode(*ToBSOrErr)); 7034 break; 7035 } 7036 case OffsetOfNode::Field: { 7037 auto ToFieldOrErr = import(FromNode.getField()); 7038 if (!ToFieldOrErr) 7039 return ToFieldOrErr.takeError(); 7040 ToNodes.push_back(OffsetOfNode(ToBeginLoc, *ToFieldOrErr, ToEndLoc)); 7041 break; 7042 } 7043 case OffsetOfNode::Identifier: { 7044 IdentifierInfo *ToII = Importer.Import(FromNode.getFieldName()); 7045 ToNodes.push_back(OffsetOfNode(ToBeginLoc, ToII, ToEndLoc)); 7046 break; 7047 } 7048 } 7049 } 7050 7051 SmallVector<Expr *, 4> ToExprs(E->getNumExpressions()); 7052 for (int I = 0, N = E->getNumExpressions(); I < N; ++I) { 7053 ExpectedExpr ToIndexExprOrErr = import(E->getIndexExpr(I)); 7054 if (!ToIndexExprOrErr) 7055 return ToIndexExprOrErr.takeError(); 7056 ToExprs[I] = *ToIndexExprOrErr; 7057 } 7058 7059 auto Imp = importSeq( 7060 E->getType(), E->getTypeSourceInfo(), E->getOperatorLoc(), 7061 E->getRParenLoc()); 7062 if (!Imp) 7063 return Imp.takeError(); 7064 7065 QualType ToType; 7066 TypeSourceInfo *ToTypeSourceInfo; 7067 SourceLocation ToOperatorLoc, ToRParenLoc; 7068 std::tie(ToType, ToTypeSourceInfo, ToOperatorLoc, ToRParenLoc) = *Imp; 7069 7070 return OffsetOfExpr::Create( 7071 Importer.getToContext(), ToType, ToOperatorLoc, ToTypeSourceInfo, ToNodes, 7072 ToExprs, ToRParenLoc); 7073 } 7074 7075 ExpectedStmt ASTNodeImporter::VisitCXXNoexceptExpr(CXXNoexceptExpr *E) { 7076 auto Imp = importSeq( 7077 E->getType(), E->getOperand(), E->getBeginLoc(), E->getEndLoc()); 7078 if (!Imp) 7079 return Imp.takeError(); 7080 7081 QualType ToType; 7082 Expr *ToOperand; 7083 SourceLocation ToBeginLoc, ToEndLoc; 7084 std::tie(ToType, ToOperand, ToBeginLoc, ToEndLoc) = *Imp; 7085 7086 CanThrowResult ToCanThrow; 7087 if (E->isValueDependent()) 7088 ToCanThrow = CT_Dependent; 7089 else 7090 ToCanThrow = E->getValue() ? CT_Can : CT_Cannot; 7091 7092 return new (Importer.getToContext()) CXXNoexceptExpr( 7093 ToType, ToOperand, ToCanThrow, ToBeginLoc, ToEndLoc); 7094 } 7095 7096 ExpectedStmt ASTNodeImporter::VisitCXXThrowExpr(CXXThrowExpr *E) { 7097 auto Imp = importSeq(E->getSubExpr(), E->getType(), E->getThrowLoc()); 7098 if (!Imp) 7099 return Imp.takeError(); 7100 7101 Expr *ToSubExpr; 7102 QualType ToType; 7103 SourceLocation ToThrowLoc; 7104 std::tie(ToSubExpr, ToType, ToThrowLoc) = *Imp; 7105 7106 return new (Importer.getToContext()) CXXThrowExpr( 7107 ToSubExpr, ToType, ToThrowLoc, E->isThrownVariableInScope()); 7108 } 7109 7110 ExpectedStmt ASTNodeImporter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *E) { 7111 ExpectedSLoc ToUsedLocOrErr = import(E->getUsedLocation()); 7112 if (!ToUsedLocOrErr) 7113 return ToUsedLocOrErr.takeError(); 7114 7115 auto ToParamOrErr = import(E->getParam()); 7116 if (!ToParamOrErr) 7117 return ToParamOrErr.takeError(); 7118 7119 auto UsedContextOrErr = Importer.ImportContext(E->getUsedContext()); 7120 if (!UsedContextOrErr) 7121 return UsedContextOrErr.takeError(); 7122 7123 // Import the default arg if it was not imported yet. 7124 // This is needed because it can happen that during the import of the 7125 // default expression (from VisitParmVarDecl) the same ParmVarDecl is 7126 // encountered here. The default argument for a ParmVarDecl is set in the 7127 // ParmVarDecl only after it is imported (set in VisitParmVarDecl if not here, 7128 // see VisitParmVarDecl). 7129 ParmVarDecl *ToParam = *ToParamOrErr; 7130 if (!ToParam->getDefaultArg()) { 7131 Optional<ParmVarDecl *> FromParam = Importer.getImportedFromDecl(ToParam); 7132 assert(FromParam && "ParmVarDecl was not imported?"); 7133 7134 if (Error Err = ImportDefaultArgOfParmVarDecl(*FromParam, ToParam)) 7135 return std::move(Err); 7136 } 7137 7138 return CXXDefaultArgExpr::Create(Importer.getToContext(), *ToUsedLocOrErr, 7139 *ToParamOrErr, *UsedContextOrErr); 7140 } 7141 7142 ExpectedStmt 7143 ASTNodeImporter::VisitCXXScalarValueInitExpr(CXXScalarValueInitExpr *E) { 7144 auto Imp = importSeq( 7145 E->getType(), E->getTypeSourceInfo(), E->getRParenLoc()); 7146 if (!Imp) 7147 return Imp.takeError(); 7148 7149 QualType ToType; 7150 TypeSourceInfo *ToTypeSourceInfo; 7151 SourceLocation ToRParenLoc; 7152 std::tie(ToType, ToTypeSourceInfo, ToRParenLoc) = *Imp; 7153 7154 return new (Importer.getToContext()) CXXScalarValueInitExpr( 7155 ToType, ToTypeSourceInfo, ToRParenLoc); 7156 } 7157 7158 ExpectedStmt 7159 ASTNodeImporter::VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E) { 7160 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr()); 7161 if (!ToSubExprOrErr) 7162 return ToSubExprOrErr.takeError(); 7163 7164 auto ToDtorOrErr = import(E->getTemporary()->getDestructor()); 7165 if (!ToDtorOrErr) 7166 return ToDtorOrErr.takeError(); 7167 7168 ASTContext &ToCtx = Importer.getToContext(); 7169 CXXTemporary *Temp = CXXTemporary::Create(ToCtx, *ToDtorOrErr); 7170 return CXXBindTemporaryExpr::Create(ToCtx, Temp, *ToSubExprOrErr); 7171 } 7172 7173 ExpectedStmt 7174 ASTNodeImporter::VisitCXXTemporaryObjectExpr(CXXTemporaryObjectExpr *E) { 7175 auto Imp = importSeq( 7176 E->getConstructor(), E->getType(), E->getTypeSourceInfo(), 7177 E->getParenOrBraceRange()); 7178 if (!Imp) 7179 return Imp.takeError(); 7180 7181 CXXConstructorDecl *ToConstructor; 7182 QualType ToType; 7183 TypeSourceInfo *ToTypeSourceInfo; 7184 SourceRange ToParenOrBraceRange; 7185 std::tie(ToConstructor, ToType, ToTypeSourceInfo, ToParenOrBraceRange) = *Imp; 7186 7187 SmallVector<Expr *, 8> ToArgs(E->getNumArgs()); 7188 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs)) 7189 return std::move(Err); 7190 7191 return CXXTemporaryObjectExpr::Create( 7192 Importer.getToContext(), ToConstructor, ToType, ToTypeSourceInfo, ToArgs, 7193 ToParenOrBraceRange, E->hadMultipleCandidates(), 7194 E->isListInitialization(), E->isStdInitListInitialization(), 7195 E->requiresZeroInitialization()); 7196 } 7197 7198 ExpectedDecl ASTNodeImporter::VisitLifetimeExtendedTemporaryDecl( 7199 LifetimeExtendedTemporaryDecl *D) { 7200 DeclContext *DC, *LexicalDC; 7201 if (Error Err = ImportDeclContext(D, DC, LexicalDC)) 7202 return std::move(Err); 7203 7204 auto Imp = importSeq(D->getTemporaryExpr(), D->getExtendingDecl()); 7205 // FIXME: the APValue should be imported as well if present. 7206 if (!Imp) 7207 return Imp.takeError(); 7208 7209 Expr *Temporary; 7210 ValueDecl *ExtendingDecl; 7211 std::tie(Temporary, ExtendingDecl) = *Imp; 7212 // FIXME: Should ManglingNumber get numbers associated with 'to' context? 7213 7214 LifetimeExtendedTemporaryDecl *To; 7215 if (GetImportedOrCreateDecl(To, D, Temporary, ExtendingDecl, 7216 D->getManglingNumber())) 7217 return To; 7218 7219 To->setLexicalDeclContext(LexicalDC); 7220 LexicalDC->addDeclInternal(To); 7221 return To; 7222 } 7223 7224 ExpectedStmt 7225 ASTNodeImporter::VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) { 7226 auto Imp = importSeq(E->getType(), 7227 E->getLifetimeExtendedTemporaryDecl() ? nullptr 7228 : E->getSubExpr(), 7229 E->getLifetimeExtendedTemporaryDecl()); 7230 if (!Imp) 7231 return Imp.takeError(); 7232 7233 QualType ToType; 7234 Expr *ToTemporaryExpr; 7235 LifetimeExtendedTemporaryDecl *ToMaterializedDecl; 7236 std::tie(ToType, ToTemporaryExpr, ToMaterializedDecl) = *Imp; 7237 if (!ToTemporaryExpr) 7238 ToTemporaryExpr = cast<Expr>(ToMaterializedDecl->getTemporaryExpr()); 7239 7240 auto *ToMTE = new (Importer.getToContext()) MaterializeTemporaryExpr( 7241 ToType, ToTemporaryExpr, E->isBoundToLvalueReference(), 7242 ToMaterializedDecl); 7243 7244 return ToMTE; 7245 } 7246 7247 ExpectedStmt ASTNodeImporter::VisitPackExpansionExpr(PackExpansionExpr *E) { 7248 auto Imp = importSeq( 7249 E->getType(), E->getPattern(), E->getEllipsisLoc()); 7250 if (!Imp) 7251 return Imp.takeError(); 7252 7253 QualType ToType; 7254 Expr *ToPattern; 7255 SourceLocation ToEllipsisLoc; 7256 std::tie(ToType, ToPattern, ToEllipsisLoc) = *Imp; 7257 7258 return new (Importer.getToContext()) PackExpansionExpr( 7259 ToType, ToPattern, ToEllipsisLoc, E->getNumExpansions()); 7260 } 7261 7262 ExpectedStmt ASTNodeImporter::VisitSizeOfPackExpr(SizeOfPackExpr *E) { 7263 auto Imp = importSeq( 7264 E->getOperatorLoc(), E->getPack(), E->getPackLoc(), E->getRParenLoc()); 7265 if (!Imp) 7266 return Imp.takeError(); 7267 7268 SourceLocation ToOperatorLoc, ToPackLoc, ToRParenLoc; 7269 NamedDecl *ToPack; 7270 std::tie(ToOperatorLoc, ToPack, ToPackLoc, ToRParenLoc) = *Imp; 7271 7272 Optional<unsigned> Length; 7273 if (!E->isValueDependent()) 7274 Length = E->getPackLength(); 7275 7276 SmallVector<TemplateArgument, 8> ToPartialArguments; 7277 if (E->isPartiallySubstituted()) { 7278 if (Error Err = ImportTemplateArguments( 7279 E->getPartialArguments().data(), 7280 E->getPartialArguments().size(), 7281 ToPartialArguments)) 7282 return std::move(Err); 7283 } 7284 7285 return SizeOfPackExpr::Create( 7286 Importer.getToContext(), ToOperatorLoc, ToPack, ToPackLoc, ToRParenLoc, 7287 Length, ToPartialArguments); 7288 } 7289 7290 7291 ExpectedStmt ASTNodeImporter::VisitCXXNewExpr(CXXNewExpr *E) { 7292 auto Imp = importSeq( 7293 E->getOperatorNew(), E->getOperatorDelete(), E->getTypeIdParens(), 7294 E->getArraySize(), E->getInitializer(), E->getType(), 7295 E->getAllocatedTypeSourceInfo(), E->getSourceRange(), 7296 E->getDirectInitRange()); 7297 if (!Imp) 7298 return Imp.takeError(); 7299 7300 FunctionDecl *ToOperatorNew, *ToOperatorDelete; 7301 SourceRange ToTypeIdParens, ToSourceRange, ToDirectInitRange; 7302 Optional<Expr *> ToArraySize; 7303 Expr *ToInitializer; 7304 QualType ToType; 7305 TypeSourceInfo *ToAllocatedTypeSourceInfo; 7306 std::tie( 7307 ToOperatorNew, ToOperatorDelete, ToTypeIdParens, ToArraySize, ToInitializer, 7308 ToType, ToAllocatedTypeSourceInfo, ToSourceRange, ToDirectInitRange) = *Imp; 7309 7310 SmallVector<Expr *, 4> ToPlacementArgs(E->getNumPlacementArgs()); 7311 if (Error Err = 7312 ImportContainerChecked(E->placement_arguments(), ToPlacementArgs)) 7313 return std::move(Err); 7314 7315 return CXXNewExpr::Create( 7316 Importer.getToContext(), E->isGlobalNew(), ToOperatorNew, 7317 ToOperatorDelete, E->passAlignment(), E->doesUsualArrayDeleteWantSize(), 7318 ToPlacementArgs, ToTypeIdParens, ToArraySize, E->getInitializationStyle(), 7319 ToInitializer, ToType, ToAllocatedTypeSourceInfo, ToSourceRange, 7320 ToDirectInitRange); 7321 } 7322 7323 ExpectedStmt ASTNodeImporter::VisitCXXDeleteExpr(CXXDeleteExpr *E) { 7324 auto Imp = importSeq( 7325 E->getType(), E->getOperatorDelete(), E->getArgument(), E->getBeginLoc()); 7326 if (!Imp) 7327 return Imp.takeError(); 7328 7329 QualType ToType; 7330 FunctionDecl *ToOperatorDelete; 7331 Expr *ToArgument; 7332 SourceLocation ToBeginLoc; 7333 std::tie(ToType, ToOperatorDelete, ToArgument, ToBeginLoc) = *Imp; 7334 7335 return new (Importer.getToContext()) CXXDeleteExpr( 7336 ToType, E->isGlobalDelete(), E->isArrayForm(), E->isArrayFormAsWritten(), 7337 E->doesUsualArrayDeleteWantSize(), ToOperatorDelete, ToArgument, 7338 ToBeginLoc); 7339 } 7340 7341 ExpectedStmt ASTNodeImporter::VisitCXXConstructExpr(CXXConstructExpr *E) { 7342 auto Imp = importSeq( 7343 E->getType(), E->getLocation(), E->getConstructor(), 7344 E->getParenOrBraceRange()); 7345 if (!Imp) 7346 return Imp.takeError(); 7347 7348 QualType ToType; 7349 SourceLocation ToLocation; 7350 CXXConstructorDecl *ToConstructor; 7351 SourceRange ToParenOrBraceRange; 7352 std::tie(ToType, ToLocation, ToConstructor, ToParenOrBraceRange) = *Imp; 7353 7354 SmallVector<Expr *, 6> ToArgs(E->getNumArgs()); 7355 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs)) 7356 return std::move(Err); 7357 7358 return CXXConstructExpr::Create( 7359 Importer.getToContext(), ToType, ToLocation, ToConstructor, 7360 E->isElidable(), ToArgs, E->hadMultipleCandidates(), 7361 E->isListInitialization(), E->isStdInitListInitialization(), 7362 E->requiresZeroInitialization(), E->getConstructionKind(), 7363 ToParenOrBraceRange); 7364 } 7365 7366 ExpectedStmt ASTNodeImporter::VisitExprWithCleanups(ExprWithCleanups *E) { 7367 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr()); 7368 if (!ToSubExprOrErr) 7369 return ToSubExprOrErr.takeError(); 7370 7371 SmallVector<ExprWithCleanups::CleanupObject, 8> ToObjects(E->getNumObjects()); 7372 if (Error Err = ImportContainerChecked(E->getObjects(), ToObjects)) 7373 return std::move(Err); 7374 7375 return ExprWithCleanups::Create( 7376 Importer.getToContext(), *ToSubExprOrErr, E->cleanupsHaveSideEffects(), 7377 ToObjects); 7378 } 7379 7380 ExpectedStmt ASTNodeImporter::VisitCXXMemberCallExpr(CXXMemberCallExpr *E) { 7381 auto Imp = importSeq( 7382 E->getCallee(), E->getType(), E->getRParenLoc()); 7383 if (!Imp) 7384 return Imp.takeError(); 7385 7386 Expr *ToCallee; 7387 QualType ToType; 7388 SourceLocation ToRParenLoc; 7389 std::tie(ToCallee, ToType, ToRParenLoc) = *Imp; 7390 7391 SmallVector<Expr *, 4> ToArgs(E->getNumArgs()); 7392 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs)) 7393 return std::move(Err); 7394 7395 return CXXMemberCallExpr::Create(Importer.getToContext(), ToCallee, ToArgs, 7396 ToType, E->getValueKind(), ToRParenLoc); 7397 } 7398 7399 ExpectedStmt ASTNodeImporter::VisitCXXThisExpr(CXXThisExpr *E) { 7400 ExpectedType ToTypeOrErr = import(E->getType()); 7401 if (!ToTypeOrErr) 7402 return ToTypeOrErr.takeError(); 7403 7404 ExpectedSLoc ToLocationOrErr = import(E->getLocation()); 7405 if (!ToLocationOrErr) 7406 return ToLocationOrErr.takeError(); 7407 7408 return new (Importer.getToContext()) CXXThisExpr( 7409 *ToLocationOrErr, *ToTypeOrErr, E->isImplicit()); 7410 } 7411 7412 ExpectedStmt ASTNodeImporter::VisitCXXBoolLiteralExpr(CXXBoolLiteralExpr *E) { 7413 ExpectedType ToTypeOrErr = import(E->getType()); 7414 if (!ToTypeOrErr) 7415 return ToTypeOrErr.takeError(); 7416 7417 ExpectedSLoc ToLocationOrErr = import(E->getLocation()); 7418 if (!ToLocationOrErr) 7419 return ToLocationOrErr.takeError(); 7420 7421 return new (Importer.getToContext()) CXXBoolLiteralExpr( 7422 E->getValue(), *ToTypeOrErr, *ToLocationOrErr); 7423 } 7424 7425 ExpectedStmt ASTNodeImporter::VisitMemberExpr(MemberExpr *E) { 7426 auto Imp1 = importSeq( 7427 E->getBase(), E->getOperatorLoc(), E->getQualifierLoc(), 7428 E->getTemplateKeywordLoc(), E->getMemberDecl(), E->getType()); 7429 if (!Imp1) 7430 return Imp1.takeError(); 7431 7432 Expr *ToBase; 7433 SourceLocation ToOperatorLoc, ToTemplateKeywordLoc; 7434 NestedNameSpecifierLoc ToQualifierLoc; 7435 ValueDecl *ToMemberDecl; 7436 QualType ToType; 7437 std::tie( 7438 ToBase, ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc, ToMemberDecl, 7439 ToType) = *Imp1; 7440 7441 auto Imp2 = importSeq( 7442 E->getFoundDecl().getDecl(), E->getMemberNameInfo().getName(), 7443 E->getMemberNameInfo().getLoc(), E->getLAngleLoc(), E->getRAngleLoc()); 7444 if (!Imp2) 7445 return Imp2.takeError(); 7446 NamedDecl *ToDecl; 7447 DeclarationName ToName; 7448 SourceLocation ToLoc, ToLAngleLoc, ToRAngleLoc; 7449 std::tie(ToDecl, ToName, ToLoc, ToLAngleLoc, ToRAngleLoc) = *Imp2; 7450 7451 DeclAccessPair ToFoundDecl = 7452 DeclAccessPair::make(ToDecl, E->getFoundDecl().getAccess()); 7453 7454 DeclarationNameInfo ToMemberNameInfo(ToName, ToLoc); 7455 7456 TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr; 7457 if (E->hasExplicitTemplateArgs()) { 7458 if (Error Err = 7459 ImportTemplateArgumentListInfo(E->getLAngleLoc(), E->getRAngleLoc(), 7460 E->template_arguments(), ToTAInfo)) 7461 return std::move(Err); 7462 ResInfo = &ToTAInfo; 7463 } 7464 7465 return MemberExpr::Create(Importer.getToContext(), ToBase, E->isArrow(), 7466 ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc, 7467 ToMemberDecl, ToFoundDecl, ToMemberNameInfo, 7468 ResInfo, ToType, E->getValueKind(), 7469 E->getObjectKind(), E->isNonOdrUse()); 7470 } 7471 7472 ExpectedStmt 7473 ASTNodeImporter::VisitCXXPseudoDestructorExpr(CXXPseudoDestructorExpr *E) { 7474 auto Imp = importSeq( 7475 E->getBase(), E->getOperatorLoc(), E->getQualifierLoc(), 7476 E->getScopeTypeInfo(), E->getColonColonLoc(), E->getTildeLoc()); 7477 if (!Imp) 7478 return Imp.takeError(); 7479 7480 Expr *ToBase; 7481 SourceLocation ToOperatorLoc, ToColonColonLoc, ToTildeLoc; 7482 NestedNameSpecifierLoc ToQualifierLoc; 7483 TypeSourceInfo *ToScopeTypeInfo; 7484 std::tie( 7485 ToBase, ToOperatorLoc, ToQualifierLoc, ToScopeTypeInfo, ToColonColonLoc, 7486 ToTildeLoc) = *Imp; 7487 7488 PseudoDestructorTypeStorage Storage; 7489 if (IdentifierInfo *FromII = E->getDestroyedTypeIdentifier()) { 7490 IdentifierInfo *ToII = Importer.Import(FromII); 7491 ExpectedSLoc ToDestroyedTypeLocOrErr = import(E->getDestroyedTypeLoc()); 7492 if (!ToDestroyedTypeLocOrErr) 7493 return ToDestroyedTypeLocOrErr.takeError(); 7494 Storage = PseudoDestructorTypeStorage(ToII, *ToDestroyedTypeLocOrErr); 7495 } else { 7496 if (auto ToTIOrErr = import(E->getDestroyedTypeInfo())) 7497 Storage = PseudoDestructorTypeStorage(*ToTIOrErr); 7498 else 7499 return ToTIOrErr.takeError(); 7500 } 7501 7502 return new (Importer.getToContext()) CXXPseudoDestructorExpr( 7503 Importer.getToContext(), ToBase, E->isArrow(), ToOperatorLoc, 7504 ToQualifierLoc, ToScopeTypeInfo, ToColonColonLoc, ToTildeLoc, Storage); 7505 } 7506 7507 ExpectedStmt ASTNodeImporter::VisitCXXDependentScopeMemberExpr( 7508 CXXDependentScopeMemberExpr *E) { 7509 auto Imp = importSeq( 7510 E->getType(), E->getOperatorLoc(), E->getQualifierLoc(), 7511 E->getTemplateKeywordLoc(), E->getFirstQualifierFoundInScope()); 7512 if (!Imp) 7513 return Imp.takeError(); 7514 7515 QualType ToType; 7516 SourceLocation ToOperatorLoc, ToTemplateKeywordLoc; 7517 NestedNameSpecifierLoc ToQualifierLoc; 7518 NamedDecl *ToFirstQualifierFoundInScope; 7519 std::tie( 7520 ToType, ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc, 7521 ToFirstQualifierFoundInScope) = *Imp; 7522 7523 Expr *ToBase = nullptr; 7524 if (!E->isImplicitAccess()) { 7525 if (ExpectedExpr ToBaseOrErr = import(E->getBase())) 7526 ToBase = *ToBaseOrErr; 7527 else 7528 return ToBaseOrErr.takeError(); 7529 } 7530 7531 TemplateArgumentListInfo ToTAInfo, *ResInfo = nullptr; 7532 if (E->hasExplicitTemplateArgs()) { 7533 if (Error Err = ImportTemplateArgumentListInfo( 7534 E->getLAngleLoc(), E->getRAngleLoc(), E->template_arguments(), 7535 ToTAInfo)) 7536 return std::move(Err); 7537 ResInfo = &ToTAInfo; 7538 } 7539 7540 auto ToMemberNameInfoOrErr = importSeq(E->getMember(), E->getMemberLoc()); 7541 if (!ToMemberNameInfoOrErr) 7542 return ToMemberNameInfoOrErr.takeError(); 7543 DeclarationNameInfo ToMemberNameInfo( 7544 std::get<0>(*ToMemberNameInfoOrErr), std::get<1>(*ToMemberNameInfoOrErr)); 7545 // Import additional name location/type info. 7546 if (Error Err = ImportDeclarationNameLoc( 7547 E->getMemberNameInfo(), ToMemberNameInfo)) 7548 return std::move(Err); 7549 7550 return CXXDependentScopeMemberExpr::Create( 7551 Importer.getToContext(), ToBase, ToType, E->isArrow(), ToOperatorLoc, 7552 ToQualifierLoc, ToTemplateKeywordLoc, ToFirstQualifierFoundInScope, 7553 ToMemberNameInfo, ResInfo); 7554 } 7555 7556 ExpectedStmt 7557 ASTNodeImporter::VisitDependentScopeDeclRefExpr(DependentScopeDeclRefExpr *E) { 7558 auto Imp = importSeq(E->getQualifierLoc(), E->getTemplateKeywordLoc(), 7559 E->getDeclName(), E->getNameInfo().getLoc(), 7560 E->getLAngleLoc(), E->getRAngleLoc()); 7561 if (!Imp) 7562 return Imp.takeError(); 7563 7564 NestedNameSpecifierLoc ToQualifierLoc; 7565 SourceLocation ToTemplateKeywordLoc, ToNameLoc, ToLAngleLoc, ToRAngleLoc; 7566 DeclarationName ToDeclName; 7567 std::tie(ToQualifierLoc, ToTemplateKeywordLoc, ToDeclName, ToNameLoc, 7568 ToLAngleLoc, ToRAngleLoc) = *Imp; 7569 7570 DeclarationNameInfo ToNameInfo(ToDeclName, ToNameLoc); 7571 if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo)) 7572 return std::move(Err); 7573 7574 TemplateArgumentListInfo ToTAInfo(ToLAngleLoc, ToRAngleLoc); 7575 TemplateArgumentListInfo *ResInfo = nullptr; 7576 if (E->hasExplicitTemplateArgs()) { 7577 if (Error Err = 7578 ImportTemplateArgumentListInfo(E->template_arguments(), ToTAInfo)) 7579 return std::move(Err); 7580 ResInfo = &ToTAInfo; 7581 } 7582 7583 return DependentScopeDeclRefExpr::Create( 7584 Importer.getToContext(), ToQualifierLoc, ToTemplateKeywordLoc, 7585 ToNameInfo, ResInfo); 7586 } 7587 7588 ExpectedStmt ASTNodeImporter::VisitCXXUnresolvedConstructExpr( 7589 CXXUnresolvedConstructExpr *E) { 7590 auto Imp = importSeq( 7591 E->getLParenLoc(), E->getRParenLoc(), E->getTypeSourceInfo()); 7592 if (!Imp) 7593 return Imp.takeError(); 7594 7595 SourceLocation ToLParenLoc, ToRParenLoc; 7596 TypeSourceInfo *ToTypeSourceInfo; 7597 std::tie(ToLParenLoc, ToRParenLoc, ToTypeSourceInfo) = *Imp; 7598 7599 SmallVector<Expr *, 8> ToArgs(E->arg_size()); 7600 if (Error Err = 7601 ImportArrayChecked(E->arg_begin(), E->arg_end(), ToArgs.begin())) 7602 return std::move(Err); 7603 7604 return CXXUnresolvedConstructExpr::Create( 7605 Importer.getToContext(), ToTypeSourceInfo, ToLParenLoc, 7606 llvm::makeArrayRef(ToArgs), ToRParenLoc); 7607 } 7608 7609 ExpectedStmt 7610 ASTNodeImporter::VisitUnresolvedLookupExpr(UnresolvedLookupExpr *E) { 7611 Expected<CXXRecordDecl *> ToNamingClassOrErr = import(E->getNamingClass()); 7612 if (!ToNamingClassOrErr) 7613 return ToNamingClassOrErr.takeError(); 7614 7615 auto ToQualifierLocOrErr = import(E->getQualifierLoc()); 7616 if (!ToQualifierLocOrErr) 7617 return ToQualifierLocOrErr.takeError(); 7618 7619 auto ToNameInfoOrErr = importSeq(E->getName(), E->getNameLoc()); 7620 if (!ToNameInfoOrErr) 7621 return ToNameInfoOrErr.takeError(); 7622 DeclarationNameInfo ToNameInfo( 7623 std::get<0>(*ToNameInfoOrErr), std::get<1>(*ToNameInfoOrErr)); 7624 // Import additional name location/type info. 7625 if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo)) 7626 return std::move(Err); 7627 7628 UnresolvedSet<8> ToDecls; 7629 for (auto *D : E->decls()) 7630 if (auto ToDOrErr = import(D)) 7631 ToDecls.addDecl(cast<NamedDecl>(*ToDOrErr)); 7632 else 7633 return ToDOrErr.takeError(); 7634 7635 if (E->hasExplicitTemplateArgs()) { 7636 TemplateArgumentListInfo ToTAInfo; 7637 if (Error Err = ImportTemplateArgumentListInfo( 7638 E->getLAngleLoc(), E->getRAngleLoc(), E->template_arguments(), 7639 ToTAInfo)) 7640 return std::move(Err); 7641 7642 ExpectedSLoc ToTemplateKeywordLocOrErr = import(E->getTemplateKeywordLoc()); 7643 if (!ToTemplateKeywordLocOrErr) 7644 return ToTemplateKeywordLocOrErr.takeError(); 7645 7646 return UnresolvedLookupExpr::Create( 7647 Importer.getToContext(), *ToNamingClassOrErr, *ToQualifierLocOrErr, 7648 *ToTemplateKeywordLocOrErr, ToNameInfo, E->requiresADL(), &ToTAInfo, 7649 ToDecls.begin(), ToDecls.end()); 7650 } 7651 7652 return UnresolvedLookupExpr::Create( 7653 Importer.getToContext(), *ToNamingClassOrErr, *ToQualifierLocOrErr, 7654 ToNameInfo, E->requiresADL(), E->isOverloaded(), ToDecls.begin(), 7655 ToDecls.end()); 7656 } 7657 7658 ExpectedStmt 7659 ASTNodeImporter::VisitUnresolvedMemberExpr(UnresolvedMemberExpr *E) { 7660 auto Imp1 = importSeq( 7661 E->getType(), E->getOperatorLoc(), E->getQualifierLoc(), 7662 E->getTemplateKeywordLoc()); 7663 if (!Imp1) 7664 return Imp1.takeError(); 7665 7666 QualType ToType; 7667 SourceLocation ToOperatorLoc, ToTemplateKeywordLoc; 7668 NestedNameSpecifierLoc ToQualifierLoc; 7669 std::tie(ToType, ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc) = *Imp1; 7670 7671 auto Imp2 = importSeq(E->getName(), E->getNameLoc()); 7672 if (!Imp2) 7673 return Imp2.takeError(); 7674 DeclarationNameInfo ToNameInfo(std::get<0>(*Imp2), std::get<1>(*Imp2)); 7675 // Import additional name location/type info. 7676 if (Error Err = ImportDeclarationNameLoc(E->getNameInfo(), ToNameInfo)) 7677 return std::move(Err); 7678 7679 UnresolvedSet<8> ToDecls; 7680 for (Decl *D : E->decls()) 7681 if (auto ToDOrErr = import(D)) 7682 ToDecls.addDecl(cast<NamedDecl>(*ToDOrErr)); 7683 else 7684 return ToDOrErr.takeError(); 7685 7686 TemplateArgumentListInfo ToTAInfo; 7687 TemplateArgumentListInfo *ResInfo = nullptr; 7688 if (E->hasExplicitTemplateArgs()) { 7689 TemplateArgumentListInfo FromTAInfo; 7690 E->copyTemplateArgumentsInto(FromTAInfo); 7691 if (Error Err = ImportTemplateArgumentListInfo(FromTAInfo, ToTAInfo)) 7692 return std::move(Err); 7693 ResInfo = &ToTAInfo; 7694 } 7695 7696 Expr *ToBase = nullptr; 7697 if (!E->isImplicitAccess()) { 7698 if (ExpectedExpr ToBaseOrErr = import(E->getBase())) 7699 ToBase = *ToBaseOrErr; 7700 else 7701 return ToBaseOrErr.takeError(); 7702 } 7703 7704 return UnresolvedMemberExpr::Create( 7705 Importer.getToContext(), E->hasUnresolvedUsing(), ToBase, ToType, 7706 E->isArrow(), ToOperatorLoc, ToQualifierLoc, ToTemplateKeywordLoc, 7707 ToNameInfo, ResInfo, ToDecls.begin(), ToDecls.end()); 7708 } 7709 7710 ExpectedStmt ASTNodeImporter::VisitCallExpr(CallExpr *E) { 7711 auto Imp = importSeq(E->getCallee(), E->getType(), E->getRParenLoc()); 7712 if (!Imp) 7713 return Imp.takeError(); 7714 7715 Expr *ToCallee; 7716 QualType ToType; 7717 SourceLocation ToRParenLoc; 7718 std::tie(ToCallee, ToType, ToRParenLoc) = *Imp; 7719 7720 unsigned NumArgs = E->getNumArgs(); 7721 llvm::SmallVector<Expr *, 2> ToArgs(NumArgs); 7722 if (Error Err = ImportContainerChecked(E->arguments(), ToArgs)) 7723 return std::move(Err); 7724 7725 if (const auto *OCE = dyn_cast<CXXOperatorCallExpr>(E)) { 7726 return CXXOperatorCallExpr::Create( 7727 Importer.getToContext(), OCE->getOperator(), ToCallee, ToArgs, ToType, 7728 OCE->getValueKind(), ToRParenLoc, OCE->getFPFeatures(), 7729 OCE->getADLCallKind()); 7730 } 7731 7732 return CallExpr::Create(Importer.getToContext(), ToCallee, ToArgs, ToType, 7733 E->getValueKind(), ToRParenLoc, /*MinNumArgs=*/0, 7734 E->getADLCallKind()); 7735 } 7736 7737 ExpectedStmt ASTNodeImporter::VisitLambdaExpr(LambdaExpr *E) { 7738 CXXRecordDecl *FromClass = E->getLambdaClass(); 7739 auto ToClassOrErr = import(FromClass); 7740 if (!ToClassOrErr) 7741 return ToClassOrErr.takeError(); 7742 CXXRecordDecl *ToClass = *ToClassOrErr; 7743 7744 auto ToCallOpOrErr = import(E->getCallOperator()); 7745 if (!ToCallOpOrErr) 7746 return ToCallOpOrErr.takeError(); 7747 7748 SmallVector<LambdaCapture, 8> ToCaptures; 7749 ToCaptures.reserve(E->capture_size()); 7750 for (const auto &FromCapture : E->captures()) { 7751 if (auto ToCaptureOrErr = import(FromCapture)) 7752 ToCaptures.push_back(*ToCaptureOrErr); 7753 else 7754 return ToCaptureOrErr.takeError(); 7755 } 7756 7757 SmallVector<Expr *, 8> ToCaptureInits(E->capture_size()); 7758 if (Error Err = ImportContainerChecked(E->capture_inits(), ToCaptureInits)) 7759 return std::move(Err); 7760 7761 auto Imp = importSeq( 7762 E->getIntroducerRange(), E->getCaptureDefaultLoc(), E->getEndLoc()); 7763 if (!Imp) 7764 return Imp.takeError(); 7765 7766 SourceRange ToIntroducerRange; 7767 SourceLocation ToCaptureDefaultLoc, ToEndLoc; 7768 std::tie(ToIntroducerRange, ToCaptureDefaultLoc, ToEndLoc) = *Imp; 7769 7770 return LambdaExpr::Create( 7771 Importer.getToContext(), ToClass, ToIntroducerRange, 7772 E->getCaptureDefault(), ToCaptureDefaultLoc, ToCaptures, 7773 E->hasExplicitParameters(), E->hasExplicitResultType(), ToCaptureInits, 7774 ToEndLoc, E->containsUnexpandedParameterPack()); 7775 } 7776 7777 7778 ExpectedStmt ASTNodeImporter::VisitInitListExpr(InitListExpr *E) { 7779 auto Imp = importSeq(E->getLBraceLoc(), E->getRBraceLoc(), E->getType()); 7780 if (!Imp) 7781 return Imp.takeError(); 7782 7783 SourceLocation ToLBraceLoc, ToRBraceLoc; 7784 QualType ToType; 7785 std::tie(ToLBraceLoc, ToRBraceLoc, ToType) = *Imp; 7786 7787 SmallVector<Expr *, 4> ToExprs(E->getNumInits()); 7788 if (Error Err = ImportContainerChecked(E->inits(), ToExprs)) 7789 return std::move(Err); 7790 7791 ASTContext &ToCtx = Importer.getToContext(); 7792 InitListExpr *To = new (ToCtx) InitListExpr( 7793 ToCtx, ToLBraceLoc, ToExprs, ToRBraceLoc); 7794 To->setType(ToType); 7795 7796 if (E->hasArrayFiller()) { 7797 if (ExpectedExpr ToFillerOrErr = import(E->getArrayFiller())) 7798 To->setArrayFiller(*ToFillerOrErr); 7799 else 7800 return ToFillerOrErr.takeError(); 7801 } 7802 7803 if (FieldDecl *FromFD = E->getInitializedFieldInUnion()) { 7804 if (auto ToFDOrErr = import(FromFD)) 7805 To->setInitializedFieldInUnion(*ToFDOrErr); 7806 else 7807 return ToFDOrErr.takeError(); 7808 } 7809 7810 if (InitListExpr *SyntForm = E->getSyntacticForm()) { 7811 if (auto ToSyntFormOrErr = import(SyntForm)) 7812 To->setSyntacticForm(*ToSyntFormOrErr); 7813 else 7814 return ToSyntFormOrErr.takeError(); 7815 } 7816 7817 // Copy InitListExprBitfields, which are not handled in the ctor of 7818 // InitListExpr. 7819 To->sawArrayRangeDesignator(E->hadArrayRangeDesignator()); 7820 7821 return To; 7822 } 7823 7824 ExpectedStmt ASTNodeImporter::VisitCXXStdInitializerListExpr( 7825 CXXStdInitializerListExpr *E) { 7826 ExpectedType ToTypeOrErr = import(E->getType()); 7827 if (!ToTypeOrErr) 7828 return ToTypeOrErr.takeError(); 7829 7830 ExpectedExpr ToSubExprOrErr = import(E->getSubExpr()); 7831 if (!ToSubExprOrErr) 7832 return ToSubExprOrErr.takeError(); 7833 7834 return new (Importer.getToContext()) CXXStdInitializerListExpr( 7835 *ToTypeOrErr, *ToSubExprOrErr); 7836 } 7837 7838 ExpectedStmt ASTNodeImporter::VisitCXXInheritedCtorInitExpr( 7839 CXXInheritedCtorInitExpr *E) { 7840 auto Imp = importSeq(E->getLocation(), E->getType(), E->getConstructor()); 7841 if (!Imp) 7842 return Imp.takeError(); 7843 7844 SourceLocation ToLocation; 7845 QualType ToType; 7846 CXXConstructorDecl *ToConstructor; 7847 std::tie(ToLocation, ToType, ToConstructor) = *Imp; 7848 7849 return new (Importer.getToContext()) CXXInheritedCtorInitExpr( 7850 ToLocation, ToType, ToConstructor, E->constructsVBase(), 7851 E->inheritedFromVBase()); 7852 } 7853 7854 ExpectedStmt ASTNodeImporter::VisitArrayInitLoopExpr(ArrayInitLoopExpr *E) { 7855 auto Imp = importSeq(E->getType(), E->getCommonExpr(), E->getSubExpr()); 7856 if (!Imp) 7857 return Imp.takeError(); 7858 7859 QualType ToType; 7860 Expr *ToCommonExpr, *ToSubExpr; 7861 std::tie(ToType, ToCommonExpr, ToSubExpr) = *Imp; 7862 7863 return new (Importer.getToContext()) ArrayInitLoopExpr( 7864 ToType, ToCommonExpr, ToSubExpr); 7865 } 7866 7867 ExpectedStmt ASTNodeImporter::VisitArrayInitIndexExpr(ArrayInitIndexExpr *E) { 7868 ExpectedType ToTypeOrErr = import(E->getType()); 7869 if (!ToTypeOrErr) 7870 return ToTypeOrErr.takeError(); 7871 return new (Importer.getToContext()) ArrayInitIndexExpr(*ToTypeOrErr); 7872 } 7873 7874 ExpectedStmt ASTNodeImporter::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *E) { 7875 ExpectedSLoc ToBeginLocOrErr = import(E->getBeginLoc()); 7876 if (!ToBeginLocOrErr) 7877 return ToBeginLocOrErr.takeError(); 7878 7879 auto ToFieldOrErr = import(E->getField()); 7880 if (!ToFieldOrErr) 7881 return ToFieldOrErr.takeError(); 7882 7883 auto UsedContextOrErr = Importer.ImportContext(E->getUsedContext()); 7884 if (!UsedContextOrErr) 7885 return UsedContextOrErr.takeError(); 7886 7887 return CXXDefaultInitExpr::Create( 7888 Importer.getToContext(), *ToBeginLocOrErr, *ToFieldOrErr, *UsedContextOrErr); 7889 } 7890 7891 ExpectedStmt ASTNodeImporter::VisitCXXNamedCastExpr(CXXNamedCastExpr *E) { 7892 auto Imp = importSeq( 7893 E->getType(), E->getSubExpr(), E->getTypeInfoAsWritten(), 7894 E->getOperatorLoc(), E->getRParenLoc(), E->getAngleBrackets()); 7895 if (!Imp) 7896 return Imp.takeError(); 7897 7898 QualType ToType; 7899 Expr *ToSubExpr; 7900 TypeSourceInfo *ToTypeInfoAsWritten; 7901 SourceLocation ToOperatorLoc, ToRParenLoc; 7902 SourceRange ToAngleBrackets; 7903 std::tie( 7904 ToType, ToSubExpr, ToTypeInfoAsWritten, ToOperatorLoc, ToRParenLoc, 7905 ToAngleBrackets) = *Imp; 7906 7907 ExprValueKind VK = E->getValueKind(); 7908 CastKind CK = E->getCastKind(); 7909 auto ToBasePathOrErr = ImportCastPath(E); 7910 if (!ToBasePathOrErr) 7911 return ToBasePathOrErr.takeError(); 7912 7913 if (isa<CXXStaticCastExpr>(E)) { 7914 return CXXStaticCastExpr::Create( 7915 Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr), 7916 ToTypeInfoAsWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets); 7917 } else if (isa<CXXDynamicCastExpr>(E)) { 7918 return CXXDynamicCastExpr::Create( 7919 Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr), 7920 ToTypeInfoAsWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets); 7921 } else if (isa<CXXReinterpretCastExpr>(E)) { 7922 return CXXReinterpretCastExpr::Create( 7923 Importer.getToContext(), ToType, VK, CK, ToSubExpr, &(*ToBasePathOrErr), 7924 ToTypeInfoAsWritten, ToOperatorLoc, ToRParenLoc, ToAngleBrackets); 7925 } else if (isa<CXXConstCastExpr>(E)) { 7926 return CXXConstCastExpr::Create( 7927 Importer.getToContext(), ToType, VK, ToSubExpr, ToTypeInfoAsWritten, 7928 ToOperatorLoc, ToRParenLoc, ToAngleBrackets); 7929 } else { 7930 llvm_unreachable("Unknown cast type"); 7931 return make_error<ImportError>(); 7932 } 7933 } 7934 7935 ExpectedStmt ASTNodeImporter::VisitSubstNonTypeTemplateParmExpr( 7936 SubstNonTypeTemplateParmExpr *E) { 7937 auto Imp = importSeq( 7938 E->getType(), E->getExprLoc(), E->getParameter(), E->getReplacement()); 7939 if (!Imp) 7940 return Imp.takeError(); 7941 7942 QualType ToType; 7943 SourceLocation ToExprLoc; 7944 NonTypeTemplateParmDecl *ToParameter; 7945 Expr *ToReplacement; 7946 std::tie(ToType, ToExprLoc, ToParameter, ToReplacement) = *Imp; 7947 7948 return new (Importer.getToContext()) SubstNonTypeTemplateParmExpr( 7949 ToType, E->getValueKind(), ToExprLoc, ToParameter, ToReplacement); 7950 } 7951 7952 ExpectedStmt ASTNodeImporter::VisitTypeTraitExpr(TypeTraitExpr *E) { 7953 auto Imp = importSeq( 7954 E->getType(), E->getBeginLoc(), E->getEndLoc()); 7955 if (!Imp) 7956 return Imp.takeError(); 7957 7958 QualType ToType; 7959 SourceLocation ToBeginLoc, ToEndLoc; 7960 std::tie(ToType, ToBeginLoc, ToEndLoc) = *Imp; 7961 7962 SmallVector<TypeSourceInfo *, 4> ToArgs(E->getNumArgs()); 7963 if (Error Err = ImportContainerChecked(E->getArgs(), ToArgs)) 7964 return std::move(Err); 7965 7966 // According to Sema::BuildTypeTrait(), if E is value-dependent, 7967 // Value is always false. 7968 bool ToValue = (E->isValueDependent() ? false : E->getValue()); 7969 7970 return TypeTraitExpr::Create( 7971 Importer.getToContext(), ToType, ToBeginLoc, E->getTrait(), ToArgs, 7972 ToEndLoc, ToValue); 7973 } 7974 7975 ExpectedStmt ASTNodeImporter::VisitCXXTypeidExpr(CXXTypeidExpr *E) { 7976 ExpectedType ToTypeOrErr = import(E->getType()); 7977 if (!ToTypeOrErr) 7978 return ToTypeOrErr.takeError(); 7979 7980 auto ToSourceRangeOrErr = import(E->getSourceRange()); 7981 if (!ToSourceRangeOrErr) 7982 return ToSourceRangeOrErr.takeError(); 7983 7984 if (E->isTypeOperand()) { 7985 if (auto ToTSIOrErr = import(E->getTypeOperandSourceInfo())) 7986 return new (Importer.getToContext()) CXXTypeidExpr( 7987 *ToTypeOrErr, *ToTSIOrErr, *ToSourceRangeOrErr); 7988 else 7989 return ToTSIOrErr.takeError(); 7990 } 7991 7992 ExpectedExpr ToExprOperandOrErr = import(E->getExprOperand()); 7993 if (!ToExprOperandOrErr) 7994 return ToExprOperandOrErr.takeError(); 7995 7996 return new (Importer.getToContext()) CXXTypeidExpr( 7997 *ToTypeOrErr, *ToExprOperandOrErr, *ToSourceRangeOrErr); 7998 } 7999 8000 Error ASTNodeImporter::ImportOverriddenMethods(CXXMethodDecl *ToMethod, 8001 CXXMethodDecl *FromMethod) { 8002 Error ImportErrors = Error::success(); 8003 for (auto *FromOverriddenMethod : FromMethod->overridden_methods()) { 8004 if (auto ImportedOrErr = import(FromOverriddenMethod)) 8005 ToMethod->getCanonicalDecl()->addOverriddenMethod(cast<CXXMethodDecl>( 8006 (*ImportedOrErr)->getCanonicalDecl())); 8007 else 8008 ImportErrors = 8009 joinErrors(std::move(ImportErrors), ImportedOrErr.takeError()); 8010 } 8011 return ImportErrors; 8012 } 8013 8014 ASTImporter::ASTImporter(ASTContext &ToContext, FileManager &ToFileManager, 8015 ASTContext &FromContext, FileManager &FromFileManager, 8016 bool MinimalImport, 8017 std::shared_ptr<ASTImporterSharedState> SharedState) 8018 : SharedState(SharedState), ToContext(ToContext), FromContext(FromContext), 8019 ToFileManager(ToFileManager), FromFileManager(FromFileManager), 8020 Minimal(MinimalImport), ODRHandling(ODRHandlingType::Conservative) { 8021 8022 // Create a default state without the lookup table: LLDB case. 8023 if (!SharedState) { 8024 this->SharedState = std::make_shared<ASTImporterSharedState>(); 8025 } 8026 8027 ImportedDecls[FromContext.getTranslationUnitDecl()] = 8028 ToContext.getTranslationUnitDecl(); 8029 } 8030 8031 ASTImporter::~ASTImporter() = default; 8032 8033 Optional<unsigned> ASTImporter::getFieldIndex(Decl *F) { 8034 assert(F && (isa<FieldDecl>(*F) || isa<IndirectFieldDecl>(*F)) && 8035 "Try to get field index for non-field."); 8036 8037 auto *Owner = dyn_cast<RecordDecl>(F->getDeclContext()); 8038 if (!Owner) 8039 return None; 8040 8041 unsigned Index = 0; 8042 for (const auto *D : Owner->decls()) { 8043 if (D == F) 8044 return Index; 8045 8046 if (isa<FieldDecl>(*D) || isa<IndirectFieldDecl>(*D)) 8047 ++Index; 8048 } 8049 8050 llvm_unreachable("Field was not found in its parent context."); 8051 8052 return None; 8053 } 8054 8055 ASTImporter::FoundDeclsTy 8056 ASTImporter::findDeclsInToCtx(DeclContext *DC, DeclarationName Name) { 8057 // We search in the redecl context because of transparent contexts. 8058 // E.g. a simple C language enum is a transparent context: 8059 // enum E { A, B }; 8060 // Now if we had a global variable in the TU 8061 // int A; 8062 // then the enum constant 'A' and the variable 'A' violates ODR. 8063 // We can diagnose this only if we search in the redecl context. 8064 DeclContext *ReDC = DC->getRedeclContext(); 8065 if (SharedState->getLookupTable()) { 8066 ASTImporterLookupTable::LookupResult LookupResult = 8067 SharedState->getLookupTable()->lookup(ReDC, Name); 8068 return FoundDeclsTy(LookupResult.begin(), LookupResult.end()); 8069 } else { 8070 DeclContext::lookup_result NoloadLookupResult = ReDC->noload_lookup(Name); 8071 FoundDeclsTy Result(NoloadLookupResult.begin(), NoloadLookupResult.end()); 8072 // We must search by the slow case of localUncachedLookup because that is 8073 // working even if there is no LookupPtr for the DC. We could use 8074 // DC::buildLookup() to create the LookupPtr, but that would load external 8075 // decls again, we must avoid that case. 8076 // Also, even if we had the LookupPtr, we must find Decls which are not 8077 // in the LookupPtr, so we need the slow case. 8078 // These cases are handled in ASTImporterLookupTable, but we cannot use 8079 // that with LLDB since that traverses through the AST which initiates the 8080 // load of external decls again via DC::decls(). And again, we must avoid 8081 // loading external decls during the import. 8082 if (Result.empty()) 8083 ReDC->localUncachedLookup(Name, Result); 8084 return Result; 8085 } 8086 } 8087 8088 void ASTImporter::AddToLookupTable(Decl *ToD) { 8089 SharedState->addDeclToLookup(ToD); 8090 } 8091 8092 Expected<Decl *> ASTImporter::ImportImpl(Decl *FromD) { 8093 // Import the decl using ASTNodeImporter. 8094 ASTNodeImporter Importer(*this); 8095 return Importer.Visit(FromD); 8096 } 8097 8098 void ASTImporter::RegisterImportedDecl(Decl *FromD, Decl *ToD) { 8099 MapImported(FromD, ToD); 8100 } 8101 8102 Expected<QualType> ASTImporter::Import(QualType FromT) { 8103 if (FromT.isNull()) 8104 return QualType{}; 8105 8106 const Type *FromTy = FromT.getTypePtr(); 8107 8108 // Check whether we've already imported this type. 8109 llvm::DenseMap<const Type *, const Type *>::iterator Pos 8110 = ImportedTypes.find(FromTy); 8111 if (Pos != ImportedTypes.end()) 8112 return ToContext.getQualifiedType(Pos->second, FromT.getLocalQualifiers()); 8113 8114 // Import the type 8115 ASTNodeImporter Importer(*this); 8116 ExpectedType ToTOrErr = Importer.Visit(FromTy); 8117 if (!ToTOrErr) 8118 return ToTOrErr.takeError(); 8119 8120 // Record the imported type. 8121 ImportedTypes[FromTy] = (*ToTOrErr).getTypePtr(); 8122 8123 return ToContext.getQualifiedType(*ToTOrErr, FromT.getLocalQualifiers()); 8124 } 8125 8126 Expected<TypeSourceInfo *> ASTImporter::Import(TypeSourceInfo *FromTSI) { 8127 if (!FromTSI) 8128 return FromTSI; 8129 8130 // FIXME: For now we just create a "trivial" type source info based 8131 // on the type and a single location. Implement a real version of this. 8132 ExpectedType TOrErr = Import(FromTSI->getType()); 8133 if (!TOrErr) 8134 return TOrErr.takeError(); 8135 ExpectedSLoc BeginLocOrErr = Import(FromTSI->getTypeLoc().getBeginLoc()); 8136 if (!BeginLocOrErr) 8137 return BeginLocOrErr.takeError(); 8138 8139 return ToContext.getTrivialTypeSourceInfo(*TOrErr, *BeginLocOrErr); 8140 } 8141 8142 Expected<Attr *> ASTImporter::Import(const Attr *FromAttr) { 8143 Attr *ToAttr = FromAttr->clone(ToContext); 8144 if (auto ToRangeOrErr = Import(FromAttr->getRange())) 8145 ToAttr->setRange(*ToRangeOrErr); 8146 else 8147 return ToRangeOrErr.takeError(); 8148 8149 return ToAttr; 8150 } 8151 8152 Decl *ASTImporter::GetAlreadyImportedOrNull(const Decl *FromD) const { 8153 auto Pos = ImportedDecls.find(FromD); 8154 if (Pos != ImportedDecls.end()) 8155 return Pos->second; 8156 else 8157 return nullptr; 8158 } 8159 8160 TranslationUnitDecl *ASTImporter::GetFromTU(Decl *ToD) { 8161 auto FromDPos = ImportedFromDecls.find(ToD); 8162 if (FromDPos == ImportedFromDecls.end()) 8163 return nullptr; 8164 return FromDPos->second->getTranslationUnitDecl(); 8165 } 8166 8167 Expected<Decl *> ASTImporter::Import(Decl *FromD) { 8168 if (!FromD) 8169 return nullptr; 8170 8171 // Push FromD to the stack, and remove that when we return. 8172 ImportPath.push(FromD); 8173 auto ImportPathBuilder = 8174 llvm::make_scope_exit([this]() { ImportPath.pop(); }); 8175 8176 // Check whether there was a previous failed import. 8177 // If yes return the existing error. 8178 if (auto Error = getImportDeclErrorIfAny(FromD)) 8179 return make_error<ImportError>(*Error); 8180 8181 // Check whether we've already imported this declaration. 8182 Decl *ToD = GetAlreadyImportedOrNull(FromD); 8183 if (ToD) { 8184 // Already imported (possibly from another TU) and with an error. 8185 if (auto Error = SharedState->getImportDeclErrorIfAny(ToD)) { 8186 setImportDeclError(FromD, *Error); 8187 return make_error<ImportError>(*Error); 8188 } 8189 8190 // If FromD has some updated flags after last import, apply it 8191 updateFlags(FromD, ToD); 8192 // If we encounter a cycle during an import then we save the relevant part 8193 // of the import path associated to the Decl. 8194 if (ImportPath.hasCycleAtBack()) 8195 SavedImportPaths[FromD].push_back(ImportPath.copyCycleAtBack()); 8196 return ToD; 8197 } 8198 8199 // Import the declaration. 8200 ExpectedDecl ToDOrErr = ImportImpl(FromD); 8201 if (!ToDOrErr) { 8202 // Failed to import. 8203 8204 auto Pos = ImportedDecls.find(FromD); 8205 if (Pos != ImportedDecls.end()) { 8206 // Import failed after the object was created. 8207 // Remove all references to it. 8208 auto *ToD = Pos->second; 8209 ImportedDecls.erase(Pos); 8210 8211 // ImportedDecls and ImportedFromDecls are not symmetric. It may happen 8212 // (e.g. with namespaces) that several decls from the 'from' context are 8213 // mapped to the same decl in the 'to' context. If we removed entries 8214 // from the LookupTable here then we may end up removing them multiple 8215 // times. 8216 8217 // The Lookuptable contains decls only which are in the 'to' context. 8218 // Remove from the Lookuptable only if it is *imported* into the 'to' 8219 // context (and do not remove it if it was added during the initial 8220 // traverse of the 'to' context). 8221 auto PosF = ImportedFromDecls.find(ToD); 8222 if (PosF != ImportedFromDecls.end()) { 8223 SharedState->removeDeclFromLookup(ToD); 8224 ImportedFromDecls.erase(PosF); 8225 } 8226 8227 // FIXME: AST may contain remaining references to the failed object. 8228 // However, the ImportDeclErrors in the shared state contains all the 8229 // failed objects together with their error. 8230 } 8231 8232 // Error encountered for the first time. 8233 // After takeError the error is not usable any more in ToDOrErr. 8234 // Get a copy of the error object (any more simple solution for this?). 8235 ImportError ErrOut; 8236 handleAllErrors(ToDOrErr.takeError(), 8237 [&ErrOut](const ImportError &E) { ErrOut = E; }); 8238 setImportDeclError(FromD, ErrOut); 8239 // Set the error for the mapped to Decl, which is in the "to" context. 8240 if (Pos != ImportedDecls.end()) 8241 SharedState->setImportDeclError(Pos->second, ErrOut); 8242 8243 // Set the error for all nodes which have been created before we 8244 // recognized the error. 8245 for (const auto &Path : SavedImportPaths[FromD]) 8246 for (Decl *FromDi : Path) { 8247 setImportDeclError(FromDi, ErrOut); 8248 //FIXME Should we remove these Decls from ImportedDecls? 8249 // Set the error for the mapped to Decl, which is in the "to" context. 8250 auto Ii = ImportedDecls.find(FromDi); 8251 if (Ii != ImportedDecls.end()) 8252 SharedState->setImportDeclError(Ii->second, ErrOut); 8253 // FIXME Should we remove these Decls from the LookupTable, 8254 // and from ImportedFromDecls? 8255 } 8256 SavedImportPaths[FromD].clear(); 8257 8258 // Do not return ToDOrErr, error was taken out of it. 8259 return make_error<ImportError>(ErrOut); 8260 } 8261 8262 ToD = *ToDOrErr; 8263 8264 // FIXME: Handle the "already imported with error" case. We can get here 8265 // nullptr only if GetImportedOrCreateDecl returned nullptr (after a 8266 // previously failed create was requested). 8267 // Later GetImportedOrCreateDecl can be updated to return the error. 8268 if (!ToD) { 8269 auto Err = getImportDeclErrorIfAny(FromD); 8270 assert(Err); 8271 return make_error<ImportError>(*Err); 8272 } 8273 8274 // We could import from the current TU without error. But previously we 8275 // already had imported a Decl as `ToD` from another TU (with another 8276 // ASTImporter object) and with an error. 8277 if (auto Error = SharedState->getImportDeclErrorIfAny(ToD)) { 8278 setImportDeclError(FromD, *Error); 8279 return make_error<ImportError>(*Error); 8280 } 8281 8282 // Make sure that ImportImpl registered the imported decl. 8283 assert(ImportedDecls.count(FromD) != 0 && "Missing call to MapImported?"); 8284 8285 // Notify subclasses. 8286 Imported(FromD, ToD); 8287 8288 updateFlags(FromD, ToD); 8289 SavedImportPaths[FromD].clear(); 8290 return ToDOrErr; 8291 } 8292 8293 Expected<DeclContext *> ASTImporter::ImportContext(DeclContext *FromDC) { 8294 if (!FromDC) 8295 return FromDC; 8296 8297 ExpectedDecl ToDCOrErr = Import(cast<Decl>(FromDC)); 8298 if (!ToDCOrErr) 8299 return ToDCOrErr.takeError(); 8300 auto *ToDC = cast<DeclContext>(*ToDCOrErr); 8301 8302 // When we're using a record/enum/Objective-C class/protocol as a context, we 8303 // need it to have a definition. 8304 if (auto *ToRecord = dyn_cast<RecordDecl>(ToDC)) { 8305 auto *FromRecord = cast<RecordDecl>(FromDC); 8306 if (ToRecord->isCompleteDefinition()) { 8307 // Do nothing. 8308 } else if (FromRecord->isCompleteDefinition()) { 8309 if (Error Err = ASTNodeImporter(*this).ImportDefinition( 8310 FromRecord, ToRecord, ASTNodeImporter::IDK_Basic)) 8311 return std::move(Err); 8312 } else { 8313 CompleteDecl(ToRecord); 8314 } 8315 } else if (auto *ToEnum = dyn_cast<EnumDecl>(ToDC)) { 8316 auto *FromEnum = cast<EnumDecl>(FromDC); 8317 if (ToEnum->isCompleteDefinition()) { 8318 // Do nothing. 8319 } else if (FromEnum->isCompleteDefinition()) { 8320 if (Error Err = ASTNodeImporter(*this).ImportDefinition( 8321 FromEnum, ToEnum, ASTNodeImporter::IDK_Basic)) 8322 return std::move(Err); 8323 } else { 8324 CompleteDecl(ToEnum); 8325 } 8326 } else if (auto *ToClass = dyn_cast<ObjCInterfaceDecl>(ToDC)) { 8327 auto *FromClass = cast<ObjCInterfaceDecl>(FromDC); 8328 if (ToClass->getDefinition()) { 8329 // Do nothing. 8330 } else if (ObjCInterfaceDecl *FromDef = FromClass->getDefinition()) { 8331 if (Error Err = ASTNodeImporter(*this).ImportDefinition( 8332 FromDef, ToClass, ASTNodeImporter::IDK_Basic)) 8333 return std::move(Err); 8334 } else { 8335 CompleteDecl(ToClass); 8336 } 8337 } else if (auto *ToProto = dyn_cast<ObjCProtocolDecl>(ToDC)) { 8338 auto *FromProto = cast<ObjCProtocolDecl>(FromDC); 8339 if (ToProto->getDefinition()) { 8340 // Do nothing. 8341 } else if (ObjCProtocolDecl *FromDef = FromProto->getDefinition()) { 8342 if (Error Err = ASTNodeImporter(*this).ImportDefinition( 8343 FromDef, ToProto, ASTNodeImporter::IDK_Basic)) 8344 return std::move(Err); 8345 } else { 8346 CompleteDecl(ToProto); 8347 } 8348 } 8349 8350 return ToDC; 8351 } 8352 8353 Expected<Expr *> ASTImporter::Import(Expr *FromE) { 8354 if (ExpectedStmt ToSOrErr = Import(cast_or_null<Stmt>(FromE))) 8355 return cast_or_null<Expr>(*ToSOrErr); 8356 else 8357 return ToSOrErr.takeError(); 8358 } 8359 8360 Expected<Stmt *> ASTImporter::Import(Stmt *FromS) { 8361 if (!FromS) 8362 return nullptr; 8363 8364 // Check whether we've already imported this statement. 8365 llvm::DenseMap<Stmt *, Stmt *>::iterator Pos = ImportedStmts.find(FromS); 8366 if (Pos != ImportedStmts.end()) 8367 return Pos->second; 8368 8369 // Import the statement. 8370 ASTNodeImporter Importer(*this); 8371 ExpectedStmt ToSOrErr = Importer.Visit(FromS); 8372 if (!ToSOrErr) 8373 return ToSOrErr; 8374 8375 if (auto *ToE = dyn_cast<Expr>(*ToSOrErr)) { 8376 auto *FromE = cast<Expr>(FromS); 8377 // Copy ExprBitfields, which may not be handled in Expr subclasses 8378 // constructors. 8379 ToE->setValueKind(FromE->getValueKind()); 8380 ToE->setObjectKind(FromE->getObjectKind()); 8381 ToE->setTypeDependent(FromE->isTypeDependent()); 8382 ToE->setValueDependent(FromE->isValueDependent()); 8383 ToE->setInstantiationDependent(FromE->isInstantiationDependent()); 8384 ToE->setContainsUnexpandedParameterPack( 8385 FromE->containsUnexpandedParameterPack()); 8386 } 8387 8388 // Record the imported statement object. 8389 ImportedStmts[FromS] = *ToSOrErr; 8390 return ToSOrErr; 8391 } 8392 8393 Expected<NestedNameSpecifier *> 8394 ASTImporter::Import(NestedNameSpecifier *FromNNS) { 8395 if (!FromNNS) 8396 return nullptr; 8397 8398 NestedNameSpecifier *Prefix = nullptr; 8399 if (Error Err = importInto(Prefix, FromNNS->getPrefix())) 8400 return std::move(Err); 8401 8402 switch (FromNNS->getKind()) { 8403 case NestedNameSpecifier::Identifier: 8404 assert(FromNNS->getAsIdentifier() && "NNS should contain identifier."); 8405 return NestedNameSpecifier::Create(ToContext, Prefix, 8406 Import(FromNNS->getAsIdentifier())); 8407 8408 case NestedNameSpecifier::Namespace: 8409 if (ExpectedDecl NSOrErr = Import(FromNNS->getAsNamespace())) { 8410 return NestedNameSpecifier::Create(ToContext, Prefix, 8411 cast<NamespaceDecl>(*NSOrErr)); 8412 } else 8413 return NSOrErr.takeError(); 8414 8415 case NestedNameSpecifier::NamespaceAlias: 8416 if (ExpectedDecl NSADOrErr = Import(FromNNS->getAsNamespaceAlias())) 8417 return NestedNameSpecifier::Create(ToContext, Prefix, 8418 cast<NamespaceAliasDecl>(*NSADOrErr)); 8419 else 8420 return NSADOrErr.takeError(); 8421 8422 case NestedNameSpecifier::Global: 8423 return NestedNameSpecifier::GlobalSpecifier(ToContext); 8424 8425 case NestedNameSpecifier::Super: 8426 if (ExpectedDecl RDOrErr = Import(FromNNS->getAsRecordDecl())) 8427 return NestedNameSpecifier::SuperSpecifier(ToContext, 8428 cast<CXXRecordDecl>(*RDOrErr)); 8429 else 8430 return RDOrErr.takeError(); 8431 8432 case NestedNameSpecifier::TypeSpec: 8433 case NestedNameSpecifier::TypeSpecWithTemplate: 8434 if (Expected<QualType> TyOrErr = 8435 Import(QualType(FromNNS->getAsType(), 0u))) { 8436 bool TSTemplate = 8437 FromNNS->getKind() == NestedNameSpecifier::TypeSpecWithTemplate; 8438 return NestedNameSpecifier::Create(ToContext, Prefix, TSTemplate, 8439 TyOrErr->getTypePtr()); 8440 } else { 8441 return TyOrErr.takeError(); 8442 } 8443 } 8444 8445 llvm_unreachable("Invalid nested name specifier kind"); 8446 } 8447 8448 Expected<NestedNameSpecifierLoc> 8449 ASTImporter::Import(NestedNameSpecifierLoc FromNNS) { 8450 // Copied from NestedNameSpecifier mostly. 8451 SmallVector<NestedNameSpecifierLoc , 8> NestedNames; 8452 NestedNameSpecifierLoc NNS = FromNNS; 8453 8454 // Push each of the nested-name-specifiers's onto a stack for 8455 // serialization in reverse order. 8456 while (NNS) { 8457 NestedNames.push_back(NNS); 8458 NNS = NNS.getPrefix(); 8459 } 8460 8461 NestedNameSpecifierLocBuilder Builder; 8462 8463 while (!NestedNames.empty()) { 8464 NNS = NestedNames.pop_back_val(); 8465 NestedNameSpecifier *Spec = nullptr; 8466 if (Error Err = importInto(Spec, NNS.getNestedNameSpecifier())) 8467 return std::move(Err); 8468 8469 NestedNameSpecifier::SpecifierKind Kind = Spec->getKind(); 8470 8471 SourceLocation ToLocalBeginLoc, ToLocalEndLoc; 8472 if (Kind != NestedNameSpecifier::Super) { 8473 if (Error Err = importInto(ToLocalBeginLoc, NNS.getLocalBeginLoc())) 8474 return std::move(Err); 8475 8476 if (Kind != NestedNameSpecifier::Global) 8477 if (Error Err = importInto(ToLocalEndLoc, NNS.getLocalEndLoc())) 8478 return std::move(Err); 8479 } 8480 8481 switch (Kind) { 8482 case NestedNameSpecifier::Identifier: 8483 Builder.Extend(getToContext(), Spec->getAsIdentifier(), ToLocalBeginLoc, 8484 ToLocalEndLoc); 8485 break; 8486 8487 case NestedNameSpecifier::Namespace: 8488 Builder.Extend(getToContext(), Spec->getAsNamespace(), ToLocalBeginLoc, 8489 ToLocalEndLoc); 8490 break; 8491 8492 case NestedNameSpecifier::NamespaceAlias: 8493 Builder.Extend(getToContext(), Spec->getAsNamespaceAlias(), 8494 ToLocalBeginLoc, ToLocalEndLoc); 8495 break; 8496 8497 case NestedNameSpecifier::TypeSpec: 8498 case NestedNameSpecifier::TypeSpecWithTemplate: { 8499 SourceLocation ToTLoc; 8500 if (Error Err = importInto(ToTLoc, NNS.getTypeLoc().getBeginLoc())) 8501 return std::move(Err); 8502 TypeSourceInfo *TSI = getToContext().getTrivialTypeSourceInfo( 8503 QualType(Spec->getAsType(), 0), ToTLoc); 8504 if (Kind == NestedNameSpecifier::TypeSpecWithTemplate) 8505 // ToLocalBeginLoc is here the location of the 'template' keyword. 8506 Builder.Extend(getToContext(), ToLocalBeginLoc, TSI->getTypeLoc(), 8507 ToLocalEndLoc); 8508 else 8509 // No location for 'template' keyword here. 8510 Builder.Extend(getToContext(), SourceLocation{}, TSI->getTypeLoc(), 8511 ToLocalEndLoc); 8512 break; 8513 } 8514 8515 case NestedNameSpecifier::Global: 8516 Builder.MakeGlobal(getToContext(), ToLocalBeginLoc); 8517 break; 8518 8519 case NestedNameSpecifier::Super: { 8520 auto ToSourceRangeOrErr = Import(NNS.getSourceRange()); 8521 if (!ToSourceRangeOrErr) 8522 return ToSourceRangeOrErr.takeError(); 8523 8524 Builder.MakeSuper(getToContext(), Spec->getAsRecordDecl(), 8525 ToSourceRangeOrErr->getBegin(), 8526 ToSourceRangeOrErr->getEnd()); 8527 } 8528 } 8529 } 8530 8531 return Builder.getWithLocInContext(getToContext()); 8532 } 8533 8534 Expected<TemplateName> ASTImporter::Import(TemplateName From) { 8535 switch (From.getKind()) { 8536 case TemplateName::Template: 8537 if (ExpectedDecl ToTemplateOrErr = Import(From.getAsTemplateDecl())) 8538 return TemplateName(cast<TemplateDecl>(*ToTemplateOrErr)); 8539 else 8540 return ToTemplateOrErr.takeError(); 8541 8542 case TemplateName::OverloadedTemplate: { 8543 OverloadedTemplateStorage *FromStorage = From.getAsOverloadedTemplate(); 8544 UnresolvedSet<2> ToTemplates; 8545 for (auto *I : *FromStorage) { 8546 if (auto ToOrErr = Import(I)) 8547 ToTemplates.addDecl(cast<NamedDecl>(*ToOrErr)); 8548 else 8549 return ToOrErr.takeError(); 8550 } 8551 return ToContext.getOverloadedTemplateName(ToTemplates.begin(), 8552 ToTemplates.end()); 8553 } 8554 8555 case TemplateName::AssumedTemplate: { 8556 AssumedTemplateStorage *FromStorage = From.getAsAssumedTemplateName(); 8557 auto DeclNameOrErr = Import(FromStorage->getDeclName()); 8558 if (!DeclNameOrErr) 8559 return DeclNameOrErr.takeError(); 8560 return ToContext.getAssumedTemplateName(*DeclNameOrErr); 8561 } 8562 8563 case TemplateName::QualifiedTemplate: { 8564 QualifiedTemplateName *QTN = From.getAsQualifiedTemplateName(); 8565 auto QualifierOrErr = Import(QTN->getQualifier()); 8566 if (!QualifierOrErr) 8567 return QualifierOrErr.takeError(); 8568 8569 if (ExpectedDecl ToTemplateOrErr = Import(From.getAsTemplateDecl())) 8570 return ToContext.getQualifiedTemplateName( 8571 *QualifierOrErr, QTN->hasTemplateKeyword(), 8572 cast<TemplateDecl>(*ToTemplateOrErr)); 8573 else 8574 return ToTemplateOrErr.takeError(); 8575 } 8576 8577 case TemplateName::DependentTemplate: { 8578 DependentTemplateName *DTN = From.getAsDependentTemplateName(); 8579 auto QualifierOrErr = Import(DTN->getQualifier()); 8580 if (!QualifierOrErr) 8581 return QualifierOrErr.takeError(); 8582 8583 if (DTN->isIdentifier()) { 8584 return ToContext.getDependentTemplateName(*QualifierOrErr, 8585 Import(DTN->getIdentifier())); 8586 } 8587 8588 return ToContext.getDependentTemplateName(*QualifierOrErr, 8589 DTN->getOperator()); 8590 } 8591 8592 case TemplateName::SubstTemplateTemplateParm: { 8593 SubstTemplateTemplateParmStorage *Subst = 8594 From.getAsSubstTemplateTemplateParm(); 8595 ExpectedDecl ParamOrErr = Import(Subst->getParameter()); 8596 if (!ParamOrErr) 8597 return ParamOrErr.takeError(); 8598 8599 auto ReplacementOrErr = Import(Subst->getReplacement()); 8600 if (!ReplacementOrErr) 8601 return ReplacementOrErr.takeError(); 8602 8603 return ToContext.getSubstTemplateTemplateParm( 8604 cast<TemplateTemplateParmDecl>(*ParamOrErr), *ReplacementOrErr); 8605 } 8606 8607 case TemplateName::SubstTemplateTemplateParmPack: { 8608 SubstTemplateTemplateParmPackStorage *SubstPack 8609 = From.getAsSubstTemplateTemplateParmPack(); 8610 ExpectedDecl ParamOrErr = Import(SubstPack->getParameterPack()); 8611 if (!ParamOrErr) 8612 return ParamOrErr.takeError(); 8613 8614 ASTNodeImporter Importer(*this); 8615 auto ArgPackOrErr = 8616 Importer.ImportTemplateArgument(SubstPack->getArgumentPack()); 8617 if (!ArgPackOrErr) 8618 return ArgPackOrErr.takeError(); 8619 8620 return ToContext.getSubstTemplateTemplateParmPack( 8621 cast<TemplateTemplateParmDecl>(*ParamOrErr), *ArgPackOrErr); 8622 } 8623 } 8624 8625 llvm_unreachable("Invalid template name kind"); 8626 } 8627 8628 Expected<SourceLocation> ASTImporter::Import(SourceLocation FromLoc) { 8629 if (FromLoc.isInvalid()) 8630 return SourceLocation{}; 8631 8632 SourceManager &FromSM = FromContext.getSourceManager(); 8633 bool IsBuiltin = FromSM.isWrittenInBuiltinFile(FromLoc); 8634 8635 std::pair<FileID, unsigned> Decomposed = FromSM.getDecomposedLoc(FromLoc); 8636 Expected<FileID> ToFileIDOrErr = Import(Decomposed.first, IsBuiltin); 8637 if (!ToFileIDOrErr) 8638 return ToFileIDOrErr.takeError(); 8639 SourceManager &ToSM = ToContext.getSourceManager(); 8640 return ToSM.getComposedLoc(*ToFileIDOrErr, Decomposed.second); 8641 } 8642 8643 Expected<SourceRange> ASTImporter::Import(SourceRange FromRange) { 8644 SourceLocation ToBegin, ToEnd; 8645 if (Error Err = importInto(ToBegin, FromRange.getBegin())) 8646 return std::move(Err); 8647 if (Error Err = importInto(ToEnd, FromRange.getEnd())) 8648 return std::move(Err); 8649 8650 return SourceRange(ToBegin, ToEnd); 8651 } 8652 8653 Expected<FileID> ASTImporter::Import(FileID FromID, bool IsBuiltin) { 8654 llvm::DenseMap<FileID, FileID>::iterator Pos = ImportedFileIDs.find(FromID); 8655 if (Pos != ImportedFileIDs.end()) 8656 return Pos->second; 8657 8658 SourceManager &FromSM = FromContext.getSourceManager(); 8659 SourceManager &ToSM = ToContext.getSourceManager(); 8660 const SrcMgr::SLocEntry &FromSLoc = FromSM.getSLocEntry(FromID); 8661 8662 // Map the FromID to the "to" source manager. 8663 FileID ToID; 8664 if (FromSLoc.isExpansion()) { 8665 const SrcMgr::ExpansionInfo &FromEx = FromSLoc.getExpansion(); 8666 ExpectedSLoc ToSpLoc = Import(FromEx.getSpellingLoc()); 8667 if (!ToSpLoc) 8668 return ToSpLoc.takeError(); 8669 ExpectedSLoc ToExLocS = Import(FromEx.getExpansionLocStart()); 8670 if (!ToExLocS) 8671 return ToExLocS.takeError(); 8672 unsigned TokenLen = FromSM.getFileIDSize(FromID); 8673 SourceLocation MLoc; 8674 if (FromEx.isMacroArgExpansion()) { 8675 MLoc = ToSM.createMacroArgExpansionLoc(*ToSpLoc, *ToExLocS, TokenLen); 8676 } else { 8677 if (ExpectedSLoc ToExLocE = Import(FromEx.getExpansionLocEnd())) 8678 MLoc = ToSM.createExpansionLoc(*ToSpLoc, *ToExLocS, *ToExLocE, TokenLen, 8679 FromEx.isExpansionTokenRange()); 8680 else 8681 return ToExLocE.takeError(); 8682 } 8683 ToID = ToSM.getFileID(MLoc); 8684 } else { 8685 const SrcMgr::ContentCache *Cache = FromSLoc.getFile().getContentCache(); 8686 8687 if (!IsBuiltin) { 8688 // Include location of this file. 8689 ExpectedSLoc ToIncludeLoc = Import(FromSLoc.getFile().getIncludeLoc()); 8690 if (!ToIncludeLoc) 8691 return ToIncludeLoc.takeError(); 8692 8693 if (Cache->OrigEntry && Cache->OrigEntry->getDir()) { 8694 // FIXME: We probably want to use getVirtualFile(), so we don't hit the 8695 // disk again 8696 // FIXME: We definitely want to re-use the existing MemoryBuffer, rather 8697 // than mmap the files several times. 8698 auto Entry = 8699 ToFileManager.getFile(Cache->OrigEntry->getName()); 8700 // FIXME: The filename may be a virtual name that does probably not 8701 // point to a valid file and we get no Entry here. In this case try with 8702 // the memory buffer below. 8703 if (Entry) 8704 ToID = ToSM.createFileID(*Entry, *ToIncludeLoc, 8705 FromSLoc.getFile().getFileCharacteristic()); 8706 } 8707 } 8708 8709 if (ToID.isInvalid() || IsBuiltin) { 8710 // FIXME: We want to re-use the existing MemoryBuffer! 8711 bool Invalid = true; 8712 const llvm::MemoryBuffer *FromBuf = 8713 Cache->getBuffer(FromContext.getDiagnostics(), 8714 FromSM.getFileManager(), SourceLocation{}, &Invalid); 8715 if (!FromBuf || Invalid) 8716 // FIXME: Use a new error kind? 8717 return llvm::make_error<ImportError>(ImportError::Unknown); 8718 8719 std::unique_ptr<llvm::MemoryBuffer> ToBuf = 8720 llvm::MemoryBuffer::getMemBufferCopy(FromBuf->getBuffer(), 8721 FromBuf->getBufferIdentifier()); 8722 ToID = ToSM.createFileID(std::move(ToBuf), 8723 FromSLoc.getFile().getFileCharacteristic()); 8724 } 8725 } 8726 8727 assert(ToID.isValid() && "Unexpected invalid fileID was created."); 8728 8729 ImportedFileIDs[FromID] = ToID; 8730 8731 if (FileIDImportHandler) 8732 FileIDImportHandler(ToID, FromID); 8733 8734 return ToID; 8735 } 8736 8737 Expected<CXXCtorInitializer *> ASTImporter::Import(CXXCtorInitializer *From) { 8738 ExpectedExpr ToExprOrErr = Import(From->getInit()); 8739 if (!ToExprOrErr) 8740 return ToExprOrErr.takeError(); 8741 8742 auto LParenLocOrErr = Import(From->getLParenLoc()); 8743 if (!LParenLocOrErr) 8744 return LParenLocOrErr.takeError(); 8745 8746 auto RParenLocOrErr = Import(From->getRParenLoc()); 8747 if (!RParenLocOrErr) 8748 return RParenLocOrErr.takeError(); 8749 8750 if (From->isBaseInitializer()) { 8751 auto ToTInfoOrErr = Import(From->getTypeSourceInfo()); 8752 if (!ToTInfoOrErr) 8753 return ToTInfoOrErr.takeError(); 8754 8755 SourceLocation EllipsisLoc; 8756 if (From->isPackExpansion()) 8757 if (Error Err = importInto(EllipsisLoc, From->getEllipsisLoc())) 8758 return std::move(Err); 8759 8760 return new (ToContext) CXXCtorInitializer( 8761 ToContext, *ToTInfoOrErr, From->isBaseVirtual(), *LParenLocOrErr, 8762 *ToExprOrErr, *RParenLocOrErr, EllipsisLoc); 8763 } else if (From->isMemberInitializer()) { 8764 ExpectedDecl ToFieldOrErr = Import(From->getMember()); 8765 if (!ToFieldOrErr) 8766 return ToFieldOrErr.takeError(); 8767 8768 auto MemberLocOrErr = Import(From->getMemberLocation()); 8769 if (!MemberLocOrErr) 8770 return MemberLocOrErr.takeError(); 8771 8772 return new (ToContext) CXXCtorInitializer( 8773 ToContext, cast_or_null<FieldDecl>(*ToFieldOrErr), *MemberLocOrErr, 8774 *LParenLocOrErr, *ToExprOrErr, *RParenLocOrErr); 8775 } else if (From->isIndirectMemberInitializer()) { 8776 ExpectedDecl ToIFieldOrErr = Import(From->getIndirectMember()); 8777 if (!ToIFieldOrErr) 8778 return ToIFieldOrErr.takeError(); 8779 8780 auto MemberLocOrErr = Import(From->getMemberLocation()); 8781 if (!MemberLocOrErr) 8782 return MemberLocOrErr.takeError(); 8783 8784 return new (ToContext) CXXCtorInitializer( 8785 ToContext, cast_or_null<IndirectFieldDecl>(*ToIFieldOrErr), 8786 *MemberLocOrErr, *LParenLocOrErr, *ToExprOrErr, *RParenLocOrErr); 8787 } else if (From->isDelegatingInitializer()) { 8788 auto ToTInfoOrErr = Import(From->getTypeSourceInfo()); 8789 if (!ToTInfoOrErr) 8790 return ToTInfoOrErr.takeError(); 8791 8792 return new (ToContext) 8793 CXXCtorInitializer(ToContext, *ToTInfoOrErr, *LParenLocOrErr, 8794 *ToExprOrErr, *RParenLocOrErr); 8795 } else { 8796 // FIXME: assert? 8797 return make_error<ImportError>(); 8798 } 8799 } 8800 8801 Expected<CXXBaseSpecifier *> 8802 ASTImporter::Import(const CXXBaseSpecifier *BaseSpec) { 8803 auto Pos = ImportedCXXBaseSpecifiers.find(BaseSpec); 8804 if (Pos != ImportedCXXBaseSpecifiers.end()) 8805 return Pos->second; 8806 8807 Expected<SourceRange> ToSourceRange = Import(BaseSpec->getSourceRange()); 8808 if (!ToSourceRange) 8809 return ToSourceRange.takeError(); 8810 Expected<TypeSourceInfo *> ToTSI = Import(BaseSpec->getTypeSourceInfo()); 8811 if (!ToTSI) 8812 return ToTSI.takeError(); 8813 ExpectedSLoc ToEllipsisLoc = Import(BaseSpec->getEllipsisLoc()); 8814 if (!ToEllipsisLoc) 8815 return ToEllipsisLoc.takeError(); 8816 CXXBaseSpecifier *Imported = new (ToContext) CXXBaseSpecifier( 8817 *ToSourceRange, BaseSpec->isVirtual(), BaseSpec->isBaseOfClass(), 8818 BaseSpec->getAccessSpecifierAsWritten(), *ToTSI, *ToEllipsisLoc); 8819 ImportedCXXBaseSpecifiers[BaseSpec] = Imported; 8820 return Imported; 8821 } 8822 8823 Error ASTImporter::ImportDefinition(Decl *From) { 8824 ExpectedDecl ToOrErr = Import(From); 8825 if (!ToOrErr) 8826 return ToOrErr.takeError(); 8827 Decl *To = *ToOrErr; 8828 8829 auto *FromDC = cast<DeclContext>(From); 8830 ASTNodeImporter Importer(*this); 8831 8832 if (auto *ToRecord = dyn_cast<RecordDecl>(To)) { 8833 if (!ToRecord->getDefinition()) { 8834 return Importer.ImportDefinition( 8835 cast<RecordDecl>(FromDC), ToRecord, 8836 ASTNodeImporter::IDK_Everything); 8837 } 8838 } 8839 8840 if (auto *ToEnum = dyn_cast<EnumDecl>(To)) { 8841 if (!ToEnum->getDefinition()) { 8842 return Importer.ImportDefinition( 8843 cast<EnumDecl>(FromDC), ToEnum, ASTNodeImporter::IDK_Everything); 8844 } 8845 } 8846 8847 if (auto *ToIFace = dyn_cast<ObjCInterfaceDecl>(To)) { 8848 if (!ToIFace->getDefinition()) { 8849 return Importer.ImportDefinition( 8850 cast<ObjCInterfaceDecl>(FromDC), ToIFace, 8851 ASTNodeImporter::IDK_Everything); 8852 } 8853 } 8854 8855 if (auto *ToProto = dyn_cast<ObjCProtocolDecl>(To)) { 8856 if (!ToProto->getDefinition()) { 8857 return Importer.ImportDefinition( 8858 cast<ObjCProtocolDecl>(FromDC), ToProto, 8859 ASTNodeImporter::IDK_Everything); 8860 } 8861 } 8862 8863 return Importer.ImportDeclContext(FromDC, true); 8864 } 8865 8866 Expected<DeclarationName> ASTImporter::Import(DeclarationName FromName) { 8867 if (!FromName) 8868 return DeclarationName{}; 8869 8870 switch (FromName.getNameKind()) { 8871 case DeclarationName::Identifier: 8872 return DeclarationName(Import(FromName.getAsIdentifierInfo())); 8873 8874 case DeclarationName::ObjCZeroArgSelector: 8875 case DeclarationName::ObjCOneArgSelector: 8876 case DeclarationName::ObjCMultiArgSelector: 8877 if (auto ToSelOrErr = Import(FromName.getObjCSelector())) 8878 return DeclarationName(*ToSelOrErr); 8879 else 8880 return ToSelOrErr.takeError(); 8881 8882 case DeclarationName::CXXConstructorName: { 8883 if (auto ToTyOrErr = Import(FromName.getCXXNameType())) 8884 return ToContext.DeclarationNames.getCXXConstructorName( 8885 ToContext.getCanonicalType(*ToTyOrErr)); 8886 else 8887 return ToTyOrErr.takeError(); 8888 } 8889 8890 case DeclarationName::CXXDestructorName: { 8891 if (auto ToTyOrErr = Import(FromName.getCXXNameType())) 8892 return ToContext.DeclarationNames.getCXXDestructorName( 8893 ToContext.getCanonicalType(*ToTyOrErr)); 8894 else 8895 return ToTyOrErr.takeError(); 8896 } 8897 8898 case DeclarationName::CXXDeductionGuideName: { 8899 if (auto ToTemplateOrErr = Import(FromName.getCXXDeductionGuideTemplate())) 8900 return ToContext.DeclarationNames.getCXXDeductionGuideName( 8901 cast<TemplateDecl>(*ToTemplateOrErr)); 8902 else 8903 return ToTemplateOrErr.takeError(); 8904 } 8905 8906 case DeclarationName::CXXConversionFunctionName: { 8907 if (auto ToTyOrErr = Import(FromName.getCXXNameType())) 8908 return ToContext.DeclarationNames.getCXXConversionFunctionName( 8909 ToContext.getCanonicalType(*ToTyOrErr)); 8910 else 8911 return ToTyOrErr.takeError(); 8912 } 8913 8914 case DeclarationName::CXXOperatorName: 8915 return ToContext.DeclarationNames.getCXXOperatorName( 8916 FromName.getCXXOverloadedOperator()); 8917 8918 case DeclarationName::CXXLiteralOperatorName: 8919 return ToContext.DeclarationNames.getCXXLiteralOperatorName( 8920 Import(FromName.getCXXLiteralIdentifier())); 8921 8922 case DeclarationName::CXXUsingDirective: 8923 // FIXME: STATICS! 8924 return DeclarationName::getUsingDirectiveName(); 8925 } 8926 8927 llvm_unreachable("Invalid DeclarationName Kind!"); 8928 } 8929 8930 IdentifierInfo *ASTImporter::Import(const IdentifierInfo *FromId) { 8931 if (!FromId) 8932 return nullptr; 8933 8934 IdentifierInfo *ToId = &ToContext.Idents.get(FromId->getName()); 8935 8936 if (!ToId->getBuiltinID() && FromId->getBuiltinID()) 8937 ToId->setBuiltinID(FromId->getBuiltinID()); 8938 8939 return ToId; 8940 } 8941 8942 Expected<Selector> ASTImporter::Import(Selector FromSel) { 8943 if (FromSel.isNull()) 8944 return Selector{}; 8945 8946 SmallVector<IdentifierInfo *, 4> Idents; 8947 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(0))); 8948 for (unsigned I = 1, N = FromSel.getNumArgs(); I < N; ++I) 8949 Idents.push_back(Import(FromSel.getIdentifierInfoForSlot(I))); 8950 return ToContext.Selectors.getSelector(FromSel.getNumArgs(), Idents.data()); 8951 } 8952 8953 Expected<DeclarationName> ASTImporter::HandleNameConflict(DeclarationName Name, 8954 DeclContext *DC, 8955 unsigned IDNS, 8956 NamedDecl **Decls, 8957 unsigned NumDecls) { 8958 if (ODRHandling == ODRHandlingType::Conservative) 8959 // Report error at any name conflict. 8960 return make_error<ImportError>(ImportError::NameConflict); 8961 else 8962 // Allow to create the new Decl with the same name. 8963 return Name; 8964 } 8965 8966 DiagnosticBuilder ASTImporter::ToDiag(SourceLocation Loc, unsigned DiagID) { 8967 if (LastDiagFromFrom) 8968 ToContext.getDiagnostics().notePriorDiagnosticFrom( 8969 FromContext.getDiagnostics()); 8970 LastDiagFromFrom = false; 8971 return ToContext.getDiagnostics().Report(Loc, DiagID); 8972 } 8973 8974 DiagnosticBuilder ASTImporter::FromDiag(SourceLocation Loc, unsigned DiagID) { 8975 if (!LastDiagFromFrom) 8976 FromContext.getDiagnostics().notePriorDiagnosticFrom( 8977 ToContext.getDiagnostics()); 8978 LastDiagFromFrom = true; 8979 return FromContext.getDiagnostics().Report(Loc, DiagID); 8980 } 8981 8982 void ASTImporter::CompleteDecl (Decl *D) { 8983 if (auto *ID = dyn_cast<ObjCInterfaceDecl>(D)) { 8984 if (!ID->getDefinition()) 8985 ID->startDefinition(); 8986 } 8987 else if (auto *PD = dyn_cast<ObjCProtocolDecl>(D)) { 8988 if (!PD->getDefinition()) 8989 PD->startDefinition(); 8990 } 8991 else if (auto *TD = dyn_cast<TagDecl>(D)) { 8992 if (!TD->getDefinition() && !TD->isBeingDefined()) { 8993 TD->startDefinition(); 8994 TD->setCompleteDefinition(true); 8995 } 8996 } 8997 else { 8998 assert(0 && "CompleteDecl called on a Decl that can't be completed"); 8999 } 9000 } 9001 9002 Decl *ASTImporter::MapImported(Decl *From, Decl *To) { 9003 llvm::DenseMap<Decl *, Decl *>::iterator Pos = ImportedDecls.find(From); 9004 assert((Pos == ImportedDecls.end() || Pos->second == To) && 9005 "Try to import an already imported Decl"); 9006 if (Pos != ImportedDecls.end()) 9007 return Pos->second; 9008 ImportedDecls[From] = To; 9009 // This mapping should be maintained only in this function. Therefore do not 9010 // check for additional consistency. 9011 ImportedFromDecls[To] = From; 9012 AddToLookupTable(To); 9013 return To; 9014 } 9015 9016 llvm::Optional<ImportError> 9017 ASTImporter::getImportDeclErrorIfAny(Decl *FromD) const { 9018 auto Pos = ImportDeclErrors.find(FromD); 9019 if (Pos != ImportDeclErrors.end()) 9020 return Pos->second; 9021 else 9022 return Optional<ImportError>(); 9023 } 9024 9025 void ASTImporter::setImportDeclError(Decl *From, ImportError Error) { 9026 auto InsertRes = ImportDeclErrors.insert({From, Error}); 9027 (void)InsertRes; 9028 // Either we set the error for the first time, or we already had set one and 9029 // now we want to set the same error. 9030 assert(InsertRes.second || InsertRes.first->second.Error == Error.Error); 9031 } 9032 9033 bool ASTImporter::IsStructurallyEquivalent(QualType From, QualType To, 9034 bool Complain) { 9035 llvm::DenseMap<const Type *, const Type *>::iterator Pos = 9036 ImportedTypes.find(From.getTypePtr()); 9037 if (Pos != ImportedTypes.end()) { 9038 if (ExpectedType ToFromOrErr = Import(From)) { 9039 if (ToContext.hasSameType(*ToFromOrErr, To)) 9040 return true; 9041 } else { 9042 llvm::consumeError(ToFromOrErr.takeError()); 9043 } 9044 } 9045 9046 StructuralEquivalenceContext Ctx(FromContext, ToContext, NonEquivalentDecls, 9047 getStructuralEquivalenceKind(*this), false, 9048 Complain); 9049 return Ctx.IsEquivalent(From, To); 9050 } 9051