Bug Summary

File:tools/clang/lib/AST/ASTImporter.cpp
Warning:line 1133, column 54
Called C++ object pointer is null

Annotated Source Code

/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/lib/AST/ASTImporter.cpp

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

/build/llvm-toolchain-snapshot-6.0~svn318882/include/llvm/Support/Casting.h

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

/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h

1//===- Decl.h - Classes for representing declarations -----------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the Decl subclasses.
11//
12//===----------------------------------------------------------------------===//
13
14#ifndef LLVM_CLANG_AST_DECL_H
15#define LLVM_CLANG_AST_DECL_H
16
17#include "clang/AST/APValue.h"
18#include "clang/AST/DeclBase.h"
19#include "clang/AST/DeclarationName.h"
20#include "clang/AST/ExternalASTSource.h"
21#include "clang/AST/NestedNameSpecifier.h"
22#include "clang/AST/Redeclarable.h"
23#include "clang/AST/Type.h"
24#include "clang/Basic/AddressSpaces.h"
25#include "clang/Basic/Diagnostic.h"
26#include "clang/Basic/IdentifierTable.h"
27#include "clang/Basic/LLVM.h"
28#include "clang/Basic/Linkage.h"
29#include "clang/Basic/OperatorKinds.h"
30#include "clang/Basic/PartialDiagnostic.h"
31#include "clang/Basic/PragmaKinds.h"
32#include "clang/Basic/SourceLocation.h"
33#include "clang/Basic/Specifiers.h"
34#include "clang/Basic/Visibility.h"
35#include "llvm/ADT/APSInt.h"
36#include "llvm/ADT/ArrayRef.h"
37#include "llvm/ADT/Optional.h"
38#include "llvm/ADT/PointerIntPair.h"
39#include "llvm/ADT/PointerUnion.h"
40#include "llvm/ADT/StringRef.h"
41#include "llvm/ADT/iterator_range.h"
42#include "llvm/Support/Casting.h"
43#include "llvm/Support/Compiler.h"
44#include "llvm/Support/TrailingObjects.h"
45#include <cassert>
46#include <cstddef>
47#include <cstdint>
48#include <string>
49#include <utility>
50
51namespace clang {
52
53class ASTContext;
54struct ASTTemplateArgumentListInfo;
55class Attr;
56class CompoundStmt;
57class DependentFunctionTemplateSpecializationInfo;
58class EnumDecl;
59class Expr;
60class FunctionTemplateDecl;
61class FunctionTemplateSpecializationInfo;
62class LabelStmt;
63class MemberSpecializationInfo;
64class Module;
65class NamespaceDecl;
66class ParmVarDecl;
67class RecordDecl;
68class Stmt;
69class StringLiteral;
70class TagDecl;
71class TemplateArgumentList;
72class TemplateArgumentListInfo;
73class TemplateParameterList;
74class TypeAliasTemplateDecl;
75class TypeLoc;
76class UnresolvedSetImpl;
77class VarTemplateDecl;
78
79/// \brief A container of type source information.
80///
81/// A client can read the relevant info using TypeLoc wrappers, e.g:
82/// @code
83/// TypeLoc TL = TypeSourceInfo->getTypeLoc();
84/// TL.getStartLoc().print(OS, SrcMgr);
85/// @endcode
86class TypeSourceInfo {
87 // Contains a memory block after the class, used for type source information,
88 // allocated by ASTContext.
89 friend class ASTContext;
90
91 QualType Ty;
92
93 TypeSourceInfo(QualType ty) : Ty(ty) {}
94
95public:
96 /// \brief Return the type wrapped by this type source info.
97 QualType getType() const { return Ty; }
98
99 /// \brief Return the TypeLoc wrapper for the type source info.
100 TypeLoc getTypeLoc() const; // implemented in TypeLoc.h
101
102 /// \brief Override the type stored in this TypeSourceInfo. Use with caution!
103 void overrideType(QualType T) { Ty = T; }
104};
105
106/// TranslationUnitDecl - The top declaration context.
107class TranslationUnitDecl : public Decl, public DeclContext {
108 ASTContext &Ctx;
109
110 /// The (most recently entered) anonymous namespace for this
111 /// translation unit, if one has been created.
112 NamespaceDecl *AnonymousNamespace = nullptr;
113
114 explicit TranslationUnitDecl(ASTContext &ctx);
115
116 virtual void anchor();
117
118public:
119 ASTContext &getASTContext() const { return Ctx; }
120
121 NamespaceDecl *getAnonymousNamespace() const { return AnonymousNamespace; }
122 void setAnonymousNamespace(NamespaceDecl *D) { AnonymousNamespace = D; }
123
124 static TranslationUnitDecl *Create(ASTContext &C);
125
126 // Implement isa/cast/dyncast/etc.
127 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
128 static bool classofKind(Kind K) { return K == TranslationUnit; }
129 static DeclContext *castToDeclContext(const TranslationUnitDecl *D) {
130 return static_cast<DeclContext *>(const_cast<TranslationUnitDecl*>(D));
131 }
132 static TranslationUnitDecl *castFromDeclContext(const DeclContext *DC) {
133 return static_cast<TranslationUnitDecl *>(const_cast<DeclContext*>(DC));
134 }
135};
136
137/// \brief Represents a `#pragma comment` line. Always a child of
138/// TranslationUnitDecl.
139class PragmaCommentDecl final
140 : public Decl,
141 private llvm::TrailingObjects<PragmaCommentDecl, char> {
142 friend class ASTDeclReader;
143 friend class ASTDeclWriter;
144 friend TrailingObjects;
145
146 PragmaMSCommentKind CommentKind;
147
148 PragmaCommentDecl(TranslationUnitDecl *TU, SourceLocation CommentLoc,
149 PragmaMSCommentKind CommentKind)
150 : Decl(PragmaComment, TU, CommentLoc), CommentKind(CommentKind) {}
151
152 virtual void anchor();
153
154public:
155 static PragmaCommentDecl *Create(const ASTContext &C, TranslationUnitDecl *DC,
156 SourceLocation CommentLoc,
157 PragmaMSCommentKind CommentKind,
158 StringRef Arg);
159 static PragmaCommentDecl *CreateDeserialized(ASTContext &C, unsigned ID,
160 unsigned ArgSize);
161
162 PragmaMSCommentKind getCommentKind() const { return CommentKind; }
163
164 StringRef getArg() const { return getTrailingObjects<char>(); }
165
166 // Implement isa/cast/dyncast/etc.
167 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
168 static bool classofKind(Kind K) { return K == PragmaComment; }
169};
170
171/// \brief Represents a `#pragma detect_mismatch` line. Always a child of
172/// TranslationUnitDecl.
173class PragmaDetectMismatchDecl final
174 : public Decl,
175 private llvm::TrailingObjects<PragmaDetectMismatchDecl, char> {
176 friend class ASTDeclReader;
177 friend class ASTDeclWriter;
178 friend TrailingObjects;
179
180 size_t ValueStart;
181
182 PragmaDetectMismatchDecl(TranslationUnitDecl *TU, SourceLocation Loc,
183 size_t ValueStart)
184 : Decl(PragmaDetectMismatch, TU, Loc), ValueStart(ValueStart) {}
185
186 virtual void anchor();
187
188public:
189 static PragmaDetectMismatchDecl *Create(const ASTContext &C,
190 TranslationUnitDecl *DC,
191 SourceLocation Loc, StringRef Name,
192 StringRef Value);
193 static PragmaDetectMismatchDecl *
194 CreateDeserialized(ASTContext &C, unsigned ID, unsigned NameValueSize);
195
196 StringRef getName() const { return getTrailingObjects<char>(); }
197 StringRef getValue() const { return getTrailingObjects<char>() + ValueStart; }
198
199 // Implement isa/cast/dyncast/etc.
200 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
201 static bool classofKind(Kind K) { return K == PragmaDetectMismatch; }
202};
203
204/// \brief Declaration context for names declared as extern "C" in C++. This
205/// is neither the semantic nor lexical context for such declarations, but is
206/// used to check for conflicts with other extern "C" declarations. Example:
207///
208/// \code
209/// namespace N { extern "C" void f(); } // #1
210/// void N::f() {} // #2
211/// namespace M { extern "C" void f(); } // #3
212/// \endcode
213///
214/// The semantic context of #1 is namespace N and its lexical context is the
215/// LinkageSpecDecl; the semantic context of #2 is namespace N and its lexical
216/// context is the TU. However, both declarations are also visible in the
217/// extern "C" context.
218///
219/// The declaration at #3 finds it is a redeclaration of \c N::f through
220/// lookup in the extern "C" context.
221class ExternCContextDecl : public Decl, public DeclContext {
222 explicit ExternCContextDecl(TranslationUnitDecl *TU)
223 : Decl(ExternCContext, TU, SourceLocation()),
224 DeclContext(ExternCContext) {}
225
226 virtual void anchor();
227
228public:
229 static ExternCContextDecl *Create(const ASTContext &C,
230 TranslationUnitDecl *TU);
231
232 // Implement isa/cast/dyncast/etc.
233 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
234 static bool classofKind(Kind K) { return K == ExternCContext; }
235 static DeclContext *castToDeclContext(const ExternCContextDecl *D) {
236 return static_cast<DeclContext *>(const_cast<ExternCContextDecl*>(D));
237 }
238 static ExternCContextDecl *castFromDeclContext(const DeclContext *DC) {
239 return static_cast<ExternCContextDecl *>(const_cast<DeclContext*>(DC));
240 }
241};
242
243/// NamedDecl - This represents a decl with a name. Many decls have names such
244/// as ObjCMethodDecl, but not \@class, etc.
245class NamedDecl : public Decl {
246 /// Name - The name of this declaration, which is typically a normal
247 /// identifier but may also be a special kind of name (C++
248 /// constructor, Objective-C selector, etc.)
249 DeclarationName Name;
250
251 virtual void anchor();
252
253private:
254 NamedDecl *getUnderlyingDeclImpl() LLVM_READONLY__attribute__((__pure__));
255
256protected:
257 NamedDecl(Kind DK, DeclContext *DC, SourceLocation L, DeclarationName N)
258 : Decl(DK, DC, L), Name(N) {}
259
260public:
261 /// getIdentifier - Get the identifier that names this declaration,
262 /// if there is one. This will return NULL if this declaration has
263 /// no name (e.g., for an unnamed class) or if the name is a special
264 /// name (C++ constructor, Objective-C selector, etc.).
265 IdentifierInfo *getIdentifier() const { return Name.getAsIdentifierInfo(); }
266
267 /// getName - Get the name of identifier for this declaration as a StringRef.
268 /// This requires that the declaration have a name and that it be a simple
269 /// identifier.
270 StringRef getName() const {
271 assert(Name.isIdentifier() && "Name is not a simple identifier")(static_cast <bool> (Name.isIdentifier() && "Name is not a simple identifier"
) ? void (0) : __assert_fail ("Name.isIdentifier() && \"Name is not a simple identifier\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 271, __extension__ __PRETTY_FUNCTION__))
;
272 return getIdentifier() ? getIdentifier()->getName() : "";
273 }
274
275 /// getNameAsString - Get a human-readable name for the declaration, even if
276 /// it is one of the special kinds of names (C++ constructor, Objective-C
277 /// selector, etc). Creating this name requires expensive string
278 /// manipulation, so it should be called only when performance doesn't matter.
279 /// For simple declarations, getNameAsCString() should suffice.
280 //
281 // FIXME: This function should be renamed to indicate that it is not just an
282 // alternate form of getName(), and clients should move as appropriate.
283 //
284 // FIXME: Deprecated, move clients to getName().
285 std::string getNameAsString() const { return Name.getAsString(); }
286
287 virtual void printName(raw_ostream &os) const;
288
289 /// getDeclName - Get the actual, stored name of the declaration,
290 /// which may be a special name.
291 DeclarationName getDeclName() const { return Name; }
292
293 /// \brief Set the name of this declaration.
294 void setDeclName(DeclarationName N) { Name = N; }
295
296 /// printQualifiedName - Returns human-readable qualified name for
297 /// declaration, like A::B::i, for i being member of namespace A::B.
298 /// If declaration is not member of context which can be named (record,
299 /// namespace), it will return same result as printName().
300 /// Creating this name is expensive, so it should be called only when
301 /// performance doesn't matter.
302 void printQualifiedName(raw_ostream &OS) const;
303 void printQualifiedName(raw_ostream &OS, const PrintingPolicy &Policy) const;
304
305 // FIXME: Remove string version.
306 std::string getQualifiedNameAsString() const;
307
308 /// getNameForDiagnostic - Appends a human-readable name for this
309 /// declaration into the given stream.
310 ///
311 /// This is the method invoked by Sema when displaying a NamedDecl
312 /// in a diagnostic. It does not necessarily produce the same
313 /// result as printName(); for example, class template
314 /// specializations are printed with their template arguments.
315 virtual void getNameForDiagnostic(raw_ostream &OS,
316 const PrintingPolicy &Policy,
317 bool Qualified) const;
318
319 /// \brief Determine whether this declaration, if
320 /// known to be well-formed within its context, will replace the
321 /// declaration OldD if introduced into scope. A declaration will
322 /// replace another declaration if, for example, it is a
323 /// redeclaration of the same variable or function, but not if it is
324 /// a declaration of a different kind (function vs. class) or an
325 /// overloaded function.
326 ///
327 /// \param IsKnownNewer \c true if this declaration is known to be newer
328 /// than \p OldD (for instance, if this declaration is newly-created).
329 bool declarationReplaces(NamedDecl *OldD, bool IsKnownNewer = true) const;
330
331 /// \brief Determine whether this declaration has linkage.
332 bool hasLinkage() const;
333
334 using Decl::isModulePrivate;
335 using Decl::setModulePrivate;
336
337 /// \brief Determine whether this declaration is a C++ class member.
338 bool isCXXClassMember() const {
339 const DeclContext *DC = getDeclContext();
340
341 // C++0x [class.mem]p1:
342 // The enumerators of an unscoped enumeration defined in
343 // the class are members of the class.
344 if (isa<EnumDecl>(DC))
345 DC = DC->getRedeclContext();
346
347 return DC->isRecord();
348 }
349
350 /// \brief Determine whether the given declaration is an instance member of
351 /// a C++ class.
352 bool isCXXInstanceMember() const;
353
354 /// \brief Determine what kind of linkage this entity has.
355 /// This is not the linkage as defined by the standard or the codegen notion
356 /// of linkage. It is just an implementation detail that is used to compute
357 /// those.
358 Linkage getLinkageInternal() const;
359
360 /// \brief Get the linkage from a semantic point of view. Entities in
361 /// anonymous namespaces are external (in c++98).
362 Linkage getFormalLinkage() const {
363 return clang::getFormalLinkage(getLinkageInternal());
364 }
365
366 /// \brief True if this decl has external linkage.
367 bool hasExternalFormalLinkage() const {
368 return isExternalFormalLinkage(getLinkageInternal());
369 }
370
371 bool isExternallyVisible() const {
372 return clang::isExternallyVisible(getLinkageInternal());
373 }
374
375 /// Determine whether this declaration can be redeclared in a
376 /// different translation unit.
377 bool isExternallyDeclarable() const {
378 return isExternallyVisible() && !getOwningModuleForLinkage();
379 }
380
381 /// \brief Determines the visibility of this entity.
382 Visibility getVisibility() const {
383 return getLinkageAndVisibility().getVisibility();
384 }
385
386 /// \brief Determines the linkage and visibility of this entity.
387 LinkageInfo getLinkageAndVisibility() const;
388
389 /// Kinds of explicit visibility.
390 enum ExplicitVisibilityKind {
391 /// Do an LV computation for, ultimately, a type.
392 /// Visibility may be restricted by type visibility settings and
393 /// the visibility of template arguments.
394 VisibilityForType,
395
396 /// Do an LV computation for, ultimately, a non-type declaration.
397 /// Visibility may be restricted by value visibility settings and
398 /// the visibility of template arguments.
399 VisibilityForValue
400 };
401
402 /// \brief If visibility was explicitly specified for this
403 /// declaration, return that visibility.
404 Optional<Visibility>
405 getExplicitVisibility(ExplicitVisibilityKind kind) const;
406
407 /// \brief True if the computed linkage is valid. Used for consistency
408 /// checking. Should always return true.
409 bool isLinkageValid() const;
410
411 /// \brief True if something has required us to compute the linkage
412 /// of this declaration.
413 ///
414 /// Language features which can retroactively change linkage (like a
415 /// typedef name for linkage purposes) may need to consider this,
416 /// but hopefully only in transitory ways during parsing.
417 bool hasLinkageBeenComputed() const {
418 return hasCachedLinkage();
419 }
420
421 /// \brief Looks through UsingDecls and ObjCCompatibleAliasDecls for
422 /// the underlying named decl.
423 NamedDecl *getUnderlyingDecl() {
424 // Fast-path the common case.
425 if (this->getKind() != UsingShadow &&
426 this->getKind() != ConstructorUsingShadow &&
427 this->getKind() != ObjCCompatibleAlias &&
428 this->getKind() != NamespaceAlias)
429 return this;
430
431 return getUnderlyingDeclImpl();
432 }
433 const NamedDecl *getUnderlyingDecl() const {
434 return const_cast<NamedDecl*>(this)->getUnderlyingDecl();
435 }
436
437 NamedDecl *getMostRecentDecl() {
438 return cast<NamedDecl>(static_cast<Decl *>(this)->getMostRecentDecl());
439 }
440 const NamedDecl *getMostRecentDecl() const {
441 return const_cast<NamedDecl*>(this)->getMostRecentDecl();
442 }
443
444 ObjCStringFormatFamily getObjCFStringFormattingFamily() const;
445
446 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
447 static bool classofKind(Kind K) { return K >= firstNamed && K <= lastNamed; }
448};
449
450inline raw_ostream &operator<<(raw_ostream &OS, const NamedDecl &ND) {
451 ND.printName(OS);
452 return OS;
453}
454
455/// LabelDecl - Represents the declaration of a label. Labels also have a
456/// corresponding LabelStmt, which indicates the position that the label was
457/// defined at. For normal labels, the location of the decl is the same as the
458/// location of the statement. For GNU local labels (__label__), the decl
459/// location is where the __label__ is.
460class LabelDecl : public NamedDecl {
461 LabelStmt *TheStmt;
462 StringRef MSAsmName;
463 bool MSAsmNameResolved = false;
464
465 /// LocStart - For normal labels, this is the same as the main declaration
466 /// label, i.e., the location of the identifier; for GNU local labels,
467 /// this is the location of the __label__ keyword.
468 SourceLocation LocStart;
469
470 LabelDecl(DeclContext *DC, SourceLocation IdentL, IdentifierInfo *II,
471 LabelStmt *S, SourceLocation StartL)
472 : NamedDecl(Label, DC, IdentL, II), TheStmt(S), LocStart(StartL) {}
473
474 void anchor() override;
475
476public:
477 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
478 SourceLocation IdentL, IdentifierInfo *II);
479 static LabelDecl *Create(ASTContext &C, DeclContext *DC,
480 SourceLocation IdentL, IdentifierInfo *II,
481 SourceLocation GnuLabelL);
482 static LabelDecl *CreateDeserialized(ASTContext &C, unsigned ID);
483
484 LabelStmt *getStmt() const { return TheStmt; }
485 void setStmt(LabelStmt *T) { TheStmt = T; }
486
487 bool isGnuLocal() const { return LocStart != getLocation(); }
488 void setLocStart(SourceLocation L) { LocStart = L; }
489
490 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
491 return SourceRange(LocStart, getLocation());
492 }
493
494 bool isMSAsmLabel() const { return !MSAsmName.empty(); }
495 bool isResolvedMSAsmLabel() const { return isMSAsmLabel() && MSAsmNameResolved; }
496 void setMSAsmLabel(StringRef Name);
497 StringRef getMSAsmLabel() const { return MSAsmName; }
498 void setMSAsmLabelResolved() { MSAsmNameResolved = true; }
499
500 // Implement isa/cast/dyncast/etc.
501 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
502 static bool classofKind(Kind K) { return K == Label; }
503};
504
505/// NamespaceDecl - Represent a C++ namespace.
506class NamespaceDecl : public NamedDecl, public DeclContext,
507 public Redeclarable<NamespaceDecl>
508{
509 /// LocStart - The starting location of the source range, pointing
510 /// to either the namespace or the inline keyword.
511 SourceLocation LocStart;
512
513 /// RBraceLoc - The ending location of the source range.
514 SourceLocation RBraceLoc;
515
516 /// \brief A pointer to either the anonymous namespace that lives just inside
517 /// this namespace or to the first namespace in the chain (the latter case
518 /// only when this is not the first in the chain), along with a
519 /// boolean value indicating whether this is an inline namespace.
520 llvm::PointerIntPair<NamespaceDecl *, 1, bool> AnonOrFirstNamespaceAndInline;
521
522 NamespaceDecl(ASTContext &C, DeclContext *DC, bool Inline,
523 SourceLocation StartLoc, SourceLocation IdLoc,
524 IdentifierInfo *Id, NamespaceDecl *PrevDecl);
525
526 using redeclarable_base = Redeclarable<NamespaceDecl>;
527
528 NamespaceDecl *getNextRedeclarationImpl() override;
529 NamespaceDecl *getPreviousDeclImpl() override;
530 NamespaceDecl *getMostRecentDeclImpl() override;
531
532public:
533 friend class ASTDeclReader;
534 friend class ASTDeclWriter;
535
536 static NamespaceDecl *Create(ASTContext &C, DeclContext *DC,
537 bool Inline, SourceLocation StartLoc,
538 SourceLocation IdLoc, IdentifierInfo *Id,
539 NamespaceDecl *PrevDecl);
540
541 static NamespaceDecl *CreateDeserialized(ASTContext &C, unsigned ID);
542
543 using redecl_range = redeclarable_base::redecl_range;
544 using redecl_iterator = redeclarable_base::redecl_iterator;
545
546 using redeclarable_base::redecls_begin;
547 using redeclarable_base::redecls_end;
548 using redeclarable_base::redecls;
549 using redeclarable_base::getPreviousDecl;
550 using redeclarable_base::getMostRecentDecl;
551 using redeclarable_base::isFirstDecl;
552
553 /// \brief Returns true if this is an anonymous namespace declaration.
554 ///
555 /// For example:
556 /// \code
557 /// namespace {
558 /// ...
559 /// };
560 /// \endcode
561 /// q.v. C++ [namespace.unnamed]
562 bool isAnonymousNamespace() const {
563 return !getIdentifier();
564 }
565
566 /// \brief Returns true if this is an inline namespace declaration.
567 bool isInline() const {
568 return AnonOrFirstNamespaceAndInline.getInt();
569 }
570
571 /// \brief Set whether this is an inline namespace declaration.
572 void setInline(bool Inline) {
573 AnonOrFirstNamespaceAndInline.setInt(Inline);
574 }
575
576 /// \brief Get the original (first) namespace declaration.
577 NamespaceDecl *getOriginalNamespace();
578
579 /// \brief Get the original (first) namespace declaration.
580 const NamespaceDecl *getOriginalNamespace() const;
581
582 /// \brief Return true if this declaration is an original (first) declaration
583 /// of the namespace. This is false for non-original (subsequent) namespace
584 /// declarations and anonymous namespaces.
585 bool isOriginalNamespace() const;
586
587 /// \brief Retrieve the anonymous namespace nested inside this namespace,
588 /// if any.
589 NamespaceDecl *getAnonymousNamespace() const {
590 return getOriginalNamespace()->AnonOrFirstNamespaceAndInline.getPointer();
591 }
592
593 void setAnonymousNamespace(NamespaceDecl *D) {
594 getOriginalNamespace()->AnonOrFirstNamespaceAndInline.setPointer(D);
595 }
596
597 /// Retrieves the canonical declaration of this namespace.
598 NamespaceDecl *getCanonicalDecl() override {
599 return getOriginalNamespace();
600 }
601 const NamespaceDecl *getCanonicalDecl() const {
602 return getOriginalNamespace();
603 }
604
605 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__)) {
606 return SourceRange(LocStart, RBraceLoc);
607 }
608
609 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) { return LocStart; }
610 SourceLocation getRBraceLoc() const { return RBraceLoc; }
611 void setLocStart(SourceLocation L) { LocStart = L; }
612 void setRBraceLoc(SourceLocation L) { RBraceLoc = L; }
613
614 // Implement isa/cast/dyncast/etc.
615 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
616 static bool classofKind(Kind K) { return K == Namespace; }
617 static DeclContext *castToDeclContext(const NamespaceDecl *D) {
618 return static_cast<DeclContext *>(const_cast<NamespaceDecl*>(D));
619 }
620 static NamespaceDecl *castFromDeclContext(const DeclContext *DC) {
621 return static_cast<NamespaceDecl *>(const_cast<DeclContext*>(DC));
622 }
623};
624
625/// ValueDecl - Represent the declaration of a variable (in which case it is
626/// an lvalue) a function (in which case it is a function designator) or
627/// an enum constant.
628class ValueDecl : public NamedDecl {
629 QualType DeclType;
630
631 void anchor() override;
632
633protected:
634 ValueDecl(Kind DK, DeclContext *DC, SourceLocation L,
635 DeclarationName N, QualType T)
636 : NamedDecl(DK, DC, L, N), DeclType(T) {}
637
638public:
639 QualType getType() const { return DeclType; }
640 void setType(QualType newType) { DeclType = newType; }
641
642 /// \brief Determine whether this symbol is weakly-imported,
643 /// or declared with the weak or weak-ref attr.
644 bool isWeak() const;
645
646 // Implement isa/cast/dyncast/etc.
647 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
648 static bool classofKind(Kind K) { return K >= firstValue && K <= lastValue; }
649};
650
651/// QualifierInfo - A struct with extended info about a syntactic
652/// name qualifier, to be used for the case of out-of-line declarations.
653struct QualifierInfo {
654 NestedNameSpecifierLoc QualifierLoc;
655
656 /// NumTemplParamLists - The number of "outer" template parameter lists.
657 /// The count includes all of the template parameter lists that were matched
658 /// against the template-ids occurring into the NNS and possibly (in the
659 /// case of an explicit specialization) a final "template <>".
660 unsigned NumTemplParamLists = 0;
661
662 /// TemplParamLists - A new-allocated array of size NumTemplParamLists,
663 /// containing pointers to the "outer" template parameter lists.
664 /// It includes all of the template parameter lists that were matched
665 /// against the template-ids occurring into the NNS and possibly (in the
666 /// case of an explicit specialization) a final "template <>".
667 TemplateParameterList** TemplParamLists = nullptr;
668
669 QualifierInfo() = default;
670 QualifierInfo(const QualifierInfo &) = delete;
671 QualifierInfo& operator=(const QualifierInfo &) = delete;
672
673 /// setTemplateParameterListsInfo - Sets info about "outer" template
674 /// parameter lists.
675 void setTemplateParameterListsInfo(ASTContext &Context,
676 ArrayRef<TemplateParameterList *> TPLists);
677};
678
679/// \brief Represents a ValueDecl that came out of a declarator.
680/// Contains type source information through TypeSourceInfo.
681class DeclaratorDecl : public ValueDecl {
682 // A struct representing both a TInfo and a syntactic qualifier,
683 // to be used for the (uncommon) case of out-of-line declarations.
684 struct ExtInfo : public QualifierInfo {
685 TypeSourceInfo *TInfo;
686 };
687
688 llvm::PointerUnion<TypeSourceInfo *, ExtInfo *> DeclInfo;
689
690 /// InnerLocStart - The start of the source range for this declaration,
691 /// ignoring outer template declarations.
692 SourceLocation InnerLocStart;
693
694 bool hasExtInfo() const { return DeclInfo.is<ExtInfo*>(); }
695 ExtInfo *getExtInfo() { return DeclInfo.get<ExtInfo*>(); }
696 const ExtInfo *getExtInfo() const { return DeclInfo.get<ExtInfo*>(); }
697
698protected:
699 DeclaratorDecl(Kind DK, DeclContext *DC, SourceLocation L,
700 DeclarationName N, QualType T, TypeSourceInfo *TInfo,
701 SourceLocation StartL)
702 : ValueDecl(DK, DC, L, N, T), DeclInfo(TInfo), InnerLocStart(StartL) {}
703
704public:
705 friend class ASTDeclReader;
706 friend class ASTDeclWriter;
707
708 TypeSourceInfo *getTypeSourceInfo() const {
709 return hasExtInfo()
710 ? getExtInfo()->TInfo
711 : DeclInfo.get<TypeSourceInfo*>();
712 }
713
714 void setTypeSourceInfo(TypeSourceInfo *TI) {
715 if (hasExtInfo())
716 getExtInfo()->TInfo = TI;
717 else
718 DeclInfo = TI;
719 }
720
721 /// getInnerLocStart - Return SourceLocation representing start of source
722 /// range ignoring outer template declarations.
723 SourceLocation getInnerLocStart() const { return InnerLocStart; }
724 void setInnerLocStart(SourceLocation L) { InnerLocStart = L; }
725
726 /// getOuterLocStart - Return SourceLocation representing start of source
727 /// range taking into account any outer template declarations.
728 SourceLocation getOuterLocStart() const;
729
730 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
731
732 SourceLocation getLocStart() const LLVM_READONLY__attribute__((__pure__)) {
733 return getOuterLocStart();
734 }
735
736 /// \brief Retrieve the nested-name-specifier that qualifies the name of this
737 /// declaration, if it was present in the source.
738 NestedNameSpecifier *getQualifier() const {
739 return hasExtInfo() ? getExtInfo()->QualifierLoc.getNestedNameSpecifier()
740 : nullptr;
741 }
742
743 /// \brief Retrieve the nested-name-specifier (with source-location
744 /// information) that qualifies the name of this declaration, if it was
745 /// present in the source.
746 NestedNameSpecifierLoc getQualifierLoc() const {
747 return hasExtInfo() ? getExtInfo()->QualifierLoc
748 : NestedNameSpecifierLoc();
749 }
750
751 void setQualifierInfo(NestedNameSpecifierLoc QualifierLoc);
752
753 unsigned getNumTemplateParameterLists() const {
754 return hasExtInfo() ? getExtInfo()->NumTemplParamLists : 0;
755 }
756
757 TemplateParameterList *getTemplateParameterList(unsigned index) const {
758 assert(index < getNumTemplateParameterLists())(static_cast <bool> (index < getNumTemplateParameterLists
()) ? void (0) : __assert_fail ("index < getNumTemplateParameterLists()"
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 758, __extension__ __PRETTY_FUNCTION__))
;
759 return getExtInfo()->TemplParamLists[index];
760 }
761
762 void setTemplateParameterListsInfo(ASTContext &Context,
763 ArrayRef<TemplateParameterList *> TPLists);
764
765 SourceLocation getTypeSpecStartLoc() const;
766
767 // Implement isa/cast/dyncast/etc.
768 static bool classof(const Decl *D) { return classofKind(D->getKind()); }
769 static bool classofKind(Kind K) {
770 return K >= firstDeclarator && K <= lastDeclarator;
771 }
772};
773
774/// \brief Structure used to store a statement, the constant value to
775/// which it was evaluated (if any), and whether or not the statement
776/// is an integral constant expression (if known).
777struct EvaluatedStmt {
778 /// \brief Whether this statement was already evaluated.
779 bool WasEvaluated : 1;
780
781 /// \brief Whether this statement is being evaluated.
782 bool IsEvaluating : 1;
783
784 /// \brief Whether we already checked whether this statement was an
785 /// integral constant expression.
786 bool CheckedICE : 1;
787
788 /// \brief Whether we are checking whether this statement is an
789 /// integral constant expression.
790 bool CheckingICE : 1;
791
792 /// \brief Whether this statement is an integral constant expression,
793 /// or in C++11, whether the statement is a constant expression. Only
794 /// valid if CheckedICE is true.
795 bool IsICE : 1;
796
797 Stmt *Value;
798 APValue Evaluated;
799
800 EvaluatedStmt() : WasEvaluated(false), IsEvaluating(false), CheckedICE(false),
801 CheckingICE(false), IsICE(false) {}
802
803};
804
805/// VarDecl - An instance of this class is created to represent a variable
806/// declaration or definition.
807class VarDecl : public DeclaratorDecl, public Redeclarable<VarDecl> {
808public:
809 /// \brief Initialization styles.
810 enum InitializationStyle {
811 /// C-style initialization with assignment
812 CInit,
813
814 /// Call-style initialization (C++98)
815 CallInit,
816
817 /// Direct list-initialization (C++11)
818 ListInit
819 };
820
821 /// \brief Kinds of thread-local storage.
822 enum TLSKind {
823 /// Not a TLS variable.
824 TLS_None,
825
826 /// TLS with a known-constant initializer.
827 TLS_Static,
828
829 /// TLS with a dynamic initializer.
830 TLS_Dynamic
831 };
832
833 /// getStorageClassSpecifierString - Return the string used to
834 /// specify the storage class \p SC.
835 ///
836 /// It is illegal to call this function with SC == None.
837 static const char *getStorageClassSpecifierString(StorageClass SC);
838
839protected:
840 // A pointer union of Stmt * and EvaluatedStmt *. When an EvaluatedStmt, we
841 // have allocated the auxiliary struct of information there.
842 //
843 // TODO: It is a bit unfortunate to use a PointerUnion inside the VarDecl for
844 // this as *many* VarDecls are ParmVarDecls that don't have default
845 // arguments. We could save some space by moving this pointer union to be
846 // allocated in trailing space when necessary.
847 using InitType = llvm::PointerUnion<Stmt *, EvaluatedStmt *>;
848
849 /// \brief The initializer for this variable or, for a ParmVarDecl, the
850 /// C++ default argument.
851 mutable InitType Init;
852
853private:
854 friend class ASTDeclReader;
855 friend class ASTNodeImporter;
856 friend class StmtIteratorBase;
857
858 class VarDeclBitfields {
859 friend class ASTDeclReader;
860 friend class VarDecl;
861
862 unsigned SClass : 3;
863 unsigned TSCSpec : 2;
864 unsigned InitStyle : 2;
865 };
866 enum { NumVarDeclBits = 7 };
867
868protected:
869 enum { NumParameterIndexBits = 8 };
870
871 enum DefaultArgKind {
872 DAK_None,
873 DAK_Unparsed,
874 DAK_Uninstantiated,
875 DAK_Normal
876 };
877
878 class ParmVarDeclBitfields {
879 friend class ASTDeclReader;
880 friend class ParmVarDecl;
881
882 unsigned : NumVarDeclBits;
883
884 /// Whether this parameter inherits a default argument from a
885 /// prior declaration.
886 unsigned HasInheritedDefaultArg : 1;
887
888 /// Describes the kind of default argument for this parameter. By default
889 /// this is none. If this is normal, then the default argument is stored in
890 /// the \c VarDecl initializer expression unless we were unable to parse
891 /// (even an invalid) expression for the default argument.
892 unsigned DefaultArgKind : 2;
893
894 /// Whether this parameter undergoes K&R argument promotion.
895 unsigned IsKNRPromoted : 1;
896
897 /// Whether this parameter is an ObjC method parameter or not.
898 unsigned IsObjCMethodParam : 1;
899
900 /// If IsObjCMethodParam, a Decl::ObjCDeclQualifier.
901 /// Otherwise, the number of function parameter scopes enclosing
902 /// the function parameter scope in which this parameter was
903 /// declared.
904 unsigned ScopeDepthOrObjCQuals : 7;
905
906 /// The number of parameters preceding this parameter in the
907 /// function parameter scope in which it was declared.
908 unsigned ParameterIndex : NumParameterIndexBits;
909 };
910
911 class NonParmVarDeclBitfields {
912 friend class ASTDeclReader;
913 friend class ImplicitParamDecl;
914 friend class VarDecl;
915
916 unsigned : NumVarDeclBits;
917
918 // FIXME: We need something similar to CXXRecordDecl::DefinitionData.
919 /// \brief Whether this variable is a definition which was demoted due to
920 /// module merge.
921 unsigned IsThisDeclarationADemotedDefinition : 1;
922
923 /// \brief Whether this variable is the exception variable in a C++ catch
924 /// or an Objective-C @catch statement.
925 unsigned ExceptionVar : 1;
926
927 /// \brief Whether this local variable could be allocated in the return
928 /// slot of its function, enabling the named return value optimization
929 /// (NRVO).
930 unsigned NRVOVariable : 1;
931
932 /// \brief Whether this variable is the for-range-declaration in a C++0x
933 /// for-range statement.
934 unsigned CXXForRangeDecl : 1;
935
936 /// \brief Whether this variable is an ARC pseudo-__strong
937 /// variable; see isARCPseudoStrong() for details.
938 unsigned ARCPseudoStrong : 1;
939
940 /// \brief Whether this variable is (C++1z) inline.
941 unsigned IsInline : 1;
942
943 /// \brief Whether this variable has (C++1z) inline explicitly specified.
944 unsigned IsInlineSpecified : 1;
945
946 /// \brief Whether this variable is (C++0x) constexpr.
947 unsigned IsConstexpr : 1;
948
949 /// \brief Whether this variable is the implicit variable for a lambda
950 /// init-capture.
951 unsigned IsInitCapture : 1;
952
953 /// \brief Whether this local extern variable's previous declaration was
954 /// declared in the same block scope. This controls whether we should merge
955 /// the type of this declaration with its previous declaration.
956 unsigned PreviousDeclInSameBlockScope : 1;
957
958 /// Defines kind of the ImplicitParamDecl: 'this', 'self', 'vtt', '_cmd' or
959 /// something else.
960 unsigned ImplicitParamKind : 3;
961 };
962
963 union {
964 unsigned AllBits;
965 VarDeclBitfields VarDeclBits;
966 ParmVarDeclBitfields ParmVarDeclBits;
967 NonParmVarDeclBitfields NonParmVarDeclBits;
968 };
969
970 VarDecl(Kind DK, ASTContext &C, DeclContext *DC, SourceLocation StartLoc,
971 SourceLocation IdLoc, IdentifierInfo *Id, QualType T,
972 TypeSourceInfo *TInfo, StorageClass SC);
973
974 using redeclarable_base = Redeclarable<VarDecl>;
975
976 VarDecl *getNextRedeclarationImpl() override {
977 return getNextRedeclaration();
978 }
979
980 VarDecl *getPreviousDeclImpl() override {
981 return getPreviousDecl();
982 }
983
984 VarDecl *getMostRecentDeclImpl() override {
985 return getMostRecentDecl();
986 }
987
988public:
989 using redecl_range = redeclarable_base::redecl_range;
990 using redecl_iterator = redeclarable_base::redecl_iterator;
991
992 using redeclarable_base::redecls_begin;
993 using redeclarable_base::redecls_end;
994 using redeclarable_base::redecls;
995 using redeclarable_base::getPreviousDecl;
996 using redeclarable_base::getMostRecentDecl;
997 using redeclarable_base::isFirstDecl;
998
999 static VarDecl *Create(ASTContext &C, DeclContext *DC,
1000 SourceLocation StartLoc, SourceLocation IdLoc,
1001 IdentifierInfo *Id, QualType T, TypeSourceInfo *TInfo,
1002 StorageClass S);
1003
1004 static VarDecl *CreateDeserialized(ASTContext &C, unsigned ID);
1005
1006 SourceRange getSourceRange() const override LLVM_READONLY__attribute__((__pure__));
1007
1008 /// \brief Returns the storage class as written in the source. For the
1009 /// computed linkage of symbol, see getLinkage.
1010 StorageClass getStorageClass() const {
1011 return (StorageClass) VarDeclBits.SClass;
1012 }
1013 void setStorageClass(StorageClass SC);
1014
1015 void setTSCSpec(ThreadStorageClassSpecifier TSC) {
1016 VarDeclBits.TSCSpec = TSC;
1017 assert(VarDeclBits.TSCSpec == TSC && "truncation")(static_cast <bool> (VarDeclBits.TSCSpec == TSC &&
"truncation") ? void (0) : __assert_fail ("VarDeclBits.TSCSpec == TSC && \"truncation\""
, "/build/llvm-toolchain-snapshot-6.0~svn318882/tools/clang/include/clang/AST/Decl.h"
, 1017, __extension__ __PRETTY_FUNCTION__))
;
1018 }
1019 ThreadStorageClassSpecifier getTSCSpec() const {
1020 return static_cast<ThreadStorageClassSpecifier>(VarDeclBits.TSCSpec);
1021 }
1022 TLSKind getTLSKind() const;
1023
1024 /// hasLocalStorage - Returns true if a variable with function scope
1025 /// is a non-static local variable.
1026 bool hasLocalStorage() const {
1027 if (getStorageClass() == SC_None) {
1028 // OpenCL v1.2 s6.5.3: The __constant or constant address space name is
1029 // used to describe variables allocated in global memory and which are
1030 // accessed inside a kernel(s) as read-only variables. As such, variables
1031 // in constant address space cannot have local storage.
1032 if (getType().getAddressSpace() == LangAS::opencl_constant)
1033 return false;
1034 // Second check is for C++11 [dcl.stc]p4.
1035 return !isFileVarDecl() && getTSCSpec() == TSCS_unspecified;
1036 }
1037
1038 // Global Named Register (GNU extension)
1039 if (getStorageClass() == SC_Register && !isLocalVarDeclOrParm())
1040 return false;
1041
1042 // Return true for: Auto, Register.
1043 // Return false for: Extern, Static, PrivateExtern, OpenCLWorkGroupLocal.
1044
1045 return getStorageClass() >= SC_Auto;
1046 }
1047
1048 /// isStaticLocal - Returns true if a variable with function scope is a
1049 /// static local variable.
1050 bool isStaticLocal() const {
1051 return (getStorageClass() == SC_Static ||
1052 // C++11 [dcl.stc]p4
1053 (getStorageClass() == SC_None && getTSCSpec() == TSCS_thread_local))
1054 && !isFileVarDecl();
1055 }
1056
1057 /// \brief Returns true if a variable has extern or __private_extern__
1058 /// storage.
1059 bool hasExternalStorage() const {
1060 return getStorageClass() == SC_Extern ||
1061 getStorageClass() == SC_PrivateExtern;
1062 }
1063
1064 /// \brief Returns true for all variables that do not have local storage.
1065 ///
1066 /// This includes all global variables as well as static variables declared
1067 /// within a function.
1068 bool hasGlobalStorage() const { return !hasLocalStorage(); }
1069
1070 /// \brief Get the storage duration of this variable, per C++ [basic.stc].
1071 StorageDuration getStorageDuration() const {
1072 return hasLocalStorage() ? SD_Automatic :
1073 getTSCSpec() ? SD_Thread : SD_Static;
1074 }
1075
1076 /// \brief Compute the language linkage.
1077 LanguageLinkage getLanguageLinkage() const;
1078
1079 /// \brief Determines whether this variable is a variable with
1080 /// external, C linkage.
1081 bool isExternC() const;
1082
1083 /// \brief Determines whether this variable's context is, or is nested within,
1084 /// a C++ extern "C" linkage spec.
1085 bool isInExternCContext() const;
1086
1087 /// \brief Determines whether this variable's context is, or is nested within,
1088 /// a C++ extern "C++" linkage spec.
1089 bool isInExternCXXContext() const;
1090
1091 /// isLocalVarDecl - Returns true for local variable declarations
1092 /// other than parameters. Note that this includes static variables
1093 /// inside of functions. It also includes variables inside blocks.
1094 ///
1095 /// void foo() { int x; static int y; extern int z; }
1096 bool isLocalVarDecl() const {
1097 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1098 return false;
1099 if (const DeclContext *DC = getLexicalDeclContext())
1100 return DC->getRedeclContext()->isFunctionOrMethod();
1101 return false;
1102 }
1103
1104 /// \brief Similar to isLocalVarDecl but also includes parameters.
1105 bool isLocalVarDeclOrParm() const {
1106 return isLocalVarDecl() || getKind() == Decl::ParmVar;
1107 }
1108
1109 /// isFunctionOrMethodVarDecl - Similar to isLocalVarDecl, but
1110 /// excludes variables declared in blocks.
1111 bool isFunctionOrMethodVarDecl() const {
1112 if (getKind() != Decl::Var && getKind() != Decl::Decomposition)
1113 return false;
1114 const DeclContext *DC = getLexicalDeclContext()->getRedeclContext();
1115 return DC->isFunctionOrMethod() && DC->getDeclKind() != Decl::Block;
1116 }
1117
1118 /// \brief Determines whether this is a static data member.
1119 ///
1120 /// This will only be true in C++, and applies to, e.g., the
1121 /// variable 'x' in:
1122 /// \code
1123 /// struct S {
1124 /// static int x;
1125 /// };
1126 /// \endcode
1127 bool isStaticDataMember() const {
1128 // If it wasn't static, it would be a FieldDecl.
1129 return getKind() != Decl::ParmVar && getDeclContext()->isRecord();
1130 }
1131
1132 VarDecl *getCanonicalDecl() override;
1133 const VarDecl *getCanonicalDecl() const {
1134 return const_cast<VarDecl*>(this)->getCanonicalDecl();
1135 }
1136
1137 enum DefinitionKind {
1138 /// This declaration is only a declaration.
1139 DeclarationOnly,
1140
1141 /// This declaration is a tentative definition.
1142 TentativeDefinition,
1143
1144 /// This declaration is definitely a definition.
1145 Definition
1146 };
1147
1148 /// \brief Check whether this declaration is a definition. If this could be
1149 /// a tentative definition (in C), don't check whether there's an overriding
1150 /// definition.
1151 DefinitionKind isThisDeclarationADefinition(ASTContext &) const;
1152 DefinitionKind isThisDeclarationADefinition() const {
1153 return isThisDeclarationADefinition(getASTContext());
1154 }
1155
1156 /// \brief Check whether this variable is defined in this
1157 /// translation unit.
1158 DefinitionKind hasDefinition(ASTContext &) const;
1159 DefinitionKind hasDefinition() const {
1160 return hasDefinition(getASTContext());
1161 }
1162
1163 /// \brief Get the tentative definition that acts as the real definition in
1164 /// a TU. Returns null if there is a proper definition available.
1165 VarDecl *getActingDefinition();
1166 const VarDecl *getActingDefinition() const {
1167 return const_cast<VarDecl*>(this)->getActingDefinition();
1168 }
1169
1170 /// \brief Get the real (not just tentative) definition for this declaration.
1171 VarDecl *getDefinition(ASTContext &);
1172 const VarDecl *getDefinition(ASTContext &C) const {
1173 return const_cast<VarDecl*>(this)->getDefinition(C);
1174 }
1175 VarDecl *getDefinition() {
1176 return getDefinition(getASTContext());
1177 }
1178 const VarDecl *getDefinition() const {
1179 return const_cast<VarDecl*>(this)->getDefinition();
1180 }
1181
1182 /// \brief Determine whether this is or was instantiated from an out-of-line
1183 /// definition of a static data member.
1184 bool isOutOfLine() const override;
1185
1186 /// isFileVarDecl - Returns true for file scoped variable declaration.
1187 bool isFileVarDecl() const {
1188 Kind K = getKind();
1189 if (K == ParmVar || K == ImplicitParam)
1190 return false;
1191
1192 if (getLexicalDeclContext()->getRedeclContext()->isFileContext())
1193 return true;
1194
1195 if (isStaticDataMember())
1196 return true;
1197
1198 return false;
1199 }
1200
1201 /// getAnyInitializer - Get the initializer for this variable, no matter which
1202 /// declaration it is attached to.
1203 const Expr *getAnyInitializer() const {
1204 const VarDecl *D;
1205 return getAnyInitializer(D);
1206 }
1207
1208 /// getAnyInitializer - Get the initializer for this variable, no matter which
1209 /// declaration it is attached to. Also get that declaration.
1210 const Expr *getAnyInitializer(const VarDecl *&D) const;
1211
1212 bool hasInit() const;
1213 const Expr *getInit() const {
1214 return const_cast<VarDecl *>(this)->getInit();
1215 }
1216 Expr *getInit();
1217
1218 /// \brief Retrieve the address of the initializer expression.
1219 Stmt **getInitAddress();
1220
1221 void setInit(Expr *I);
1222
1223 /// \brief Determine whether this variable's value can be used in a
1224 /// constant expression, according to the relevant language standard.
1225 /// This only checks properties of the declaration, and does not check
1226 /// whether the initializer is in fact a constant expression.
1227 bool isUsableInConstantExpressions(ASTContext &C) const;
1228
1229 EvaluatedStmt *ensureEvaluatedStmt() const;
1230
1231 /// \brief Attempt to evaluate the value of the initializer attached to this
1232 /// declaration, and produce notes explaining why it cannot be evaluated or is
1233 /// not a constant expression. Returns a pointer to the value if evaluation
1234 /// succeeded, 0 otherwise.
1235 APValue *evaluateValue() const;
1236 APValue *evaluateValue(SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
1237
1238 /// \brief Return the already-evaluated value of this variable's
1239 /// initializer, or NULL if the value is not yet known. Returns pointer
1240 /// to untyped APValue if the value could not be evaluated.
1241 APValue *getEvaluatedValue() const;
1242
1243 /// \brief Determines whether it is