aboutsummaryrefslogtreecommitdiffstats
path: root/lib
diff options
context:
space:
mode:
authorDimitry Andric <dim@FreeBSD.org>2013-06-10 20:45:12 +0000
committerDimitry Andric <dim@FreeBSD.org>2013-06-10 20:45:12 +0000
commit6a0372513edbc473b538d2f724efac50405d6fef (patch)
tree8f7776b7310bebaf415ac5b69e46e9f928c37144 /lib
parent809500fc2c13c8173a16b052304d983864e4a1e1 (diff)
downloadsrc-6a0372513edbc473b538d2f724efac50405d6fef.tar.gz
src-6a0372513edbc473b538d2f724efac50405d6fef.zip
Vendor import of clang tags/RELEASE_33/final r183502 (effectively, 3.3vendor/clang/clang-release_33-r183502
Notes
Notes: svn path=/vendor/clang/dist/; revision=251609 svn path=/vendor/clang/clang-release_33-r183502/; revision=251610; tag=vendor/clang/clang-release_33-r183502
Diffstat (limited to 'lib')
-rw-r--r--lib/ARCMigrate/ARCMT.cpp8
-rw-r--r--lib/ARCMigrate/TransAPIUses.cpp4
-rw-r--r--lib/ARCMigrate/TransRetainReleaseDealloc.cpp4
-rw-r--r--lib/ARCMigrate/Transforms.h2
-rw-r--r--lib/AST/ASTContext.cpp209
-rw-r--r--lib/AST/ASTDumper.cpp7
-rw-r--r--lib/AST/ASTImporter.cpp11
-rw-r--r--lib/AST/Comment.cpp2
-rw-r--r--lib/AST/CommentLexer.cpp7
-rw-r--r--lib/AST/CommentParser.cpp29
-rw-r--r--lib/AST/Decl.cpp111
-rw-r--r--lib/AST/DeclBase.cpp70
-rw-r--r--lib/AST/DeclCXX.cpp52
-rw-r--r--lib/AST/DeclObjC.cpp75
-rw-r--r--lib/AST/DeclPrinter.cpp53
-rw-r--r--lib/AST/Expr.cpp40
-rw-r--r--lib/AST/ExprCXX.cpp14
-rw-r--r--lib/AST/ExprClassification.cpp5
-rw-r--r--lib/AST/ExprConstant.cpp1251
-rw-r--r--lib/AST/ItaniumMangle.cpp34
-rw-r--r--lib/AST/MicrosoftCXXABI.cpp20
-rw-r--r--lib/AST/MicrosoftMangle.cpp191
-rw-r--r--lib/AST/RawCommentList.cpp21
-rw-r--r--lib/AST/Stmt.cpp145
-rw-r--r--lib/AST/StmtPrinter.cpp35
-rw-r--r--lib/AST/StmtProfile.cpp14
-rw-r--r--lib/AST/Type.cpp24
-rw-r--r--lib/AST/TypePrinter.cpp6
-rw-r--r--lib/Analysis/BodyFarm.cpp8
-rw-r--r--lib/Analysis/CFG.cpp5
-rw-r--r--lib/Analysis/ThreadSafety.cpp58
-rw-r--r--lib/Basic/Diagnostic.cpp17
-rw-r--r--lib/Basic/IdentifierTable.cpp2
-rw-r--r--lib/Basic/SourceManager.cpp41
-rw-r--r--lib/Basic/TargetInfo.cpp5
-rw-r--r--lib/Basic/Targets.cpp306
-rw-r--r--lib/Basic/Version.cpp2
-rw-r--r--lib/CodeGen/ABIInfo.h2
-rw-r--r--lib/CodeGen/CGAtomic.cpp11
-rw-r--r--lib/CodeGen/CGBlocks.cpp70
-rw-r--r--lib/CodeGen/CGBuiltin.cpp31
-rw-r--r--lib/CodeGen/CGCXXABI.cpp15
-rw-r--r--lib/CodeGen/CGCXXABI.h44
-rw-r--r--lib/CodeGen/CGCall.cpp30
-rw-r--r--lib/CodeGen/CGClass.cpp11
-rw-r--r--lib/CodeGen/CGCleanup.cpp12
-rw-r--r--lib/CodeGen/CGDebugInfo.cpp35
-rw-r--r--lib/CodeGen/CGDebugInfo.h5
-rw-r--r--lib/CodeGen/CGDecl.cpp11
-rw-r--r--lib/CodeGen/CGDeclCXX.cpp89
-rw-r--r--lib/CodeGen/CGException.cpp12
-rw-r--r--lib/CodeGen/CGExpr.cpp303
-rw-r--r--lib/CodeGen/CGExprAgg.cpp11
-rw-r--r--lib/CodeGen/CGExprComplex.cpp4
-rw-r--r--lib/CodeGen/CGExprConstant.cpp6
-rw-r--r--lib/CodeGen/CGExprScalar.cpp8
-rw-r--r--lib/CodeGen/CGObjC.cpp12
-rw-r--r--lib/CodeGen/CGObjCMac.cpp20
-rw-r--r--lib/CodeGen/CGObjCRuntime.cpp2
-rw-r--r--lib/CodeGen/CGRTTI.cpp6
-rw-r--r--lib/CodeGen/CGRecordLayoutBuilder.cpp8
-rw-r--r--lib/CodeGen/CGStmt.cpp49
-rw-r--r--lib/CodeGen/CodeGenFunction.cpp66
-rw-r--r--lib/CodeGen/CodeGenFunction.h78
-rw-r--r--lib/CodeGen/CodeGenModule.cpp157
-rw-r--r--lib/CodeGen/CodeGenModule.h100
-rw-r--r--lib/CodeGen/CodeGenTBAA.cpp82
-rw-r--r--lib/CodeGen/CodeGenTBAA.h12
-rw-r--r--lib/CodeGen/CodeGenTypes.cpp14
-rw-r--r--lib/CodeGen/CodeGenTypes.h13
-rw-r--r--lib/CodeGen/ItaniumCXXABI.cpp192
-rw-r--r--lib/CodeGen/MicrosoftCXXABI.cpp488
-rw-r--r--lib/CodeGen/ModuleBuilder.cpp14
-rw-r--r--lib/CodeGen/TargetInfo.cpp526
-rw-r--r--lib/Driver/ArgList.cpp15
-rw-r--r--lib/Driver/Driver.cpp56
-rw-r--r--lib/Driver/SanitizerArgs.h8
-rw-r--r--lib/Driver/ToolChain.cpp8
-rw-r--r--lib/Driver/ToolChains.cpp249
-rw-r--r--lib/Driver/ToolChains.h13
-rw-r--r--lib/Driver/Tools.cpp440
-rw-r--r--lib/Driver/WindowsToolChain.cpp4
-rw-r--r--lib/Edit/EditedSource.cpp2
-rw-r--r--lib/Format/BreakableToken.cpp179
-rw-r--r--lib/Format/BreakableToken.h240
-rw-r--r--lib/Format/CMakeLists.txt4
-rw-r--r--lib/Format/Format.cpp747
-rw-r--r--lib/Format/TokenAnnotator.cpp198
-rw-r--r--lib/Format/TokenAnnotator.h55
-rw-r--r--lib/Format/UnwrappedLineParser.cpp132
-rw-r--r--lib/Format/UnwrappedLineParser.h24
-rw-r--r--lib/Format/WhitespaceManager.cpp211
-rw-r--r--lib/Format/WhitespaceManager.h119
-rw-r--r--lib/Frontend/ASTMerge.cpp7
-rw-r--r--lib/Frontend/ASTUnit.cpp57
-rw-r--r--lib/Frontend/ChainedIncludesSource.cpp1
-rw-r--r--lib/Frontend/CompilerInstance.cpp20
-rw-r--r--lib/Frontend/CompilerInvocation.cpp33
-rw-r--r--lib/Frontend/DiagnosticRenderer.cpp5
-rw-r--r--lib/Frontend/FrontendAction.cpp2
-rw-r--r--lib/Frontend/InitHeaderSearch.cpp9
-rw-r--r--lib/Frontend/InitPreprocessor.cpp7
-rw-r--r--lib/Frontend/LogDiagnosticPrinter.cpp5
-rw-r--r--lib/Frontend/PrintPreprocessedOutput.cpp87
-rw-r--r--lib/Frontend/SerializedDiagnosticPrinter.cpp4
-rw-r--r--lib/Frontend/TextDiagnostic.cpp4
-rw-r--r--lib/Frontend/TextDiagnosticBuffer.cpp3
-rw-r--r--lib/Frontend/TextDiagnosticPrinter.cpp5
-rw-r--r--lib/Frontend/VerifyDiagnosticConsumer.cpp90
-rw-r--r--lib/Frontend/Warnings.cpp1
-rw-r--r--lib/Headers/CMakeLists.txt1
-rw-r--r--lib/Headers/avxintrin.h48
-rw-r--r--lib/Headers/emmintrin.h24
-rw-r--r--lib/Headers/stddef.h14
-rw-r--r--lib/Headers/stdint.h47
-rw-r--r--lib/Headers/xopintrin.h4
-rw-r--r--lib/Lex/Lexer.cpp17
-rw-r--r--lib/Lex/LiteralSupport.cpp9
-rw-r--r--lib/Lex/MacroArgs.cpp2
-rw-r--r--lib/Lex/MacroArgs.h125
-rw-r--r--lib/Lex/ModuleMap.cpp60
-rw-r--r--lib/Lex/PPDirectives.cpp19
-rw-r--r--lib/Lex/PPMacroExpansion.cpp29
-rw-r--r--lib/Lex/Pragma.cpp267
-rw-r--r--lib/Lex/PreprocessingRecord.cpp3
-rw-r--r--lib/Lex/Preprocessor.cpp8
-rw-r--r--lib/Lex/TokenLexer.cpp2
-rw-r--r--lib/Parse/CMakeLists.txt1
-rw-r--r--lib/Parse/ParseCXXInlineMethods.cpp39
-rw-r--r--lib/Parse/ParseDecl.cpp256
-rw-r--r--lib/Parse/ParseDeclCXX.cpp79
-rw-r--r--lib/Parse/ParseExpr.cpp11
-rw-r--r--lib/Parse/ParseExprCXX.cpp6
-rw-r--r--lib/Parse/ParseInit.cpp2
-rw-r--r--lib/Parse/ParseObjc.cpp22
-rw-r--r--lib/Parse/ParsePragma.cpp96
-rw-r--r--lib/Parse/ParsePragma.h8
-rw-r--r--lib/Parse/ParseStmt.cpp400
-rw-r--r--lib/Parse/ParseTemplate.cpp133
-rw-r--r--lib/Parse/ParseTentative.cpp14
-rw-r--r--lib/Parse/Parser.cpp14
-rw-r--r--lib/Rewrite/Frontend/FixItRewriter.cpp5
-rw-r--r--lib/Rewrite/Frontend/InclusionRewriter.cpp160
-rw-r--r--lib/Sema/AnalysisBasedWarnings.cpp8
-rw-r--r--lib/Sema/AttributeList.cpp2
-rw-r--r--lib/Sema/DeclSpec.cpp126
-rw-r--r--lib/Sema/ScopeInfo.cpp1
-rw-r--r--lib/Sema/Sema.cpp43
-rw-r--r--lib/Sema/SemaAccess.cpp18
-rw-r--r--lib/Sema/SemaCast.cpp16
-rw-r--r--lib/Sema/SemaChecking.cpp21
-rw-r--r--lib/Sema/SemaCodeComplete.cpp13
-rw-r--r--lib/Sema/SemaDecl.cpp509
-rw-r--r--lib/Sema/SemaDeclAttr.cpp14
-rw-r--r--lib/Sema/SemaDeclCXX.cpp1156
-rw-r--r--lib/Sema/SemaDeclObjC.cpp93
-rw-r--r--lib/Sema/SemaExceptionSpec.cpp10
-rw-r--r--lib/Sema/SemaExpr.cpp398
-rw-r--r--lib/Sema/SemaExprCXX.cpp145
-rw-r--r--lib/Sema/SemaExprMember.cpp71
-rw-r--r--lib/Sema/SemaExprObjC.cpp78
-rw-r--r--lib/Sema/SemaInit.cpp402
-rw-r--r--lib/Sema/SemaLambda.cpp10
-rw-r--r--lib/Sema/SemaLookup.cpp58
-rw-r--r--lib/Sema/SemaObjCProperty.cpp49
-rw-r--r--lib/Sema/SemaOpenMP.cpp4
-rw-r--r--lib/Sema/SemaOverload.cpp328
-rw-r--r--lib/Sema/SemaPseudoObject.cpp131
-rw-r--r--lib/Sema/SemaStmt.cpp308
-rw-r--r--lib/Sema/SemaStmtAsm.cpp314
-rw-r--r--lib/Sema/SemaTemplate.cpp4
-rw-r--r--lib/Sema/SemaTemplateDeduction.cpp270
-rw-r--r--lib/Sema/SemaTemplateInstantiate.cpp7
-rw-r--r--lib/Sema/SemaTemplateInstantiateDecl.cpp132
-rw-r--r--lib/Sema/SemaTemplateVariadic.cpp1
-rw-r--r--lib/Sema/SemaType.cpp118
-rw-r--r--lib/Sema/TreeTransform.h173
-rw-r--r--lib/Serialization/ASTCommon.cpp3
-rw-r--r--lib/Serialization/ASTReader.cpp212
-rw-r--r--lib/Serialization/ASTReaderDecl.cpp24
-rw-r--r--lib/Serialization/ASTReaderInternals.h2
-rw-r--r--lib/Serialization/ASTReaderStmt.cpp125
-rw-r--r--lib/Serialization/ASTWriter.cpp83
-rw-r--r--lib/Serialization/ASTWriterDecl.cpp27
-rw-r--r--lib/Serialization/ASTWriterStmt.cpp90
-rw-r--r--lib/Serialization/GlobalModuleIndex.cpp31
-rw-r--r--lib/StaticAnalyzer/Checkers/AllocationDiagnostics.cpp24
-rw-r--r--lib/StaticAnalyzer/Checkers/AllocationDiagnostics.h31
-rw-r--r--lib/StaticAnalyzer/Checkers/BasicObjCFoundationChecks.cpp112
-rw-r--r--lib/StaticAnalyzer/Checkers/CMakeLists.txt3
-rw-r--r--lib/StaticAnalyzer/Checkers/CStringChecker.cpp62
-rw-r--r--lib/StaticAnalyzer/Checkers/CStringSyntaxChecker.cpp2
-rw-r--r--lib/StaticAnalyzer/Checkers/CheckSecuritySyntaxOnly.cpp6
-rw-r--r--lib/StaticAnalyzer/Checkers/Checkers.td9
-rw-r--r--lib/StaticAnalyzer/Checkers/DeadStoresChecker.cpp14
-rw-r--r--lib/StaticAnalyzer/Checkers/DebugCheckers.cpp2
-rw-r--r--lib/StaticAnalyzer/Checkers/DynamicTypePropagation.cpp18
-rw-r--r--lib/StaticAnalyzer/Checkers/IvarInvalidationChecker.cpp47
-rw-r--r--lib/StaticAnalyzer/Checkers/MallocChecker.cpp220
-rw-r--r--lib/StaticAnalyzer/Checkers/MallocSizeofChecker.cpp2
-rw-r--r--lib/StaticAnalyzer/Checkers/RetainCountChecker.cpp158
-rw-r--r--lib/StaticAnalyzer/Checkers/ReturnUndefChecker.cpp13
-rw-r--r--lib/StaticAnalyzer/Core/BugReporter.cpp717
-rw-r--r--lib/StaticAnalyzer/Core/BugReporterVisitors.cpp206
-rw-r--r--lib/StaticAnalyzer/Core/CallEvent.cpp14
-rw-r--r--lib/StaticAnalyzer/Core/Environment.cpp42
-rw-r--r--lib/StaticAnalyzer/Core/ExprEngine.cpp48
-rw-r--r--lib/StaticAnalyzer/Core/ExprEngineC.cpp79
-rw-r--r--lib/StaticAnalyzer/Core/ExprEngineCallAndReturn.cpp48
-rw-r--r--lib/StaticAnalyzer/Core/MemRegion.cpp62
-rw-r--r--lib/StaticAnalyzer/Core/PathDiagnostic.cpp89
-rw-r--r--lib/StaticAnalyzer/Core/PlistDiagnostics.cpp2
-rw-r--r--lib/StaticAnalyzer/Core/ProgramState.cpp12
-rw-r--r--lib/StaticAnalyzer/Core/RegionStore.cpp276
-rw-r--r--lib/StaticAnalyzer/Core/SValBuilder.cpp105
-rw-r--r--lib/StaticAnalyzer/Core/SVals.cpp20
-rw-r--r--lib/StaticAnalyzer/Core/SimpleConstraintManager.cpp23
-rw-r--r--lib/StaticAnalyzer/Core/SimpleSValBuilder.cpp10
-rw-r--r--lib/StaticAnalyzer/Core/Store.cpp88
-rw-r--r--lib/StaticAnalyzer/Core/SymbolManager.cpp4
-rw-r--r--lib/StaticAnalyzer/Frontend/CheckerRegistration.cpp5
221 files changed, 13295 insertions, 5312 deletions
diff --git a/lib/ARCMigrate/ARCMT.cpp b/lib/ARCMigrate/ARCMT.cpp
index 72f35205ca8e..a6d48762fe55 100644
--- a/lib/ARCMigrate/ARCMT.cpp
+++ b/lib/ARCMigrate/ARCMT.cpp
@@ -140,12 +140,6 @@ public:
// Non-ARC warnings are ignored.
Diags.setLastDiagnosticIgnored();
}
-
- DiagnosticConsumer *clone(DiagnosticsEngine &Diags) const {
- // Just drop any diagnostics that come from cloned consumers; they'll
- // have different source managers anyway.
- return new IgnoringDiagConsumer();
- }
};
} // end anonymous namespace
@@ -482,7 +476,7 @@ public:
: ARCMTMacroLocs(ARCMTMacroLocs) { }
virtual void MacroExpands(const Token &MacroNameTok, const MacroDirective *MD,
- SourceRange Range) {
+ SourceRange Range, const MacroArgs *Args) {
if (MacroNameTok.getIdentifierInfo()->getName() == getARCMTMacroName())
ARCMTMacroLocs.push_back(MacroNameTok.getLocation());
}
diff --git a/lib/ARCMigrate/TransAPIUses.cpp b/lib/ARCMigrate/TransAPIUses.cpp
index 2305b6defd9c..a0994a6b459a 100644
--- a/lib/ARCMigrate/TransAPIUses.cpp
+++ b/lib/ARCMigrate/TransAPIUses.cpp
@@ -91,12 +91,12 @@ public:
E->getSelector() == zoneSel &&
Pass.TA.hasDiagnostic(diag::err_unavailable,
diag::err_unavailable_message,
- E->getInstanceReceiver()->getExprLoc())) {
+ E->getSelectorLoc(0))) {
// Calling -zone is meaningless in ARC, change it to nil.
Transaction Trans(Pass.TA);
Pass.TA.clearDiagnostic(diag::err_unavailable,
diag::err_unavailable_message,
- E->getInstanceReceiver()->getExprLoc());
+ E->getSelectorLoc(0));
Pass.TA.replace(E->getSourceRange(), getNilString(Pass.Ctx));
}
return true;
diff --git a/lib/ARCMigrate/TransRetainReleaseDealloc.cpp b/lib/ARCMigrate/TransRetainReleaseDealloc.cpp
index 0c8d15544610..446a284a286f 100644
--- a/lib/ARCMigrate/TransRetainReleaseDealloc.cpp
+++ b/lib/ARCMigrate/TransRetainReleaseDealloc.cpp
@@ -118,7 +118,7 @@ public:
return true;
case ObjCMessageExpr::SuperInstance: {
Transaction Trans(Pass.TA);
- clearDiagnostics(E->getSuperLoc());
+ clearDiagnostics(E->getSelectorLoc(0));
if (tryRemoving(E))
return true;
Pass.TA.replace(E->getSourceRange(), "self");
@@ -132,7 +132,7 @@ public:
if (!rec) return true;
Transaction Trans(Pass.TA);
- clearDiagnostics(rec->getExprLoc());
+ clearDiagnostics(E->getSelectorLoc(0));
ObjCMessageExpr *Msg = E;
Expr *RecContainer = Msg;
diff --git a/lib/ARCMigrate/Transforms.h b/lib/ARCMigrate/Transforms.h
index cb7d1535c628..e20fe5927f39 100644
--- a/lib/ARCMigrate/Transforms.h
+++ b/lib/ARCMigrate/Transforms.h
@@ -169,7 +169,7 @@ bool isPlusOne(const Expr *E);
/// source location will be invalid.
SourceLocation findLocationAfterSemi(SourceLocation loc, ASTContext &Ctx);
-/// \brief \arg Loc is the end of a statement range. This returns the location
+/// \brief 'Loc' is the end of a statement range. This returns the location
/// of the semicolon following the statement.
/// If no semicolon is found or the location is inside a macro, the returned
/// source location will be invalid.
diff --git a/lib/AST/ASTContext.cpp b/lib/AST/ASTContext.cpp
index 7245c0316082..176aec53a252 100644
--- a/lib/AST/ASTContext.cpp
+++ b/lib/AST/ASTContext.cpp
@@ -97,7 +97,12 @@ RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
if (ED->getTemplateSpecializationKind() == TSK_ImplicitInstantiation)
return NULL;
}
-
+ if (const TagDecl *TD = dyn_cast<TagDecl>(D)) {
+ // When tag declaration (but not definition!) is part of the
+ // decl-specifier-seq of some other declaration, it doesn't get comment
+ if (TD->isEmbeddedInDeclarator() && !TD->isCompleteDefinition())
+ return NULL;
+ }
// TODO: handle comments for function parameters properly.
if (isa<ParmVarDecl>(D))
return NULL;
@@ -141,7 +146,9 @@ RawComment *ASTContext::getRawCommentForDeclNoCache(const Decl *D) const {
// When searching for comments during parsing, the comment we are looking
// for is usually among the last two comments we parsed -- check them
// first.
- RawComment CommentAtDeclLoc(SourceMgr, SourceRange(DeclLoc));
+ RawComment CommentAtDeclLoc(
+ SourceMgr, SourceRange(DeclLoc), false,
+ LangOpts.CommentOpts.ParseAllComments);
BeforeThanCompare<RawComment> Compare(SourceMgr);
ArrayRef<RawComment *>::iterator MaybeBeforeDecl = RawComments.end() - 1;
bool Found = Compare(*MaybeBeforeDecl, &CommentAtDeclLoc);
@@ -435,7 +442,7 @@ comments::FullComment *ASTContext::getCommentForDecl(
if (comments::FullComment *FC = getCommentForDecl(Overridden[i], PP))
return cloneFullComment(FC, D);
}
- else if (const TypedefDecl *TD = dyn_cast<TypedefDecl>(D)) {
+ else if (const TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
// Attach any tag type's documentation to its typedef if latter
// does not have one of its own.
QualType QT = TD->getUnderlyingType();
@@ -444,6 +451,53 @@ comments::FullComment *ASTContext::getCommentForDecl(
if (comments::FullComment *FC = getCommentForDecl(TD, PP))
return cloneFullComment(FC, D);
}
+ else if (const ObjCInterfaceDecl *IC = dyn_cast<ObjCInterfaceDecl>(D)) {
+ while (IC->getSuperClass()) {
+ IC = IC->getSuperClass();
+ if (comments::FullComment *FC = getCommentForDecl(IC, PP))
+ return cloneFullComment(FC, D);
+ }
+ }
+ else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
+ if (const ObjCInterfaceDecl *IC = CD->getClassInterface())
+ if (comments::FullComment *FC = getCommentForDecl(IC, PP))
+ return cloneFullComment(FC, D);
+ }
+ else if (const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(D)) {
+ if (!(RD = RD->getDefinition()))
+ return NULL;
+ // Check non-virtual bases.
+ for (CXXRecordDecl::base_class_const_iterator I =
+ RD->bases_begin(), E = RD->bases_end(); I != E; ++I) {
+ if (I->isVirtual() || (I->getAccessSpecifier() != AS_public))
+ continue;
+ QualType Ty = I->getType();
+ if (Ty.isNull())
+ continue;
+ if (const CXXRecordDecl *NonVirtualBase = Ty->getAsCXXRecordDecl()) {
+ if (!(NonVirtualBase= NonVirtualBase->getDefinition()))
+ continue;
+
+ if (comments::FullComment *FC = getCommentForDecl((NonVirtualBase), PP))
+ return cloneFullComment(FC, D);
+ }
+ }
+ // Check virtual bases.
+ for (CXXRecordDecl::base_class_const_iterator I =
+ RD->vbases_begin(), E = RD->vbases_end(); I != E; ++I) {
+ if (I->getAccessSpecifier() != AS_public)
+ continue;
+ QualType Ty = I->getType();
+ if (Ty.isNull())
+ continue;
+ if (const CXXRecordDecl *VirtualBase = Ty->getAsCXXRecordDecl()) {
+ if (!(VirtualBase= VirtualBase->getDefinition()))
+ continue;
+ if (comments::FullComment *FC = getCommentForDecl((VirtualBase), PP))
+ return cloneFullComment(FC, D);
+ }
+ }
+ }
return NULL;
}
@@ -1125,8 +1179,8 @@ void ASTContext::getOverriddenMethods(
assert(D);
if (const CXXMethodDecl *CXXMethod = dyn_cast<CXXMethodDecl>(D)) {
- Overridden.append(CXXMethod->begin_overridden_methods(),
- CXXMethod->end_overridden_methods());
+ Overridden.append(overridden_methods_begin(CXXMethod),
+ overridden_methods_end(CXXMethod));
return;
}
@@ -1229,6 +1283,10 @@ CharUnits ASTContext::getDeclAlign(const Decl *D, bool RefAsPointee) const {
T = getBaseElementType(arrayType);
}
Align = std::max(Align, getPreferredTypeAlign(T.getTypePtr()));
+ if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
+ if (VD->hasGlobalStorage())
+ Align = std::max(Align, getTargetInfo().getMinGlobalAlign());
+ }
}
// Fields can be subject to extra alignment constraints, like if
@@ -1543,7 +1601,8 @@ ASTContext::getTypeInfoImpl(const Type *T) const {
case Type::Auto: {
const AutoType *A = cast<AutoType>(T);
- assert(A->isDeduced() && "Cannot request the size of a dependent type");
+ assert(!A->getDeducedType().isNull() &&
+ "cannot request the size of an undeduced or dependent auto type");
return getTypeInfo(A->getDeducedType().getTypePtr());
}
@@ -1670,6 +1729,18 @@ unsigned ASTContext::getPreferredTypeAlign(const Type *T) const {
return ABIAlign;
}
+/// getAlignOfGlobalVar - Return the alignment in bits that should be given
+/// to a global variable of the specified type.
+unsigned ASTContext::getAlignOfGlobalVar(QualType T) const {
+ return std::max(getTypeAlign(T), getTargetInfo().getMinGlobalAlign());
+}
+
+/// getAlignOfGlobalVarInChars - Return the alignment in characters that
+/// should be given to a global variable of the specified type.
+CharUnits ASTContext::getAlignOfGlobalVarInChars(QualType T) const {
+ return toCharUnitsFromBits(getAlignOfGlobalVar(T));
+}
+
/// DeepCollectObjCIvars -
/// This routine first collects all declared, but not synthesized, ivars in
/// super class and then collects all ivars, including those synthesized for
@@ -1980,6 +2051,16 @@ const FunctionType *ASTContext::adjustFunctionType(const FunctionType *T,
return cast<FunctionType>(Result.getTypePtr());
}
+void ASTContext::adjustDeducedFunctionResultType(FunctionDecl *FD,
+ QualType ResultType) {
+ // FIXME: Need to inform serialization code about this!
+ for (FD = FD->getMostRecentDecl(); FD; FD = FD->getPreviousDecl()) {
+ const FunctionProtoType *FPT = FD->getType()->castAs<FunctionProtoType>();
+ FunctionProtoType::ExtProtoInfo EPI = FPT->getExtProtoInfo();
+ FD->setType(getFunctionType(ResultType, FPT->getArgTypes(), EPI));
+ }
+}
+
/// getComplexType - Return the uniqued reference to the type for a complex
/// number with the specified element type.
QualType ASTContext::getComplexType(QualType T) const {
@@ -3508,18 +3589,24 @@ QualType ASTContext::getUnaryTransformType(QualType BaseType,
return QualType(Ty, 0);
}
-/// getAutoType - We only unique auto types after they've been deduced.
-QualType ASTContext::getAutoType(QualType DeducedType) const {
+/// getAutoType - Return the uniqued reference to the 'auto' type which has been
+/// deduced to the given type, or to the canonical undeduced 'auto' type, or the
+/// canonical deduced-but-dependent 'auto' type.
+QualType ASTContext::getAutoType(QualType DeducedType, bool IsDecltypeAuto,
+ bool IsDependent) const {
+ if (DeducedType.isNull() && !IsDecltypeAuto && !IsDependent)
+ return getAutoDeductType();
+
+ // Look in the folding set for an existing type.
void *InsertPos = 0;
- if (!DeducedType.isNull()) {
- // Look in the folding set for an existing type.
- llvm::FoldingSetNodeID ID;
- AutoType::Profile(ID, DeducedType);
- if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
- return QualType(AT, 0);
- }
+ llvm::FoldingSetNodeID ID;
+ AutoType::Profile(ID, DeducedType, IsDecltypeAuto, IsDependent);
+ if (AutoType *AT = AutoTypes.FindNodeOrInsertPos(ID, InsertPos))
+ return QualType(AT, 0);
- AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType);
+ AutoType *AT = new (*this, TypeAlignment) AutoType(DeducedType,
+ IsDecltypeAuto,
+ IsDependent);
Types.push_back(AT);
if (InsertPos)
AutoTypes.InsertNode(AT, InsertPos);
@@ -3557,8 +3644,10 @@ QualType ASTContext::getAtomicType(QualType T) const {
/// getAutoDeductType - Get type pattern for deducing against 'auto'.
QualType ASTContext::getAutoDeductType() const {
if (AutoDeductTy.isNull())
- AutoDeductTy = getAutoType(QualType());
- assert(!AutoDeductTy.isNull() && "can't build 'auto' pattern");
+ AutoDeductTy = QualType(
+ new (*this, TypeAlignment) AutoType(QualType(), /*decltype(auto)*/false,
+ /*dependent*/false),
+ 0);
return AutoDeductTy;
}
@@ -4188,7 +4277,7 @@ QualType ASTContext::isPromotableBitField(Expr *E) const {
if (E->isTypeDependent() || E->isValueDependent())
return QualType();
- FieldDecl *Field = E->getBitField();
+ FieldDecl *Field = E->getSourceBitField(); // FIXME: conditional bit-fields?
if (!Field)
return QualType();
@@ -5331,6 +5420,11 @@ void ASTContext::getObjCEncodingForTypeImpl(QualType T, std::string& S,
// FIXME. We should do a better job than gcc.
return;
+ case Type::Auto:
+ // We could see an undeduced auto type here during error recovery.
+ // Just ignore it.
+ return;
+
#define ABSTRACT_TYPE(KIND, BASE)
#define TYPE(KIND, BASE)
#define DEPENDENT_TYPE(KIND, BASE) \
@@ -5886,6 +5980,80 @@ CreateAAPCSABIBuiltinVaListDecl(const ASTContext *Context) {
return VaListTypeDecl;
}
+static TypedefDecl *
+CreateSystemZBuiltinVaListDecl(const ASTContext *Context) {
+ // typedef struct __va_list_tag {
+ RecordDecl *VaListTagDecl;
+ VaListTagDecl = CreateRecordDecl(*Context, TTK_Struct,
+ Context->getTranslationUnitDecl(),
+ &Context->Idents.get("__va_list_tag"));
+ VaListTagDecl->startDefinition();
+
+ const size_t NumFields = 4;
+ QualType FieldTypes[NumFields];
+ const char *FieldNames[NumFields];
+
+ // long __gpr;
+ FieldTypes[0] = Context->LongTy;
+ FieldNames[0] = "__gpr";
+
+ // long __fpr;
+ FieldTypes[1] = Context->LongTy;
+ FieldNames[1] = "__fpr";
+
+ // void *__overflow_arg_area;
+ FieldTypes[2] = Context->getPointerType(Context->VoidTy);
+ FieldNames[2] = "__overflow_arg_area";
+
+ // void *__reg_save_area;
+ FieldTypes[3] = Context->getPointerType(Context->VoidTy);
+ FieldNames[3] = "__reg_save_area";
+
+ // Create fields
+ for (unsigned i = 0; i < NumFields; ++i) {
+ FieldDecl *Field = FieldDecl::Create(const_cast<ASTContext &>(*Context),
+ VaListTagDecl,
+ SourceLocation(),
+ SourceLocation(),
+ &Context->Idents.get(FieldNames[i]),
+ FieldTypes[i], /*TInfo=*/0,
+ /*BitWidth=*/0,
+ /*Mutable=*/false,
+ ICIS_NoInit);
+ Field->setAccess(AS_public);
+ VaListTagDecl->addDecl(Field);
+ }
+ VaListTagDecl->completeDefinition();
+ QualType VaListTagType = Context->getRecordType(VaListTagDecl);
+ Context->VaListTagTy = VaListTagType;
+
+ // } __va_list_tag;
+ TypedefDecl *VaListTagTypedefDecl
+ = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
+ Context->getTranslationUnitDecl(),
+ SourceLocation(), SourceLocation(),
+ &Context->Idents.get("__va_list_tag"),
+ Context->getTrivialTypeSourceInfo(VaListTagType));
+ QualType VaListTagTypedefType =
+ Context->getTypedefType(VaListTagTypedefDecl);
+
+ // typedef __va_list_tag __builtin_va_list[1];
+ llvm::APInt Size(Context->getTypeSize(Context->getSizeType()), 1);
+ QualType VaListTagArrayType
+ = Context->getConstantArrayType(VaListTagTypedefType,
+ Size, ArrayType::Normal,0);
+ TypeSourceInfo *TInfo
+ = Context->getTrivialTypeSourceInfo(VaListTagArrayType);
+ TypedefDecl *VaListTypedefDecl
+ = TypedefDecl::Create(const_cast<ASTContext &>(*Context),
+ Context->getTranslationUnitDecl(),
+ SourceLocation(), SourceLocation(),
+ &Context->Idents.get("__builtin_va_list"),
+ TInfo);
+
+ return VaListTypedefDecl;
+}
+
static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
TargetInfo::BuiltinVaListKind Kind) {
switch (Kind) {
@@ -5903,6 +6071,8 @@ static TypedefDecl *CreateVaListDecl(const ASTContext *Context,
return CreatePNaClABIBuiltinVaListDecl(Context);
case TargetInfo::AAPCSABIBuiltinVaList:
return CreateAAPCSABIBuiltinVaListDecl(Context);
+ case TargetInfo::SystemZBuiltinVaList:
+ return CreateSystemZBuiltinVaListDecl(Context);
}
llvm_unreachable("Unhandled __builtin_va_list type kind");
@@ -6972,6 +7142,7 @@ QualType ASTContext::mergeTypes(QualType LHS, QualType RHS,
#include "clang/AST/TypeNodes.def"
llvm_unreachable("Non-canonical and dependent types shouldn't get here");
+ case Type::Auto:
case Type::LValueReference:
case Type::RValueReference:
case Type::MemberPointer:
diff --git a/lib/AST/ASTDumper.cpp b/lib/AST/ASTDumper.cpp
index b1d174b855eb..340cc41f7e81 100644
--- a/lib/AST/ASTDumper.cpp
+++ b/lib/AST/ASTDumper.cpp
@@ -853,8 +853,11 @@ void ASTDumper::VisitVarDecl(const VarDecl *D) {
StorageClass SC = D->getStorageClass();
if (SC != SC_None)
OS << ' ' << VarDecl::getStorageClassSpecifierString(SC);
- if (D->isThreadSpecified())
- OS << " __thread";
+ switch (D->getTLSKind()) {
+ case VarDecl::TLS_None: break;
+ case VarDecl::TLS_Static: OS << " tls"; break;
+ case VarDecl::TLS_Dynamic: OS << " tls_dynamic"; break;
+ }
if (D->isModulePrivate())
OS << " __module_private__";
if (D->isNRVOVariable())
diff --git a/lib/AST/ASTImporter.cpp b/lib/AST/ASTImporter.cpp
index d2e6d2970531..915eb6feb85e 100644
--- a/lib/AST/ASTImporter.cpp
+++ b/lib/AST/ASTImporter.cpp
@@ -839,6 +839,12 @@ static bool IsStructurallyEquivalent(StructuralEquivalenceContext &Context,
RecordDecl *D2 = Field2->getType()->castAs<RecordType>()->getDecl();
return IsStructurallyEquivalent(Context, D1, D2);
}
+
+ // Check for equivalent field names.
+ IdentifierInfo *Name1 = Field1->getIdentifier();
+ IdentifierInfo *Name2 = Field2->getIdentifier();
+ if (!::IsStructurallyEquivalent(Name1, Name2))
+ return false;
if (!IsStructurallyEquivalent(Context,
Field1->getType(), Field2->getType())) {
@@ -1680,7 +1686,7 @@ QualType ASTNodeImporter::VisitUnaryTransformType(const UnaryTransformType *T) {
}
QualType ASTNodeImporter::VisitAutoType(const AutoType *T) {
- // FIXME: Make sure that the "to" context supports C++0x!
+ // FIXME: Make sure that the "to" context supports C++11!
QualType FromDeduced = T->getDeducedType();
QualType ToDeduced;
if (!FromDeduced.isNull()) {
@@ -1689,7 +1695,7 @@ QualType ASTNodeImporter::VisitAutoType(const AutoType *T) {
return QualType();
}
- return Importer.getToContext().getAutoType(ToDeduced);
+ return Importer.getToContext().getAutoType(ToDeduced, T->isDecltypeAuto());
}
QualType ASTNodeImporter::VisitRecordType(const RecordType *T) {
@@ -3644,6 +3650,7 @@ Decl *ASTNodeImporter::VisitObjCImplementationDecl(ObjCImplementationDecl *D) {
Iface, Super,
Importer.Import(D->getLocation()),
Importer.Import(D->getAtStartLoc()),
+ Importer.Import(D->getSuperClassLoc()),
Importer.Import(D->getIvarLBraceLoc()),
Importer.Import(D->getIvarRBraceLoc()));
diff --git a/lib/AST/Comment.cpp b/lib/AST/Comment.cpp
index db55c045449d..68c73fd48e3c 100644
--- a/lib/AST/Comment.cpp
+++ b/lib/AST/Comment.cpp
@@ -134,7 +134,7 @@ void DeclInfo::fill() {
IsObjCMethod = false;
IsInstanceMethod = false;
IsClassMethod = false;
- ParamVars = ArrayRef<const ParmVarDecl *>();
+ ParamVars = None;
TemplateParameters = NULL;
if (!CommentDecl) {
diff --git a/lib/AST/CommentLexer.cpp b/lib/AST/CommentLexer.cpp
index 1194520bf360..70410d61085d 100644
--- a/lib/AST/CommentLexer.cpp
+++ b/lib/AST/CommentLexer.cpp
@@ -1,5 +1,6 @@
#include "clang/AST/CommentLexer.h"
#include "clang/AST/CommentCommandTraits.h"
+#include "clang/AST/CommentDiagnostic.h"
#include "clang/Basic/CharInfo.h"
#include "llvm/ADT/StringExtras.h"
#include "llvm/ADT/StringSwitch.h"
@@ -353,6 +354,7 @@ void Lexer::lexCommentText(Token &T) {
if (!Info) {
formTokenWithChars(T, TokenPtr, tok::unknown_command);
T.setUnknownCommandName(CommandName);
+ Diag(T.getLocation(), diag::warn_unknown_comment_command_name);
return;
}
if (Info->IsVerbatimBlockCommand) {
@@ -685,10 +687,11 @@ void Lexer::lexHTMLEndTag(Token &T) {
State = LS_Normal;
}
-Lexer::Lexer(llvm::BumpPtrAllocator &Allocator, const CommandTraits &Traits,
+Lexer::Lexer(llvm::BumpPtrAllocator &Allocator, DiagnosticsEngine &Diags,
+ const CommandTraits &Traits,
SourceLocation FileLoc,
const char *BufferStart, const char *BufferEnd):
- Allocator(Allocator), Traits(Traits),
+ Allocator(Allocator), Diags(Diags), Traits(Traits),
BufferStart(BufferStart), BufferEnd(BufferEnd),
FileLoc(FileLoc), BufferPtr(BufferStart),
CommentState(LCS_BeforeComment), State(LS_Normal) {
diff --git a/lib/AST/CommentParser.cpp b/lib/AST/CommentParser.cpp
index 09912c618864..d89c79b3d93d 100644
--- a/lib/AST/CommentParser.cpp
+++ b/lib/AST/CommentParser.cpp
@@ -302,22 +302,18 @@ void Parser::parseBlockCommandArgs(BlockCommandComment *BC,
BlockCommandComment *Parser::parseBlockCommand() {
assert(Tok.is(tok::backslash_command) || Tok.is(tok::at_command));
- ParamCommandComment *PC;
- TParamCommandComment *TPC;
- BlockCommandComment *BC;
- bool IsParam = false;
- bool IsTParam = false;
+ ParamCommandComment *PC = 0;
+ TParamCommandComment *TPC = 0;
+ BlockCommandComment *BC = 0;
const CommandInfo *Info = Traits.getCommandInfo(Tok.getCommandID());
CommandMarkerKind CommandMarker =
Tok.is(tok::backslash_command) ? CMK_Backslash : CMK_At;
if (Info->IsParamCommand) {
- IsParam = true;
PC = S.actOnParamCommandStart(Tok.getLocation(),
Tok.getEndLocation(),
Tok.getCommandID(),
CommandMarker);
} else if (Info->IsTParamCommand) {
- IsTParam = true;
TPC = S.actOnTParamCommandStart(Tok.getLocation(),
Tok.getEndLocation(),
Tok.getCommandID(),
@@ -333,12 +329,11 @@ BlockCommandComment *Parser::parseBlockCommand() {
if (isTokBlockCommand()) {
// Block command ahead. We can't nest block commands, so pretend that this
// command has an empty argument.
- ParagraphComment *Paragraph = S.actOnParagraphComment(
- ArrayRef<InlineContentComment *>());
- if (IsParam) {
+ ParagraphComment *Paragraph = S.actOnParagraphComment(None);
+ if (PC) {
S.actOnParamCommandFinish(PC, Paragraph);
return PC;
- } else if (IsTParam) {
+ } else if (TPC) {
S.actOnTParamCommandFinish(TPC, Paragraph);
return TPC;
} else {
@@ -347,14 +342,14 @@ BlockCommandComment *Parser::parseBlockCommand() {
}
}
- if (IsParam || IsTParam || Info->NumArgs > 0) {
+ if (PC || TPC || Info->NumArgs > 0) {
// In order to parse command arguments we need to retokenize a few
// following text tokens.
TextTokenRetokenizer Retokenizer(Allocator, *this);
- if (IsParam)
+ if (PC)
parseParamCommandArgs(PC, Retokenizer);
- else if (IsTParam)
+ else if (TPC)
parseTParamCommandArgs(TPC, Retokenizer);
else
parseBlockCommandArgs(BC, Retokenizer, Info->NumArgs);
@@ -376,7 +371,7 @@ BlockCommandComment *Parser::parseBlockCommand() {
ParagraphComment *Paragraph;
if (EmptyParagraph)
- Paragraph = S.actOnParagraphComment(ArrayRef<InlineContentComment *>());
+ Paragraph = S.actOnParagraphComment(None);
else {
BlockContentComment *Block = parseParagraphOrBlockCommand();
// Since we have checked for a block command, we should have parsed a
@@ -384,10 +379,10 @@ BlockCommandComment *Parser::parseBlockCommand() {
Paragraph = cast<ParagraphComment>(Block);
}
- if (IsParam) {
+ if (PC) {
S.actOnParamCommandFinish(PC, Paragraph);
return PC;
- } else if (IsTParam) {
+ } else if (TPC) {
S.actOnTParamCommandFinish(TPC, Paragraph);
return TPC;
} else {
diff --git a/lib/AST/Decl.cpp b/lib/AST/Decl.cpp
index bf807aeb1d69..ab9d73b9178e 100644
--- a/lib/AST/Decl.cpp
+++ b/lib/AST/Decl.cpp
@@ -471,9 +471,16 @@ static bool useInlineVisibilityHidden(const NamedDecl *D) {
FD->hasBody(Def) && Def->isInlined() && !Def->hasAttr<GNUInlineAttr>();
}
-template <typename T> static bool isInExternCContext(T *D) {
+template <typename T> static bool isFirstInExternCContext(T *D) {
const T *First = D->getFirstDeclaration();
- return First->getDeclContext()->isExternCContext();
+ return First->isInExternCContext();
+}
+
+static bool isSingleLineExternC(const Decl &D) {
+ if (const LinkageSpecDecl *SD = dyn_cast<LinkageSpecDecl>(D.getDeclContext()))
+ if (SD->getLanguage() == LinkageSpecDecl::lang_c && !SD->hasBraces())
+ return true;
+ return false;
}
static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
@@ -504,7 +511,8 @@ static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
return PrevVar->getLinkageAndVisibility();
if (Var->getStorageClass() != SC_Extern &&
- Var->getStorageClass() != SC_PrivateExtern)
+ Var->getStorageClass() != SC_PrivateExtern &&
+ !isSingleLineExternC(*Var))
return LinkageInfo::internal();
}
@@ -540,8 +548,8 @@ static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
if (D->isInAnonymousNamespace()) {
const VarDecl *Var = dyn_cast<VarDecl>(D);
const FunctionDecl *Func = dyn_cast<FunctionDecl>(D);
- if ((!Var || !isInExternCContext(Var)) &&
- (!Func || !isInExternCContext(Func)))
+ if ((!Var || !isFirstInExternCContext(Var)) &&
+ (!Func || !isFirstInExternCContext(Func)))
return LinkageInfo::uniqueExternal();
}
@@ -618,7 +626,7 @@ static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
//
// Note that we don't want to make the variable non-external
// because of this, but unique-external linkage suits us.
- if (Context.getLangOpts().CPlusPlus && !isInExternCContext(Var)) {
+ if (Context.getLangOpts().CPlusPlus && !isFirstInExternCContext(Var)) {
LinkageInfo TypeLV = Var->getType()->getLinkageAndVisibility();
if (TypeLV.getLinkage() != ExternalLinkage)
return LinkageInfo::uniqueExternal();
@@ -652,7 +660,7 @@ static LinkageInfo getLVForNamespaceScopeDecl(const NamedDecl *D,
// this translation unit. However, we should use the C linkage
// rules instead for extern "C" declarations.
if (Context.getLangOpts().CPlusPlus &&
- !Function->getDeclContext()->isExternCContext() &&
+ !Function->isInExternCContext() &&
Function->getType()->getLinkage() == UniqueExternalLinkage)
return LinkageInfo::uniqueExternal();
@@ -866,10 +874,6 @@ bool NamedDecl::isLinkageValid() const {
Linkage(CachedLinkage);
}
-bool NamedDecl::hasExternalLinkageUncached() const {
- return getLVForDecl(this, LVForExplicitValue).getLinkage() == ExternalLinkage;
-}
-
Linkage NamedDecl::getLinkage() const {
if (HasCachedLinkage)
return Linkage(CachedLinkage);
@@ -993,7 +997,7 @@ static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
LVComputationKind computation) {
if (const FunctionDecl *Function = dyn_cast<FunctionDecl>(D)) {
if (Function->isInAnonymousNamespace() &&
- !Function->getDeclContext()->isExternCContext())
+ !Function->isInExternCContext())
return LinkageInfo::uniqueExternal();
// This is a "void f();" which got merged with a file static.
@@ -1016,8 +1020,7 @@ static LinkageInfo getLVForLocalDecl(const NamedDecl *D,
if (const VarDecl *Var = dyn_cast<VarDecl>(D)) {
if (Var->hasExternalStorage()) {
- if (Var->isInAnonymousNamespace() &&
- !Var->getDeclContext()->isExternCContext())
+ if (Var->isInAnonymousNamespace() && !Var->isInExternCContext())
return LinkageInfo::uniqueExternal();
LinkageInfo LV;
@@ -1297,7 +1300,7 @@ bool NamedDecl::isCXXInstanceMember() const {
if (isa<UsingShadowDecl>(D))
D = cast<UsingShadowDecl>(D)->getTargetDecl();
- if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D))
+ if (isa<FieldDecl>(D) || isa<IndirectFieldDecl>(D) || isa<MSPropertyDecl>(D))
return true;
if (isa<CXXMethodDecl>(D))
return cast<CXXMethodDecl>(D)->isInstance();
@@ -1518,8 +1521,7 @@ static LanguageLinkage getLanguageLinkageTemplate(const T &D) {
// If the first decl is in an extern "C" context, any other redeclaration
// will have C language linkage. If the first one is not in an extern "C"
// context, we would have reported an error for any other decl being in one.
- const T *First = D.getFirstDeclaration();
- if (First->getDeclContext()->isExternCContext())
+ if (isFirstInExternCContext(&D))
return CLanguageLinkage;
return CXXLanguageLinkage;
}
@@ -1545,6 +1547,29 @@ bool VarDecl::isExternC() const {
return isExternCTemplate(*this);
}
+static bool isLinkageSpecContext(const DeclContext *DC,
+ LinkageSpecDecl::LanguageIDs ID) {
+ while (DC->getDeclKind() != Decl::TranslationUnit) {
+ if (DC->getDeclKind() == Decl::LinkageSpec)
+ return cast<LinkageSpecDecl>(DC)->getLanguage() == ID;
+ DC = DC->getParent();
+ }
+ return false;
+}
+
+template <typename T>
+static bool isInLanguageSpecContext(T *D, LinkageSpecDecl::LanguageIDs ID) {
+ return isLinkageSpecContext(D->getLexicalDeclContext(), ID);
+}
+
+bool VarDecl::isInExternCContext() const {
+ return isInLanguageSpecContext(this, LinkageSpecDecl::lang_c);
+}
+
+bool VarDecl::isInExternCXXContext() const {
+ return isInLanguageSpecContext(this, LinkageSpecDecl::lang_cxx);
+}
+
VarDecl *VarDecl::getCanonicalDecl() {
return getFirstDeclaration();
}
@@ -1576,17 +1601,17 @@ VarDecl::DefinitionKind VarDecl::isThisDeclarationADefinition(
// initializer, the declaration is an external definition for the identifier
if (hasInit())
return Definition;
- // AST for 'extern "C" int foo;' is annotated with 'extern'.
+
if (hasExternalStorage())
return DeclarationOnly;
- if (hasExternalStorage()) {
- for (const VarDecl *PrevVar = getPreviousDecl();
- PrevVar; PrevVar = PrevVar->getPreviousDecl()) {
- if (PrevVar->getLinkage() == InternalLinkage)
- return DeclarationOnly;
- }
- }
+ // [dcl.link] p7:
+ // A declaration directly contained in a linkage-specification is treated
+ // as if it contains the extern specifier for the purpose of determining
+ // the linkage of the declared name and whether it is a definition.
+ if (isSingleLineExternC(*this))
+ return DeclarationOnly;
+
// C99 6.9.2p2:
// A declaration of an object that has file scope without an initializer,
// and without a storage class specifier or the scs 'static', constitutes
@@ -1896,6 +1921,11 @@ SourceRange ParmVarDecl::getSourceRange() const {
return SourceRange(getOuterLocStart(), ArgRange.getEnd());
}
+ // DeclaratorDecl considers the range of postfix types as overlapping with the
+ // declaration name, but this is not the case with parameters in ObjC methods.
+ if (isa<ObjCMethodDecl>(getDeclContext()))
+ return SourceRange(DeclaratorDecl::getLocStart(), getLocation());
+
return DeclaratorDecl::getSourceRange();
}
@@ -2061,6 +2091,14 @@ bool FunctionDecl::isExternC() const {
return isExternCTemplate(*this);
}
+bool FunctionDecl::isInExternCContext() const {
+ return isInLanguageSpecContext(this, LinkageSpecDecl::lang_c);
+}
+
+bool FunctionDecl::isInExternCXXContext() const {
+ return isInLanguageSpecContext(this, LinkageSpecDecl::lang_cxx);
+}
+
bool FunctionDecl::isGlobal() const {
if (const CXXMethodDecl *Method = dyn_cast<CXXMethodDecl>(this))
return Method->isStatic();
@@ -3230,6 +3268,27 @@ BlockDecl *BlockDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
return new (Mem) BlockDecl(0, SourceLocation());
}
+MSPropertyDecl *MSPropertyDecl::CreateDeserialized(ASTContext &C,
+ unsigned ID) {
+ void *Mem = AllocateDeserializedDecl(C, ID, sizeof(MSPropertyDecl));
+ return new (Mem) MSPropertyDecl(0, SourceLocation(), DeclarationName(),
+ QualType(), 0, SourceLocation(),
+ 0, 0);
+}
+
+CapturedDecl *CapturedDecl::Create(ASTContext &C, DeclContext *DC,
+ unsigned NumParams) {
+ unsigned Size = sizeof(CapturedDecl) + NumParams * sizeof(ImplicitParamDecl*);
+ return new (C.Allocate(Size)) CapturedDecl(DC, NumParams);
+}
+
+CapturedDecl *CapturedDecl::CreateDeserialized(ASTContext &C, unsigned ID,
+ unsigned NumParams) {
+ unsigned Size = sizeof(CapturedDecl) + NumParams * sizeof(ImplicitParamDecl*);
+ void *Mem = AllocateDeserializedDecl(C, ID, Size);
+ return new (Mem) CapturedDecl(0, NumParams);
+}
+
EnumConstantDecl *EnumConstantDecl::Create(ASTContext &C, EnumDecl *CD,
SourceLocation L,
IdentifierInfo *Id, QualType T,
@@ -3399,7 +3458,7 @@ ImportDecl *ImportDecl::CreateDeserialized(ASTContext &C, unsigned ID,
ArrayRef<SourceLocation> ImportDecl::getIdentifierLocs() const {
if (!ImportedAndComplete.getInt())
- return ArrayRef<SourceLocation>();
+ return None;
const SourceLocation *StoredLocs
= reinterpret_cast<const SourceLocation *>(this + 1);
diff --git a/lib/AST/DeclBase.cpp b/lib/AST/DeclBase.cpp
index bd6d99cd59ea..084a4321d8f1 100644
--- a/lib/AST/DeclBase.cpp
+++ b/lib/AST/DeclBase.cpp
@@ -493,6 +493,7 @@ unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
case NonTypeTemplateParm:
case ObjCMethod:
case ObjCProperty:
+ case MSProperty:
return IDNS_Ordinary;
case Label:
return IDNS_Label;
@@ -552,6 +553,7 @@ unsigned Decl::getIdentifierNamespaceForKind(Kind DeclKind) {
case StaticAssert:
case ObjCPropertyImpl:
case Block:
+ case Captured:
case TranslationUnit:
case UsingDirective:
@@ -702,21 +704,37 @@ void Decl::CheckAccessDeclContext() const {
#endif
}
-DeclContext *Decl::getNonClosureContext() {
- return getDeclContext()->getNonClosureAncestor();
+static Decl::Kind getKind(const Decl *D) { return D->getKind(); }
+static Decl::Kind getKind(const DeclContext *DC) { return DC->getDeclKind(); }
+
+/// Starting at a given context (a Decl or DeclContext), look for a
+/// code context that is not a closure (a lambda, block, etc.).
+template <class T> static Decl *getNonClosureContext(T *D) {
+ if (getKind(D) == Decl::CXXMethod) {
+ CXXMethodDecl *MD = cast<CXXMethodDecl>(D);
+ if (MD->getOverloadedOperator() == OO_Call &&
+ MD->getParent()->isLambda())
+ return getNonClosureContext(MD->getParent()->getParent());
+ return MD;
+ } else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
+ return FD;
+ } else if (ObjCMethodDecl *MD = dyn_cast<ObjCMethodDecl>(D)) {
+ return MD;
+ } else if (BlockDecl *BD = dyn_cast<BlockDecl>(D)) {
+ return getNonClosureContext(BD->getParent());
+ } else if (CapturedDecl *CD = dyn_cast<CapturedDecl>(D)) {
+ return getNonClosureContext(CD->getParent());
+ } else {
+ return 0;
+ }
}
-DeclContext *DeclContext::getNonClosureAncestor() {
- DeclContext *DC = this;
-
- // This is basically "while (DC->isClosure()) DC = DC->getParent();"
- // except that it's significantly more efficient to cast to a known
- // decl type and call getDeclContext() than to call getParent().
- while (isa<BlockDecl>(DC))
- DC = cast<BlockDecl>(DC)->getDeclContext();
+Decl *Decl::getNonClosureContext() {
+ return ::getNonClosureContext(this);
+}
- assert(!DC->isClosure());
- return DC;
+Decl *DeclContext::getNonClosureAncestor() {
+ return ::getNonClosureContext(this);
}
//===----------------------------------------------------------------------===//
@@ -801,28 +819,6 @@ bool DeclContext::isTransparentContext() const {
return false;
}
-bool DeclContext::isExternCContext() const {
- const DeclContext *DC = this;
- while (DC->DeclKind != Decl::TranslationUnit) {
- if (DC->DeclKind == Decl::LinkageSpec)
- return cast<LinkageSpecDecl>(DC)->getLanguage()
- == LinkageSpecDecl::lang_c;
- DC = DC->getParent();
- }
- return false;
-}
-
-bool DeclContext::isExternCXXContext() const {
- const DeclContext *DC = this;
- while (DC->DeclKind != Decl::TranslationUnit) {
- if (DC->DeclKind == Decl::LinkageSpec)
- return cast<LinkageSpecDecl>(DC)->getLanguage()
- == LinkageSpecDecl::lang_cxx;
- DC = DC->getParent();
- }
- return false;
-}
-
bool DeclContext::Encloses(const DeclContext *DC) const {
if (getPrimaryContext() != this)
return getPrimaryContext()->Encloses(DC);
@@ -838,6 +834,7 @@ DeclContext *DeclContext::getPrimaryContext() {
case Decl::TranslationUnit:
case Decl::LinkageSpec:
case Decl::Block:
+ case Decl::Captured:
// There is only one DeclContext for these entities.
return this;
@@ -1045,6 +1042,11 @@ bool DeclContext::decls_empty() const {
return !FirstDecl;
}
+bool DeclContext::containsDecl(Decl *D) const {
+ return (D->getLexicalDeclContext() == this &&
+ (D->NextInContextAndBits.getPointer() || D == LastDecl));
+}
+
void DeclContext::removeDecl(Decl *D) {
assert(D->getLexicalDeclContext() == this &&
"decl being removed from non-lexical context");
diff --git a/lib/AST/DeclCXX.cpp b/lib/AST/DeclCXX.cpp
index ffad9ae93cc8..064649904d30 100644
--- a/lib/AST/DeclCXX.cpp
+++ b/lib/AST/DeclCXX.cpp
@@ -186,7 +186,7 @@ CXXRecordDecl::setBases(CXXBaseSpecifier const * const *Bases,
data().IsStandardLayout = false;
// Record if this base is the first non-literal field or base.
- if (!hasNonLiteralTypeFieldsOrBases() && !BaseType->isLiteralType())
+ if (!hasNonLiteralTypeFieldsOrBases() && !BaseType->isLiteralType(C))
data().HasNonLiteralTypeFieldsOrBases = true;
// Now go through all virtual bases of this base and add them.
@@ -505,7 +505,7 @@ void CXXRecordDecl::addedMember(Decl *D) {
// C++ [dcl.init.aggr]p1:
// An aggregate is an array or a class with no user-declared
// constructors [...].
- // C++0x [dcl.init.aggr]p1:
+ // C++11 [dcl.init.aggr]p1:
// An aggregate is an array or a class with no user-provided
// constructors [...].
if (getASTContext().getLangOpts().CPlusPlus11
@@ -542,22 +542,28 @@ void CXXRecordDecl::addedMember(Decl *D) {
// Keep the list of conversion functions up-to-date.
if (CXXConversionDecl *Conversion = dyn_cast<CXXConversionDecl>(D)) {
- // FIXME: We intentionally don't use the decl's access here because it
- // hasn't been set yet. That's really just a misdesign in Sema.
+ // FIXME: We use the 'unsafe' accessor for the access specifier here,
+ // because Sema may not have set it yet. That's really just a misdesign
+ // in Sema. However, LLDB *will* have set the access specifier correctly,
+ // and adds declarations after the class is technically completed,
+ // so completeDefinition()'s overriding of the access specifiers doesn't
+ // work.
+ AccessSpecifier AS = Conversion->getAccessUnsafe();
+
if (Conversion->getPrimaryTemplate()) {
// We don't record specializations.
} else if (FunTmpl) {
if (FunTmpl->getPreviousDecl())
data().Conversions.replace(FunTmpl->getPreviousDecl(),
- FunTmpl);
+ FunTmpl, AS);
else
- data().Conversions.addDecl(getASTContext(), FunTmpl);
+ data().Conversions.addDecl(getASTContext(), FunTmpl, AS);
} else {
if (Conversion->getPreviousDecl())
data().Conversions.replace(Conversion->getPreviousDecl(),
- Conversion);
+ Conversion, AS);
else
- data().Conversions.addDecl(getASTContext(), Conversion);
+ data().Conversions.addDecl(getASTContext(), Conversion, AS);
}
}
@@ -670,7 +676,7 @@ void CXXRecordDecl::addedMember(Decl *D) {
}
// Record if this field is the first non-literal or volatile field or base.
- if (!T->isLiteralType() || T.isVolatileQualified())
+ if (!T->isLiteralType(Context) || T.isVolatileQualified())
data().HasNonLiteralTypeFieldsOrBases = true;
if (Field->hasInClassInitializer()) {
@@ -684,7 +690,10 @@ void CXXRecordDecl::addedMember(Decl *D) {
// C++11 [dcl.init.aggr]p1:
// An aggregate is a [...] class with [...] no
// brace-or-equal-initializers for non-static data members.
- data().Aggregate = false;
+ //
+ // This rule was removed in C++1y.
+ if (!getASTContext().getLangOpts().CPlusPlus1y)
+ data().Aggregate = false;
// C++11 [class]p10:
// A POD struct is [...] a trivial class.
@@ -836,7 +845,7 @@ void CXXRecordDecl::addedMember(Decl *D) {
}
} else {
// Base element type of field is a non-class type.
- if (!T->isLiteralType() ||
+ if (!T->isLiteralType(Context) ||
(!Field->hasInClassInitializer() && !isUnion()))
data().DefaultedDefaultConstructorIsConstexpr = false;
@@ -1252,20 +1261,7 @@ bool CXXRecordDecl::mayBeAbstract() const {
void CXXMethodDecl::anchor() { }
bool CXXMethodDecl::isStatic() const {
- const CXXMethodDecl *MD = this;
- for (;;) {
- const CXXMethodDecl *C = MD->getCanonicalDecl();
- if (C != MD) {
- MD = C;
- continue;
- }
-
- FunctionTemplateSpecializationInfo *Info =
- MD->getTemplateSpecializationInfo();
- if (!Info)
- break;
- MD = cast<CXXMethodDecl>(Info->getTemplate()->getTemplatedDecl());
- }
+ const CXXMethodDecl *MD = getCanonicalDecl();
if (MD->getStorageClass() == SC_Static)
return true;
@@ -1820,14 +1816,14 @@ LinkageSpecDecl *LinkageSpecDecl::Create(ASTContext &C,
SourceLocation ExternLoc,
SourceLocation LangLoc,
LanguageIDs Lang,
- SourceLocation RBraceLoc) {
- return new (C) LinkageSpecDecl(DC, ExternLoc, LangLoc, Lang, RBraceLoc);
+ bool HasBraces) {
+ return new (C) LinkageSpecDecl(DC, ExternLoc, LangLoc, Lang, HasBraces);
}
LinkageSpecDecl *LinkageSpecDecl::CreateDeserialized(ASTContext &C, unsigned ID) {
void *Mem = AllocateDeserializedDecl(C, ID, sizeof(LinkageSpecDecl));
return new (Mem) LinkageSpecDecl(0, SourceLocation(), SourceLocation(),
- lang_c, SourceLocation());
+ lang_c, false);
}
void UsingDirectiveDecl::anchor() { }
diff --git a/lib/AST/DeclObjC.cpp b/lib/AST/DeclObjC.cpp
index 5f5ba52947d6..4ddbb22199b2 100644
--- a/lib/AST/DeclObjC.cpp
+++ b/lib/AST/DeclObjC.cpp
@@ -443,9 +443,12 @@ ObjCInterfaceDecl *ObjCInterfaceDecl::lookupInheritedClass(
/// lookupMethod - This method returns an instance/class method by looking in
/// the class, its categories, and its super classes (using a linear search).
+/// When argument category "C" is specified, any implicit method found
+/// in this category is ignored.
ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel,
bool isInstance,
- bool shallowCategoryLookup) const {
+ bool shallowCategoryLookup,
+ const ObjCCategoryDecl *C) const {
// FIXME: Should make sure no callers ever do this.
if (!hasDefinition())
return 0;
@@ -469,20 +472,22 @@ ObjCMethodDecl *ObjCInterfaceDecl::lookupMethod(Selector Sel,
// Didn't find one yet - now look through categories.
for (ObjCInterfaceDecl::visible_categories_iterator
- Cat = ClassDecl->visible_categories_begin(),
- CatEnd = ClassDecl->visible_categories_end();
+ Cat = ClassDecl->visible_categories_begin(),
+ CatEnd = ClassDecl->visible_categories_end();
Cat != CatEnd; ++Cat) {
if ((MethodDecl = Cat->getMethod(Sel, isInstance)))
- return MethodDecl;
+ if (C != (*Cat) || !MethodDecl->isImplicit())
+ return MethodDecl;
if (!shallowCategoryLookup) {
// Didn't find one yet - look through protocols.
const ObjCList<ObjCProtocolDecl> &Protocols =
- Cat->getReferencedProtocols();
+ Cat->getReferencedProtocols();
for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
E = Protocols.end(); I != E; ++I)
if ((MethodDecl = (*I)->lookupMethod(Sel, isInstance)))
- return MethodDecl;
+ if (C != (*Cat) || !MethodDecl->isImplicit())
+ return MethodDecl;
}
}
@@ -599,12 +604,12 @@ void ObjCMethodDecl::setMethodParams(ASTContext &C,
assert((!SelLocs.empty() || isImplicit()) &&
"No selector locs for non-implicit method");
if (isImplicit())
- return setParamsAndSelLocs(C, Params, ArrayRef<SourceLocation>());
+ return setParamsAndSelLocs(C, Params, llvm::None);
SelLocsKind = hasStandardSelectorLocs(getSelector(), SelLocs, Params,
DeclEndLoc);
if (SelLocsKind != SelLoc_NonStandard)
- return setParamsAndSelLocs(C, Params, ArrayRef<SourceLocation>());
+ return setParamsAndSelLocs(C, Params, llvm::None);
setParamsAndSelLocs(C, Params, SelLocs);
}
@@ -959,52 +964,6 @@ static void collectOverriddenMethodsSlow(const ObjCMethodDecl *Method,
}
}
-static void collectOnCategoriesAfterLocation(SourceLocation Loc,
- const ObjCInterfaceDecl *Class,
- SourceManager &SM,
- const ObjCMethodDecl *Method,
- SmallVectorImpl<const ObjCMethodDecl *> &Methods) {
- if (!Class)
- return;
-
- for (ObjCInterfaceDecl::known_categories_iterator
- Cat = Class->known_categories_begin(),
- CatEnd = Class->known_categories_end();
- Cat != CatEnd; ++Cat) {
- if (SM.isBeforeInTranslationUnit(Loc, Cat->getLocation()))
- CollectOverriddenMethodsRecurse(*Cat, Method, Methods, true);
- }
-
- collectOnCategoriesAfterLocation(Loc, Class->getSuperClass(), SM,
- Method, Methods);
-}
-
-/// \brief Faster collection that is enabled when ObjCMethodDecl::isOverriding()
-/// returns false.
-/// You'd think that in that case there are no overrides but categories can
-/// "introduce" new overridden methods that are missed by Sema because the
-/// overrides lookup that it does for methods, inside implementations, will
-/// stop at the interface level (if there is a method there) and not look
-/// further in super classes.
-/// Methods in an implementation can overide methods in super class's category
-/// but not in current class's category. But, such methods
-static void collectOverriddenMethodsFast(SourceManager &SM,
- const ObjCMethodDecl *Method,
- SmallVectorImpl<const ObjCMethodDecl *> &Methods) {
- assert(!Method->isOverriding());
-
- const ObjCContainerDecl *
- ContD = cast<ObjCContainerDecl>(Method->getDeclContext());
- if (isa<ObjCInterfaceDecl>(ContD) || isa<ObjCProtocolDecl>(ContD))
- return;
- const ObjCInterfaceDecl *Class = Method->getClassInterface();
- if (!Class)
- return;
-
- collectOnCategoriesAfterLocation(Class->getLocation(), Class->getSuperClass(),
- SM, Method, Methods);
-}
-
void ObjCMethodDecl::getOverriddenMethods(
SmallVectorImpl<const ObjCMethodDecl *> &Overridden) const {
const ObjCMethodDecl *Method = this;
@@ -1014,10 +973,7 @@ void ObjCMethodDecl::getOverriddenMethods(
getMethod(Method->getSelector(), Method->isInstanceMethod());
}
- if (!Method->isOverriding()) {
- collectOverriddenMethodsFast(getASTContext().getSourceManager(),
- Method, Overridden);
- } else {
+ if (Method->isOverriding()) {
collectOverriddenMethodsSlow(Method, Overridden);
assert(!Overridden.empty() &&
"ObjCMethodDecl's overriding bit is not as expected");
@@ -1692,12 +1648,13 @@ ObjCImplementationDecl::Create(ASTContext &C, DeclContext *DC,
ObjCInterfaceDecl *SuperDecl,
SourceLocation nameLoc,
SourceLocation atStartLoc,
+ SourceLocation superLoc,
SourceLocation IvarLBraceLoc,
SourceLocation IvarRBraceLoc) {
if (ClassInterface && ClassInterface->hasDefinition())
ClassInterface = ClassInterface->getDefinition();
return new (C) ObjCImplementationDecl(DC, ClassInterface, SuperDecl,
- nameLoc, atStartLoc,
+ nameLoc, atStartLoc, superLoc,
IvarLBraceLoc, IvarRBraceLoc);
}
diff --git a/lib/AST/DeclPrinter.cpp b/lib/AST/DeclPrinter.cpp
index c3bf8f89b297..d47972bc6130 100644
--- a/lib/AST/DeclPrinter.cpp
+++ b/lib/AST/DeclPrinter.cpp
@@ -487,7 +487,7 @@ void DeclPrinter::VisitFunctionDecl(FunctionDecl *D) {
for (CXXConstructorDecl::init_const_iterator B = CDecl->init_begin(),
E = CDecl->init_end();
B != E; ++B) {
- CXXCtorInitializer * BMInitializer = (*B);
+ CXXCtorInitializer *BMInitializer = (*B);
if (BMInitializer->isInClassMemberInitializer())
continue;
@@ -617,7 +617,8 @@ void DeclPrinter::VisitFieldDecl(FieldDecl *D) {
if (!Policy.SuppressSpecifiers && D->isModulePrivate())
Out << "__module_private__ ";
- Out << D->getType().stream(Policy, D->getName());
+ Out << D->getASTContext().getUnqualifiedObjCPointerType(D->getType()).
+ stream(Policy, D->getName());
if (D->isBitField()) {
Out << " : ";
@@ -641,16 +642,30 @@ void DeclPrinter::VisitLabelDecl(LabelDecl *D) {
void DeclPrinter::VisitVarDecl(VarDecl *D) {
- StorageClass SC = D->getStorageClass();
- if (!Policy.SuppressSpecifiers && SC != SC_None)
- Out << VarDecl::getStorageClassSpecifierString(SC) << " ";
+ if (!Policy.SuppressSpecifiers) {
+ StorageClass SC = D->getStorageClass();
+ if (SC != SC_None)
+ Out << VarDecl::getStorageClassSpecifierString(SC) << " ";
- if (!Policy.SuppressSpecifiers && D->isThreadSpecified())
- Out << "__thread ";
- if (!Policy.SuppressSpecifiers && D->isModulePrivate())
- Out << "__module_private__ ";
+ switch (D->getTSCSpec()) {
+ case TSCS_unspecified:
+ break;
+ case TSCS___thread:
+ Out << "__thread ";
+ break;
+ case TSCS__Thread_local:
+ Out << "_Thread_local ";
+ break;
+ case TSCS_thread_local:
+ Out << "thread_local ";
+ break;
+ }
+
+ if (D->isModulePrivate())
+ Out << "__module_private__ ";
+ }
- QualType T = D->getType();
+ QualType T = D->getASTContext().getUnqualifiedObjCPointerType(D->getType());
if (ParmVarDecl *Parm = dyn_cast<ParmVarDecl>(D))
T = Parm->getOriginalType();
T.print(Out, Policy, D->getName());
@@ -899,7 +914,8 @@ void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) {
else
Out << "+ ";
if (!OMD->getResultType().isNull())
- Out << '(' << OMD->getResultType().getAsString(Policy) << ")";
+ Out << '(' << OMD->getASTContext().getUnqualifiedObjCPointerType(OMD->getResultType()).
+ getAsString(Policy) << ")";
std::string name = OMD->getSelector().getAsString();
std::string::size_type pos, lastPos = 0;
@@ -908,7 +924,8 @@ void DeclPrinter::VisitObjCMethodDecl(ObjCMethodDecl *OMD) {
// FIXME: selector is missing here!
pos = name.find_first_of(':', lastPos);
Out << " " << name.substr(lastPos, pos - lastPos);
- Out << ":(" << (*PI)->getType().getAsString(Policy) << ')' << **PI;
+ Out << ":(" << (*PI)->getASTContext().getUnqualifiedObjCPointerType((*PI)->getType()).
+ getAsString(Policy) << ')' << **PI;
lastPos = pos + 1;
}
@@ -941,7 +958,8 @@ void DeclPrinter::VisitObjCImplementationDecl(ObjCImplementationDecl *OID) {
Indentation += Policy.Indentation;
for (ObjCImplementationDecl::ivar_iterator I = OID->ivar_begin(),
E = OID->ivar_end(); I != E; ++I) {
- Indent() << I->getType().getAsString(Policy) << ' ' << **I << ";\n";
+ Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
+ getAsString(Policy) << ' ' << **I << ";\n";
}
Indentation -= Policy.Indentation;
Out << "}\n";
@@ -979,7 +997,8 @@ void DeclPrinter::VisitObjCInterfaceDecl(ObjCInterfaceDecl *OID) {
Indentation += Policy.Indentation;
for (ObjCInterfaceDecl::ivar_iterator I = OID->ivar_begin(),
E = OID->ivar_end(); I != E; ++I) {
- Indent() << I->getType().getAsString(Policy) << ' ' << **I << ";\n";
+ Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
+ getAsString(Policy) << ' ' << **I << ";\n";
}
Indentation -= Policy.Indentation;
Out << "}\n";
@@ -1030,7 +1049,8 @@ void DeclPrinter::VisitObjCCategoryDecl(ObjCCategoryDecl *PID) {
Indentation += Policy.Indentation;
for (ObjCCategoryDecl::ivar_iterator I = PID->ivar_begin(),
E = PID->ivar_end(); I != E; ++I) {
- Indent() << I->getType().getAsString(Policy) << ' ' << **I << ";\n";
+ Indent() << I->getASTContext().getUnqualifiedObjCPointerType(I->getType()).
+ getAsString(Policy) << ' ' << **I << ";\n";
}
Indentation -= Policy.Indentation;
Out << "}\n";
@@ -1116,7 +1136,8 @@ void DeclPrinter::VisitObjCPropertyDecl(ObjCPropertyDecl *PDecl) {
(void) first; // Silence dead store warning due to idiomatic code.
Out << " )";
}
- Out << ' ' << PDecl->getType().getAsString(Policy) << ' ' << *PDecl;
+ Out << ' ' << PDecl->getASTContext().getUnqualifiedObjCPointerType(PDecl->getType()).
+ getAsString(Policy) << ' ' << *PDecl;
if (Policy.PolishForDeclaration)
Out << ';';
}
diff --git a/lib/AST/Expr.cpp b/lib/AST/Expr.cpp
index b97f4d1d3a9a..9538ddf9416c 100644
--- a/lib/AST/Expr.cpp
+++ b/lib/AST/Expr.cpp
@@ -100,11 +100,20 @@ Expr::skipRValueSubobjectAdjustments(
const Expr *
Expr::findMaterializedTemporary(const MaterializeTemporaryExpr *&MTE) const {
const Expr *E = this;
+
+ // This might be a default initializer for a reference member. Walk over the
+ // wrapper node for that.
+ if (const CXXDefaultInitExpr *DAE = dyn_cast<CXXDefaultInitExpr>(E))
+ E = DAE->getExpr();
+
// Look through single-element init lists that claim to be lvalues. They're
// just syntactic wrappers in this case.
if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E)) {
- if (ILE->getNumInits() == 1 && ILE->isGLValue())
+ if (ILE->getNumInits() == 1 && ILE->isGLValue()) {
E = ILE->getInit(0);
+ if (const CXXDefaultInitExpr *DAE = dyn_cast<CXXDefaultInitExpr>(E))
+ E = DAE->getExpr();
+ }
}
// Look through expressions for materialized temporaries (for now).
@@ -280,7 +289,7 @@ static void computeDeclRefDependence(ASTContext &Ctx, NamedDecl *D, QualType T,
// expression that is value-dependent [C++11]
if (VarDecl *Var = dyn_cast<VarDecl>(D)) {
if ((Ctx.getLangOpts().CPlusPlus11 ?
- Var->getType()->isLiteralType() :
+ Var->getType()->isLiteralType(Ctx) :
Var->getType()->isIntegralOrEnumerationType()) &&
(Var->getType().isConstQualified() ||
Var->getType()->isReferenceType())) {
@@ -2174,6 +2183,9 @@ bool Expr::isUnusedResultAWarning(const Expr *&WarnE, SourceLocation &Loc,
case CXXDefaultArgExprClass:
return (cast<CXXDefaultArgExpr>(this)
->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
+ case CXXDefaultInitExprClass:
+ return (cast<CXXDefaultInitExpr>(this)
+ ->getExpr()->isUnusedResultAWarning(WarnE, Loc, R1, R2, Ctx));
case CXXNewExprClass:
// FIXME: In theory, there might be new expressions that don't have side
@@ -2789,6 +2801,7 @@ bool Expr::HasSideEffects(const ASTContext &Ctx) const {
return false;
case CallExprClass:
+ case MSPropertyRefExprClass:
case CompoundAssignOperatorClass:
case VAArgExprClass:
case AtomicExprClass:
@@ -2850,6 +2863,12 @@ bool Expr::HasSideEffects(const ASTContext &Ctx) const {
case CXXDefaultArgExprClass:
return cast<CXXDefaultArgExpr>(this)->getExpr()->HasSideEffects(Ctx);
+ case CXXDefaultInitExprClass:
+ if (const Expr *E = cast<CXXDefaultInitExpr>(this)->getExpr())
+ return E->HasSideEffects(Ctx);
+ // If we've not yet parsed the initializer, assume it has side-effects.
+ return true;
+
case CXXDynamicCastExprClass: {
// A dynamic_cast expression has side-effects if it can throw.
const CXXDynamicCastExpr *DCE = cast<CXXDynamicCastExpr>(this);
@@ -3037,8 +3056,12 @@ Expr::isNullPointerConstant(ASTContext &Ctx,
return GE->getResultExpr()->isNullPointerConstant(Ctx, NPC);
} else if (const CXXDefaultArgExpr *DefaultArg
= dyn_cast<CXXDefaultArgExpr>(this)) {
- // See through default argument expressions
+ // See through default argument expressions.
return DefaultArg->getExpr()->isNullPointerConstant(Ctx, NPC);
+ } else if (const CXXDefaultInitExpr *DefaultInit
+ = dyn_cast<CXXDefaultInitExpr>(this)) {
+ // See through default initializer expressions.
+ return DefaultInit->getExpr()->isNullPointerConstant(Ctx, NPC);
} else if (isa<GNUNullExpr>(this)) {
// The GNU __null extension is always a null pointer constant.
return NPCK_GNUNull;
@@ -3126,7 +3149,7 @@ bool Expr::isObjCSelfExpr() const {
return M->getSelfDecl() == Param;
}
-FieldDecl *Expr::getBitField() {
+FieldDecl *Expr::getSourceBitField() {
Expr *E = this->IgnoreParens();
while (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(E)) {
@@ -3142,6 +3165,11 @@ FieldDecl *Expr::getBitField() {
if (Field->isBitField())
return Field;
+ if (ObjCIvarRefExpr *IvarRef = dyn_cast<ObjCIvarRefExpr>(E))
+ if (FieldDecl *Ivar = dyn_cast<FieldDecl>(IvarRef->getDecl()))
+ if (Ivar->isBitField())
+ return Ivar;
+
if (DeclRefExpr *DeclRef = dyn_cast<DeclRefExpr>(E))
if (FieldDecl *Field = dyn_cast<FieldDecl>(DeclRef->getDecl()))
if (Field->isBitField())
@@ -3149,10 +3177,10 @@ FieldDecl *Expr::getBitField() {
if (BinaryOperator *BinOp = dyn_cast<BinaryOperator>(E)) {
if (BinOp->isAssignmentOp() && BinOp->getLHS())
- return BinOp->getLHS()->getBitField();
+ return BinOp->getLHS()->getSourceBitField();
if (BinOp->getOpcode() == BO_Comma && BinOp->getRHS())
- return BinOp->getRHS()->getBitField();
+ return BinOp->getRHS()->getSourceBitField();
}
return 0;
diff --git a/lib/AST/ExprCXX.cpp b/lib/AST/ExprCXX.cpp
index 12a47fcd7829..402d7b532b21 100644
--- a/lib/AST/ExprCXX.cpp
+++ b/lib/AST/ExprCXX.cpp
@@ -178,8 +178,7 @@ CXXPseudoDestructorExpr::CXXPseudoDestructorExpr(ASTContext &Context,
SourceLocation ColonColonLoc, SourceLocation TildeLoc,
PseudoDestructorTypeStorage DestroyedType)
: Expr(CXXPseudoDestructorExprClass,
- Context.getPointerType(Context.getFunctionType(Context.VoidTy,
- ArrayRef<QualType>(),
+ Context.getPointerType(Context.getFunctionType(Context.VoidTy, None,
FunctionProtoType::ExtProtoInfo())),
VK_RValue, OK_Ordinary,
/*isTypeDependent=*/(Base->isTypeDependent() ||
@@ -704,6 +703,17 @@ CXXDefaultArgExpr::Create(ASTContext &C, SourceLocation Loc,
SubExpr);
}
+CXXDefaultInitExpr::CXXDefaultInitExpr(ASTContext &C, SourceLocation Loc,
+ FieldDecl *Field, QualType T)
+ : Expr(CXXDefaultInitExprClass, T.getNonLValueExprType(C),
+ T->isLValueReferenceType() ? VK_LValue : T->isRValueReferenceType()
+ ? VK_XValue
+ : VK_RValue,
+ /*FIXME*/ OK_Ordinary, false, false, false, false),
+ Field(Field), Loc(Loc) {
+ assert(Field->hasInClassInitializer());
+}
+
CXXTemporary *CXXTemporary::Create(ASTContext &C,
const CXXDestructorDecl *Destructor) {
return new (C) CXXTemporary(Destructor);
diff --git a/lib/AST/ExprClassification.cpp b/lib/AST/ExprClassification.cpp
index 61bc3e2de5ce..bcb6d4e809bf 100644
--- a/lib/AST/ExprClassification.cpp
+++ b/lib/AST/ExprClassification.cpp
@@ -134,6 +134,7 @@ static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E) {
// FIXME: ObjC++0x might have different rules
case Expr::ObjCIvarRefExprClass:
case Expr::FunctionParmPackExprClass:
+ case Expr::MSPropertyRefExprClass:
return Cl::CL_LValue;
// C99 6.5.2.5p5 says that compound literals are lvalues.
@@ -297,6 +298,10 @@ static Cl::Kinds ClassifyInternal(ASTContext &Ctx, const Expr *E) {
case Expr::CXXDefaultArgExprClass:
return ClassifyInternal(Ctx, cast<CXXDefaultArgExpr>(E)->getExpr());
+ // Same idea for default initializers.
+ case Expr::CXXDefaultInitExprClass:
+ return ClassifyInternal(Ctx, cast<CXXDefaultInitExpr>(E)->getExpr());
+
// Same idea for temporary binding.
case Expr::CXXBindTemporaryExprClass:
return ClassifyInternal(Ctx, cast<CXXBindTemporaryExpr>(E)->getSubExpr());
diff --git a/lib/AST/ExprConstant.cpp b/lib/AST/ExprConstant.cpp
index ae86150ee2a4..8c650290b579 100644
--- a/lib/AST/ExprConstant.cpp
+++ b/lib/AST/ExprConstant.cpp
@@ -286,21 +286,37 @@ namespace {
/// ParmBindings - Parameter bindings for this function call, indexed by
/// parameters' function scope indices.
- const APValue *Arguments;
+ APValue *Arguments;
// Note that we intentionally use std::map here so that references to
// values are stable.
- typedef std::map<const Expr*, APValue> MapTy;
+ typedef std::map<const void*, APValue> MapTy;
typedef MapTy::const_iterator temp_iterator;
/// Temporaries - Temporary lvalues materialized within this stack frame.
MapTy Temporaries;
CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
const FunctionDecl *Callee, const LValue *This,
- const APValue *Arguments);
+ APValue *Arguments);
~CallStackFrame();
};
+ /// Temporarily override 'this'.
+ class ThisOverrideRAII {
+ public:
+ ThisOverrideRAII(CallStackFrame &Frame, const LValue *NewThis, bool Enable)
+ : Frame(Frame), OldThis(Frame.This) {
+ if (Enable)
+ Frame.This = NewThis;
+ }
+ ~ThisOverrideRAII() {
+ Frame.This = OldThis;
+ }
+ private:
+ CallStackFrame &Frame;
+ const LValue *OldThis;
+ };
+
/// A partial diagnostic which we might know in advance that we are not going
/// to emit.
class OptionalDiagnostic {
@@ -581,7 +597,7 @@ void SubobjectDesignator::diagnosePointerArithmetic(EvalInfo &Info,
CallStackFrame::CallStackFrame(EvalInfo &Info, SourceLocation CallLoc,
const FunctionDecl *Callee, const LValue *This,
- const APValue *Arguments)
+ APValue *Arguments)
: Info(Info), Caller(Info.CurrentCall), CallLoc(CallLoc), Callee(Callee),
Index(Info.NextCallIndex++), This(This), Arguments(Arguments) {
Info.CurrentCall = this;
@@ -897,6 +913,18 @@ static bool EvaluateComplex(const Expr *E, ComplexValue &Res, EvalInfo &Info);
// Misc utilities
//===----------------------------------------------------------------------===//
+/// Evaluate an expression to see if it had side-effects, and discard its
+/// result.
+/// \return \c true if the caller should keep evaluating.
+static bool EvaluateIgnoredValue(EvalInfo &Info, const Expr *E) {
+ APValue Scratch;
+ if (!Evaluate(Scratch, Info, E)) {
+ Info.EvalStatus.HasSideEffects = true;
+ return Info.keepEvaluatingAfterFailure();
+ }
+ return true;
+}
+
/// Should this call expression be treated as a string literal?
static bool IsStringLiteralCall(const CallExpr *E) {
unsigned Builtin = E->isBuiltinCall();
@@ -999,7 +1027,7 @@ static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
// Check if this is a thread-local variable.
if (const ValueDecl *VD = Base.dyn_cast<const ValueDecl*>()) {
if (const VarDecl *Var = dyn_cast<const VarDecl>(VD)) {
- if (Var->isThreadSpecified())
+ if (Var->getTLSKind())
return false;
}
}
@@ -1030,7 +1058,7 @@ static bool CheckLValueConstantExpression(EvalInfo &Info, SourceLocation Loc,
/// Check that this core constant expression is of literal type, and if not,
/// produce an appropriate diagnostic.
static bool CheckLiteralType(EvalInfo &Info, const Expr *E) {
- if (!E->isRValue() || E->getType()->isLiteralType())
+ if (!E->isRValue() || E->getType()->isLiteralType(Info.Ctx))
return true;
// Prvalue constant expressions must be of literal types.
@@ -1427,9 +1455,16 @@ static bool HandleLValueComplexElement(EvalInfo &Info, const Expr *E,
}
/// Try to evaluate the initializer for a variable declaration.
-static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
- const VarDecl *VD,
- CallStackFrame *Frame, APValue &Result) {
+///
+/// \param Info Information about the ongoing evaluation.
+/// \param E An expression to be used when printing diagnostics.
+/// \param VD The variable whose initializer should be obtained.
+/// \param Frame The frame in which the variable was created. Must be null
+/// if this variable is not local to the evaluation.
+/// \param Result Filled in with a pointer to the value of the variable.
+static bool evaluateVarDeclInit(EvalInfo &Info, const Expr *E,
+ const VarDecl *VD, CallStackFrame *Frame,
+ APValue *&Result) {
// If this is a parameter to an active constexpr function call, perform
// argument substitution.
if (const ParmVarDecl *PVD = dyn_cast<ParmVarDecl>(VD)) {
@@ -1441,10 +1476,19 @@ static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
return false;
}
- Result = Frame->Arguments[PVD->getFunctionScopeIndex()];
+ Result = &Frame->Arguments[PVD->getFunctionScopeIndex()];
return true;
}
+ // If this is a local variable, dig out its value.
+ if (Frame) {
+ Result = &Frame->Temporaries[VD];
+ // If we've carried on past an unevaluatable local variable initializer,
+ // we can't go any further. This can happen during potential constant
+ // expression checking.
+ return !Result->isUninit();
+ }
+
// Dig out the initializer, and use the declaration which it's attached to.
const Expr *Init = VD->getAnyInitializer(VD);
if (!Init || Init->isValueDependent()) {
@@ -1458,8 +1502,8 @@ static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
// If we're currently evaluating the initializer of this declaration, use that
// in-flight value.
if (Info.EvaluatingDecl == VD) {
- Result = *Info.EvaluatingDeclValue;
- return !Result.isUninit();
+ Result = Info.EvaluatingDeclValue;
+ return !Result->isUninit();
}
// Never evaluate the initializer of a weak variable. We can't be sure that
@@ -1485,7 +1529,7 @@ static bool EvaluateVarDeclInit(EvalInfo &Info, const Expr *E,
Info.addNotes(Notes);
}
- Result = *VD->getEvaluatedValue();
+ Result = VD->getEvaluatedValue();
return true;
}
@@ -1509,15 +1553,15 @@ static unsigned getBaseIndex(const CXXRecordDecl *Derived,
llvm_unreachable("base class missing from derived class's bases list");
}
-/// Extract the value of a character from a string literal. CharType is used to
-/// determine the expected signedness of the result -- a string literal used to
-/// initialize an array of 'signed char' or 'unsigned char' might contain chars
-/// of the wrong signedness.
-static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
- uint64_t Index, QualType CharType) {
+/// Extract the value of a character from a string literal.
+static APSInt extractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
+ uint64_t Index) {
// FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
- const StringLiteral *S = dyn_cast<StringLiteral>(Lit);
- assert(S && "unexpected string literal expression kind");
+ const StringLiteral *S = cast<StringLiteral>(Lit);
+ const ConstantArrayType *CAT =
+ Info.Ctx.getAsConstantArrayType(S->getType());
+ assert(CAT && "string literal isn't an array");
+ QualType CharType = CAT->getElementType();
assert(CharType->isIntegerType() && "unexpected character type");
APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
@@ -1527,26 +1571,99 @@ static APSInt ExtractStringLiteralCharacter(EvalInfo &Info, const Expr *Lit,
return Value;
}
-/// Extract the designated sub-object of an rvalue.
-static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
- APValue &Obj, QualType ObjType,
- const SubobjectDesignator &Sub, QualType SubType) {
+// Expand a string literal into an array of characters.
+static void expandStringLiteral(EvalInfo &Info, const Expr *Lit,
+ APValue &Result) {
+ const StringLiteral *S = cast<StringLiteral>(Lit);
+ const ConstantArrayType *CAT =
+ Info.Ctx.getAsConstantArrayType(S->getType());
+ assert(CAT && "string literal isn't an array");
+ QualType CharType = CAT->getElementType();
+ assert(CharType->isIntegerType() && "unexpected character type");
+
+ unsigned Elts = CAT->getSize().getZExtValue();
+ Result = APValue(APValue::UninitArray(),
+ std::min(S->getLength(), Elts), Elts);
+ APSInt Value(S->getCharByteWidth() * Info.Ctx.getCharWidth(),
+ CharType->isUnsignedIntegerType());
+ if (Result.hasArrayFiller())
+ Result.getArrayFiller() = APValue(Value);
+ for (unsigned I = 0, N = Result.getArrayInitializedElts(); I != N; ++I) {
+ Value = S->getCodeUnit(I);
+ Result.getArrayInitializedElt(I) = APValue(Value);
+ }
+}
+
+// Expand an array so that it has more than Index filled elements.
+static void expandArray(APValue &Array, unsigned Index) {
+ unsigned Size = Array.getArraySize();
+ assert(Index < Size);
+
+ // Always at least double the number of elements for which we store a value.
+ unsigned OldElts = Array.getArrayInitializedElts();
+ unsigned NewElts = std::max(Index+1, OldElts * 2);
+ NewElts = std::min(Size, std::max(NewElts, 8u));
+
+ // Copy the data across.
+ APValue NewValue(APValue::UninitArray(), NewElts, Size);
+ for (unsigned I = 0; I != OldElts; ++I)
+ NewValue.getArrayInitializedElt(I).swap(Array.getArrayInitializedElt(I));
+ for (unsigned I = OldElts; I != NewElts; ++I)
+ NewValue.getArrayInitializedElt(I) = Array.getArrayFiller();
+ if (NewValue.hasArrayFiller())
+ NewValue.getArrayFiller() = Array.getArrayFiller();
+ Array.swap(NewValue);
+}
+
+/// Kinds of access we can perform on an object.
+enum AccessKinds {
+ AK_Read,
+ AK_Assign,
+ AK_Increment,
+ AK_Decrement
+};
+
+/// A handle to a complete object (an object that is not a subobject of
+/// another object).
+struct CompleteObject {
+ /// The value of the complete object.
+ APValue *Value;
+ /// The type of the complete object.
+ QualType Type;
+
+ CompleteObject() : Value(0) {}
+ CompleteObject(APValue *Value, QualType Type)
+ : Value(Value), Type(Type) {
+ assert(Value && "missing value for complete object");
+ }
+
+ operator bool() const { return Value; }
+};
+
+/// Find the designated sub-object of an rvalue.
+template<typename SubobjectHandler>
+typename SubobjectHandler::result_type
+findSubobject(EvalInfo &Info, const Expr *E, const CompleteObject &Obj,
+ const SubobjectDesignator &Sub, SubobjectHandler &handler) {
if (Sub.Invalid)
// A diagnostic will have already been produced.
- return false;
+ return handler.failed();
if (Sub.isOnePastTheEnd()) {
- Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
- (unsigned)diag::note_constexpr_read_past_end :
- (unsigned)diag::note_invalid_subexpr_in_const_expr);
- return false;
+ if (Info.getLangOpts().CPlusPlus11)
+ Info.Diag(E, diag::note_constexpr_access_past_end)
+ << handler.AccessKind;
+ else
+ Info.Diag(E);
+ return handler.failed();
}
if (Sub.Entries.empty())
- return true;
- if (Info.CheckingPotentialConstantExpression && Obj.isUninit())
+ return handler.found(*Obj.Value, Obj.Type);
+ if (Info.CheckingPotentialConstantExpression && Obj.Value->isUninit())
// This object might be initialized later.
- return false;
+ return handler.failed();
- APValue *O = &Obj;
+ APValue *O = Obj.Value;
+ QualType ObjType = Obj.Type;
// Walk the designator's path to find the subobject.
for (unsigned I = 0, N = Sub.Entries.size(); I != N; ++I) {
if (ObjType->isArrayType()) {
@@ -1557,49 +1674,67 @@ static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
if (CAT->getSize().ule(Index)) {
// Note, it should not be possible to form a pointer with a valid
// designator which points more than one past the end of the array.
- Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
- (unsigned)diag::note_constexpr_read_past_end :
- (unsigned)diag::note_invalid_subexpr_in_const_expr);
- return false;
+ if (Info.getLangOpts().CPlusPlus11)
+ Info.Diag(E, diag::note_constexpr_access_past_end)
+ << handler.AccessKind;
+ else
+ Info.Diag(E);
+ return handler.failed();
}
+
+ ObjType = CAT->getElementType();
+
// An array object is represented as either an Array APValue or as an
// LValue which refers to a string literal.
if (O->isLValue()) {
assert(I == N - 1 && "extracting subobject of character?");
assert(!O->hasLValuePath() || O->getLValuePath().empty());
- Obj = APValue(ExtractStringLiteralCharacter(
- Info, O->getLValueBase().get<const Expr*>(), Index, SubType));
- return true;
- } else if (O->getArrayInitializedElts() > Index)
+ if (handler.AccessKind != AK_Read)
+ expandStringLiteral(Info, O->getLValueBase().get<const Expr *>(),
+ *O);
+ else
+ return handler.foundString(*O, ObjType, Index);
+ }
+
+ if (O->getArrayInitializedElts() > Index)
O = &O->getArrayInitializedElt(Index);
- else
+ else if (handler.AccessKind != AK_Read) {
+ expandArray(*O, Index);
+ O = &O->getArrayInitializedElt(Index);
+ } else
O = &O->getArrayFiller();
- ObjType = CAT->getElementType();
} else if (ObjType->isAnyComplexType()) {
// Next subobject is a complex number.
uint64_t Index = Sub.Entries[I].ArrayIndex;
if (Index > 1) {
- Info.Diag(E, Info.getLangOpts().CPlusPlus11 ?
- (unsigned)diag::note_constexpr_read_past_end :
- (unsigned)diag::note_invalid_subexpr_in_const_expr);
- return false;
+ if (Info.getLangOpts().CPlusPlus11)
+ Info.Diag(E, diag::note_constexpr_access_past_end)
+ << handler.AccessKind;
+ else
+ Info.Diag(E);
+ return handler.failed();
}
+
+ bool WasConstQualified = ObjType.isConstQualified();
+ ObjType = ObjType->castAs<ComplexType>()->getElementType();
+ if (WasConstQualified)
+ ObjType.addConst();
+
assert(I == N - 1 && "extracting subobject of scalar?");
if (O->isComplexInt()) {
- Obj = APValue(Index ? O->getComplexIntImag()
- : O->getComplexIntReal());
+ return handler.found(Index ? O->getComplexIntImag()
+ : O->getComplexIntReal(), ObjType);
} else {
assert(O->isComplexFloat());
- Obj = APValue(Index ? O->getComplexFloatImag()
- : O->getComplexFloatReal());
+ return handler.found(Index ? O->getComplexFloatImag()
+ : O->getComplexFloatReal(), ObjType);
}
- return true;
} else if (const FieldDecl *Field = getAsField(Sub.Entries[I])) {
- if (Field->isMutable()) {
+ if (Field->isMutable() && handler.AccessKind == AK_Read) {
Info.Diag(E, diag::note_constexpr_ltor_mutable, 1)
<< Field;
Info.Note(Field->getLocation(), diag::note_declared_at);
- return false;
+ return handler.failed();
}
// Next subobject is a class, struct or union field.
@@ -1608,49 +1743,150 @@ static bool ExtractSubobject(EvalInfo &Info, const Expr *E,
const FieldDecl *UnionField = O->getUnionField();
if (!UnionField ||
UnionField->getCanonicalDecl() != Field->getCanonicalDecl()) {
- Info.Diag(E, diag::note_constexpr_read_inactive_union_member)
- << Field << !UnionField << UnionField;
- return false;
+ Info.Diag(E, diag::note_constexpr_access_inactive_union_member)
+ << handler.AccessKind << Field << !UnionField << UnionField;
+ return handler.failed();
}
O = &O->getUnionValue();
} else
O = &O->getStructField(Field->getFieldIndex());
+
+ bool WasConstQualified = ObjType.isConstQualified();
ObjType = Field->getType();
+ if (WasConstQualified && !Field->isMutable())
+ ObjType.addConst();
if (ObjType.isVolatileQualified()) {
if (Info.getLangOpts().CPlusPlus) {
// FIXME: Include a description of the path to the volatile subobject.
- Info.Diag(E, diag::note_constexpr_ltor_volatile_obj, 1)
- << 2 << Field;
+ Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
+ << handler.AccessKind << 2 << Field;
Info.Note(Field->getLocation(), diag::note_declared_at);
} else {
Info.Diag(E, diag::note_invalid_subexpr_in_const_expr);
}
- return false;
+ return handler.failed();
}
} else {
// Next subobject is a base class.
const CXXRecordDecl *Derived = ObjType->getAsCXXRecordDecl();
const CXXRecordDecl *Base = getAsBaseClass(Sub.Entries[I]);
O = &O->getStructBase(getBaseIndex(Derived, Base));
+
+ bool WasConstQualified = ObjType.isConstQualified();
ObjType = Info.Ctx.getRecordType(Base);
+ if (WasConstQualified)
+ ObjType.addConst();
}
if (O->isUninit()) {
if (!Info.CheckingPotentialConstantExpression)
- Info.Diag(E, diag::note_constexpr_read_uninit);
+ Info.Diag(E, diag::note_constexpr_access_uninit) << handler.AccessKind;
+ return handler.failed();
+ }
+ }
+
+ return handler.found(*O, ObjType);
+}
+
+namespace {
+struct ExtractSubobjectHandler {
+ EvalInfo &Info;
+ APValue &Result;
+
+ static const AccessKinds AccessKind = AK_Read;
+
+ typedef bool result_type;
+ bool failed() { return false; }
+ bool found(APValue &Subobj, QualType SubobjType) {
+ Result = Subobj;
+ return true;
+ }
+ bool found(APSInt &Value, QualType SubobjType) {
+ Result = APValue(Value);
+ return true;
+ }
+ bool found(APFloat &Value, QualType SubobjType) {
+ Result = APValue(Value);
+ return true;
+ }
+ bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
+ Result = APValue(extractStringLiteralCharacter(
+ Info, Subobj.getLValueBase().get<const Expr *>(), Character));
+ return true;
+ }
+};
+} // end anonymous namespace
+
+const AccessKinds ExtractSubobjectHandler::AccessKind;
+
+/// Extract the designated sub-object of an rvalue.
+static bool extractSubobject(EvalInfo &Info, const Expr *E,
+ const CompleteObject &Obj,
+ const SubobjectDesignator &Sub,
+ APValue &Result) {
+ ExtractSubobjectHandler Handler = { Info, Result };
+ return findSubobject(Info, E, Obj, Sub, Handler);
+}
+
+namespace {
+struct ModifySubobjectHandler {
+ EvalInfo &Info;
+ APValue &NewVal;
+ const Expr *E;
+
+ typedef bool result_type;
+ static const AccessKinds AccessKind = AK_Assign;
+
+ bool checkConst(QualType QT) {
+ // Assigning to a const object has undefined behavior.
+ if (QT.isConstQualified()) {
+ Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
return false;
}
+ return true;
}
- // This may look super-stupid, but it serves an important purpose: if we just
- // swapped Obj and *O, we'd create an object which had itself as a subobject.
- // To avoid the leak, we ensure that Tmp ends up owning the original complete
- // object, which is destroyed by Tmp's destructor.
- APValue Tmp;
- O->swap(Tmp);
- Obj.swap(Tmp);
- return true;
+ bool failed() { return false; }
+ bool found(APValue &Subobj, QualType SubobjType) {
+ if (!checkConst(SubobjType))
+ return false;
+ // We've been given ownership of NewVal, so just swap it in.
+ Subobj.swap(NewVal);
+ return true;
+ }
+ bool found(APSInt &Value, QualType SubobjType) {
+ if (!checkConst(SubobjType))
+ return false;
+ if (!NewVal.isInt()) {
+ // Maybe trying to write a cast pointer value into a complex?
+ Info.Diag(E);
+ return false;
+ }
+ Value = NewVal.getInt();
+ return true;
+ }
+ bool found(APFloat &Value, QualType SubobjType) {
+ if (!checkConst(SubobjType))
+ return false;
+ Value = NewVal.getFloat();
+ return true;
+ }
+ bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
+ llvm_unreachable("shouldn't encounter string elements with ExpandArrays");
+ }
+};
+} // end anonymous namespace
+
+const AccessKinds ModifySubobjectHandler::AccessKind;
+
+/// Update the designated sub-object of an rvalue to the given value.
+static bool modifySubobject(EvalInfo &Info, const Expr *E,
+ const CompleteObject &Obj,
+ const SubobjectDesignator &Sub,
+ APValue &NewVal) {
+ ModifySubobjectHandler Handler = { Info, NewVal, E };
+ return findSubobject(Info, E, Obj, Sub, Handler);
}
/// Find the position where two subobject designators diverge, or equivalently
@@ -1710,59 +1946,52 @@ static bool AreElementsOfSameArray(QualType ObjType,
return CommonLength >= A.Entries.size() - IsArray;
}
-/// HandleLValueToRValueConversion - Perform an lvalue-to-rvalue conversion on
-/// the given lvalue. This can also be used for 'lvalue-to-lvalue' conversions
-/// for looking up the glvalue referred to by an entity of reference type.
-///
-/// \param Info - Information about the ongoing evaluation.
-/// \param Conv - The expression for which we are performing the conversion.
-/// Used for diagnostics.
-/// \param Type - The type we expect this conversion to produce, before
-/// stripping cv-qualifiers in the case of a non-clas type.
-/// \param LVal - The glvalue on which we are attempting to perform this action.
-/// \param RVal - The produced value will be placed here.
-static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
- QualType Type,
- const LValue &LVal, APValue &RVal) {
- if (LVal.Designator.Invalid)
- // A diagnostic will have already been produced.
- return false;
-
- const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
-
+/// Find the complete object to which an LValue refers.
+CompleteObject findCompleteObject(EvalInfo &Info, const Expr *E, AccessKinds AK,
+ const LValue &LVal, QualType LValType) {
if (!LVal.Base) {
- // FIXME: Indirection through a null pointer deserves a specific diagnostic.
- Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
- return false;
+ Info.Diag(E, diag::note_constexpr_access_null) << AK;
+ return CompleteObject();
}
CallStackFrame *Frame = 0;
if (LVal.CallIndex) {
Frame = Info.getCallFrame(LVal.CallIndex);
if (!Frame) {
- Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
+ Info.Diag(E, diag::note_constexpr_lifetime_ended, 1)
+ << AK << LVal.Base.is<const ValueDecl*>();
NoteLValueLocation(Info, LVal.Base);
- return false;
+ return CompleteObject();
}
+ } else if (AK != AK_Read) {
+ Info.Diag(E, diag::note_constexpr_modify_global);
+ return CompleteObject();
}
// C++11 DR1311: An lvalue-to-rvalue conversion on a volatile-qualified type
// is not a constant expression (even if the object is non-volatile). We also
// apply this rule to C++98, in order to conform to the expected 'volatile'
// semantics.
- if (Type.isVolatileQualified()) {
+ if (LValType.isVolatileQualified()) {
if (Info.getLangOpts().CPlusPlus)
- Info.Diag(Conv, diag::note_constexpr_ltor_volatile_type) << Type;
+ Info.Diag(E, diag::note_constexpr_access_volatile_type)
+ << AK << LValType;
else
- Info.Diag(Conv);
- return false;
+ Info.Diag(E);
+ return CompleteObject();
}
+ // Compute value storage location and type of base object.
+ APValue *BaseVal = 0;
+ QualType BaseType;
+
if (const ValueDecl *D = LVal.Base.dyn_cast<const ValueDecl*>()) {
// In C++98, const, non-volatile integers initialized with ICEs are ICEs.
// In C++11, constexpr, non-volatile variables initialized with constant
// expressions are constant expressions too. Inside constexpr functions,
// parameters are constant expressions even if they're non-const.
+ // In C++1y, objects local to a constant expression (those with a Frame) are
+ // both readable and writable inside constant expressions.
// In C, such things can also be folded, although they are not ICEs.
const VarDecl *VD = dyn_cast<VarDecl>(D);
if (VD) {
@@ -1770,120 +1999,312 @@ static bool HandleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
VD = VDef;
}
if (!VD || VD->isInvalidDecl()) {
- Info.Diag(Conv);
- return false;
+ Info.Diag(E);
+ return CompleteObject();
}
- // DR1313: If the object is volatile-qualified but the glvalue was not,
- // behavior is undefined so the result is not a constant expression.
- QualType VT = VD->getType();
- if (VT.isVolatileQualified()) {
+ // Accesses of volatile-qualified objects are not allowed.
+ BaseType = VD->getType();
+ if (BaseType.isVolatileQualified()) {
if (Info.getLangOpts().CPlusPlus) {
- Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 1 << VD;
+ Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
+ << AK << 1 << VD;
Info.Note(VD->getLocation(), diag::note_declared_at);
} else {
- Info.Diag(Conv);
+ Info.Diag(E);
}
- return false;
+ return CompleteObject();
}
- if (!isa<ParmVarDecl>(VD)) {
+ // Unless we're looking at a local variable or argument in a constexpr call,
+ // the variable we're reading must be const.
+ if (!Frame) {
+ assert(AK == AK_Read && "can't modify non-local");
if (VD->isConstexpr()) {
// OK, we can read this variable.
- } else if (VT->isIntegralOrEnumerationType()) {
- if (!VT.isConstQualified()) {
+ } else if (BaseType->isIntegralOrEnumerationType()) {
+ if (!BaseType.isConstQualified()) {
if (Info.getLangOpts().CPlusPlus) {
- Info.Diag(Conv, diag::note_constexpr_ltor_non_const_int, 1) << VD;
+ Info.Diag(E, diag::note_constexpr_ltor_non_const_int, 1) << VD;
Info.Note(VD->getLocation(), diag::note_declared_at);
} else {
- Info.Diag(Conv);
+ Info.Diag(E);
}
- return false;
+ return CompleteObject();
}
- } else if (VT->isFloatingType() && VT.isConstQualified()) {
+ } else if (BaseType->isFloatingType() && BaseType.isConstQualified()) {
// We support folding of const floating-point types, in order to make
// static const data members of such types (supported as an extension)
// more useful.
if (Info.getLangOpts().CPlusPlus11) {
- Info.CCEDiag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
+ Info.CCEDiag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Info.Note(VD->getLocation(), diag::note_declared_at);
} else {
- Info.CCEDiag(Conv);
+ Info.CCEDiag(E);
}
} else {
// FIXME: Allow folding of values of any literal type in all languages.
if (Info.getLangOpts().CPlusPlus11) {
- Info.Diag(Conv, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
+ Info.Diag(E, diag::note_constexpr_ltor_non_constexpr, 1) << VD;
Info.Note(VD->getLocation(), diag::note_declared_at);
} else {
- Info.Diag(Conv);
+ Info.Diag(E);
}
- return false;
+ return CompleteObject();
}
}
- if (!EvaluateVarDeclInit(Info, Conv, VD, Frame, RVal))
- return false;
+ if (!evaluateVarDeclInit(Info, E, VD, Frame, BaseVal))
+ return CompleteObject();
+ } else {
+ const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
+
+ if (!Frame) {
+ Info.Diag(E);
+ return CompleteObject();
+ }
- if (isa<ParmVarDecl>(VD) || !VD->getAnyInitializer()->isLValue())
- return ExtractSubobject(Info, Conv, RVal, VT, LVal.Designator, Type);
-
- // The declaration was initialized by an lvalue, with no lvalue-to-rvalue
- // conversion. This happens when the declaration and the lvalue should be
- // considered synonymous, for instance when initializing an array of char
- // from a string literal. Continue as if the initializer lvalue was the
- // value we were originally given.
- assert(RVal.getLValueOffset().isZero() &&
- "offset for lvalue init of non-reference");
- Base = RVal.getLValueBase().get<const Expr*>();
-
- if (unsigned CallIndex = RVal.getLValueCallIndex()) {
- Frame = Info.getCallFrame(CallIndex);
- if (!Frame) {
- Info.Diag(Conv, diag::note_constexpr_lifetime_ended, 1) << !Base;
- NoteLValueLocation(Info, RVal.getLValueBase());
+ BaseType = Base->getType();
+ BaseVal = &Frame->Temporaries[Base];
+
+ // Volatile temporary objects cannot be accessed in constant expressions.
+ if (BaseType.isVolatileQualified()) {
+ if (Info.getLangOpts().CPlusPlus) {
+ Info.Diag(E, diag::note_constexpr_access_volatile_obj, 1)
+ << AK << 0;
+ Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
+ } else {
+ Info.Diag(E);
+ }
+ return CompleteObject();
+ }
+ }
+
+ // In C++1y, we can't safely access any mutable state when checking a
+ // potential constant expression.
+ if (Frame && Info.getLangOpts().CPlusPlus1y &&
+ Info.CheckingPotentialConstantExpression)
+ return CompleteObject();
+
+ return CompleteObject(BaseVal, BaseType);
+}
+
+/// \brief Perform an lvalue-to-rvalue conversion on the given glvalue. This
+/// can also be used for 'lvalue-to-lvalue' conversions for looking up the
+/// glvalue referred to by an entity of reference type.
+///
+/// \param Info - Information about the ongoing evaluation.
+/// \param Conv - The expression for which we are performing the conversion.
+/// Used for diagnostics.
+/// \param Type - The type of the glvalue (before stripping cv-qualifiers in the
+/// case of a non-class type).
+/// \param LVal - The glvalue on which we are attempting to perform this action.
+/// \param RVal - The produced value will be placed here.
+static bool handleLValueToRValueConversion(EvalInfo &Info, const Expr *Conv,
+ QualType Type,
+ const LValue &LVal, APValue &RVal) {
+ if (LVal.Designator.Invalid)
+ return false;
+
+ // Check for special cases where there is no existing APValue to look at.
+ const Expr *Base = LVal.Base.dyn_cast<const Expr*>();
+ if (!LVal.Designator.Invalid && Base && !LVal.CallIndex &&
+ !Type.isVolatileQualified()) {
+ if (const CompoundLiteralExpr *CLE = dyn_cast<CompoundLiteralExpr>(Base)) {
+ // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
+ // initializer until now for such expressions. Such an expression can't be
+ // an ICE in C, so this only matters for fold.
+ assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
+ if (Type.isVolatileQualified()) {
+ Info.Diag(Conv);
return false;
}
- } else {
- Frame = 0;
+ APValue Lit;
+ if (!Evaluate(Lit, Info, CLE->getInitializer()))
+ return false;
+ CompleteObject LitObj(&Lit, Base->getType());
+ return extractSubobject(Info, Conv, LitObj, LVal.Designator, RVal);
+ } else if (isa<StringLiteral>(Base)) {
+ // We represent a string literal array as an lvalue pointing at the
+ // corresponding expression, rather than building an array of chars.
+ // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
+ APValue Str(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
+ CompleteObject StrObj(&Str, Base->getType());
+ return extractSubobject(Info, Conv, StrObj, LVal.Designator, RVal);
}
}
- // Volatile temporary objects cannot be read in constant expressions.
- if (Base->getType().isVolatileQualified()) {
- if (Info.getLangOpts().CPlusPlus) {
- Info.Diag(Conv, diag::note_constexpr_ltor_volatile_obj, 1) << 0;
- Info.Note(Base->getExprLoc(), diag::note_constexpr_temporary_here);
+ CompleteObject Obj = findCompleteObject(Info, Conv, AK_Read, LVal, Type);
+ return Obj && extractSubobject(Info, Conv, Obj, LVal.Designator, RVal);
+}
+
+/// Perform an assignment of Val to LVal. Takes ownership of Val.
+static bool handleAssignment(EvalInfo &Info, const Expr *E, const LValue &LVal,
+ QualType LValType, APValue &Val) {
+ if (LVal.Designator.Invalid)
+ return false;
+
+ if (!Info.getLangOpts().CPlusPlus1y) {
+ Info.Diag(E);
+ return false;
+ }
+
+ CompleteObject Obj = findCompleteObject(Info, E, AK_Assign, LVal, LValType);
+ return Obj && modifySubobject(Info, E, Obj, LVal.Designator, Val);
+}
+
+static bool isOverflowingIntegerType(ASTContext &Ctx, QualType T) {
+ return T->isSignedIntegerType() &&
+ Ctx.getIntWidth(T) >= Ctx.getIntWidth(Ctx.IntTy);
+}
+
+namespace {
+struct IncDecSubobjectHandler {
+ EvalInfo &Info;
+ const Expr *E;
+ AccessKinds AccessKind;
+ APValue *Old;
+
+ typedef bool result_type;
+
+ bool checkConst(QualType QT) {
+ // Assigning to a const object has undefined behavior.
+ if (QT.isConstQualified()) {
+ Info.Diag(E, diag::note_constexpr_modify_const_type) << QT;
+ return false;
+ }
+ return true;
+ }
+
+ bool failed() { return false; }
+ bool found(APValue &Subobj, QualType SubobjType) {
+ // Stash the old value. Also clear Old, so we don't clobber it later
+ // if we're post-incrementing a complex.
+ if (Old) {
+ *Old = Subobj;
+ Old = 0;
+ }
+
+ switch (Subobj.getKind()) {
+ case APValue::Int:
+ return found(Subobj.getInt(), SubobjType);
+ case APValue::Float:
+ return found(Subobj.getFloat(), SubobjType);
+ case APValue::ComplexInt:
+ return found(Subobj.getComplexIntReal(),
+ SubobjType->castAs<ComplexType>()->getElementType()
+ .withCVRQualifiers(SubobjType.getCVRQualifiers()));
+ case APValue::ComplexFloat:
+ return found(Subobj.getComplexFloatReal(),
+ SubobjType->castAs<ComplexType>()->getElementType()
+ .withCVRQualifiers(SubobjType.getCVRQualifiers()));
+ case APValue::LValue:
+ return foundPointer(Subobj, SubobjType);
+ default:
+ // FIXME: can this happen?
+ Info.Diag(E);
+ return false;
+ }
+ }
+ bool found(APSInt &Value, QualType SubobjType) {
+ if (!checkConst(SubobjType))
+ return false;
+
+ if (!SubobjType->isIntegerType()) {
+ // We don't support increment / decrement on integer-cast-to-pointer
+ // values.
+ Info.Diag(E);
+ return false;
+ }
+
+ if (Old) *Old = APValue(Value);
+
+ // bool arithmetic promotes to int, and the conversion back to bool
+ // doesn't reduce mod 2^n, so special-case it.
+ if (SubobjType->isBooleanType()) {
+ if (AccessKind == AK_Increment)
+ Value = 1;
+ else
+ Value = !Value;
+ return true;
+ }
+
+ bool WasNegative = Value.isNegative();
+ if (AccessKind == AK_Increment) {
+ ++Value;
+
+ if (!WasNegative && Value.isNegative() &&
+ isOverflowingIntegerType(Info.Ctx, SubobjType)) {
+ APSInt ActualValue(Value, /*IsUnsigned*/true);
+ HandleOverflow(Info, E, ActualValue, SubobjType);
+ }
} else {
- Info.Diag(Conv);
+ --Value;
+
+ if (WasNegative && !Value.isNegative() &&
+ isOverflowingIntegerType(Info.Ctx, SubobjType)) {
+ unsigned BitWidth = Value.getBitWidth();
+ APSInt ActualValue(Value.sext(BitWidth + 1), /*IsUnsigned*/false);
+ ActualValue.setBit(BitWidth);
+ HandleOverflow(Info, E, ActualValue, SubobjType);
+ }
}
- return false;
+ return true;
}
+ bool found(APFloat &Value, QualType SubobjType) {
+ if (!checkConst(SubobjType))
+ return false;
- if (Frame) {
- // If this is a temporary expression with a nontrivial initializer, grab the
- // value from the relevant stack frame.
- RVal = Frame->Temporaries[Base];
- } else if (const CompoundLiteralExpr *CLE
- = dyn_cast<CompoundLiteralExpr>(Base)) {
- // In C99, a CompoundLiteralExpr is an lvalue, and we defer evaluating the
- // initializer until now for such expressions. Such an expression can't be
- // an ICE in C, so this only matters for fold.
- assert(!Info.getLangOpts().CPlusPlus && "lvalue compound literal in c++?");
- if (!Evaluate(RVal, Info, CLE->getInitializer()))
+ if (Old) *Old = APValue(Value);
+
+ APFloat One(Value.getSemantics(), 1);
+ if (AccessKind == AK_Increment)
+ Value.add(One, APFloat::rmNearestTiesToEven);
+ else
+ Value.subtract(One, APFloat::rmNearestTiesToEven);
+ return true;
+ }
+ bool foundPointer(APValue &Subobj, QualType SubobjType) {
+ if (!checkConst(SubobjType))
return false;
- } else if (isa<StringLiteral>(Base)) {
- // We represent a string literal array as an lvalue pointing at the
- // corresponding expression, rather than building an array of chars.
- // FIXME: Support PredefinedExpr, ObjCEncodeExpr, MakeStringConstant
- RVal = APValue(Base, CharUnits::Zero(), APValue::NoLValuePath(), 0);
- } else {
- Info.Diag(Conv, diag::note_invalid_subexpr_in_const_expr);
+
+ QualType PointeeType;
+ if (const PointerType *PT = SubobjType->getAs<PointerType>())
+ PointeeType = PT->getPointeeType();
+ else {
+ Info.Diag(E);
+ return false;
+ }
+
+ LValue LVal;
+ LVal.setFrom(Info.Ctx, Subobj);
+ if (!HandleLValueArrayAdjustment(Info, E, LVal, PointeeType,
+ AccessKind == AK_Increment ? 1 : -1))
+ return false;
+ LVal.moveInto(Subobj);
+ return true;
+ }
+ bool foundString(APValue &Subobj, QualType SubobjType, uint64_t Character) {
+ llvm_unreachable("shouldn't encounter string elements here");
+ }
+};
+} // end anonymous namespace
+
+/// Perform an increment or decrement on LVal.
+static bool handleIncDec(EvalInfo &Info, const Expr *E, const LValue &LVal,
+ QualType LValType, bool IsIncrement, APValue *Old) {
+ if (LVal.Designator.Invalid)
+ return false;
+
+ if (!Info.getLangOpts().CPlusPlus1y) {
+ Info.Diag(E);
return false;
}
- return ExtractSubobject(Info, Conv, RVal, Base->getType(), LVal.Designator,
- Type);
+ AccessKinds AK = IsIncrement ? AK_Increment : AK_Decrement;
+ CompleteObject Obj = findCompleteObject(Info, E, AK, LVal, LValType);
+ IncDecSubobjectHandler Handler = { Info, E, AK, Old };
+ return Obj && findSubobject(Info, E, Obj, LVal.Designator, Handler);
}
/// Build an lvalue for the object argument of a member function call.
@@ -1895,7 +2316,7 @@ static bool EvaluateObjectArgument(EvalInfo &Info, const Expr *Object,
if (Object->isGLValue())
return EvaluateLValue(Object, This, Info);
- if (Object->getType()->isLiteralType())
+ if (Object->getType()->isLiteralType(Info.Ctx))
return EvaluateTemporary(Object, This, Info);
return false;
@@ -2040,24 +2461,95 @@ enum EvalStmtResult {
/// Hit a 'return' statement.
ESR_Returned,
/// Evaluation succeeded.
- ESR_Succeeded
+ ESR_Succeeded,
+ /// Hit a 'continue' statement.
+ ESR_Continue,
+ /// Hit a 'break' statement.
+ ESR_Break
};
}
+static bool EvaluateDecl(EvalInfo &Info, const Decl *D) {
+ if (const VarDecl *VD = dyn_cast<VarDecl>(D)) {
+ // We don't need to evaluate the initializer for a static local.
+ if (!VD->hasLocalStorage())
+ return true;
+
+ LValue Result;
+ Result.set(VD, Info.CurrentCall->Index);
+ APValue &Val = Info.CurrentCall->Temporaries[VD];
+
+ if (!EvaluateInPlace(Val, Info, Result, VD->getInit())) {
+ // Wipe out any partially-computed value, to allow tracking that this
+ // evaluation failed.
+ Val = APValue();
+ return false;
+ }
+ }
+
+ return true;
+}
+
+/// Evaluate a condition (either a variable declaration or an expression).
+static bool EvaluateCond(EvalInfo &Info, const VarDecl *CondDecl,
+ const Expr *Cond, bool &Result) {
+ if (CondDecl && !EvaluateDecl(Info, CondDecl))
+ return false;
+ return EvaluateAsBooleanCondition(Cond, Result, Info);
+}
+
+static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
+ const Stmt *S);
+
+/// Evaluate the body of a loop, and translate the result as appropriate.
+static EvalStmtResult EvaluateLoopBody(APValue &Result, EvalInfo &Info,
+ const Stmt *Body) {
+ switch (EvalStmtResult ESR = EvaluateStmt(Result, Info, Body)) {
+ case ESR_Break:
+ return ESR_Succeeded;
+ case ESR_Succeeded:
+ case ESR_Continue:
+ return ESR_Continue;
+ case ESR_Failed:
+ case ESR_Returned:
+ return ESR;
+ }
+ llvm_unreachable("Invalid EvalStmtResult!");
+}
+
// Evaluate a statement.
static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
const Stmt *S) {
+ // FIXME: Mark all temporaries in the current frame as destroyed at
+ // the end of each full-expression.
switch (S->getStmtClass()) {
default:
+ if (const Expr *E = dyn_cast<Expr>(S)) {
+ // Don't bother evaluating beyond an expression-statement which couldn't
+ // be evaluated.
+ if (!EvaluateIgnoredValue(Info, E))
+ return ESR_Failed;
+ return ESR_Succeeded;
+ }
+
+ Info.Diag(S->getLocStart());
return ESR_Failed;
case Stmt::NullStmtClass:
- case Stmt::DeclStmtClass:
return ESR_Succeeded;
+ case Stmt::DeclStmtClass: {
+ const DeclStmt *DS = cast<DeclStmt>(S);
+ for (DeclStmt::const_decl_iterator DclIt = DS->decl_begin(),
+ DclEnd = DS->decl_end(); DclIt != DclEnd; ++DclIt)
+ if (!EvaluateDecl(Info, *DclIt) && !Info.keepEvaluatingAfterFailure())
+ return ESR_Failed;
+ return ESR_Succeeded;
+ }
+
case Stmt::ReturnStmtClass: {
const Expr *RetExpr = cast<ReturnStmt>(S)->getRetValue();
- if (!Evaluate(Result, Info, RetExpr))
+ if (RetExpr && !Evaluate(Result, Info, RetExpr))
return ESR_Failed;
return ESR_Returned;
}
@@ -2072,6 +2564,123 @@ static EvalStmtResult EvaluateStmt(APValue &Result, EvalInfo &Info,
}
return ESR_Succeeded;
}
+
+ case Stmt::IfStmtClass: {
+ const IfStmt *IS = cast<IfStmt>(S);
+
+ // Evaluate the condition, as either a var decl or as an expression.
+ bool Cond;
+ if (!EvaluateCond(Info, IS->getConditionVariable(), IS->getCond(), Cond))
+ return ESR_Failed;
+
+ if (const Stmt *SubStmt = Cond ? IS->getThen() : IS->getElse()) {
+ EvalStmtResult ESR = EvaluateStmt(Result, Info, SubStmt);
+ if (ESR != ESR_Succeeded)
+ return ESR;
+ }
+ return ESR_Succeeded;
+ }
+
+ case Stmt::WhileStmtClass: {
+ const WhileStmt *WS = cast<WhileStmt>(S);
+ while (true) {
+ bool Continue;
+ if (!EvaluateCond(Info, WS->getConditionVariable(), WS->getCond(),
+ Continue))
+ return ESR_Failed;
+ if (!Continue)
+ break;
+
+ EvalStmtResult ESR = EvaluateLoopBody(Result, Info, WS->getBody());
+ if (ESR != ESR_Continue)
+ return ESR;
+ }
+ return ESR_Succeeded;
+ }
+
+ case Stmt::DoStmtClass: {
+ const DoStmt *DS = cast<DoStmt>(S);
+ bool Continue;
+ do {
+ EvalStmtResult ESR = EvaluateLoopBody(Result, Info, DS->getBody());
+ if (ESR != ESR_Continue)
+ return ESR;
+
+ if (!EvaluateAsBooleanCondition(DS->getCond(), Continue, Info))
+ return ESR_Failed;
+ } while (Continue);
+ return ESR_Succeeded;
+ }
+
+ case Stmt::ForStmtClass: {
+ const ForStmt *FS = cast<ForStmt>(S);
+ if (FS->getInit()) {
+ EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getInit());
+ if (ESR != ESR_Succeeded)
+ return ESR;
+ }
+ while (true) {
+ bool Continue = true;
+ if (FS->getCond() && !EvaluateCond(Info, FS->getConditionVariable(),
+ FS->getCond(), Continue))
+ return ESR_Failed;
+ if (!Continue)
+ break;
+
+ EvalStmtResult ESR = EvaluateLoopBody(Result, Info, FS->getBody());
+ if (ESR != ESR_Continue)
+ return ESR;
+
+ if (FS->getInc() && !EvaluateIgnoredValue(Info, FS->getInc()))
+ return ESR_Failed;
+ }
+ return ESR_Succeeded;
+ }
+
+ case Stmt::CXXForRangeStmtClass: {
+ const CXXForRangeStmt *FS = cast<CXXForRangeStmt>(S);
+
+ // Initialize the __range variable.
+ EvalStmtResult ESR = EvaluateStmt(Result, Info, FS->getRangeStmt());
+ if (ESR != ESR_Succeeded)
+ return ESR;
+
+ // Create the __begin and __end iterators.
+ ESR = EvaluateStmt(Result, Info, FS->getBeginEndStmt());
+ if (ESR != ESR_Succeeded)
+ return ESR;
+
+ while (true) {
+ // Condition: __begin != __end.
+ bool Continue = true;
+ if (!EvaluateAsBooleanCondition(FS->getCond(), Continue, Info))
+ return ESR_Failed;
+ if (!Continue)
+ break;
+
+ // User's variable declaration, initialized by *__begin.
+ ESR = EvaluateStmt(Result, Info, FS->getLoopVarStmt());
+ if (ESR != ESR_Succeeded)
+ return ESR;
+
+ // Loop body.
+ ESR = EvaluateLoopBody(Result, Info, FS->getBody());
+ if (ESR != ESR_Continue)
+ return ESR;
+
+ // Increment: ++__begin
+ if (!EvaluateIgnoredValue(Info, FS->getInc()))
+ return ESR_Failed;
+ }
+
+ return ESR_Succeeded;
+ }
+
+ case Stmt::ContinueStmtClass:
+ return ESR_Continue;
+
+ case Stmt::BreakStmtClass:
+ return ESR_Break;
}
}
@@ -2165,7 +2774,13 @@ static bool HandleFunctionCall(SourceLocation CallLoc,
return false;
CallStackFrame Frame(Info, CallLoc, Callee, This, ArgValues.data());
- return EvaluateStmt(Result, Info, Body) == ESR_Returned;
+ EvalStmtResult ESR = EvaluateStmt(Result, Info, Body);
+ if (ESR == ESR_Succeeded) {
+ if (Callee->getResultType()->isVoidType())
+ return true;
+ Info.Diag(Callee->getLocEnd(), diag::note_constexpr_no_return);
+ }
+ return ESR == ESR_Returned;
}
/// Evaluate a constructor call.
@@ -2191,7 +2806,9 @@ static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
// If it's a delegating constructor, just delegate.
if (Definition->isDelegatingConstructor()) {
CXXConstructorDecl::init_const_iterator I = Definition->init_begin();
- return EvaluateInPlace(Result, Info, This, (*I)->getInit());
+ if (!EvaluateInPlace(Result, Info, This, (*I)->getInit()))
+ return false;
+ return EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
}
// For a trivial copy or move constructor, perform an APValue copy. This is
@@ -2202,7 +2819,7 @@ static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
(Definition->isMoveConstructor() && Definition->isTrivial()))) {
LValue RHS;
RHS.setFrom(Info.Ctx, ArgValues[0]);
- return HandleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
+ return handleLValueToRValueConversion(Info, Args[0], Args[0]->getType(),
RHS, Result);
}
@@ -2291,7 +2908,8 @@ static bool HandleConstructorCall(SourceLocation CallLoc, const LValue &This,
}
}
- return Success;
+ return Success &&
+ EvaluateStmt(Result, Info, Definition->getBody()) != ESR_Failed;
}
//===----------------------------------------------------------------------===//
@@ -2397,6 +3015,8 @@ public:
{ return StmtVisitorTy::Visit(E->getReplacement()); }
RetTy VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *E)
{ return StmtVisitorTy::Visit(E->getExpr()); }
+ RetTy VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *E)
+ { return StmtVisitorTy::Visit(E->getExpr()); }
// We cannot create any objects for which cleanups are required, so there is
// nothing to do here; all cleanups must come from unevaluated subexpressions.
RetTy VisitExprWithCleanups(const ExprWithCleanups *E)
@@ -2426,7 +3046,7 @@ public:
if (!HandleMemberPointerAccess(Info, E, Obj))
return false;
APValue Result;
- if (!HandleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
+ if (!handleLValueToRValueConversion(Info, E, E->getType(), Obj, Result))
return false;
return DerivedSuccess(Result, E);
}
@@ -2606,11 +3226,13 @@ public:
assert(BaseTy->castAs<RecordType>()->getDecl()->getCanonicalDecl() ==
FD->getParent()->getCanonicalDecl() && "record / field mismatch");
+ CompleteObject Obj(&Val, BaseTy);
SubobjectDesignator Designator(BaseTy);
Designator.addDeclUnchecked(FD);
- return ExtractSubobject(Info, E, Val, BaseTy, Designator, E->getType()) &&
- DerivedSuccess(Val, E);
+ APValue Result;
+ return extractSubobject(Info, E, Obj, Designator, Result) &&
+ DerivedSuccess(Result, E);
}
RetTy VisitCastExpr(const CastExpr *E) {
@@ -2630,7 +3252,7 @@ public:
return false;
APValue RVal;
// Note, we use the subexpression's type in order to retain cv-qualifiers.
- if (!HandleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
+ if (!handleLValueToRValueConversion(Info, E, E->getSubExpr()->getType(),
LVal, RVal))
return false;
return DerivedSuccess(RVal, E);
@@ -2640,11 +3262,29 @@ public:
return Error(E);
}
+ RetTy VisitUnaryPostInc(const UnaryOperator *UO) {
+ return VisitUnaryPostIncDec(UO);
+ }
+ RetTy VisitUnaryPostDec(const UnaryOperator *UO) {
+ return VisitUnaryPostIncDec(UO);
+ }
+ RetTy VisitUnaryPostIncDec(const UnaryOperator *UO) {
+ if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
+ return Error(UO);
+
+ LValue LVal;
+ if (!EvaluateLValue(UO->getSubExpr(), LVal, Info))
+ return false;
+ APValue RVal;
+ if (!handleIncDec(this->Info, UO, LVal, UO->getSubExpr()->getType(),
+ UO->isIncrementOp(), &RVal))
+ return false;
+ return DerivedSuccess(RVal, UO);
+ }
+
/// Visit a value which is evaluated, but whose value is ignored.
void VisitIgnoredValue(const Expr *E) {
- APValue Scratch;
- if (!Evaluate(Scratch, Info, E))
- Info.EvalStatus.HasSideEffects = true;
+ EvaluateIgnoredValue(Info, E);
}
};
@@ -2709,7 +3349,7 @@ public:
if (MD->getType()->isReferenceType()) {
APValue RefValue;
- if (!HandleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
+ if (!handleLValueToRValueConversion(this->Info, E, MD->getType(), Result,
RefValue))
return false;
return Success(RefValue, E);
@@ -2792,6 +3432,7 @@ public:
LValueExprEvaluatorBaseTy(Info, Result) {}
bool VisitVarDecl(const Expr *E, const VarDecl *VD);
+ bool VisitUnaryPreIncDec(const UnaryOperator *UO);
bool VisitDeclRefExpr(const DeclRefExpr *E);
bool VisitPredefinedExpr(const PredefinedExpr *E) { return Success(E); }
@@ -2806,6 +3447,14 @@ public:
bool VisitUnaryDeref(const UnaryOperator *E);
bool VisitUnaryReal(const UnaryOperator *E);
bool VisitUnaryImag(const UnaryOperator *E);
+ bool VisitUnaryPreInc(const UnaryOperator *UO) {
+ return VisitUnaryPreIncDec(UO);
+ }
+ bool VisitUnaryPreDec(const UnaryOperator *UO) {
+ return VisitUnaryPreIncDec(UO);
+ }
+ bool VisitBinAssign(const BinaryOperator *BO);
+ bool VisitCompoundAssignOperator(const CompoundAssignOperator *CAO);
bool VisitCastExpr(const CastExpr *E) {
switch (E->getCastKind()) {
@@ -2829,14 +3478,12 @@ public:
} // end anonymous namespace
/// Evaluate an expression as an lvalue. This can be legitimately called on
-/// expressions which are not glvalues, in a few cases:
-/// * function designators in C,
-/// * "extern void" objects,
-/// * temporaries, if building with -Wno-address-of-temporary.
-static bool EvaluateLValue(const Expr* E, LValue& Result, EvalInfo &Info) {
- assert((E->isGLValue() || E->getType()->isFunctionType() ||
- E->getType()->isVoidType() || isa<CXXTemporaryObjectExpr>(E)) &&
- "can't evaluate expression as an lvalue");
+/// expressions which are not glvalues, in two cases:
+/// * function designators in C, and
+/// * "extern void" objects
+static bool EvaluateLValue(const Expr *E, LValue &Result, EvalInfo &Info) {
+ assert(E->isGLValue() || E->getType()->isFunctionType() ||
+ E->getType()->isVoidType());
return LValueExprEvaluator(Info, Result).Visit(E);
}
@@ -2849,41 +3496,32 @@ bool LValueExprEvaluator::VisitDeclRefExpr(const DeclRefExpr *E) {
}
bool LValueExprEvaluator::VisitVarDecl(const Expr *E, const VarDecl *VD) {
+ CallStackFrame *Frame = 0;
+ if (VD->hasLocalStorage() && Info.CurrentCall->Index > 1)
+ Frame = Info.CurrentCall;
+
if (!VD->getType()->isReferenceType()) {
- if (isa<ParmVarDecl>(VD)) {
- Result.set(VD, Info.CurrentCall->Index);
+ if (Frame) {
+ Result.set(VD, Frame->Index);
return true;
}
return Success(VD);
}
- APValue V;
- if (!EvaluateVarDeclInit(Info, E, VD, Info.CurrentCall, V))
+ APValue *V;
+ if (!evaluateVarDeclInit(Info, E, VD, Frame, V))
return false;
- return Success(V, E);
+ return Success(*V, E);
}
bool LValueExprEvaluator::VisitMaterializeTemporaryExpr(
const MaterializeTemporaryExpr *E) {
- if (E->GetTemporaryExpr()->isRValue()) {
- if (E->getType()->isRecordType())
- return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
+ if (E->getType()->isRecordType())
+ return EvaluateTemporary(E->GetTemporaryExpr(), Result, Info);
- Result.set(E, Info.CurrentCall->Index);
- return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
- Result, E->GetTemporaryExpr());
- }
-
- // Materialization of an lvalue temporary occurs when we need to force a copy
- // (for instance, if it's a bitfield).
- // FIXME: The AST should contain an lvalue-to-rvalue node for such cases.
- if (!Visit(E->GetTemporaryExpr()))
- return false;
- if (!HandleLValueToRValueConversion(Info, E, E->getType(), Result,
- Info.CurrentCall->Temporaries[E]))
- return false;
Result.set(E, Info.CurrentCall->Index);
- return true;
+ return EvaluateInPlace(Info.CurrentCall->Temporaries[E], Info,
+ Result, E->GetTemporaryExpr());
}
bool
@@ -2906,7 +3544,7 @@ bool LValueExprEvaluator::VisitCXXTypeidExpr(const CXXTypeidExpr *E) {
bool LValueExprEvaluator::VisitCXXUuidofExpr(const CXXUuidofExpr *E) {
return Success(E);
-}
+}
bool LValueExprEvaluator::VisitMemberExpr(const MemberExpr *E) {
// Handle static data members.
@@ -2967,6 +3605,64 @@ bool LValueExprEvaluator::VisitUnaryImag(const UnaryOperator *E) {
return true;
}
+bool LValueExprEvaluator::VisitUnaryPreIncDec(const UnaryOperator *UO) {
+ if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
+ return Error(UO);
+
+ if (!this->Visit(UO->getSubExpr()))
+ return false;
+
+ return handleIncDec(
+ this->Info, UO, Result, UO->getSubExpr()->getType(),
+ UO->isIncrementOp(), 0);
+}
+
+bool LValueExprEvaluator::VisitCompoundAssignOperator(
+ const CompoundAssignOperator *CAO) {
+ if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
+ return Error(CAO);
+
+ APValue RHS;
+
+ // The overall lvalue result is the result of evaluating the LHS.
+ if (!this->Visit(CAO->getLHS())) {
+ if (Info.keepEvaluatingAfterFailure())
+ Evaluate(RHS, this->Info, CAO->getRHS());
+ return false;
+ }
+
+ if (!Evaluate(RHS, this->Info, CAO->getRHS()))
+ return false;
+
+ // FIXME:
+ //return handleCompoundAssignment(
+ // this->Info, CAO,
+ // Result, CAO->getLHS()->getType(), CAO->getComputationLHSType(),
+ // RHS, CAO->getRHS()->getType(),
+ // CAO->getOpForCompoundAssignment(CAO->getOpcode()),
+ // CAO->getComputationResultType());
+ return Error(CAO);
+}
+
+bool LValueExprEvaluator::VisitBinAssign(const BinaryOperator *E) {
+ if (!Info.getLangOpts().CPlusPlus1y && !Info.keepEvaluatingAfterFailure())
+ return Error(E);
+
+ APValue NewVal;
+
+ if (!this->Visit(E->getLHS())) {
+ if (Info.keepEvaluatingAfterFailure())
+ Evaluate(NewVal, this->Info, E->getRHS());
+ return false;
+ }
+
+ if (!Evaluate(NewVal, this->Info, E->getRHS()))
+ return false;
+
+ return handleAssignment(this->Info, E, Result, E->getLHS()->getType(),
+ NewVal);
+}
+
//===----------------------------------------------------------------------===//
// Pointer Evaluation
//===----------------------------------------------------------------------===//
@@ -3411,12 +4107,20 @@ bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
// If the initializer list for a union does not contain any elements, the
// first element of the union is value-initialized.
+ // FIXME: The element should be initialized from an initializer list.
+ // Is this difference ever observable for initializer lists which
+ // we don't build?
ImplicitValueInitExpr VIE(Field->getType());
const Expr *InitExpr = E->getNumInits() ? E->getInit(0) : &VIE;
LValue Subobject = This;
if (!HandleLValueMember(Info, InitExpr, Subobject, Field, &Layout))
return false;
+
+ // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
+ ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
+ isa<CXXDefaultInitExpr>(InitExpr));
+
return EvaluateInPlace(Result.getUnionValue(), Info, Subobject, InitExpr);
}
@@ -3446,10 +4150,14 @@ bool RecordExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
// Perform an implicit value-initialization for members beyond the end of
// the initializer list.
ImplicitValueInitExpr VIE(HaveInit ? Info.Ctx.IntTy : Field->getType());
+ const Expr *Init = HaveInit ? E->getInit(ElementNo++) : &VIE;
- if (!EvaluateInPlace(
- Result.getStructField(Field->getFieldIndex()),
- Info, Subobject, HaveInit ? E->getInit(ElementNo++) : &VIE)) {
+ // Temporarily override This, in case there's a CXXDefaultInitExpr in here.
+ ThisOverrideRAII ThisOverride(*Info.CurrentCall, &This,
+ isa<CXXDefaultInitExpr>(Init));
+
+ if (!EvaluateInPlace(Result.getStructField(Field->getFieldIndex()), Info,
+ Subobject, Init)) {
if (!Info.keepEvaluatingAfterFailure())
return false;
Success = false;
@@ -3777,6 +4485,9 @@ namespace {
bool VisitInitListExpr(const InitListExpr *E);
bool VisitCXXConstructExpr(const CXXConstructExpr *E);
+ bool VisitCXXConstructExpr(const CXXConstructExpr *E,
+ const LValue &Subobject,
+ APValue *Value, QualType Type);
};
} // end anonymous namespace
@@ -3810,8 +4521,16 @@ bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
if (Result.isArray() && Result.hasArrayFiller())
Filler = Result.getArrayFiller();
- Result = APValue(APValue::UninitArray(), E->getNumInits(),
- CAT->getSize().getZExtValue());
+ unsigned NumEltsToInit = E->getNumInits();
+ unsigned NumElts = CAT->getSize().getZExtValue();
+ const Expr *FillerExpr = E->hasArrayFiller() ? E->getArrayFiller() : 0;
+
+ // If the initializer might depend on the array index, run it for each
+ // array element. For now, just whitelist non-class value-initialization.
+ if (NumEltsToInit != NumElts && !isa<ImplicitValueInitExpr>(FillerExpr))
+ NumEltsToInit = NumElts;
+
+ Result = APValue(APValue::UninitArray(), NumEltsToInit, NumElts);
// If the array was previously zero-initialized, preserve the
// zero-initialized values.
@@ -3824,12 +4543,12 @@ bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
LValue Subobject = This;
Subobject.addArray(Info, E, CAT);
- unsigned Index = 0;
- for (InitListExpr::const_iterator I = E->begin(), End = E->end();
- I != End; ++I, ++Index) {
+ for (unsigned Index = 0; Index != NumEltsToInit; ++Index) {
+ const Expr *Init =
+ Index < E->getNumInits() ? E->getInit(Index) : FillerExpr;
if (!EvaluateInPlace(Result.getArrayInitializedElt(Index),
- Info, Subobject, cast<Expr>(*I)) ||
- !HandleLValueArrayAdjustment(Info, cast<Expr>(*I), Subobject,
+ Info, Subobject, Init) ||
+ !HandleLValueArrayAdjustment(Info, Init, Subobject,
CAT->getElementType(), 1)) {
if (!Info.keepEvaluatingAfterFailure())
return false;
@@ -3837,39 +4556,54 @@ bool ArrayExprEvaluator::VisitInitListExpr(const InitListExpr *E) {
}
}
- if (!Result.hasArrayFiller()) return Success;
- assert(E->hasArrayFiller() && "no array filler for incomplete init list");
- // FIXME: The Subobject here isn't necessarily right. This rarely matters,
- // but sometimes does:
- // struct S { constexpr S() : p(&p) {} void *p; };
- // S s[10] = {};
- return EvaluateInPlace(Result.getArrayFiller(), Info,
- Subobject, E->getArrayFiller()) && Success;
+ if (!Result.hasArrayFiller())
+ return Success;
+
+ // If we get here, we have a trivial filler, which we can just evaluate
+ // once and splat over the rest of the array elements.
+ assert(FillerExpr && "no array filler for incomplete init list");
+ return EvaluateInPlace(Result.getArrayFiller(), Info, Subobject,
+ FillerExpr) && Success;
}
bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
- // FIXME: The Subobject here isn't necessarily right. This rarely matters,
- // but sometimes does:
- // struct S { constexpr S() : p(&p) {} void *p; };
- // S s[10];
- LValue Subobject = This;
+ return VisitCXXConstructExpr(E, This, &Result, E->getType());
+}
- APValue *Value = &Result;
- bool HadZeroInit = true;
- QualType ElemTy = E->getType();
- while (const ConstantArrayType *CAT =
- Info.Ctx.getAsConstantArrayType(ElemTy)) {
- Subobject.addArray(Info, E, CAT);
- HadZeroInit &= !Value->isUninit();
- if (!HadZeroInit)
- *Value = APValue(APValue::UninitArray(), 0, CAT->getSize().getZExtValue());
- if (!Value->hasArrayFiller())
- return true;
- Value = &Value->getArrayFiller();
- ElemTy = CAT->getElementType();
+bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E,
+ const LValue &Subobject,
+ APValue *Value,
+ QualType Type) {
+ bool HadZeroInit = !Value->isUninit();
+
+ if (const ConstantArrayType *CAT = Info.Ctx.getAsConstantArrayType(Type)) {
+ unsigned N = CAT->getSize().getZExtValue();
+
+ // Preserve the array filler if we had prior zero-initialization.
+ APValue Filler =
+ HadZeroInit && Value->hasArrayFiller() ? Value->getArrayFiller()
+ : APValue();
+
+ *Value = APValue(APValue::UninitArray(), N, N);
+
+ if (HadZeroInit)
+ for (unsigned I = 0; I != N; ++I)
+ Value->getArrayInitializedElt(I) = Filler;
+
+ // Initialize the elements.
+ LValue ArrayElt = Subobject;
+ ArrayElt.addArray(Info, E, CAT);
+ for (unsigned I = 0; I != N; ++I)
+ if (!VisitCXXConstructExpr(E, ArrayElt, &Value->getArrayInitializedElt(I),
+ CAT->getElementType()) ||
+ !HandleLValueArrayAdjustment(Info, E, ArrayElt,
+ CAT->getElementType(), 1))
+ return false;
+
+ return true;
}
- if (!ElemTy->isRecordType())
+ if (!Type->isRecordType())
return Error(E);
const CXXConstructorDecl *FD = E->getConstructor();
@@ -3880,7 +4614,7 @@ bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
return true;
if (ZeroInit) {
- ImplicitValueInitExpr VIE(ElemTy);
+ ImplicitValueInitExpr VIE(Type);
return EvaluateInPlace(*Value, Info, Subobject, &VIE);
}
@@ -3901,7 +4635,7 @@ bool ArrayExprEvaluator::VisitCXXConstructExpr(const CXXConstructExpr *E) {
return false;
if (ZeroInit && !HadZeroInit) {
- ImplicitValueInitExpr VIE(ElemTy);
+ ImplicitValueInitExpr VIE(Type);
if (!EvaluateInPlace(*Value, Info, Subobject, &VIE))
return false;
}
@@ -5182,6 +5916,10 @@ CharUnits IntExprEvaluator::GetAlignOfType(QualType T) {
CharUnits IntExprEvaluator::GetAlignOfExpr(const Expr *E) {
E = E->IgnoreParens();
+ // The kinds of expressions that we have special-case logic here for
+ // should be kept up to date with the special checks for those
+ // expressions in Sema.
+
// alignof decl is always accepted, even if it doesn't make sense: we default
// to 1 in those cases.
if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E))
@@ -6267,7 +7005,7 @@ static bool EvaluateAsRValue(EvalInfo &Info, const Expr *E, APValue &Result) {
if (E->isGLValue()) {
LValue LV;
LV.setFrom(Info.Ctx, Result);
- if (!HandleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
+ if (!handleLValueToRValueConversion(Info, E, E->getType(), LV, Result))
return false;
}
@@ -6501,6 +7239,7 @@ static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
case Expr::CXXDynamicCastExprClass:
case Expr::CXXTypeidExprClass:
case Expr::CXXUuidofExprClass:
+ case Expr::MSPropertyRefExprClass:
case Expr::CXXNullPtrLiteralExprClass:
case Expr::UserDefinedLiteralClass:
case Expr::CXXThisExprClass:
@@ -6819,6 +7558,8 @@ static ICEDiag CheckICE(const Expr* E, ASTContext &Ctx) {
}
case Expr::CXXDefaultArgExprClass:
return CheckICE(cast<CXXDefaultArgExpr>(E)->getExpr(), Ctx);
+ case Expr::CXXDefaultInitExprClass:
+ return CheckICE(cast<CXXDefaultInitExpr>(E)->getExpr(), Ctx);
case Expr::ChooseExprClass: {
return CheckICE(cast<ChooseExpr>(E)->getChosenSubExpr(Ctx), Ctx);
}
diff --git a/lib/AST/ItaniumMangle.cpp b/lib/AST/ItaniumMangle.cpp
index 21c499317f5e..5ad8021fac92 100644
--- a/lib/AST/ItaniumMangle.cpp
+++ b/lib/AST/ItaniumMangle.cpp
@@ -141,6 +141,8 @@ public:
raw_ostream &);
void mangleItaniumGuardVariable(const VarDecl *D, raw_ostream &);
+ void mangleItaniumThreadLocalInit(const VarDecl *D, raw_ostream &);
+ void mangleItaniumThreadLocalWrapper(const VarDecl *D, raw_ostream &);
void mangleInitDiscriminator() {
Discriminator = 0;
@@ -1095,6 +1097,15 @@ void CXXNameMangler::mangleUnqualifiedName(const NamedDecl *ND,
mangleSourceName(FD->getIdentifier());
break;
}
+
+ // Class extensions have no name as a category, and it's possible
+ // for them to be the semantic parent of certain declarations
+ // (primarily, tag decls defined within declarations). Such
+ // declarations will always have internal linkage, so the name
+ // doesn't really matter, but we shouldn't crash on them. For
+ // safety, just handle all ObjC containers here.
+ if (isa<ObjCContainerDecl>(ND))
+ break;
// We must have an anonymous struct.
const TagDecl *TD = cast<TagDecl>(ND);
@@ -2264,7 +2275,7 @@ void CXXNameMangler::mangleType(const AutoType *T) {
QualType D = T->getDeducedType();
// <builtin-type> ::= Da # dependent auto
if (D.isNull())
- Out << "Da";
+ Out << (T->isDecltypeAuto() ? "Dc" : "Da");
else
mangleType(D);
}
@@ -2385,6 +2396,7 @@ recurse:
case Expr::ImplicitValueInitExprClass:
case Expr::ParenListExprClass:
case Expr::LambdaExprClass:
+ case Expr::MSPropertyRefExprClass:
llvm_unreachable("unexpected statement kind");
// FIXME: invent manglings for all these.
@@ -2461,6 +2473,10 @@ recurse:
mangleExpression(cast<CXXDefaultArgExpr>(E)->getExpr(), Arity);
break;
+ case Expr::CXXDefaultInitExprClass:
+ mangleExpression(cast<CXXDefaultInitExpr>(E)->getExpr(), Arity);
+ break;
+
case Expr::SubstNonTypeTemplateParmExprClass:
mangleExpression(cast<SubstNonTypeTemplateParmExpr>(E)->getReplacement(),
Arity);
@@ -3521,6 +3537,22 @@ void ItaniumMangleContext::mangleItaniumGuardVariable(const VarDecl *D,
Mangler.mangleName(D);
}
+void ItaniumMangleContext::mangleItaniumThreadLocalInit(const VarDecl *D,
+ raw_ostream &Out) {
+ // <special-name> ::= TH <object name>
+ CXXNameMangler Mangler(*this, Out);
+ Mangler.getStream() << "_ZTH";
+ Mangler.mangleName(D);
+}
+
+void ItaniumMangleContext::mangleItaniumThreadLocalWrapper(const VarDecl *D,
+ raw_ostream &Out) {
+ // <special-name> ::= TW <object name>
+ CXXNameMangler Mangler(*this, Out);
+ Mangler.getStream() << "_ZTW";
+ Mangler.mangleName(D);
+}
+
void ItaniumMangleContext::mangleReferenceTemporary(const VarDecl *D,
raw_ostream &Out) {
// We match the GCC mangling here.
diff --git a/lib/AST/MicrosoftCXXABI.cpp b/lib/AST/MicrosoftCXXABI.cpp
index 6553e9d74943..fd932f7330a5 100644
--- a/lib/AST/MicrosoftCXXABI.cpp
+++ b/lib/AST/MicrosoftCXXABI.cpp
@@ -89,8 +89,8 @@ MSInheritanceModel CXXRecordDecl::getMSInheritanceModel() const {
if (this->getNumVBases() > 0)
return MSIM_Virtual;
if (usesMultipleInheritanceModel(this))
- return MSIM_Multiple;
- return MSIM_Single;
+ return this->isPolymorphic() ? MSIM_MultiplePolymorphic : MSIM_Multiple;
+ return this->isPolymorphic() ? MSIM_SinglePolymorphic : MSIM_Single;
}
// Returns the number of pointer and integer slots used to represent a member
@@ -119,15 +119,15 @@ MSInheritanceModel CXXRecordDecl::getMSInheritanceModel() const {
//
// // The offset of the vb-table pointer within the object. Only needed for
// // incomplete types.
-// int VBTableOffset;
+// int VBPtrOffset;
// };
-std::pair<unsigned, unsigned>
-MemberPointerType::getMSMemberPointerSlots() const {
- const CXXRecordDecl *RD = this->getClass()->getAsCXXRecordDecl();
+static std::pair<unsigned, unsigned>
+getMSMemberPointerSlots(const MemberPointerType *MPT) {
+ const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
unsigned Ptrs;
unsigned Ints = 0;
- if (this->isMemberFunctionPointer()) {
+ if (MPT->isMemberFunctionPointer()) {
// Member function pointers are a struct of a function pointer followed by a
// variable number of ints depending on the inheritance model used. The
// function pointer is a real function if it is non-virtual and a vftable
@@ -137,7 +137,9 @@ MemberPointerType::getMSMemberPointerSlots() const {
switch (Inheritance) {
case MSIM_Unspecified: ++Ints; // VBTableOffset
case MSIM_Virtual: ++Ints; // VirtualBaseAdjustmentOffset
+ case MSIM_MultiplePolymorphic:
case MSIM_Multiple: ++Ints; // NonVirtualBaseAdjustment
+ case MSIM_SinglePolymorphic:
case MSIM_Single: break; // Nothing
}
} else {
@@ -147,7 +149,9 @@ MemberPointerType::getMSMemberPointerSlots() const {
switch (Inheritance) {
case MSIM_Unspecified: ++Ints; // VBTableOffset
case MSIM_Virtual: ++Ints; // VirtualBaseAdjustmentOffset
+ case MSIM_MultiplePolymorphic:
case MSIM_Multiple: // Nothing
+ case MSIM_SinglePolymorphic:
case MSIM_Single: ++Ints; // Field offset
}
}
@@ -160,7 +164,7 @@ std::pair<uint64_t, unsigned> MicrosoftCXXABI::getMemberPointerWidthAndAlign(
assert(Target.getTriple().getArch() == llvm::Triple::x86 ||
Target.getTriple().getArch() == llvm::Triple::x86_64);
unsigned Ptrs, Ints;
- llvm::tie(Ptrs, Ints) = MPT->getMSMemberPointerSlots();
+ llvm::tie(Ptrs, Ints) = getMSMemberPointerSlots(MPT);
// The nominal struct is laid out with pointers followed by ints and aligned
// to a pointer width if any are present and an int width otherwise.
unsigned PtrSize = Target.getPointerWidth(0);
diff --git a/lib/AST/MicrosoftMangle.cpp b/lib/AST/MicrosoftMangle.cpp
index 40f8730e61af..1785063d7b1a 100644
--- a/lib/AST/MicrosoftMangle.cpp
+++ b/lib/AST/MicrosoftMangle.cpp
@@ -59,6 +59,8 @@ class MicrosoftCXXNameMangler {
ASTContext &getASTContext() const { return Context.getASTContext(); }
public:
+ enum QualifierMangleMode { QMM_Drop, QMM_Mangle, QMM_Escape, QMM_Result };
+
MicrosoftCXXNameMangler(MangleContext &C, raw_ostream &Out_)
: Context(C), Out(Out_),
Structor(0), StructorType(-1),
@@ -78,7 +80,8 @@ public:
void mangleVariableEncoding(const VarDecl *VD);
void mangleNumber(int64_t Number);
void mangleNumber(const llvm::APSInt &Value);
- void mangleType(QualType T, SourceRange Range, bool MangleQualifiers = true);
+ void mangleType(QualType T, SourceRange Range,
+ QualifierMangleMode QMM = QMM_Mangle);
private:
void disableBackReferences() { UseNameBackReferences = false; }
@@ -112,10 +115,10 @@ private:
#undef TYPE
void mangleType(const TagType*);
- void mangleType(const FunctionType *T, const FunctionDecl *D,
- bool IsStructor, bool IsInstMethod);
- void mangleType(const ArrayType *T, bool IsGlobal);
- void mangleExtraDimensions(QualType T);
+ void mangleFunctionType(const FunctionType *T, const FunctionDecl *D,
+ bool IsStructor, bool IsInstMethod);
+ void mangleDecayedArrayType(const ArrayType *T, bool IsGlobal);
+ void mangleArrayType(const ArrayType *T, Qualifiers Quals);
void mangleFunctionClass(const FunctionDecl *FD);
void mangleCallingConvention(const FunctionType *T, bool IsInstMethod = false);
void mangleIntegerLiteral(const llvm::APSInt &Number, bool IsBoolean);
@@ -264,7 +267,7 @@ void MicrosoftCXXNameMangler::mangleFunctionEncoding(const FunctionDecl *FD) {
// First, the function class.
mangleFunctionClass(FD);
- mangleType(FT, FD, InStructor, InInstMethod);
+ mangleFunctionType(FT, FD, InStructor, InInstMethod);
}
void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
@@ -297,14 +300,17 @@ void MicrosoftCXXNameMangler::mangleVariableEncoding(const VarDecl *VD) {
TypeLoc TL = VD->getTypeSourceInfo()->getTypeLoc();
QualType Ty = TL.getType();
if (Ty->isPointerType() || Ty->isReferenceType()) {
- mangleType(Ty, TL.getSourceRange());
+ mangleType(Ty, TL.getSourceRange(), QMM_Drop);
mangleQualifiers(Ty->getPointeeType().getQualifiers(), false);
} else if (const ArrayType *AT = getASTContext().getAsArrayType(Ty)) {
// Global arrays are funny, too.
- mangleType(AT, true);
- mangleQualifiers(Ty.getQualifiers(), false);
+ mangleDecayedArrayType(AT, true);
+ if (AT->getElementType()->isArrayType())
+ Out << 'A';
+ else
+ mangleQualifiers(Ty.getQualifiers(), false);
} else {
- mangleType(Ty.getLocalUnqualifiedType(), TL.getSourceRange());
+ mangleType(Ty, TL.getSourceRange(), QMM_Drop);
mangleQualifiers(Ty.getLocalQualifiers(), false);
}
}
@@ -824,9 +830,11 @@ MicrosoftCXXNameMangler::mangleTemplateArgs(const TemplateDecl *TD,
switch (TA.getKind()) {
case TemplateArgument::Null:
llvm_unreachable("Can't mangle null template arguments!");
- case TemplateArgument::Type:
- mangleType(TA.getAsType(), SourceRange());
+ case TemplateArgument::Type: {
+ QualType T = TA.getAsType();
+ mangleType(T, SourceRange(), QMM_Escape);
break;
+ }
case TemplateArgument::Declaration:
mangle(cast<NamedDecl>(TA.getAsDecl()), "$1?");
break;
@@ -964,7 +972,14 @@ void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
if (Found == TypeBackReferences.end()) {
size_t OutSizeBefore = Out.GetNumBytesInBuffer();
- mangleType(T, Range, false);
+ if (const ArrayType *AT = getASTContext().getAsArrayType(T)) {
+ mangleDecayedArrayType(AT, false);
+ } else if (const FunctionType *FT = T->getAs<FunctionType>()) {
+ Out << "P6";
+ mangleFunctionType(FT, 0, false, false);
+ } else {
+ mangleType(T, Range, QMM_Drop);
+ }
// See if it's worth creating a back reference.
// Only types longer than 1 character are considered
@@ -980,28 +995,53 @@ void MicrosoftCXXNameMangler::mangleArgumentType(QualType T,
}
void MicrosoftCXXNameMangler::mangleType(QualType T, SourceRange Range,
- bool MangleQualifiers) {
+ QualifierMangleMode QMM) {
// Only operate on the canonical type!
T = getASTContext().getCanonicalType(T);
-
Qualifiers Quals = T.getLocalQualifiers();
- // We have to mangle these now, while we still have enough information.
- if (T->isAnyPointerType() || T->isMemberPointerType() ||
- T->isBlockPointerType()) {
- manglePointerQualifiers(Quals);
- } else if (Quals && MangleQualifiers) {
- mangleQualifiers(Quals, false);
+
+ if (const ArrayType *AT = dyn_cast<ArrayType>(T)) {
+ if (QMM == QMM_Mangle)
+ Out << 'A';
+ else if (QMM == QMM_Escape || QMM == QMM_Result)
+ Out << "$$B";
+ mangleArrayType(AT, Quals);
+ return;
}
- SplitQualType split = T.split();
- const Type *ty = split.Ty;
+ bool IsPointer = T->isAnyPointerType() || T->isMemberPointerType() ||
+ T->isBlockPointerType();
- // If we're mangling a qualified array type, push the qualifiers to
- // the element type.
- if (split.Quals && isa<ArrayType>(T)) {
- ty = Context.getASTContext().getAsArrayType(T);
+ switch (QMM) {
+ case QMM_Drop:
+ break;
+ case QMM_Mangle:
+ if (const FunctionType *FT = dyn_cast<FunctionType>(T)) {
+ Out << '6';
+ mangleFunctionType(FT, 0, false, false);
+ return;
+ }
+ mangleQualifiers(Quals, false);
+ break;
+ case QMM_Escape:
+ if (!IsPointer && Quals) {
+ Out << "$$C";
+ mangleQualifiers(Quals, false);
+ }
+ break;
+ case QMM_Result:
+ if ((!IsPointer && Quals) || isa<TagType>(T)) {
+ Out << '?';
+ mangleQualifiers(Quals, false);
+ }
+ break;
}
+ // We have to mangle these now, while we still have enough information.
+ if (IsPointer)
+ manglePointerQualifiers(Quals);
+ const Type *ty = T.getTypePtr();
+
switch (ty->getTypeClass()) {
#define ABSTRACT_TYPE(CLASS, PARENT)
#define NON_CANONICAL_TYPE(CLASS, PARENT) \
@@ -1111,17 +1151,17 @@ void MicrosoftCXXNameMangler::mangleType(const FunctionProtoType *T,
// structor type.
// FIXME: This may not be lambda-friendly.
Out << "$$A6";
- mangleType(T, NULL, false, false);
+ mangleFunctionType(T, NULL, false, false);
}
void MicrosoftCXXNameMangler::mangleType(const FunctionNoProtoType *T,
SourceRange) {
llvm_unreachable("Can't mangle K&R function prototypes");
}
-void MicrosoftCXXNameMangler::mangleType(const FunctionType *T,
- const FunctionDecl *D,
- bool IsStructor,
- bool IsInstMethod) {
+void MicrosoftCXXNameMangler::mangleFunctionType(const FunctionType *T,
+ const FunctionDecl *D,
+ bool IsStructor,
+ bool IsInstMethod) {
// <function-type> ::= <this-cvr-qualifiers> <calling-convention>
// <return-type> <argument-list> <throw-spec>
const FunctionProtoType *Proto = cast<FunctionProtoType>(T);
@@ -1147,21 +1187,7 @@ void MicrosoftCXXNameMangler::mangleType(const FunctionType *T,
}
Out << '@';
} else {
- QualType Result = Proto->getResultType();
- const Type* RT = Result.getTypePtr();
- if (!RT->isAnyPointerType() && !RT->isReferenceType()) {
- if (Result.hasQualifiers() || !RT->isBuiltinType())
- Out << '?';
- if (!RT->isBuiltinType() && !Result.hasQualifiers()) {
- // Lack of qualifiers for user types is mangled as 'A'.
- Out << 'A';
- }
- }
-
- // FIXME: Get the source range for the result type. Or, better yet,
- // implement the unimplemented stuff so we don't need accurate source
- // location info anymore :).
- mangleType(Result, SourceRange());
+ mangleType(Proto->getResultType(), SourceRange(), QMM_Result);
}
// <argument-list> ::= X # void
@@ -1356,7 +1382,8 @@ void MicrosoftCXXNameMangler::mangleType(const TagType *T) {
// It's supposed to be the other way around, but for some strange reason, it
// isn't. Today this behavior is retained for the sole purpose of backwards
// compatibility.
-void MicrosoftCXXNameMangler::mangleType(const ArrayType *T, bool IsGlobal) {
+void MicrosoftCXXNameMangler::mangleDecayedArrayType(const ArrayType *T,
+ bool IsGlobal) {
// This isn't a recursive mangling, so now we have to do it all in this
// one call.
if (IsGlobal) {
@@ -1364,25 +1391,27 @@ void MicrosoftCXXNameMangler::mangleType(const ArrayType *T, bool IsGlobal) {
} else {
Out << 'Q';
}
- mangleExtraDimensions(T->getElementType());
+ mangleType(T->getElementType(), SourceRange());
}
void MicrosoftCXXNameMangler::mangleType(const ConstantArrayType *T,
SourceRange) {
- mangleType(cast<ArrayType>(T), false);
+ llvm_unreachable("Should have been special cased");
}
void MicrosoftCXXNameMangler::mangleType(const VariableArrayType *T,
SourceRange) {
- mangleType(cast<ArrayType>(T), false);
+ llvm_unreachable("Should have been special cased");
}
void MicrosoftCXXNameMangler::mangleType(const DependentSizedArrayType *T,
SourceRange) {
- mangleType(cast<ArrayType>(T), false);
+ llvm_unreachable("Should have been special cased");
}
void MicrosoftCXXNameMangler::mangleType(const IncompleteArrayType *T,
SourceRange) {
- mangleType(cast<ArrayType>(T), false);
+ llvm_unreachable("Should have been special cased");
}
-void MicrosoftCXXNameMangler::mangleExtraDimensions(QualType ElementTy) {
+void MicrosoftCXXNameMangler::mangleArrayType(const ArrayType *T,
+ Qualifiers Quals) {
+ QualType ElementTy(T, 0);
SmallVector<llvm::APInt, 3> Dimensions;
for (;;) {
if (const ConstantArrayType *CAT =
@@ -1408,20 +1437,20 @@ void MicrosoftCXXNameMangler::mangleExtraDimensions(QualType ElementTy) {
Diags.Report(DSAT->getSizeExpr()->getExprLoc(), DiagID)
<< DSAT->getBracketsRange();
return;
- } else if (ElementTy->isIncompleteArrayType()) continue;
- else break;
- }
- mangleQualifiers(ElementTy.getQualifiers(), false);
- // If there are any additional dimensions, mangle them now.
- if (Dimensions.size() > 0) {
- Out << 'Y';
- // <dimension-count> ::= <number> # number of extra dimensions
- mangleNumber(Dimensions.size());
- for (unsigned Dim = 0; Dim < Dimensions.size(); ++Dim) {
- mangleNumber(Dimensions[Dim].getLimitedValue());
+ } else if (const IncompleteArrayType *IAT =
+ getASTContext().getAsIncompleteArrayType(ElementTy)) {
+ Dimensions.push_back(llvm::APInt(32, 0));
+ ElementTy = IAT->getElementType();
}
+ else break;
}
- mangleType(ElementTy.getLocalUnqualifiedType(), SourceRange());
+ Out << 'Y';
+ // <dimension-count> ::= <number> # number of extra dimensions
+ mangleNumber(Dimensions.size());
+ for (unsigned Dim = 0; Dim < Dimensions.size(); ++Dim)
+ mangleNumber(Dimensions[Dim].getLimitedValue());
+ mangleType(getASTContext().getQualifiedType(ElementTy.getTypePtr(), Quals),
+ SourceRange(), QMM_Escape);
}
// <type> ::= <pointer-to-member-type>
@@ -1433,11 +1462,11 @@ void MicrosoftCXXNameMangler::mangleType(const MemberPointerType *T,
if (const FunctionProtoType *FPT = PointeeType->getAs<FunctionProtoType>()) {
Out << '8';
mangleName(T->getClass()->castAs<RecordType>()->getDecl());
- mangleType(FPT, NULL, false, true);
+ mangleFunctionType(FPT, NULL, false, true);
} else {
mangleQualifiers(PointeeType.getQualifiers(), true);
mangleName(T->getClass()->castAs<RecordType>()->getDecl());
- mangleType(PointeeType.getLocalUnqualifiedType(), Range);
+ mangleType(PointeeType, Range, QMM_Drop);
}
}
@@ -1465,17 +1494,7 @@ void MicrosoftCXXNameMangler::mangleType(
void MicrosoftCXXNameMangler::mangleType(const PointerType *T,
SourceRange Range) {
QualType PointeeTy = T->getPointeeType();
- if (PointeeTy->isArrayType()) {
- // Pointers to arrays are mangled like arrays.
- mangleExtraDimensions(PointeeTy);
- } else if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
- // Function pointers are special.
- Out << '6';
- mangleType(FT, NULL, false, false);
- } else {
- mangleQualifiers(PointeeTy.getQualifiers(), false);
- mangleType(PointeeTy, Range, false);
- }
+ mangleType(PointeeTy, Range);
}
void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
SourceRange Range) {
@@ -1489,11 +1508,7 @@ void MicrosoftCXXNameMangler::mangleType(const ObjCObjectPointerType *T,
void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
SourceRange Range) {
Out << 'A';
- QualType PointeeTy = T->getPointeeType();
- if (!PointeeTy.hasQualifiers())
- // Lack of qualifiers is mangled as 'A'.
- Out << 'A';
- mangleType(PointeeTy, Range);
+ mangleType(T->getPointeeType(), Range);
}
// <type> ::= <r-value-reference-type>
@@ -1501,11 +1516,7 @@ void MicrosoftCXXNameMangler::mangleType(const LValueReferenceType *T,
void MicrosoftCXXNameMangler::mangleType(const RValueReferenceType *T,
SourceRange Range) {
Out << "$$Q";
- QualType PointeeTy = T->getPointeeType();
- if (!PointeeTy.hasQualifiers())
- // Lack of qualifiers is mangled as 'A'.
- Out << 'A';
- mangleType(PointeeTy, Range);
+ mangleType(T->getPointeeType(), Range);
}
void MicrosoftCXXNameMangler::mangleType(const ComplexType *T,
@@ -1587,7 +1598,7 @@ void MicrosoftCXXNameMangler::mangleType(const BlockPointerType *T,
Out << "_E";
QualType pointee = T->getPointeeType();
- mangleType(pointee->castAs<FunctionProtoType>(), NULL, false, false);
+ mangleFunctionType(pointee->castAs<FunctionProtoType>(), NULL, false, false);
}
void MicrosoftCXXNameMangler::mangleType(const InjectedClassNameType *T,
diff --git a/lib/AST/RawCommentList.cpp b/lib/AST/RawCommentList.cpp
index f2386a56fcc7..92b96dc8e5a1 100644
--- a/lib/AST/RawCommentList.cpp
+++ b/lib/AST/RawCommentList.cpp
@@ -21,8 +21,10 @@ using namespace clang;
namespace {
/// Get comment kind and bool describing if it is a trailing comment.
-std::pair<RawComment::CommentKind, bool> getCommentKind(StringRef Comment) {
- if (Comment.size() < 3 || Comment[0] != '/')
+std::pair<RawComment::CommentKind, bool> getCommentKind(StringRef Comment,
+ bool ParseAllComments) {
+ const size_t MinCommentLength = ParseAllComments ? 2 : 3;
+ if ((Comment.size() < MinCommentLength) || Comment[0] != '/')
return std::make_pair(RawComment::RCK_Invalid, false);
RawComment::CommentKind K;
@@ -63,9 +65,10 @@ bool mergedCommentIsTrailingComment(StringRef Comment) {
} // unnamed namespace
RawComment::RawComment(const SourceManager &SourceMgr, SourceRange SR,
- bool Merged) :
+ bool Merged, bool ParseAllComments) :
Range(SR), RawTextValid(false), BriefTextValid(false),
IsAttached(false), IsAlmostTrailingComment(false),
+ ParseAllComments(ParseAllComments),
BeginLineValid(false), EndLineValid(false) {
// Extract raw comment text, if possible.
if (SR.getBegin() == SR.getEnd() || getRawText(SourceMgr).empty()) {
@@ -75,7 +78,7 @@ RawComment::RawComment(const SourceManager &SourceMgr, SourceRange SR,
if (!Merged) {
// Guess comment kind.
- std::pair<CommentKind, bool> K = getCommentKind(RawText);
+ std::pair<CommentKind, bool> K = getCommentKind(RawText, ParseAllComments);
Kind = K.first;
IsTrailingComment = K.second;
@@ -143,7 +146,8 @@ const char *RawComment::extractBriefText(const ASTContext &Context) const {
// a separate allocator for all temporary stuff.
llvm::BumpPtrAllocator Allocator;
- comments::Lexer L(Allocator, Context.getCommentCommandTraits(),
+ comments::Lexer L(Allocator, Context.getDiagnostics(),
+ Context.getCommentCommandTraits(),
Range.getBegin(),
RawText.begin(), RawText.end());
comments::BriefParser P(L, Context.getCommentCommandTraits());
@@ -164,7 +168,8 @@ comments::FullComment *RawComment::parse(const ASTContext &Context,
// Make sure that RawText is valid.
getRawText(Context.getSourceManager());
- comments::Lexer L(Context.getAllocator(), Context.getCommentCommandTraits(),
+ comments::Lexer L(Context.getAllocator(), Context.getDiagnostics(),
+ Context.getCommentCommandTraits(),
getSourceRange().getBegin(),
RawText.begin(), RawText.end());
comments::Sema S(Context.getAllocator(), Context.getSourceManager(),
@@ -253,7 +258,8 @@ void RawCommentList::addComment(const RawComment &RC,
if (C1EndLine + 1 == C2BeginLine || C1EndLine == C2BeginLine) {
SourceRange MergedRange(C1.getSourceRange().getBegin(),
C2.getSourceRange().getEnd());
- *Comments.back() = RawComment(SourceMgr, MergedRange, true);
+ *Comments.back() = RawComment(SourceMgr, MergedRange, true,
+ RC.isParseAllComments());
Merged = true;
}
}
@@ -262,4 +268,3 @@ void RawCommentList::addComment(const RawComment &RC,
OnlyWhitespaceSeen = true;
}
-
diff --git a/lib/AST/Stmt.cpp b/lib/AST/Stmt.cpp
index 2ae5a1266c18..5b29c073f928 100644
--- a/lib/AST/Stmt.cpp
+++ b/lib/AST/Stmt.cpp
@@ -673,19 +673,38 @@ GCCAsmStmt::GCCAsmStmt(ASTContext &C, SourceLocation asmloc, bool issimple,
MSAsmStmt::MSAsmStmt(ASTContext &C, SourceLocation asmloc,
SourceLocation lbraceloc, bool issimple, bool isvolatile,
ArrayRef<Token> asmtoks, unsigned numoutputs,
- unsigned numinputs, ArrayRef<IdentifierInfo*> names,
+ unsigned numinputs,
ArrayRef<StringRef> constraints, ArrayRef<Expr*> exprs,
StringRef asmstr, ArrayRef<StringRef> clobbers,
SourceLocation endloc)
: AsmStmt(MSAsmStmtClass, asmloc, issimple, isvolatile, numoutputs,
numinputs, clobbers.size()), LBraceLoc(lbraceloc),
- EndLoc(endloc), AsmStr(asmstr.str()), NumAsmToks(asmtoks.size()) {
+ EndLoc(endloc), NumAsmToks(asmtoks.size()) {
- unsigned NumExprs = NumOutputs + NumInputs;
+ initialize(C, asmstr, asmtoks, constraints, exprs, clobbers);
+}
- Names = new (C) IdentifierInfo*[NumExprs];
- for (unsigned i = 0, e = NumExprs; i != e; ++i)
- Names[i] = names[i];
+static StringRef copyIntoContext(ASTContext &C, StringRef str) {
+ size_t size = str.size();
+ char *buffer = new (C) char[size];
+ memcpy(buffer, str.data(), size);
+ return StringRef(buffer, size);
+}
+
+void MSAsmStmt::initialize(ASTContext &C,
+ StringRef asmstr,
+ ArrayRef<Token> asmtoks,
+ ArrayRef<StringRef> constraints,
+ ArrayRef<Expr*> exprs,
+ ArrayRef<StringRef> clobbers) {
+ assert(NumAsmToks == asmtoks.size());
+ assert(NumClobbers == clobbers.size());
+
+ unsigned NumExprs = exprs.size();
+ assert(NumExprs == NumOutputs + NumInputs);
+ assert(NumExprs == constraints.size());
+
+ AsmStr = copyIntoContext(C, asmstr);
Exprs = new (C) Stmt*[NumExprs];
for (unsigned i = 0, e = NumExprs; i != e; ++i)
@@ -697,19 +716,13 @@ MSAsmStmt::MSAsmStmt(ASTContext &C, SourceLocation asmloc,
Constraints = new (C) StringRef[NumExprs];
for (unsigned i = 0, e = NumExprs; i != e; ++i) {
- size_t size = constraints[i].size();
- char *dest = new (C) char[size];
- std::strncpy(dest, constraints[i].data(), size);
- Constraints[i] = StringRef(dest, size);
+ Constraints[i] = copyIntoContext(C, constraints[i]);
}
Clobbers = new (C) StringRef[NumClobbers];
for (unsigned i = 0, e = NumClobbers; i != e; ++i) {
// FIXME: Avoid the allocation/copy if at all possible.
- size_t size = clobbers[i].size();
- char *dest = new (C) char[size];
- std::strncpy(dest, clobbers[i].data(), size);
- Clobbers[i] = StringRef(dest, size);
+ Clobbers[i] = copyIntoContext(C, clobbers[i]);
}
}
@@ -1023,3 +1036,107 @@ SEHFinallyStmt* SEHFinallyStmt::Create(ASTContext &C,
Stmt *Block) {
return new(C)SEHFinallyStmt(Loc,Block);
}
+
+CapturedStmt::Capture *CapturedStmt::getStoredCaptures() const {
+ unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (NumCaptures + 1);
+
+ // Offset of the first Capture object.
+ unsigned FirstCaptureOffset =
+ llvm::RoundUpToAlignment(Size, llvm::alignOf<Capture>());
+
+ return reinterpret_cast<Capture *>(
+ reinterpret_cast<char *>(const_cast<CapturedStmt *>(this))
+ + FirstCaptureOffset);
+}
+
+CapturedStmt::CapturedStmt(Stmt *S, CapturedRegionKind Kind,
+ ArrayRef<Capture> Captures,
+ ArrayRef<Expr *> CaptureInits,
+ CapturedDecl *CD,
+ RecordDecl *RD)
+ : Stmt(CapturedStmtClass), NumCaptures(Captures.size()),
+ CapDeclAndKind(CD, Kind), TheRecordDecl(RD) {
+ assert( S && "null captured statement");
+ assert(CD && "null captured declaration for captured statement");
+ assert(RD && "null record declaration for captured statement");
+
+ // Copy initialization expressions.
+ Stmt **Stored = getStoredStmts();
+ for (unsigned I = 0, N = NumCaptures; I != N; ++I)
+ *Stored++ = CaptureInits[I];
+
+ // Copy the statement being captured.
+ *Stored = S;
+
+ // Copy all Capture objects.
+ Capture *Buffer = getStoredCaptures();
+ std::copy(Captures.begin(), Captures.end(), Buffer);
+}
+
+CapturedStmt::CapturedStmt(EmptyShell Empty, unsigned NumCaptures)
+ : Stmt(CapturedStmtClass, Empty), NumCaptures(NumCaptures),
+ CapDeclAndKind(0, CR_Default), TheRecordDecl(0) {
+ getStoredStmts()[NumCaptures] = 0;
+}
+
+CapturedStmt *CapturedStmt::Create(ASTContext &Context, Stmt *S,
+ CapturedRegionKind Kind,
+ ArrayRef<Capture> Captures,
+ ArrayRef<Expr *> CaptureInits,
+ CapturedDecl *CD,
+ RecordDecl *RD) {
+ // The layout is
+ //
+ // -----------------------------------------------------------
+ // | CapturedStmt, Init, ..., Init, S, Capture, ..., Capture |
+ // ----------------^-------------------^----------------------
+ // getStoredStmts() getStoredCaptures()
+ //
+ // where S is the statement being captured.
+ //
+ assert(CaptureInits.size() == Captures.size() && "wrong number of arguments");
+
+ unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (Captures.size() + 1);
+ if (!Captures.empty()) {
+ // Realign for the following Capture array.
+ Size = llvm::RoundUpToAlignment(Size, llvm::alignOf<Capture>());
+ Size += sizeof(Capture) * Captures.size();
+ }
+
+ void *Mem = Context.Allocate(Size);
+ return new (Mem) CapturedStmt(S, Kind, Captures, CaptureInits, CD, RD);
+}
+
+CapturedStmt *CapturedStmt::CreateDeserialized(ASTContext &Context,
+ unsigned NumCaptures) {
+ unsigned Size = sizeof(CapturedStmt) + sizeof(Stmt *) * (NumCaptures + 1);
+ if (NumCaptures > 0) {
+ // Realign for the following Capture array.
+ Size = llvm::RoundUpToAlignment(Size, llvm::alignOf<Capture>());
+ Size += sizeof(Capture) * NumCaptures;
+ }
+
+ void *Mem = Context.Allocate(Size);
+ return new (Mem) CapturedStmt(EmptyShell(), NumCaptures);
+}
+
+Stmt::child_range CapturedStmt::children() {
+ // Children are captured field initilizers.
+ return child_range(getStoredStmts(), getStoredStmts() + NumCaptures);
+}
+
+bool CapturedStmt::capturesVariable(const VarDecl *Var) const {
+ for (const_capture_iterator I = capture_begin(),
+ E = capture_end(); I != E; ++I) {
+ if (I->capturesThis())
+ continue;
+
+ // This does not handle variable redeclarations. This should be
+ // extended to capture variables with redeclarations, for example
+ // a thread-private variable in OpenMP.
+ if (I->getCapturedVar() == Var)
+ return true;
+ }
+
+ return false;
+}
diff --git a/lib/AST/StmtPrinter.cpp b/lib/AST/StmtPrinter.cpp
index 7df7fdb92bf2..9203dc1584bb 100644
--- a/lib/AST/StmtPrinter.cpp
+++ b/lib/AST/StmtPrinter.cpp
@@ -445,11 +445,15 @@ void StmtPrinter::VisitMSAsmStmt(MSAsmStmt *Node) {
Indent() << "__asm ";
if (Node->hasBraces())
OS << "{\n";
- OS << *(Node->getAsmString()) << "\n";
+ OS << Node->getAsmString() << "\n";
if (Node->hasBraces())
Indent() << "}\n";
}
+void StmtPrinter::VisitCapturedStmt(CapturedStmt *Node) {
+ PrintStmt(Node->getCapturedDecl()->getBody());
+}
+
void StmtPrinter::VisitObjCAtTryStmt(ObjCAtTryStmt *Node) {
Indent() << "@try";
if (CompoundStmt *TS = dyn_cast<CompoundStmt>(Node->getTryBody())) {
@@ -1109,24 +1113,25 @@ void StmtPrinter::VisitAtomicExpr(AtomicExpr *Node) {
// AtomicExpr stores its subexpressions in a permuted order.
PrintExpr(Node->getPtr());
- OS << ", ";
if (Node->getOp() != AtomicExpr::AO__c11_atomic_load &&
Node->getOp() != AtomicExpr::AO__atomic_load_n) {
- PrintExpr(Node->getVal1());
OS << ", ";
+ PrintExpr(Node->getVal1());
}
if (Node->getOp() == AtomicExpr::AO__atomic_exchange ||
Node->isCmpXChg()) {
- PrintExpr(Node->getVal2());
OS << ", ";
+ PrintExpr(Node->getVal2());
}
if (Node->getOp() == AtomicExpr::AO__atomic_compare_exchange ||
Node->getOp() == AtomicExpr::AO__atomic_compare_exchange_n) {
- PrintExpr(Node->getWeak());
OS << ", ";
+ PrintExpr(Node->getWeak());
}
- if (Node->getOp() != AtomicExpr::AO__c11_atomic_init)
+ if (Node->getOp() != AtomicExpr::AO__c11_atomic_init) {
+ OS << ", ";
PrintExpr(Node->getOrder());
+ }
if (Node->isCmpXChg()) {
OS << ", ";
PrintExpr(Node->getOrderFail());
@@ -1238,6 +1243,18 @@ void StmtPrinter::VisitCXXUuidofExpr(CXXUuidofExpr *Node) {
OS << ")";
}
+void StmtPrinter::VisitMSPropertyRefExpr(MSPropertyRefExpr *Node) {
+ PrintExpr(Node->getBaseExpr());
+ if (Node->isArrow())
+ OS << "->";
+ else
+ OS << ".";
+ if (NestedNameSpecifier *Qualifier =
+ Node->getQualifierLoc().getNestedNameSpecifier())
+ Qualifier->print(OS, Policy);
+ OS << Node->getPropertyDecl()->getDeclName();
+}
+
void StmtPrinter::VisitUserDefinedLiteral(UserDefinedLiteral *Node) {
switch (Node->getLiteralOperatorKind()) {
case UserDefinedLiteral::LOK_Raw:
@@ -1298,7 +1315,11 @@ void StmtPrinter::VisitCXXThrowExpr(CXXThrowExpr *Node) {
}
void StmtPrinter::VisitCXXDefaultArgExpr(CXXDefaultArgExpr *Node) {
- // Nothing to print: we picked up the default argument
+ // Nothing to print: we picked up the default argument.
+}
+
+void StmtPrinter::VisitCXXDefaultInitExpr(CXXDefaultInitExpr *Node) {
+ // Nothing to print: we picked up the default initializer.
}
void StmtPrinter::VisitCXXFunctionalCastExpr(CXXFunctionalCastExpr *Node) {
diff --git a/lib/AST/StmtProfile.cpp b/lib/AST/StmtProfile.cpp
index bfd3132506ec..8ade242d56d9 100644
--- a/lib/AST/StmtProfile.cpp
+++ b/lib/AST/StmtProfile.cpp
@@ -215,6 +215,10 @@ void StmtProfiler::VisitSEHExceptStmt(const SEHExceptStmt *S) {
VisitStmt(S);
}
+void StmtProfiler::VisitCapturedStmt(const CapturedStmt *S) {
+ VisitStmt(S);
+}
+
void StmtProfiler::VisitObjCForCollectionStmt(const ObjCForCollectionStmt *S) {
VisitStmt(S);
}
@@ -766,6 +770,11 @@ void StmtProfiler::VisitCXXUuidofExpr(const CXXUuidofExpr *S) {
VisitType(S->getTypeOperand());
}
+void StmtProfiler::VisitMSPropertyRefExpr(const MSPropertyRefExpr *S) {
+ VisitExpr(S);
+ VisitDecl(S->getPropertyDecl());
+}
+
void StmtProfiler::VisitCXXThisExpr(const CXXThisExpr *S) {
VisitExpr(S);
ID.AddBoolean(S->isImplicit());
@@ -780,6 +789,11 @@ void StmtProfiler::VisitCXXDefaultArgExpr(const CXXDefaultArgExpr *S) {
VisitDecl(S->getParam());
}
+void StmtProfiler::VisitCXXDefaultInitExpr(const CXXDefaultInitExpr *S) {
+ VisitExpr(S);
+ VisitDecl(S->getField());
+}
+
void StmtProfiler::VisitCXXBindTemporaryExpr(const CXXBindTemporaryExpr *S) {
VisitExpr(S);
VisitDecl(
diff --git a/lib/AST/Type.cpp b/lib/AST/Type.cpp
index 0c5636d84067..fa16facb634f 100644
--- a/lib/AST/Type.cpp
+++ b/lib/AST/Type.cpp
@@ -1142,16 +1142,20 @@ bool QualType::isTriviallyCopyableType(ASTContext &Context) const {
-bool Type::isLiteralType() const {
+bool Type::isLiteralType(ASTContext &Ctx) const {
if (isDependentType())
return false;
- // C++0x [basic.types]p10:
+ // C++1y [basic.types]p10:
+ // A type is a literal type if it is:
+ // -- cv void; or
+ if (Ctx.getLangOpts().CPlusPlus1y && isVoidType())
+ return true;
+
+ // C++11 [basic.types]p10:
// A type is a literal type if it is:
// [...]
- // -- an array of literal type.
- // Extension: variable arrays cannot be literal types, since they're
- // runtime-sized.
+ // -- an array of literal type other than an array of runtime bound; or
if (isVariableArrayType())
return false;
const Type *BaseTy = getBaseElementTypeUnsafe();
@@ -1162,7 +1166,7 @@ bool Type::isLiteralType() const {
if (BaseTy->isIncompleteType())
return false;
- // C++0x [basic.types]p10:
+ // C++11 [basic.types]p10:
// A type is a literal type if it is:
// -- a scalar type; or
// As an extension, Clang treats vector types and complex types as
@@ -2101,6 +2105,11 @@ static CachedProperties computeCachedProperties(const Type *T) {
assert(T->isInstantiationDependentType());
return CachedProperties(ExternalLinkage, false);
+ case Type::Auto:
+ // Give non-deduced 'auto' types external linkage. We should only see them
+ // here in error recovery.
+ return CachedProperties(ExternalLinkage, false);
+
case Type::Builtin:
// C++ [basic.link]p8:
// A type is said to have linkage if and only if:
@@ -2202,6 +2211,9 @@ static LinkageInfo computeLinkageInfo(const Type *T) {
case Type::Builtin:
return LinkageInfo::external();
+ case Type::Auto:
+ return LinkageInfo::external();
+
case Type::Record:
case Type::Enum:
return cast<TagType>(T)->getDecl()->getLinkageAndVisibility();
diff --git a/lib/AST/TypePrinter.cpp b/lib/AST/TypePrinter.cpp
index 9d1717a220cd..043707622bd5 100644
--- a/lib/AST/TypePrinter.cpp
+++ b/lib/AST/TypePrinter.cpp
@@ -776,16 +776,16 @@ void TypePrinter::printUnaryTransformAfter(const UnaryTransformType *T,
void TypePrinter::printAutoBefore(const AutoType *T, raw_ostream &OS) {
// If the type has been deduced, do not print 'auto'.
- if (T->isDeduced()) {
+ if (!T->getDeducedType().isNull()) {
printBefore(T->getDeducedType(), OS);
} else {
- OS << "auto";
+ OS << (T->isDecltypeAuto() ? "decltype(auto)" : "auto");
spaceBeforePlaceHolder(OS);
}
}
void TypePrinter::printAutoAfter(const AutoType *T, raw_ostream &OS) {
// If the type has been deduced, do not print 'auto'.
- if (T->isDeduced())
+ if (!T->getDeducedType().isNull())
printAfter(T->getDeducedType(), OS);
}
diff --git a/lib/Analysis/BodyFarm.cpp b/lib/Analysis/BodyFarm.cpp
index dda26bfab894..4d5c2ee236f9 100644
--- a/lib/Analysis/BodyFarm.cpp
+++ b/lib/Analysis/BodyFarm.cpp
@@ -194,8 +194,8 @@ static Stmt *create_dispatch_once(ASTContext &C, const FunctionDecl *D) {
// (1) Create the call.
DeclRefExpr *DR = M.makeDeclRefExpr(Block);
ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
- CallExpr *CE = new (C) CallExpr(C, ICE, ArrayRef<Expr*>(), C.VoidTy,
- VK_RValue, SourceLocation());
+ CallExpr *CE = new (C) CallExpr(C, ICE, None, C.VoidTy, VK_RValue,
+ SourceLocation());
// (2) Create the assignment to the predicate.
IntegerLiteral *IL =
@@ -257,8 +257,8 @@ static Stmt *create_dispatch_sync(ASTContext &C, const FunctionDecl *D) {
ASTMaker M(C);
DeclRefExpr *DR = M.makeDeclRefExpr(PV);
ImplicitCastExpr *ICE = M.makeLvalueToRvalue(DR, Ty);
- CallExpr *CE = new (C) CallExpr(C, ICE, ArrayRef<Expr*>(), C.VoidTy,
- VK_RValue, SourceLocation());
+ CallExpr *CE = new (C) CallExpr(C, ICE, None, C.VoidTy, VK_RValue,
+ SourceLocation());
return CE;
}
diff --git a/lib/Analysis/CFG.cpp b/lib/Analysis/CFG.cpp
index 1adb8b84e462..096c7a080bf6 100644
--- a/lib/Analysis/CFG.cpp
+++ b/lib/Analysis/CFG.cpp
@@ -1085,11 +1085,16 @@ CFGBlock *CFGBuilder::Visit(Stmt * S, AddStmtChoice asc) {
return VisitExprWithCleanups(cast<ExprWithCleanups>(S), asc);
case Stmt::CXXDefaultArgExprClass:
+ case Stmt::CXXDefaultInitExprClass:
// FIXME: The expression inside a CXXDefaultArgExpr is owned by the
// called function's declaration, not by the caller. If we simply add
// this expression to the CFG, we could end up with the same Expr
// appearing multiple times.
// PR13385 / <rdar://problem/12156507>
+ //
+ // It's likewise possible for multiple CXXDefaultInitExprs for the same
+ // expression to be used in the same function (through aggregate
+ // initialization).
return VisitStmt(S, asc);
case Stmt::CXXBindTemporaryExprClass:
diff --git a/lib/Analysis/ThreadSafety.cpp b/lib/Analysis/ThreadSafety.cpp
index 4fe342dcc8c2..479d9a301f4b 100644
--- a/lib/Analysis/ThreadSafety.cpp
+++ b/lib/Analysis/ThreadSafety.cpp
@@ -2279,6 +2279,10 @@ void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
// Fill in source locations for all CFGBlocks.
findBlockLocations(CFGraph, SortedGraph, BlockInfo);
+ MutexIDList ExclusiveLocksAcquired;
+ MutexIDList SharedLocksAcquired;
+ MutexIDList LocksReleased;
+
// Add locks from exclusive_locks_required and shared_locks_required
// to initial lockset. Also turn off checking for lock and unlock functions.
// FIXME: is there a more intelligent way to check lock/unlock functions?
@@ -2300,15 +2304,30 @@ void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
} else if (SharedLocksRequiredAttr *A
= dyn_cast<SharedLocksRequiredAttr>(Attr)) {
getMutexIDs(SharedLocksToAdd, A, (Expr*) 0, D);
- } else if (isa<UnlockFunctionAttr>(Attr)) {
- // Don't try to check unlock functions for now
- return;
- } else if (isa<ExclusiveLockFunctionAttr>(Attr)) {
- // Don't try to check lock functions for now
- return;
- } else if (isa<SharedLockFunctionAttr>(Attr)) {
- // Don't try to check lock functions for now
- return;
+ } else if (UnlockFunctionAttr *A = dyn_cast<UnlockFunctionAttr>(Attr)) {
+ if (!Handler.issueBetaWarnings())
+ return;
+ // UNLOCK_FUNCTION() is used to hide the underlying lock implementation.
+ // We must ignore such methods.
+ if (A->args_size() == 0)
+ return;
+ // FIXME -- deal with exclusive vs. shared unlock functions?
+ getMutexIDs(ExclusiveLocksToAdd, A, (Expr*) 0, D);
+ getMutexIDs(LocksReleased, A, (Expr*) 0, D);
+ } else if (ExclusiveLockFunctionAttr *A
+ = dyn_cast<ExclusiveLockFunctionAttr>(Attr)) {
+ if (!Handler.issueBetaWarnings())
+ return;
+ if (A->args_size() == 0)
+ return;
+ getMutexIDs(ExclusiveLocksAcquired, A, (Expr*) 0, D);
+ } else if (SharedLockFunctionAttr *A
+ = dyn_cast<SharedLockFunctionAttr>(Attr)) {
+ if (!Handler.issueBetaWarnings())
+ return;
+ if (A->args_size() == 0)
+ return;
+ getMutexIDs(SharedLocksAcquired, A, (Expr*) 0, D);
} else if (isa<ExclusiveTrylockFunctionAttr>(Attr)) {
// Don't try to check trylock functions for now
return;
@@ -2491,8 +2510,27 @@ void ThreadSafetyAnalyzer::runAnalysis(AnalysisDeclContext &AC) {
if (!Final->Reachable)
return;
+ // By default, we expect all locks held on entry to be held on exit.
+ FactSet ExpectedExitSet = Initial->EntrySet;
+
+ // Adjust the expected exit set by adding or removing locks, as declared
+ // by *-LOCK_FUNCTION and UNLOCK_FUNCTION. The intersect below will then
+ // issue the appropriate warning.
+ // FIXME: the location here is not quite right.
+ for (unsigned i=0,n=ExclusiveLocksAcquired.size(); i<n; ++i) {
+ ExpectedExitSet.addLock(FactMan, ExclusiveLocksAcquired[i],
+ LockData(D->getLocation(), LK_Exclusive));
+ }
+ for (unsigned i=0,n=SharedLocksAcquired.size(); i<n; ++i) {
+ ExpectedExitSet.addLock(FactMan, SharedLocksAcquired[i],
+ LockData(D->getLocation(), LK_Shared));
+ }
+ for (unsigned i=0,n=LocksReleased.size(); i<n; ++i) {
+ ExpectedExitSet.removeLock(FactMan, LocksReleased[i]);
+ }
+
// FIXME: Should we call this function for all blocks which exit the function?
- intersectAndWarn(Initial->EntrySet, Final->ExitSet,
+ intersectAndWarn(ExpectedExitSet, Final->ExitSet,
Final->ExitLoc,
LEK_LockedAtEndOfFunction,
LEK_NotLockedAtEndOfFunction,
diff --git a/lib/Basic/Diagnostic.cpp b/lib/Basic/Diagnostic.cpp
index 842bacb9a5d0..45d4b539e8c2 100644
--- a/lib/Basic/Diagnostic.cpp
+++ b/lib/Basic/Diagnostic.cpp
@@ -971,6 +971,23 @@ bool DiagnosticConsumer::IncludeInDiagnosticCounts() const { return true; }
void IgnoringDiagConsumer::anchor() { }
+ForwardingDiagnosticConsumer::~ForwardingDiagnosticConsumer() {}
+
+void ForwardingDiagnosticConsumer::HandleDiagnostic(
+ DiagnosticsEngine::Level DiagLevel,
+ const Diagnostic &Info) {
+ Target.HandleDiagnostic(DiagLevel, Info);
+}
+
+void ForwardingDiagnosticConsumer::clear() {
+ DiagnosticConsumer::clear();
+ Target.clear();
+}
+
+bool ForwardingDiagnosticConsumer::IncludeInDiagnosticCounts() const {
+ return Target.IncludeInDiagnosticCounts();
+}
+
PartialDiagnostic::StorageAllocator::StorageAllocator() {
for (unsigned I = 0; I != NumCached; ++I)
FreeList[I] = Cached + I;
diff --git a/lib/Basic/IdentifierTable.cpp b/lib/Basic/IdentifierTable.cpp
index 429d9d8cb21e..951c718d183a 100644
--- a/lib/Basic/IdentifierTable.cpp
+++ b/lib/Basic/IdentifierTable.cpp
@@ -65,7 +65,7 @@ namespace {
};
}
-IdentifierIterator *IdentifierInfoLookup::getIdentifiers() const {
+IdentifierIterator *IdentifierInfoLookup::getIdentifiers() {
return new EmptyLookupIterator();
}
diff --git a/lib/Basic/SourceManager.cpp b/lib/Basic/SourceManager.cpp
index 1b8383bc4261..d6dc6d6328af 100644
--- a/lib/Basic/SourceManager.cpp
+++ b/lib/Basic/SourceManager.cpp
@@ -1848,23 +1848,42 @@ SourceManager::getMacroArgExpandedLocation(SourceLocation Loc) const {
return Loc;
}
+std::pair<FileID, unsigned>
+SourceManager::getDecomposedIncludedLoc(FileID FID) const {
+ // Uses IncludedLocMap to retrieve/cache the decomposed loc.
+
+ typedef std::pair<FileID, unsigned> DecompTy;
+ typedef llvm::DenseMap<FileID, DecompTy> MapTy;
+ std::pair<MapTy::iterator, bool>
+ InsertOp = IncludedLocMap.insert(std::make_pair(FID, DecompTy()));
+ DecompTy &DecompLoc = InsertOp.first->second;
+ if (!InsertOp.second)
+ return DecompLoc; // already in map.
+
+ SourceLocation UpperLoc;
+ const SrcMgr::SLocEntry &Entry = getSLocEntry(FID);
+ if (Entry.isExpansion())
+ UpperLoc = Entry.getExpansion().getExpansionLocStart();
+ else
+ UpperLoc = Entry.getFile().getIncludeLoc();
+
+ if (UpperLoc.isValid())
+ DecompLoc = getDecomposedLoc(UpperLoc);
+
+ return DecompLoc;
+}
+
/// Given a decomposed source location, move it up the include/expansion stack
/// to the parent source location. If this is possible, return the decomposed
/// version of the parent in Loc and return false. If Loc is the top-level
/// entry, return true and don't modify it.
static bool MoveUpIncludeHierarchy(std::pair<FileID, unsigned> &Loc,
const SourceManager &SM) {
- SourceLocation UpperLoc;
- const SrcMgr::SLocEntry &Entry = SM.getSLocEntry(Loc.first);
- if (Entry.isExpansion())
- UpperLoc = Entry.getExpansion().getExpansionLocStart();
- else
- UpperLoc = Entry.getFile().getIncludeLoc();
-
- if (UpperLoc.isInvalid())
+ std::pair<FileID, unsigned> UpperLoc = SM.getDecomposedIncludedLoc(Loc.first);
+ if (UpperLoc.first.isInvalid())
return true; // We reached the top.
-
- Loc = SM.getDecomposedLoc(UpperLoc);
+
+ Loc = UpperLoc;
return false;
}
@@ -1929,7 +1948,7 @@ bool SourceManager::isBeforeInTranslationUnit(SourceLocation LHS,
// of the other looking for a match.
// We use a map from FileID to Offset to store the chain. Easier than writing
// a custom set hash info that only depends on the first part of a pair.
- typedef llvm::DenseMap<FileID, unsigned> LocSet;
+ typedef llvm::SmallDenseMap<FileID, unsigned, 16> LocSet;
LocSet LChain;
do {
LChain.insert(LOffs);
diff --git a/lib/Basic/TargetInfo.cpp b/lib/Basic/TargetInfo.cpp
index 70ea2351ec35..0d44dc010e1a 100644
--- a/lib/Basic/TargetInfo.cpp
+++ b/lib/Basic/TargetInfo.cpp
@@ -37,6 +37,7 @@ TargetInfo::TargetInfo(const std::string &T) : TargetOpts(), Triple(T)
LongWidth = LongAlign = 32;
LongLongWidth = LongLongAlign = 64;
SuitableAlign = 64;
+ MinGlobalAlign = 0;
HalfWidth = 16;
HalfAlign = 16;
FloatWidth = 32;
@@ -373,7 +374,9 @@ bool TargetInfo::validateOutputConstraint(ConstraintInfo &Info) const {
Name++;
}
- return true;
+ // If a constraint allows neither memory nor register operands it contains
+ // only modifiers. Reject it.
+ return Info.allowsMemory() || Info.allowsRegister();
}
bool TargetInfo::resolveSymbolicName(const char *&Name,
diff --git a/lib/Basic/Targets.cpp b/lib/Basic/Targets.cpp
index 3eda9d8c1841..a622a11aa5a2 100644
--- a/lib/Basic/Targets.cpp
+++ b/lib/Basic/Targets.cpp
@@ -621,7 +621,7 @@ class NaClTargetInfo : public OSTargetInfo<Target> {
this->SizeType = TargetInfo::UnsignedInt;
this->PtrDiffType = TargetInfo::SignedInt;
this->IntPtrType = TargetInfo::SignedInt;
- this->RegParmMax = 2;
+ // RegParmMax is inherited from the underlying architecture
this->LongDoubleFormat = &llvm::APFloat::IEEEdouble;
this->DescriptionString = "e-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"
"f32:32:32-f64:64:64-p:32:32:32-v128:32:32";
@@ -1835,6 +1835,7 @@ class X86TargetInfo : public TargetInfo {
/// Bobcat architecture processors.
//@{
CK_BTVER1,
+ CK_BTVER2,
//@}
/// \name Bulldozer
@@ -1959,6 +1960,7 @@ public:
.Case("opteron-sse3", CK_OpteronSSE3)
.Case("amdfam10", CK_AMDFAM10)
.Case("btver1", CK_BTVER1)
+ .Case("btver2", CK_BTVER2)
.Case("bdver1", CK_BDVER1)
.Case("bdver2", CK_BDVER2)
.Case("x86-64", CK_x86_64)
@@ -2024,6 +2026,7 @@ public:
case CK_OpteronSSE3:
case CK_AMDFAM10:
case CK_BTVER1:
+ case CK_BTVER2:
case CK_BDVER1:
case CK_BDVER2:
case CK_x86_64:
@@ -2193,6 +2196,15 @@ void X86TargetInfo::getDefaultFeatures(llvm::StringMap<bool> &Features) const {
setFeatureEnabled(Features, "lzcnt", true);
setFeatureEnabled(Features, "popcnt", true);
break;
+ case CK_BTVER2:
+ setFeatureEnabled(Features, "avx", true);
+ setFeatureEnabled(Features, "sse4a", true);
+ setFeatureEnabled(Features, "lzcnt", true);
+ setFeatureEnabled(Features, "aes", true);
+ setFeatureEnabled(Features, "pclmul", true);
+ setFeatureEnabled(Features, "bmi", true);
+ setFeatureEnabled(Features, "f16c", true);
+ break;
case CK_BDVER1:
setFeatureEnabled(Features, "xop", true);
setFeatureEnabled(Features, "lzcnt", true);
@@ -2611,6 +2623,9 @@ void X86TargetInfo::getTargetDefines(const LangOptions &Opts,
case CK_BTVER1:
defineCPUMacros(Builder, "btver1");
break;
+ case CK_BTVER2:
+ defineCPUMacros(Builder, "btver2");
+ break;
case CK_BDVER1:
defineCPUMacros(Builder, "bdver1");
break;
@@ -3292,6 +3307,8 @@ namespace {
class AArch64TargetInfo : public TargetInfo {
static const char * const GCCRegNames[];
static const TargetInfo::GCCRegAlias GCCRegAliases[];
+
+ static const Builtin::Info BuiltinInfo[];
public:
AArch64TargetInfo(const std::string& triple) : TargetInfo(triple) {
BigEndian = false;
@@ -3323,45 +3340,45 @@ public:
// FIXME: these were written based on an unreleased version of a 32-bit ACLE
// which was intended to be compatible with a 64-bit implementation. They
// will need updating when a real 64-bit ACLE exists. Particularly pressing
- // instances are: __AARCH_ISA_A32, __AARCH_ISA_T32, __ARCH_PCS.
- Builder.defineMacro("__AARCH_ACLE", "101");
- Builder.defineMacro("__AARCH", "8");
- Builder.defineMacro("__AARCH_PROFILE", "'A'");
+ // instances are: __ARM_ARCH_ISA_ARM, __ARM_ARCH_ISA_THUMB, __ARM_PCS.
+ Builder.defineMacro("__ARM_ACLE", "101");
+ Builder.defineMacro("__ARM_ARCH", "8");
+ Builder.defineMacro("__ARM_ARCH_PROFILE", "'A'");
- Builder.defineMacro("__AARCH_FEATURE_UNALIGNED");
- Builder.defineMacro("__AARCH_FEATURE_CLZ");
- Builder.defineMacro("__AARCH_FEATURE_FMA");
+ Builder.defineMacro("__ARM_FEATURE_UNALIGNED");
+ Builder.defineMacro("__ARM_FEATURE_CLZ");
+ Builder.defineMacro("__ARM_FEATURE_FMA");
// FIXME: ACLE 1.1 reserves bit 4. Will almost certainly come to mean
// 128-bit LDXP present, at which point this becomes 0x1f.
- Builder.defineMacro("__AARCH_FEATURE_LDREX", "0xf");
+ Builder.defineMacro("__ARM_FEATURE_LDREX", "0xf");
// 0xe implies support for half, single and double precision operations.
- Builder.defineMacro("__AARCH_FP", "0xe");
+ Builder.defineMacro("__ARM_FP", "0xe");
// PCS specifies this for SysV variants, which is all we support. Other ABIs
- // may choose __AARCH_FP16_FORMAT_ALTERNATIVE.
- Builder.defineMacro("__AARCH_FP16_FORMAT_IEEE");
+ // may choose __ARM_FP16_FORMAT_ALTERNATIVE.
+ Builder.defineMacro("__ARM_FP16_FORMAT_IEEE");
if (Opts.FastMath || Opts.FiniteMathOnly)
- Builder.defineMacro("__AARCH_FP_FAST");
+ Builder.defineMacro("__ARM_FP_FAST");
if ((Opts.C99 || Opts.C11) && !Opts.Freestanding)
- Builder.defineMacro("__AARCH_FP_FENV_ROUNDING");
+ Builder.defineMacro("__ARM_FP_FENV_ROUNDING");
- Builder.defineMacro("__AARCH_SIZEOF_WCHAR_T",
+ Builder.defineMacro("__ARM_SIZEOF_WCHAR_T",
Opts.ShortWChar ? "2" : "4");
- Builder.defineMacro("__AARCH_SIZEOF_MINIMAL_ENUM",
+ Builder.defineMacro("__ARM_SIZEOF_MINIMAL_ENUM",
Opts.ShortEnums ? "1" : "4");
if (BigEndian)
- Builder.defineMacro("__AARCH_BIG_ENDIAN");
+ Builder.defineMacro("__ARM_BIG_ENDIAN");
}
virtual void getTargetBuiltins(const Builtin::Info *&Records,
unsigned &NumRecords) const {
- Records = 0;
- NumRecords = 0;
+ Records = BuiltinInfo;
+ NumRecords = clang::AArch64::LastTSBuiltin-Builtin::FirstTSBuiltin;
}
virtual bool hasFeature(StringRef Feature) const {
return Feature == "aarch64";
@@ -3470,6 +3487,14 @@ void AArch64TargetInfo::getGCCRegAliases(const GCCRegAlias *&Aliases,
NumAliases = llvm::array_lengthof(GCCRegAliases);
}
+
+const Builtin::Info AArch64TargetInfo::BuiltinInfo[] = {
+#define BUILTIN(ID, TYPE, ATTRS) { #ID, TYPE, ATTRS, 0, ALL_LANGUAGES },
+#define LIBBUILTIN(ID, TYPE, ATTRS, HEADER) { #ID, TYPE, ATTRS, HEADER,\
+ ALL_LANGUAGES },
+#include "clang/Basic/BuiltinsAArch64.def"
+};
+
} // end anonymous namespace
namespace {
@@ -3502,6 +3527,34 @@ class ARMTargetInfo : public TargetInfo {
static const Builtin::Info BuiltinInfo[];
+ static bool shouldUseInlineAtomic(const llvm::Triple &T) {
+ // On linux, binaries targeting old cpus call functions in libgcc to
+ // perform atomic operations. The implementation in libgcc then calls into
+ // the kernel which on armv6 and newer uses ldrex and strex. The net result
+ // is that if we assume the kernel is at least as recent as the hardware,
+ // it is safe to use atomic instructions on armv6 and newer.
+ if (T.getOS() != llvm::Triple::Linux)
+ return false;
+ StringRef ArchName = T.getArchName();
+ if (T.getArch() == llvm::Triple::arm) {
+ if (!ArchName.startswith("armv"))
+ return false;
+ StringRef VersionStr = ArchName.substr(4);
+ unsigned Version;
+ if (VersionStr.getAsInteger(10, Version))
+ return false;
+ return Version >= 6;
+ }
+ assert(T.getArch() == llvm::Triple::thumb);
+ if (!ArchName.startswith("thumbv"))
+ return false;
+ StringRef VersionStr = ArchName.substr(6);
+ unsigned Version;
+ if (VersionStr.getAsInteger(10, Version))
+ return false;
+ return Version >= 7;
+ }
+
public:
ARMTargetInfo(const std::string &TripleStr)
: TargetInfo(TripleStr), ABI("aapcs-linux"), CPU("arm1136j-s"), IsAAPCS(true)
@@ -3534,8 +3587,9 @@ public:
TheCXXABI.set(TargetCXXABI::GenericARM);
// ARM has atomics up to 8 bytes
- // FIXME: Set MaxAtomicInlineWidth if we have the feature v6e
MaxAtomicPromoteWidth = 64;
+ if (shouldUseInlineAtomic(getTriple()))
+ MaxAtomicInlineWidth = 64;
// Do force alignment of members that follow zero length bitfields. If
// the alignment of the zero-length bitfield is greater than the member
@@ -4111,16 +4165,14 @@ const Builtin::Info HexagonTargetInfo::BuiltinInfo[] = {
namespace {
-class SparcV8TargetInfo : public TargetInfo {
+// Shared base class for SPARC v8 (32-bit) and SPARC v9 (64-bit).
+class SparcTargetInfo : public TargetInfo {
static const TargetInfo::GCCRegAlias GCCRegAliases[];
static const char * const GCCRegNames[];
bool SoftFloat;
public:
- SparcV8TargetInfo(const std::string& triple) : TargetInfo(triple) {
- // FIXME: Support Sparc quad-precision long double?
- DescriptionString = "e-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-"
- "i64:64:64-f32:32:32-f64:64:64-v64:64:64-n32";
- }
+ SparcTargetInfo(const std::string &triple) : TargetInfo(triple) {}
+
virtual bool setFeatureEnabled(llvm::StringMap<bool> &Features,
StringRef Name,
bool Enabled) const {
@@ -4140,7 +4192,6 @@ public:
virtual void getTargetDefines(const LangOptions &Opts,
MacroBuilder &Builder) const {
DefineStd(Builder, "sparc", Opts);
- Builder.defineMacro("__sparcv8");
Builder.defineMacro("__REGISTER_PREFIX__", "");
if (SoftFloat)
@@ -4176,20 +4227,20 @@ public:
}
};
-const char * const SparcV8TargetInfo::GCCRegNames[] = {
+const char * const SparcTargetInfo::GCCRegNames[] = {
"r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
"r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
"r16", "r17", "r18", "r19", "r20", "r21", "r22", "r23",
"r24", "r25", "r26", "r27", "r28", "r29", "r30", "r31"
};
-void SparcV8TargetInfo::getGCCRegNames(const char * const *&Names,
- unsigned &NumNames) const {
+void SparcTargetInfo::getGCCRegNames(const char * const *&Names,
+ unsigned &NumNames) const {
Names = GCCRegNames;
NumNames = llvm::array_lengthof(GCCRegNames);
}
-const TargetInfo::GCCRegAlias SparcV8TargetInfo::GCCRegAliases[] = {
+const TargetInfo::GCCRegAlias SparcTargetInfo::GCCRegAliases[] = {
{ { "g0" }, "r0" },
{ { "g1" }, "r1" },
{ { "g2" }, "r2" },
@@ -4224,11 +4275,53 @@ const TargetInfo::GCCRegAlias SparcV8TargetInfo::GCCRegAliases[] = {
{ { "i7" }, "r31" },
};
-void SparcV8TargetInfo::getGCCRegAliases(const GCCRegAlias *&Aliases,
- unsigned &NumAliases) const {
+void SparcTargetInfo::getGCCRegAliases(const GCCRegAlias *&Aliases,
+ unsigned &NumAliases) const {
Aliases = GCCRegAliases;
NumAliases = llvm::array_lengthof(GCCRegAliases);
}
+
+// SPARC v8 is the 32-bit mode selected by Triple::sparc.
+class SparcV8TargetInfo : public SparcTargetInfo {
+public:
+ SparcV8TargetInfo(const std::string& triple) : SparcTargetInfo(triple) {
+ // FIXME: Support Sparc quad-precision long double?
+ DescriptionString = "E-p:32:32:32-i1:8:8-i8:8:8-i16:16:16-i32:32:32-"
+ "i64:64:64-f32:32:32-f64:64:64-v64:64:64-n32-S64";
+ }
+
+ virtual void getTargetDefines(const LangOptions &Opts,
+ MacroBuilder &Builder) const {
+ SparcTargetInfo::getTargetDefines(Opts, Builder);
+ Builder.defineMacro("__sparcv8");
+ }
+};
+
+// SPARC v9 is the 64-bit mode selected by Triple::sparcv9.
+class SparcV9TargetInfo : public SparcTargetInfo {
+public:
+ SparcV9TargetInfo(const std::string& triple) : SparcTargetInfo(triple) {
+ // FIXME: Support Sparc quad-precision long double?
+ DescriptionString = "E-p:64:64:64-i1:8:8-i8:8:8-i16:16:16-i32:32:32-"
+ "i64:64:64-f32:32:32-f64:64:64-v64:64:64-n32:64-S128";
+ }
+
+ virtual void getTargetDefines(const LangOptions &Opts,
+ MacroBuilder &Builder) const {
+ SparcTargetInfo::getTargetDefines(Opts, Builder);
+ Builder.defineMacro("__sparcv9");
+ Builder.defineMacro("__arch64__");
+ // Solaris and its derivative AuroraUX don't need these variants, but the
+ // BSDs do.
+ if (getTriple().getOS() != llvm::Triple::Solaris &&
+ getTriple().getOS() != llvm::Triple::AuroraUX) {
+ Builder.defineMacro("__sparc64__");
+ Builder.defineMacro("__sparc_v9__");
+ Builder.defineMacro("__sparcv9__");
+ }
+ }
+};
+
} // end anonymous namespace.
namespace {
@@ -4251,6 +4344,100 @@ public:
} // end anonymous namespace.
namespace {
+ class SystemZTargetInfo : public TargetInfo {
+ static const char *const GCCRegNames[];
+
+ public:
+ SystemZTargetInfo(const std::string& triple) : TargetInfo(triple) {
+ TLSSupported = true;
+ IntWidth = IntAlign = 32;
+ LongWidth = LongLongWidth = LongAlign = LongLongAlign = 64;
+ PointerWidth = PointerAlign = 64;
+ LongDoubleWidth = 128;
+ LongDoubleAlign = 64;
+ LongDoubleFormat = &llvm::APFloat::IEEEquad;
+ MinGlobalAlign = 16;
+ DescriptionString = "E-p:64:64:64-i1:8:16-i8:8:16-i16:16-i32:32-i64:64"
+ "-f32:32-f64:64-f128:64-a0:8:16-n32:64";
+ MaxAtomicPromoteWidth = MaxAtomicInlineWidth = 64;
+ }
+ virtual void getTargetDefines(const LangOptions &Opts,
+ MacroBuilder &Builder) const {
+ Builder.defineMacro("__s390__");
+ Builder.defineMacro("__s390x__");
+ Builder.defineMacro("__zarch__");
+ Builder.defineMacro("__LONG_DOUBLE_128__");
+ }
+ virtual void getTargetBuiltins(const Builtin::Info *&Records,
+ unsigned &NumRecords) const {
+ // FIXME: Implement.
+ Records = 0;
+ NumRecords = 0;
+ }
+
+ virtual void getGCCRegNames(const char *const *&Names,
+ unsigned &NumNames) const;
+ virtual void getGCCRegAliases(const GCCRegAlias *&Aliases,
+ unsigned &NumAliases) const {
+ // No aliases.
+ Aliases = 0;
+ NumAliases = 0;
+ }
+ virtual bool validateAsmConstraint(const char *&Name,
+ TargetInfo::ConstraintInfo &info) const;
+ virtual const char *getClobbers() const {
+ // FIXME: Is this really right?
+ return "";
+ }
+ virtual BuiltinVaListKind getBuiltinVaListKind() const {
+ return TargetInfo::SystemZBuiltinVaList;
+ }
+ };
+
+ const char *const SystemZTargetInfo::GCCRegNames[] = {
+ "r0", "r1", "r2", "r3", "r4", "r5", "r6", "r7",
+ "r8", "r9", "r10", "r11", "r12", "r13", "r14", "r15",
+ "f0", "f2", "f4", "f6", "f1", "f3", "f5", "f7",
+ "f8", "f10", "f12", "f14", "f9", "f11", "f13", "f15"
+ };
+
+ void SystemZTargetInfo::getGCCRegNames(const char *const *&Names,
+ unsigned &NumNames) const {
+ Names = GCCRegNames;
+ NumNames = llvm::array_lengthof(GCCRegNames);
+ }
+
+ bool SystemZTargetInfo::
+ validateAsmConstraint(const char *&Name,
+ TargetInfo::ConstraintInfo &Info) const {
+ switch (*Name) {
+ default:
+ return false;
+
+ case 'a': // Address register
+ case 'd': // Data register (equivalent to 'r')
+ case 'f': // Floating-point register
+ Info.setAllowsRegister();
+ return true;
+
+ case 'I': // Unsigned 8-bit constant
+ case 'J': // Unsigned 12-bit constant
+ case 'K': // Signed 16-bit constant
+ case 'L': // Signed 20-bit displacement (on all targets we support)
+ case 'M': // 0x7fffffff
+ return true;
+
+ case 'Q': // Memory with base and unsigned 12-bit displacement
+ case 'R': // Likewise, plus an index
+ case 'S': // Memory with base and signed 20-bit displacement
+ case 'T': // Likewise, plus an index
+ Info.setAllowsMemory();
+ return true;
+ }
+ }
+}
+
+namespace {
class MSP430TargetInfo : public TargetInfo {
static const char * const GCCRegNames[];
public:
@@ -4405,8 +4592,10 @@ class MipsTargetInfoBase : public TargetInfo {
static const Builtin::Info BuiltinInfo[];
std::string CPU;
bool IsMips16;
+ bool IsMicromips;
+ bool IsSingleFloat;
enum MipsFloatABI {
- HardFloat, SingleFloat, SoftFloat
+ HardFloat, SoftFloat
} FloatABI;
enum DspRevEnum {
NoDSP, DSP1, DSP2
@@ -4422,6 +4611,8 @@ public:
: TargetInfo(triple),
CPU(CPUStr),
IsMips16(false),
+ IsMicromips(false),
+ IsSingleFloat(false),
FloatABI(HardFloat),
DspRev(NoDSP),
ABI(ABIStr)
@@ -4448,18 +4639,20 @@ public:
case HardFloat:
Builder.defineMacro("__mips_hard_float", Twine(1));
break;
- case SingleFloat:
- Builder.defineMacro("__mips_hard_float", Twine(1));
- Builder.defineMacro("__mips_single_float", Twine(1));
- break;
case SoftFloat:
Builder.defineMacro("__mips_soft_float", Twine(1));
break;
}
+ if (IsSingleFloat)
+ Builder.defineMacro("__mips_single_float", Twine(1));
+
if (IsMips16)
Builder.defineMacro("__mips16", Twine(1));
+ if (IsMicromips)
+ Builder.defineMacro("__mips_micromips", Twine(1));
+
switch (DspRev) {
default:
break;
@@ -4549,7 +4742,8 @@ public:
Name == "o32" || Name == "n32" || Name == "n64" || Name == "eabi" ||
Name == "mips32" || Name == "mips32r2" ||
Name == "mips64" || Name == "mips64r2" ||
- Name == "mips16" || Name == "dsp" || Name == "dspr2") {
+ Name == "mips16" || Name == "micromips" ||
+ Name == "dsp" || Name == "dspr2") {
Features[Name] = Enabled;
return true;
} else if (Name == "32") {
@@ -4564,17 +4758,21 @@ public:
virtual void HandleTargetFeatures(std::vector<std::string> &Features) {
IsMips16 = false;
+ IsMicromips = false;
+ IsSingleFloat = false;
FloatABI = HardFloat;
DspRev = NoDSP;
for (std::vector<std::string>::iterator it = Features.begin(),
ie = Features.end(); it != ie; ++it) {
if (*it == "+single-float")
- FloatABI = SingleFloat;
+ IsSingleFloat = true;
else if (*it == "+soft-float")
FloatABI = SoftFloat;
else if (*it == "+mips16")
IsMips16 = true;
+ else if (*it == "+micromips")
+ IsMicromips = true;
else if (*it == "+dsp")
DspRev = std::max(DspRev, DSP1);
else if (*it == "+dspr2")
@@ -4862,7 +5060,7 @@ public:
this->SizeType = TargetInfo::UnsignedInt;
this->PtrDiffType = TargetInfo::SignedInt;
this->IntPtrType = TargetInfo::SignedInt;
- this->RegParmMax = 2;
+ this->RegParmMax = 0; // Disallow regparm
DescriptionString = "e-i1:8:8-i8:8:8-i16:16:16-i32:32:32-i64:64:64-"
"f32:32:32-f64:64:64-p:32:32:32-v128:32:32";
}
@@ -5188,6 +5386,32 @@ static TargetInfo *AllocateTarget(const std::string &T) {
return new SparcV8TargetInfo(T);
}
+ case llvm::Triple::sparcv9:
+ switch (os) {
+ case llvm::Triple::Linux:
+ return new LinuxTargetInfo<SparcV9TargetInfo>(T);
+ case llvm::Triple::AuroraUX:
+ return new AuroraUXTargetInfo<SparcV9TargetInfo>(T);
+ case llvm::Triple::Solaris:
+ return new SolarisTargetInfo<SparcV9TargetInfo>(T);
+ case llvm::Triple::NetBSD:
+ return new NetBSDTargetInfo<SparcV9TargetInfo>(T);
+ case llvm::Triple::OpenBSD:
+ return new OpenBSDTargetInfo<SparcV9TargetInfo>(T);
+ case llvm::Triple::FreeBSD:
+ return new FreeBSDTargetInfo<SparcV9TargetInfo>(T);
+ default:
+ return new SparcV9TargetInfo(T);
+ }
+
+ case llvm::Triple::systemz:
+ switch (os) {
+ case llvm::Triple::Linux:
+ return new LinuxTargetInfo<SystemZTargetInfo>(T);
+ default:
+ return new SystemZTargetInfo(T);
+ }
+
case llvm::Triple::tce:
return new TCETargetInfo(T);
diff --git a/lib/Basic/Version.cpp b/lib/Basic/Version.cpp
index 7381e7025083..743143d643ae 100644
--- a/lib/Basic/Version.cpp
+++ b/lib/Basic/Version.cpp
@@ -36,7 +36,7 @@ std::string getClangRepositoryPath() {
// If the SVN_REPOSITORY is empty, try to use the SVN keyword. This helps us
// pick up a tag in an SVN export, for example.
- static StringRef SVNRepository("$URL: http://llvm.org/svn/llvm-project/cfe/trunk/lib/Basic/Version.cpp $");
+ static StringRef SVNRepository("$URL: http://llvm.org/svn/llvm-project/cfe/tags/RELEASE_33/final/lib/Basic/Version.cpp $");
if (URL.empty()) {
URL = SVNRepository.slice(SVNRepository.find(':'),
SVNRepository.find("/lib/Basic"));
diff --git a/lib/CodeGen/ABIInfo.h b/lib/CodeGen/ABIInfo.h
index 35780f1556dd..df6dc7216a47 100644
--- a/lib/CodeGen/ABIInfo.h
+++ b/lib/CodeGen/ABIInfo.h
@@ -22,6 +22,7 @@ namespace llvm {
namespace clang {
class ASTContext;
+ class TargetInfo;
namespace CodeGen {
class CGFunctionInfo;
@@ -196,6 +197,7 @@ namespace clang {
ASTContext &getContext() const;
llvm::LLVMContext &getVMContext() const;
const llvm::DataLayout &getDataLayout() const;
+ const TargetInfo &getTarget() const;
/// Return the calling convention to use for system runtime
/// functions.
diff --git a/lib/CodeGen/CGAtomic.cpp b/lib/CodeGen/CGAtomic.cpp
index 817d5c4cc687..0b48a5c66435 100644
--- a/lib/CodeGen/CGAtomic.cpp
+++ b/lib/CodeGen/CGAtomic.cpp
@@ -327,7 +327,7 @@ RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest) {
CharUnits alignChars = getContext().getTypeAlignInChars(AtomicTy);
unsigned Align = alignChars.getQuantity();
unsigned MaxInlineWidthInBits =
- getContext().getTargetInfo().getMaxAtomicInlineWidth();
+ getTarget().getMaxAtomicInlineWidth();
bool UseLibcall = (Size != Align ||
getContext().toBits(sizeChars) > MaxInlineWidthInBits);
@@ -483,15 +483,6 @@ RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E, llvm::Value *Dest) {
Args.add(RValue::get(EmitCastToVoidPtr(Dest)),
getContext().VoidPtrTy);
break;
-#if 0
- // These are only defined for 1-16 byte integers. It is not clear what
- // their semantics would be on anything else...
- case AtomicExpr::Add: LibCallName = "__atomic_fetch_add_generic"; break;
- case AtomicExpr::Sub: LibCallName = "__atomic_fetch_sub_generic"; break;
- case AtomicExpr::And: LibCallName = "__atomic_fetch_and_generic"; break;
- case AtomicExpr::Or: LibCallName = "__atomic_fetch_or_generic"; break;
- case AtomicExpr::Xor: LibCallName = "__atomic_fetch_xor_generic"; break;
-#endif
default: return EmitUnsupportedRValue(E, "atomic library call");
}
// order is always the last parameter
diff --git a/lib/CodeGen/CGBlocks.cpp b/lib/CodeGen/CGBlocks.cpp
index 227ee2d024c6..ded019e64ae8 100644
--- a/lib/CodeGen/CGBlocks.cpp
+++ b/lib/CodeGen/CGBlocks.cpp
@@ -695,8 +695,8 @@ llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
bool isLambdaConv = blockInfo.getBlockDecl()->isConversionFromLambda();
llvm::Constant *blockFn
= CodeGenFunction(CGM, true).GenerateBlockFunction(CurGD, blockInfo,
- CurFuncDecl, LocalDeclMap,
- isLambdaConv);
+ LocalDeclMap,
+ isLambdaConv);
blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
// If there is nothing to capture, we can emit this as a global block.
@@ -753,6 +753,7 @@ llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
if (capture.isConstant()) continue;
QualType type = variable->getType();
+ CharUnits align = getContext().getDeclAlign(variable);
// This will be a [[type]]*, except that a byref entry will just be
// an i8**.
@@ -796,21 +797,21 @@ llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
if (ci->isByRef()) {
// Get a void* that points to the byref struct.
if (ci->isNested())
- src = Builder.CreateLoad(src, "byref.capture");
+ src = Builder.CreateAlignedLoad(src, align.getQuantity(),
+ "byref.capture");
else
src = Builder.CreateBitCast(src, VoidPtrTy);
// Write that void* into the capture field.
- Builder.CreateStore(src, blockField);
+ Builder.CreateAlignedStore(src, blockField, align.getQuantity());
// If we have a copy constructor, evaluate that into the block field.
} else if (const Expr *copyExpr = ci->getCopyExpr()) {
if (blockDecl->isConversionFromLambda()) {
// If we have a lambda conversion, emit the expression
// directly into the block instead.
- CharUnits Align = getContext().getTypeAlignInChars(type);
AggValueSlot Slot =
- AggValueSlot::forAddr(blockField, Align, Qualifiers(),
+ AggValueSlot::forAddr(blockField, align, Qualifiers(),
AggValueSlot::IsDestructed,
AggValueSlot::DoesNotNeedGCBarriers,
AggValueSlot::IsNotAliased);
@@ -821,7 +822,27 @@ llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
// If it's a reference variable, copy the reference into the block field.
} else if (type->isReferenceType()) {
- Builder.CreateStore(Builder.CreateLoad(src, "ref.val"), blockField);
+ llvm::Value *ref =
+ Builder.CreateAlignedLoad(src, align.getQuantity(), "ref.val");
+ Builder.CreateAlignedStore(ref, blockField, align.getQuantity());
+
+ // If this is an ARC __strong block-pointer variable, don't do a
+ // block copy.
+ //
+ // TODO: this can be generalized into the normal initialization logic:
+ // we should never need to do a block-copy when initializing a local
+ // variable, because the local variable's lifetime should be strictly
+ // contained within the stack block's.
+ } else if (type.getObjCLifetime() == Qualifiers::OCL_Strong &&
+ type->isBlockPointerType()) {
+ // Load the block and do a simple retain.
+ LValue srcLV = MakeAddrLValue(src, type, align);
+ llvm::Value *value = EmitLoadOfScalar(srcLV);
+ value = EmitARCRetainNonBlock(value);
+
+ // Do a primitive store to the block field.
+ LValue destLV = MakeAddrLValue(blockField, type, align);
+ EmitStoreOfScalar(value, destLV, /*init*/ true);
// Otherwise, fake up a POD copy into the block field.
} else {
@@ -839,8 +860,7 @@ llvm::Value *CodeGenFunction::EmitBlockLiteral(const CGBlockInfo &blockInfo) {
ImplicitCastExpr l2r(ImplicitCastExpr::OnStack, type, CK_LValueToRValue,
&declRef, VK_RValue);
EmitExprAsInit(&l2r, &blockFieldPseudoVar,
- MakeAddrLValue(blockField, type,
- getContext().getDeclAlign(variable)),
+ MakeAddrLValue(blockField, type, align),
/*captured by init*/ false);
}
@@ -1014,7 +1034,7 @@ CodeGenModule::GetAddrOfGlobalBlock(const BlockExpr *blockExpr,
llvm::DenseMap<const Decl*, llvm::Value*> LocalDeclMap;
blockFn = CodeGenFunction(*this).GenerateBlockFunction(GlobalDecl(),
blockInfo,
- 0, LocalDeclMap,
+ LocalDeclMap,
false);
}
blockFn = llvm::ConstantExpr::getBitCast(blockFn, VoidPtrTy);
@@ -1068,7 +1088,6 @@ static llvm::Constant *buildGlobalBlock(CodeGenModule &CGM,
llvm::Function *
CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
const CGBlockInfo &blockInfo,
- const Decl *outerFnDecl,
const DeclMapTy &ldm,
bool IsLambdaConversionToBlock) {
const BlockDecl *blockDecl = blockInfo.getBlockDecl();
@@ -1128,7 +1147,6 @@ CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
// Begin generating the function.
StartFunction(blockDecl, fnType->getResultType(), fn, fnInfo, args,
blockInfo.getBlockExpr()->getBody()->getLocStart());
- CurFuncDecl = outerFnDecl; // StartFunction sets this to blockDecl
// Okay. Undo some of what StartFunction did.
@@ -1149,11 +1167,9 @@ CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
Alloca->setAlignment(Align);
// Set the DebugLocation to empty, so the store is recognized as a
// frame setup instruction by llvm::DwarfDebug::beginFunction().
- llvm::DebugLoc Empty;
- llvm::DebugLoc Loc = Builder.getCurrentDebugLocation();
- Builder.SetCurrentDebugLocation(Empty);
+ Builder.DisableDebugLocations();
Builder.CreateAlignedStore(BlockPointer, Alloca, Align);
- Builder.SetCurrentDebugLocation(Loc);
+ Builder.EnableDebugLocations();
BlockPointerDbgLoc = Alloca;
}
@@ -1166,23 +1182,6 @@ CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
CXXThisValue = Builder.CreateLoad(addr, "this");
}
- // LoadObjCSelf() expects there to be an entry for 'self' in LocalDeclMap;
- // appease it.
- if (const ObjCMethodDecl *method
- = dyn_cast_or_null<ObjCMethodDecl>(CurFuncDecl)) {
- const VarDecl *self = method->getSelfDecl();
-
- // There might not be a capture for 'self', but if there is...
- if (blockInfo.Captures.count(self)) {
- const CGBlockInfo::Capture &capture = blockInfo.getCapture(self);
-
- llvm::Value *selfAddr = Builder.CreateStructGEP(BlockPointer,
- capture.getIndex(),
- "block.captured-self");
- LocalDeclMap[self] = selfAddr;
- }
- }
-
// Also force all the constant captures.
for (BlockDecl::capture_const_iterator ci = blockDecl->capture_begin(),
ce = blockDecl->capture_end(); ci != ce; ++ci) {
@@ -1241,7 +1240,7 @@ CodeGenFunction::GenerateBlockFunction(GlobalDecl GD,
}
// Recover location if it was changed in the above loop.
DI->EmitLocation(Builder,
- cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
+ cast<CompoundStmt>(blockDecl->getBody())->getRBracLoc());
}
// And resume where we left off.
@@ -2062,7 +2061,8 @@ llvm::Type *CodeGenFunction::BuildByRefType(const VarDecl *D) {
bool Packed = false;
CharUnits Align = getContext().getDeclAlign(D);
- if (Align > getContext().toCharUnitsFromBits(Target.getPointerAlign(0))) {
+ if (Align >
+ getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0))) {
// We have to insert padding.
// The struct above has 2 32-bit integers.
diff --git a/lib/CodeGen/CGBuiltin.cpp b/lib/CodeGen/CGBuiltin.cpp
index 3c89652b6dd5..d18767897f39 100644
--- a/lib/CodeGen/CGBuiltin.cpp
+++ b/lib/CodeGen/CGBuiltin.cpp
@@ -296,7 +296,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD,
Value *F = CGM.getIntrinsic(Intrinsic::cttz, ArgType);
llvm::Type *ResultType = ConvertType(E->getType());
- Value *ZeroUndef = Builder.getInt1(Target.isCLZForZeroUndef());
+ Value *ZeroUndef = Builder.getInt1(getTarget().isCLZForZeroUndef());
Value *Result = Builder.CreateCall2(F, ArgValue, ZeroUndef);
if (Result->getType() != ResultType)
Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
@@ -313,7 +313,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD,
Value *F = CGM.getIntrinsic(Intrinsic::ctlz, ArgType);
llvm::Type *ResultType = ConvertType(E->getType());
- Value *ZeroUndef = Builder.getInt1(Target.isCLZForZeroUndef());
+ Value *ZeroUndef = Builder.getInt1(getTarget().isCLZForZeroUndef());
Value *Result = Builder.CreateCall2(F, ArgValue, ZeroUndef);
if (Result->getType() != ResultType)
Result = Builder.CreateIntCast(Result, ResultType, /*isSigned*/true,
@@ -1430,7 +1430,7 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD,
const char *Name = getContext().BuiltinInfo.GetName(BuiltinID);
Intrinsic::ID IntrinsicID = Intrinsic::not_intrinsic;
if (const char *Prefix =
- llvm::Triple::getArchTypePrefix(Target.getTriple().getArch()))
+ llvm::Triple::getArchTypePrefix(getTarget().getTriple().getArch()))
IntrinsicID = Intrinsic::getIntrinsicForGCCBuiltin(Prefix, Name);
if (IntrinsicID != Intrinsic::not_intrinsic) {
@@ -1501,7 +1501,9 @@ RValue CodeGenFunction::EmitBuiltinExpr(const FunctionDecl *FD,
Value *CodeGenFunction::EmitTargetBuiltinExpr(unsigned BuiltinID,
const CallExpr *E) {
- switch (Target.getTriple().getArch()) {
+ switch (getTarget().getTriple().getArch()) {
+ case llvm::Triple::aarch64:
+ return EmitAArch64BuiltinExpr(BuiltinID, E);
case llvm::Triple::arm:
case llvm::Triple::thumb:
return EmitARMBuiltinExpr(BuiltinID, E);
@@ -1621,6 +1623,25 @@ CodeGenFunction::EmitPointerWithAlignment(const Expr *Addr) {
return std::make_pair(EmitScalarExpr(Addr), Align);
}
+Value *CodeGenFunction::EmitAArch64BuiltinExpr(unsigned BuiltinID,
+ const CallExpr *E) {
+ if (BuiltinID == AArch64::BI__clear_cache) {
+ assert(E->getNumArgs() == 2 &&
+ "Variadic __clear_cache slipped through on AArch64");
+
+ const FunctionDecl *FD = E->getDirectCallee();
+ SmallVector<Value *, 2> Ops;
+ for (unsigned i = 0; i < E->getNumArgs(); i++)
+ Ops.push_back(EmitScalarExpr(E->getArg(i)));
+ llvm::Type *Ty = CGM.getTypes().ConvertType(FD->getType());
+ llvm::FunctionType *FTy = cast<llvm::FunctionType>(Ty);
+ StringRef Name = FD->getName();
+ return EmitNounwindRuntimeCall(CGM.CreateRuntimeFunction(FTy, Name), Ops);
+ }
+
+ return 0;
+}
+
Value *CodeGenFunction::EmitARMBuiltinExpr(unsigned BuiltinID,
const CallExpr *E) {
if (BuiltinID == ARM::BI__clear_cache) {
@@ -1852,7 +1873,7 @@ Value *CodeGenFunction::EmitARMBuiltinExpr(unsigned BuiltinID,
// Generate target-independent intrinsic; also need to add second argument
// for whether or not clz of zero is undefined; on ARM it isn't.
Function *F = CGM.getIntrinsic(Intrinsic::ctlz, Ty);
- Ops.push_back(Builder.getInt1(Target.isCLZForZeroUndef()));
+ Ops.push_back(Builder.getInt1(getTarget().isCLZForZeroUndef()));
return EmitNeonCall(F, Ops, "vclz");
}
case ARM::BI__builtin_neon_vcnt_v:
diff --git a/lib/CodeGen/CGCXXABI.cpp b/lib/CodeGen/CGCXXABI.cpp
index 0c0a76f346a5..68fecb2d0cb8 100644
--- a/lib/CodeGen/CGCXXABI.cpp
+++ b/lib/CodeGen/CGCXXABI.cpp
@@ -220,8 +220,12 @@ void CGCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
}
void CGCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
+ const VarDecl &D,
llvm::Constant *dtor,
llvm::Constant *addr) {
+ if (D.getTLSKind())
+ CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
+
// The default behavior is to use atexit.
CGF.registerGlobalDtorWithAtExit(dtor, addr);
}
@@ -255,3 +259,14 @@ llvm::BasicBlock *CGCXXABI::EmitCtorCompleteObjectHandler(
ErrorUnsupportedABI(CGF, "complete object detection in ctor");
return 0;
}
+
+void CGCXXABI::EmitThreadLocalInitFuncs(
+ llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
+ llvm::Function *InitFunc) {
+}
+
+LValue CGCXXABI::EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
+ const DeclRefExpr *DRE) {
+ ErrorUnsupportedABI(CGF, "odr-use of thread_local global");
+ return LValue();
+}
diff --git a/lib/CodeGen/CGCXXABI.h b/lib/CodeGen/CGCXXABI.h
index 702e59b71a72..1e4da631d6f6 100644
--- a/lib/CodeGen/CGCXXABI.h
+++ b/lib/CodeGen/CGCXXABI.h
@@ -101,6 +101,27 @@ public:
/// kinds that the ABI says returns 'this'.
virtual bool HasThisReturn(GlobalDecl GD) const { return false; }
+ /// Returns true if the given record type should be returned indirectly.
+ virtual bool isReturnTypeIndirect(const CXXRecordDecl *RD) const = 0;
+
+ /// Specify how one should pass an argument of a record type.
+ enum RecordArgABI {
+ /// Pass it using the normal C aggregate rules for the ABI, potentially
+ /// introducing extra copies and passing some or all of it in registers.
+ RAA_Default = 0,
+
+ /// Pass it on the stack using its defined layout. The argument must be
+ /// evaluated directly into the correct stack position in the arguments area,
+ /// and the call machinery must not move it or introduce extra copies.
+ RAA_DirectInMemory,
+
+ /// Pass it as a pointer to temporary memory.
+ RAA_Indirect
+ };
+
+ /// Returns how an argument of the given record type should be passed.
+ virtual RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const = 0;
+
/// Find the LLVM type used to represent the given member pointer
/// type.
virtual llvm::Type *
@@ -330,8 +351,27 @@ public:
///
/// \param dtor - a function taking a single pointer argument
/// \param addr - a pointer to pass to the destructor function.
- virtual void registerGlobalDtor(CodeGenFunction &CGF, llvm::Constant *dtor,
- llvm::Constant *addr);
+ virtual void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
+ llvm::Constant *dtor, llvm::Constant *addr);
+
+ /*************************** thread_local initialization ********************/
+
+ /// Emits ABI-required functions necessary to initialize thread_local
+ /// variables in this translation unit.
+ ///
+ /// \param Decls The thread_local declarations in this translation unit.
+ /// \param InitFunc If this translation unit contains any non-constant
+ /// initialization or non-trivial destruction for thread_local
+ /// variables, a function to perform the initialization. Otherwise, 0.
+ virtual void EmitThreadLocalInitFuncs(
+ llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
+ llvm::Function *InitFunc);
+
+ /// Emit a reference to a non-local thread_local variable (including
+ /// triggering the initialization of all thread_local variables in its
+ /// translation unit).
+ virtual LValue EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
+ const DeclRefExpr *DRE);
};
// Create an instance of a C++ ABI class:
diff --git a/lib/CodeGen/CGCall.cpp b/lib/CodeGen/CGCall.cpp
index faf32e300830..b0f460ec0e7b 100644
--- a/lib/CodeGen/CGCall.cpp
+++ b/lib/CodeGen/CGCall.cpp
@@ -77,9 +77,7 @@ CodeGenTypes::arrangeFreeFunctionType(CanQual<FunctionNoProtoType> FTNP) {
// When translating an unprototyped function type, always use a
// variadic type.
return arrangeLLVMFunctionInfo(FTNP->getResultType().getUnqualifiedType(),
- ArrayRef<CanQualType>(),
- FTNP->getExtInfo(),
- RequiredArgs(0));
+ None, FTNP->getExtInfo(), RequiredArgs(0));
}
/// Arrange the LLVM function layout for a value of the given function
@@ -257,10 +255,8 @@ CodeGenTypes::arrangeFunctionDeclaration(const FunctionDecl *FD) {
// non-variadic type.
if (isa<FunctionNoProtoType>(FTy)) {
CanQual<FunctionNoProtoType> noProto = FTy.getAs<FunctionNoProtoType>();
- return arrangeLLVMFunctionInfo(noProto->getResultType(),
- ArrayRef<CanQualType>(),
- noProto->getExtInfo(),
- RequiredArgs::All);
+ return arrangeLLVMFunctionInfo(noProto->getResultType(), None,
+ noProto->getExtInfo(), RequiredArgs::All);
}
assert(isa<FunctionProtoType>(FTy));
@@ -420,7 +416,7 @@ CodeGenTypes::arrangeFunctionDeclaration(QualType resultType,
}
const CGFunctionInfo &CodeGenTypes::arrangeNullaryFunction() {
- return arrangeLLVMFunctionInfo(getContext().VoidTy, ArrayRef<CanQualType>(),
+ return arrangeLLVMFunctionInfo(getContext().VoidTy, None,
FunctionType::ExtInfo(), RequiredArgs::All);
}
@@ -837,12 +833,11 @@ bool CodeGenModule::ReturnTypeUsesFPRet(QualType ResultType) {
default:
return false;
case BuiltinType::Float:
- return getContext().getTargetInfo().useObjCFPRetForRealType(TargetInfo::Float);
+ return getTarget().useObjCFPRetForRealType(TargetInfo::Float);
case BuiltinType::Double:
- return getContext().getTargetInfo().useObjCFPRetForRealType(TargetInfo::Double);
+ return getTarget().useObjCFPRetForRealType(TargetInfo::Double);
case BuiltinType::LongDouble:
- return getContext().getTargetInfo().useObjCFPRetForRealType(
- TargetInfo::LongDouble);
+ return getTarget().useObjCFPRetForRealType(TargetInfo::LongDouble);
}
}
@@ -853,7 +848,7 @@ bool CodeGenModule::ReturnTypeUsesFP2Ret(QualType ResultType) {
if (const ComplexType *CT = ResultType->getAs<ComplexType>()) {
if (const BuiltinType *BT = CT->getElementType()->getAs<BuiltinType>()) {
if (BT->getKind() == BuiltinType::LongDouble)
- return getContext().getTargetInfo().useObjCFP2RetForComplexLongDouble();
+ return getTarget().useObjCFP2RetForComplexLongDouble();
}
}
@@ -1197,7 +1192,7 @@ void CodeGenFunction::EmitFunctionProlog(const CGFunctionInfo &FI,
// initialize the return value. TODO: it might be nice to have
// a more general mechanism for this that didn't require synthesized
// return statements.
- if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurFuncDecl)) {
+ if (const FunctionDecl *FD = dyn_cast_or_null<FunctionDecl>(CurCodeDecl)) {
if (FD->hasImplicitReturnZero()) {
QualType RetTy = FD->getResultType().getUnqualifiedType();
llvm::Type* LLVMTy = CGM.getTypes().ConvertType(RetTy);
@@ -1626,7 +1621,8 @@ static bool checkThisPointer(llvm::Value *ThisArg, llvm::Value *This) {
return false;
}
-void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI) {
+void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI,
+ bool EmitRetDbgLoc) {
// Functions with no result always return void.
if (ReturnValue == 0) {
Builder.CreateRetVoid();
@@ -1671,8 +1667,10 @@ void CodeGenFunction::EmitFunctionEpilog(const CGFunctionInfo &FI) {
// If there is a dominating store to ReturnValue, we can elide
// the load, zap the store, and usually zap the alloca.
if (llvm::StoreInst *SI = findDominatingStoreToReturnValue(*this)) {
+ // Reuse the debug location from the store unless we're told not to.
+ if (EmitRetDbgLoc)
+ RetDbgLoc = SI->getDebugLoc();
// Get the stored value and nuke the now-dead store.
- RetDbgLoc = SI->getDebugLoc();
RV = SI->getValueOperand();
SI->eraseFromParent();
diff --git a/lib/CodeGen/CGClass.cpp b/lib/CodeGen/CGClass.cpp
index 2ececb03651a..3fd075701d03 100644
--- a/lib/CodeGen/CGClass.cpp
+++ b/lib/CodeGen/CGClass.cpp
@@ -290,7 +290,7 @@ llvm::Value *CodeGenFunction::GetVTTParameter(GlobalDecl GD,
return 0;
}
- const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurFuncDecl)->getParent();
+ const CXXRecordDecl *RD = cast<CXXMethodDecl>(CurCodeDecl)->getParent();
const CXXRecordDecl *Base = cast<CXXMethodDecl>(GD.getDecl())->getParent();
llvm::Value *VTT;
@@ -710,7 +710,7 @@ void CodeGenFunction::EmitConstructorBody(FunctionArgList &Args) {
// Before we go any further, try the complete->base constructor
// delegation optimization.
if (CtorType == Ctor_Complete && IsConstructorDelegationValid(Ctor) &&
- CGM.getContext().getTargetInfo().getCXXABI().hasConstructorVariants()) {
+ CGM.getTarget().getCXXABI().hasConstructorVariants()) {
if (CGDebugInfo *DI = getDebugInfo())
DI->EmitLocation(Builder, Ctor->getLocEnd());
EmitDelegateCXXConstructorCall(Ctor, Ctor_Base, Args);
@@ -1139,6 +1139,7 @@ void CodeGenFunction::EmitCtorPrologue(const CXXConstructorDecl *CD,
InitializeVTablePointers(ClassDecl);
// And finally, initialize class members.
+ FieldConstructionScope FCS(*this, CXXThisValue);
ConstructorMemcpyizer CM(*this, CD, Args);
for (; B != E; B++) {
CXXCtorInitializer *Member = (*B);
@@ -1278,7 +1279,7 @@ void CodeGenFunction::EmitDestructorBody(FunctionArgList &Args) {
EnterDtorCleanups(Dtor, Dtor_Complete);
if (!isTryBody &&
- CGM.getContext().getTargetInfo().getCXXABI().hasDestructorVariants()) {
+ CGM.getTarget().getCXXABI().hasDestructorVariants()) {
EmitCXXDestructorCall(Dtor, Dtor_Base, /*ForVirtualBase=*/false,
/*Delegating=*/false, LoadCXXThis());
break;
@@ -2231,10 +2232,10 @@ void CodeGenFunction::EmitLambdaBlockInvokeBody() {
}
void CodeGenFunction::EmitLambdaToBlockPointerBody(FunctionArgList &Args) {
- if (cast<CXXMethodDecl>(CurFuncDecl)->isVariadic()) {
+ if (cast<CXXMethodDecl>(CurCodeDecl)->isVariadic()) {
// FIXME: Making this work correctly is nasty because it requires either
// cloning the body of the call operator or making the call operator forward.
- CGM.ErrorUnsupported(CurFuncDecl, "lambda conversion to variadic function");
+ CGM.ErrorUnsupported(CurCodeDecl, "lambda conversion to variadic function");
return;
}
diff --git a/lib/CodeGen/CGCleanup.cpp b/lib/CodeGen/CGCleanup.cpp
index 861d31fb7fc9..ba6b56c2676f 100644
--- a/lib/CodeGen/CGCleanup.cpp
+++ b/lib/CodeGen/CGCleanup.cpp
@@ -371,7 +371,8 @@ void CodeGenFunction::ResolveBranchFixups(llvm::BasicBlock *Block) {
}
/// Pops cleanup blocks until the given savepoint is reached.
-void CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old) {
+void CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old,
+ SourceLocation EHLoc) {
assert(Old.isValid());
while (EHStack.stable_begin() != Old) {
@@ -383,7 +384,7 @@ void CodeGenFunction::PopCleanupBlocks(EHScopeStack::stable_iterator Old) {
bool FallThroughIsBranchThrough =
Old.strictlyEncloses(Scope.getEnclosingNormalCleanup());
- PopCleanupBlock(FallThroughIsBranchThrough);
+ PopCleanupBlock(FallThroughIsBranchThrough, EHLoc);
}
}
@@ -532,7 +533,8 @@ static void destroyOptimisticNormalEntry(CodeGenFunction &CGF,
/// Pops a cleanup block. If the block includes a normal cleanup, the
/// current insertion point is threaded through the cleanup, as are
/// any branch fixups on the cleanup.
-void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
+void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough,
+ SourceLocation EHLoc) {
assert(!EHStack.empty() && "cleanup stack is empty!");
assert(isa<EHCleanupScope>(*EHStack.begin()) && "top not a cleanup!");
EHCleanupScope &Scope = cast<EHCleanupScope>(*EHStack.begin());
@@ -833,6 +835,9 @@ void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
// Emit the EH cleanup if required.
if (RequiresEHCleanup) {
+ if (CGDebugInfo *DI = getDebugInfo())
+ DI->EmitLocation(Builder, EHLoc);
+
CGBuilderTy::InsertPoint SavedIP = Builder.saveAndClearIP();
EmitBlock(EHEntry);
@@ -840,6 +845,7 @@ void CodeGenFunction::PopCleanupBlock(bool FallthroughIsBranchThrough) {
// We only actually emit the cleanup code if the cleanup is either
// active or was used before it was deactivated.
if (EHActiveFlag || IsActive) {
+
cleanupFlags.setIsForEHCleanup();
EmitCleanup(*this, Fn, cleanupFlags, EHActiveFlag);
}
diff --git a/lib/CodeGen/CGDebugInfo.cpp b/lib/CodeGen/CGDebugInfo.cpp
index 711d6861507c..ddcb931e46c5 100644
--- a/lib/CodeGen/CGDebugInfo.cpp
+++ b/lib/CodeGen/CGDebugInfo.cpp
@@ -89,7 +89,7 @@ void CGDebugInfo::setLocation(SourceLocation Loc) {
}
/// getContextDescriptor - Get context info for the decl.
-llvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context) {
+llvm::DIScope CGDebugInfo::getContextDescriptor(const Decl *Context) {
if (!Context)
return TheCU;
@@ -97,20 +97,17 @@ llvm::DIDescriptor CGDebugInfo::getContextDescriptor(const Decl *Context) {
I = RegionMap.find(Context);
if (I != RegionMap.end()) {
llvm::Value *V = I->second;
- return llvm::DIDescriptor(dyn_cast_or_null<llvm::MDNode>(V));
+ return llvm::DIScope(dyn_cast_or_null<llvm::MDNode>(V));
}
// Check namespace.
if (const NamespaceDecl *NSDecl = dyn_cast<NamespaceDecl>(Context))
- return llvm::DIDescriptor(getOrCreateNameSpace(NSDecl));
+ return getOrCreateNameSpace(NSDecl);
- if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context)) {
- if (!RDecl->isDependentType()) {
- llvm::DIType Ty = getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
+ if (const RecordDecl *RDecl = dyn_cast<RecordDecl>(Context))
+ if (!RDecl->isDependentType())
+ return getOrCreateType(CGM.getContext().getTypeDeclType(RDecl),
getOrCreateMainFile());
- return llvm::DIDescriptor(Ty);
- }
- }
return TheCU;
}
@@ -642,7 +639,7 @@ llvm::DIType CGDebugInfo::CreatePointerLikeType(unsigned Tag,
// Size is always the size of a pointer. We can't use getTypeSize here
// because that does not return the correct value for references.
unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
- uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS);
+ uint64_t Size = CGM.getTarget().getPointerWidth(AS);
uint64_t Align = CGM.getContext().getTypeAlign(Ty);
return DBuilder.createPointerType(CreatePointeeType(PointeeTy, Unit),
@@ -984,7 +981,7 @@ llvm::DIType CGDebugInfo::getOrCreateInstanceMethodType(
const PointerType *ThisPtrTy = cast<PointerType>(ThisPtr);
QualType PointeeTy = ThisPtrTy->getPointeeType();
unsigned AS = CGM.getContext().getTargetAddressSpace(PointeeTy);
- uint64_t Size = CGM.getContext().getTargetInfo().getPointerWidth(AS);
+ uint64_t Size = CGM.getTarget().getPointerWidth(AS);
uint64_t Align = CGM.getContext().getTypeAlign(ThisPtrTy);
llvm::DIType PointeeType = getOrCreateType(PointeeTy, Unit);
llvm::DIType ThisPtrType = DBuilder.createPointerType(PointeeType, Size, Align);
@@ -1699,7 +1696,7 @@ llvm::DIType CGDebugInfo::CreateEnumType(const EnumDecl *ED) {
unsigned Line = getLineNumber(ED->getLocation());
llvm::DIDescriptor EnumContext =
getContextDescriptor(cast<Decl>(ED->getDeclContext()));
- llvm::DIType ClassTy = ED->isScopedUsingClassTag() ?
+ llvm::DIType ClassTy = ED->isFixed() ?
getOrCreateType(ED->getIntegerType(), DefUnit) : llvm::DIType();
llvm::DIType DbgTy =
DBuilder.createEnumerationType(EnumContext, ED->getName(), DefUnit, Line,
@@ -2398,7 +2395,7 @@ llvm::DIType CGDebugInfo::EmitTypeForVarWithBlocksAttr(const VarDecl *VD,
CharUnits Align = CGM.getContext().getDeclAlign(VD);
if (Align > CGM.getContext().toCharUnitsFromBits(
- CGM.getContext().getTargetInfo().getPointerAlign(0))) {
+ CGM.getTarget().getPointerAlign(0))) {
CharUnits FieldOffsetInBytes
= CGM.getContext().toCharUnitsFromBits(FieldOffset);
CharUnits AlignedOffsetInBytes
@@ -2494,7 +2491,7 @@ void CGDebugInfo::EmitDeclare(const VarDecl *VD, unsigned Tag,
addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
// offset of __forwarding field
offset = CGM.getContext().toCharUnitsFromBits(
- CGM.getContext().getTargetInfo().getPointerWidth(0));
+ CGM.getTarget().getPointerWidth(0));
addr.push_back(llvm::ConstantInt::get(Int64Ty, offset.getQuantity()));
addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpDeref));
addr.push_back(llvm::ConstantInt::get(Int64Ty, llvm::DIBuilder::OpPlus));
@@ -2932,6 +2929,16 @@ void CGDebugInfo::EmitGlobalVariable(const ValueDecl *VD,
getStaticDataMemberDeclaration(VD));
}
+void CGDebugInfo::EmitUsingDirective(const UsingDirectiveDecl &UD) {
+ llvm::DIScope Scope =
+ LexicalBlockStack.empty()
+ ? getContextDescriptor(cast<Decl>(UD.getDeclContext()))
+ : llvm::DIScope(LexicalBlockStack.back());
+ DBuilder.createImportedModule(
+ Scope, getOrCreateNameSpace(UD.getNominatedNamespace()),
+ getLineNumber(UD.getLocation()));
+}
+
/// getOrCreateNamesSpace - Return namespace descriptor for the given
/// namespace decl.
llvm::DINameSpace
diff --git a/lib/CodeGen/CGDebugInfo.h b/lib/CodeGen/CGDebugInfo.h
index 3a0df999b540..4080492a1c68 100644
--- a/lib/CodeGen/CGDebugInfo.h
+++ b/lib/CodeGen/CGDebugInfo.h
@@ -262,6 +262,9 @@ public:
/// EmitGlobalVariable - Emit global variable's debug info.
void EmitGlobalVariable(const ValueDecl *VD, llvm::Constant *Init);
+ /// \brief - Emit C++ using directive.
+ void EmitUsingDirective(const UsingDirectiveDecl &UD);
+
/// getOrCreateRecordType - Emit record type's standalone debug info.
llvm::DIType getOrCreateRecordType(QualType Ty, SourceLocation L);
@@ -281,7 +284,7 @@ private:
uint64_t *OffSet);
/// getContextDescriptor - Get context info for the decl.
- llvm::DIDescriptor getContextDescriptor(const Decl *Decl);
+ llvm::DIScope getContextDescriptor(const Decl *Decl);
/// createRecordFwdDecl - Create a forward decl for a RecordType in a given
/// context.
diff --git a/lib/CodeGen/CGDecl.cpp b/lib/CodeGen/CGDecl.cpp
index 5375c5e18f2f..3ce6dec6a53c 100644
--- a/lib/CodeGen/CGDecl.cpp
+++ b/lib/CodeGen/CGDecl.cpp
@@ -45,6 +45,7 @@ void CodeGenFunction::EmitDecl(const Decl &D) {
case Decl::CXXDestructor:
case Decl::CXXConversion:
case Decl::Field:
+ case Decl::MSProperty:
case Decl::IndirectField:
case Decl::ObjCIvar:
case Decl::ObjCAtDefsField:
@@ -69,6 +70,7 @@ void CodeGenFunction::EmitDecl(const Decl &D) {
case Decl::Friend:
case Decl::FriendTemplate:
case Decl::Block:
+ case Decl::Captured:
case Decl::ClassScopeFunctionSpecialization:
llvm_unreachable("Declaration should not be in declstmts!");
case Decl::Function: // void X();
@@ -78,7 +80,6 @@ void CodeGenFunction::EmitDecl(const Decl &D) {
case Decl::CXXRecord: // struct/union/class X; [C++]
case Decl::Using: // using X; [C++]
case Decl::UsingShadow:
- case Decl::UsingDirective: // using namespace X; [C++]
case Decl::NamespaceAlias:
case Decl::StaticAssert: // static_assert(X, ""); [C++0x]
case Decl::Label: // __label__ x;
@@ -88,6 +89,10 @@ void CodeGenFunction::EmitDecl(const Decl &D) {
// None of these decls require codegen support.
return;
+ case Decl::UsingDirective: // using namespace X; [C++]
+ if (CGDebugInfo *DI = getDebugInfo())
+ DI->EmitUsingDirective(cast<UsingDirectiveDecl>(D));
+ return;
case Decl::Var: {
const VarDecl &VD = cast<VarDecl>(D);
assert(VD.isLocalVarDecl() &&
@@ -198,7 +203,7 @@ CodeGenFunction::CreateStaticVarDecl(const VarDecl &D,
if (Linkage != llvm::GlobalValue::InternalLinkage)
GV->setVisibility(CurFn->getVisibility());
- if (D.isThreadSpecified())
+ if (D.getTLSKind())
CGM.setTLSMode(GV, D);
return GV;
@@ -898,7 +903,7 @@ CodeGenFunction::EmitAutoVarAlloca(const VarDecl &D) {
CharUnits allocaAlignment = alignment;
if (isByRef)
allocaAlignment = std::max(allocaAlignment,
- getContext().toCharUnitsFromBits(Target.getPointerAlign(0)));
+ getContext().toCharUnitsFromBits(getTarget().getPointerAlign(0)));
Alloc->setAlignment(allocaAlignment.getQuantity());
DeclPtr = Alloc;
diff --git a/lib/CodeGen/CGDeclCXX.cpp b/lib/CodeGen/CGDeclCXX.cpp
index 0448d31f4073..9ffcff276623 100644
--- a/lib/CodeGen/CGDeclCXX.cpp
+++ b/lib/CodeGen/CGDeclCXX.cpp
@@ -39,7 +39,7 @@ static void EmitDeclInit(CodeGenFunction &CGF, const VarDecl &D,
CodeGenModule &CGM = CGF.CGM;
if (lv.isObjCStrong())
CGM.getObjCRuntime().EmitObjCGlobalAssign(CGF, CGF.EmitScalarExpr(Init),
- DeclPtr, D.isThreadSpecified());
+ DeclPtr, D.getTLSKind());
else if (lv.isObjCWeak())
CGM.getObjCRuntime().EmitObjCWeakAssign(CGF, CGF.EmitScalarExpr(Init),
DeclPtr);
@@ -80,6 +80,7 @@ static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
case QualType::DK_objc_strong_lifetime:
case QualType::DK_objc_weak_lifetime:
// We don't care about releasing objects during process teardown.
+ assert(!D.getTLSKind() && "should have rejected this");
return;
}
@@ -105,7 +106,7 @@ static void EmitDeclDestroy(CodeGenFunction &CGF, const VarDecl &D,
argument = llvm::Constant::getNullValue(CGF.Int8PtrTy);
}
- CGM.getCXXABI().registerGlobalDtor(CGF, function, argument);
+ CGM.getCXXABI().registerGlobalDtor(CGF, D, function, argument);
}
/// Emit code to cause the variable at the given address to be considered as
@@ -155,7 +156,8 @@ void CodeGenFunction::EmitCXXGlobalVarDeclInit(const VarDecl &D,
static llvm::Function *
CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
llvm::FunctionType *ty,
- const Twine &name);
+ const Twine &name,
+ bool TLS = false);
/// Create a stub function, suitable for being passed to atexit,
/// which passes the given address to the given destructor function.
@@ -224,14 +226,14 @@ void CodeGenFunction::EmitCXXGuardedInit(const VarDecl &D,
static llvm::Function *
CreateGlobalInitOrDestructFunction(CodeGenModule &CGM,
llvm::FunctionType *FTy,
- const Twine &Name) {
+ const Twine &Name, bool TLS) {
llvm::Function *Fn =
llvm::Function::Create(FTy, llvm::GlobalValue::InternalLinkage,
Name, &CGM.getModule());
- if (!CGM.getLangOpts().AppleKext) {
+ if (!CGM.getLangOpts().AppleKext && !TLS) {
// Set the section if needed.
if (const char *Section =
- CGM.getContext().getTargetInfo().getStaticInitSectionSpecifier())
+ CGM.getTarget().getStaticInitSectionSpecifier())
Fn->setSection(Section);
}
@@ -263,12 +265,20 @@ CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
CodeGenFunction(*this).GenerateCXXGlobalVarDeclInitFunc(Fn, D, Addr,
PerformInit);
- if (D->hasAttr<InitPriorityAttr>()) {
+ if (D->getTLSKind()) {
+ // FIXME: Should we support init_priority for thread_local?
+ // FIXME: Ideally, initialization of instantiated thread_local static data
+ // members of class templates should not trigger initialization of other
+ // entities in the TU.
+ // FIXME: We only need to register one __cxa_thread_atexit function for the
+ // entire TU.
+ CXXThreadLocalInits.push_back(Fn);
+ } else if (D->hasAttr<InitPriorityAttr>()) {
unsigned int order = D->getAttr<InitPriorityAttr>()->getPriority();
OrderGlobalInits Key(order, PrioritizedCXXGlobalInits.size());
PrioritizedCXXGlobalInits.push_back(std::make_pair(Key, Fn));
DelayedCXXInitPosition.erase(D);
- } else {
+ } else {
llvm::DenseMap<const Decl *, unsigned>::iterator I =
DelayedCXXInitPosition.find(D);
if (I == DelayedCXXInitPosition.end()) {
@@ -281,6 +291,27 @@ CodeGenModule::EmitCXXGlobalVarDeclInitFunc(const VarDecl *D,
}
}
+void CodeGenModule::EmitCXXThreadLocalInitFunc() {
+ llvm::Function *InitFn = 0;
+ if (!CXXThreadLocalInits.empty()) {
+ // Generate a guarded initialization function.
+ llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
+ InitFn = CreateGlobalInitOrDestructFunction(*this, FTy, "__tls_init",
+ /*TLS*/ true);
+ llvm::GlobalVariable *Guard = new llvm::GlobalVariable(
+ getModule(), Int8Ty, false, llvm::GlobalVariable::InternalLinkage,
+ llvm::ConstantInt::get(Int8Ty, 0), "__tls_guard");
+ Guard->setThreadLocal(true);
+ CodeGenFunction(*this)
+ .GenerateCXXGlobalInitFunc(InitFn, CXXThreadLocalInits, Guard);
+ }
+
+ getCXXABI().EmitThreadLocalInitFuncs(CXXThreadLocals, InitFn);
+
+ CXXThreadLocalInits.clear();
+ CXXThreadLocals.clear();
+}
+
void
CodeGenModule::EmitCXXGlobalInitFunc() {
while (!CXXGlobalInits.empty() && !CXXGlobalInits.back())
@@ -320,9 +351,7 @@ CodeGenModule::EmitCXXGlobalInitFunc() {
for (; I < PrioE; ++I)
LocalCXXGlobalInits.push_back(I->second);
- CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
- &LocalCXXGlobalInits[0],
- LocalCXXGlobalInits.size());
+ CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, LocalCXXGlobalInits);
AddGlobalCtor(Fn, Priority);
}
}
@@ -330,9 +359,7 @@ CodeGenModule::EmitCXXGlobalInitFunc() {
llvm::Function *Fn =
CreateGlobalInitOrDestructFunction(*this, FTy, "_GLOBAL__I_a");
- CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn,
- &CXXGlobalInits[0],
- CXXGlobalInits.size());
+ CodeGenFunction(*this).GenerateCXXGlobalInitFunc(Fn, CXXGlobalInits);
AddGlobalCtor(Fn);
CXXGlobalInits.clear();
@@ -379,9 +406,10 @@ void CodeGenFunction::GenerateCXXGlobalVarDeclInitFunc(llvm::Function *Fn,
FinishFunction();
}
-void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
- llvm::Constant **Decls,
- unsigned NumDecls) {
+void
+CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
+ ArrayRef<llvm::Constant *> Decls,
+ llvm::GlobalVariable *Guard) {
// Initialize debug info if needed.
maybeInitializeDebugInfo();
@@ -389,6 +417,22 @@ void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
getTypes().arrangeNullaryFunction(),
FunctionArgList(), SourceLocation());
+ llvm::BasicBlock *ExitBlock = 0;
+ if (Guard) {
+ // If we have a guard variable, check whether we've already performed these
+ // initializations. This happens for TLS initialization functions.
+ llvm::Value *GuardVal = Builder.CreateLoad(Guard);
+ llvm::Value *Uninit = Builder.CreateIsNull(GuardVal, "guard.uninitialized");
+ // Mark as initialized before initializing anything else. If the
+ // initializers use previously-initialized thread_local vars, that's
+ // probably supposed to be OK, but the standard doesn't say.
+ Builder.CreateStore(llvm::ConstantInt::get(GuardVal->getType(), 1), Guard);
+ llvm::BasicBlock *InitBlock = createBasicBlock("init");
+ ExitBlock = createBasicBlock("exit");
+ Builder.CreateCondBr(Uninit, InitBlock, ExitBlock);
+ EmitBlock(InitBlock);
+ }
+
RunCleanupsScope Scope(*this);
// When building in Objective-C++ ARC mode, create an autorelease pool
@@ -397,13 +441,18 @@ void CodeGenFunction::GenerateCXXGlobalInitFunc(llvm::Function *Fn,
llvm::Value *token = EmitObjCAutoreleasePoolPush();
EmitObjCAutoreleasePoolCleanup(token);
}
-
- for (unsigned i = 0; i != NumDecls; ++i)
+
+ for (unsigned i = 0, e = Decls.size(); i != e; ++i)
if (Decls[i])
EmitRuntimeCall(Decls[i]);
Scope.ForceCleanup();
-
+
+ if (ExitBlock) {
+ Builder.CreateBr(ExitBlock);
+ EmitBlock(ExitBlock);
+ }
+
FinishFunction();
}
diff --git a/lib/CodeGen/CGException.cpp b/lib/CodeGen/CGException.cpp
index 36642bcc48ff..a088d78641fa 100644
--- a/lib/CodeGen/CGException.cpp
+++ b/lib/CodeGen/CGException.cpp
@@ -419,14 +419,16 @@ llvm::Value *CodeGenFunction::getSelectorFromSlot() {
return Builder.CreateLoad(getEHSelectorSlot(), "sel");
}
-void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
+void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E,
+ bool KeepInsertionPoint) {
if (!E->getSubExpr()) {
EmitNoreturnRuntimeCallOrInvoke(getReThrowFn(CGM),
ArrayRef<llvm::Value*>());
// throw is an expression, and the expression emitters expect us
// to leave ourselves at a valid insertion point.
- EmitBlock(createBasicBlock("throw.cont"));
+ if (KeepInsertionPoint)
+ EmitBlock(createBasicBlock("throw.cont"));
return;
}
@@ -440,7 +442,8 @@ void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
CGM.getObjCRuntime().EmitThrowStmt(*this, S, false);
// This will clear insertion point which was not cleared in
// call to EmitThrowStmt.
- EmitBlock(createBasicBlock("throw.cont"));
+ if (KeepInsertionPoint)
+ EmitBlock(createBasicBlock("throw.cont"));
return;
}
@@ -478,7 +481,8 @@ void CodeGenFunction::EmitCXXThrowExpr(const CXXThrowExpr *E) {
// throw is an expression, and the expression emitters expect us
// to leave ourselves at a valid insertion point.
- EmitBlock(createBasicBlock("throw.cont"));
+ if (KeepInsertionPoint)
+ EmitBlock(createBasicBlock("throw.cont"));
}
void CodeGenFunction::EmitStartEHSpec(const Decl *D) {
diff --git a/lib/CodeGen/CGExpr.cpp b/lib/CodeGen/CGExpr.cpp
index 2f5186d1f4ff..64670c5e81e4 100644
--- a/lib/CodeGen/CGExpr.cpp
+++ b/lib/CodeGen/CGExpr.cpp
@@ -184,12 +184,16 @@ CreateReferenceTemporary(CodeGenFunction &CGF, QualType Type,
llvm::Type *RefTempTy = CGF.ConvertTypeForMem(Type);
// Create the reference temporary.
- llvm::GlobalValue *RefTemp =
+ llvm::GlobalVariable *RefTemp =
new llvm::GlobalVariable(CGF.CGM.getModule(),
RefTempTy, /*isConstant=*/false,
llvm::GlobalValue::InternalLinkage,
llvm::Constant::getNullValue(RefTempTy),
Name.str());
+ // If we're binding to a thread_local variable, the temporary is also
+ // thread local.
+ if (VD->getTLSKind())
+ CGF.CGM.setTLSMode(RefTemp, *VD);
return RefTemp;
}
}
@@ -201,6 +205,7 @@ static llvm::Value *
EmitExprForReferenceBinding(CodeGenFunction &CGF, const Expr *E,
llvm::Value *&ReferenceTemporary,
const CXXDestructorDecl *&ReferenceTemporaryDtor,
+ const InitListExpr *&ReferenceInitializerList,
QualType &ObjCARCReferenceLifetimeType,
const NamedDecl *InitializedDecl) {
const MaterializeTemporaryExpr *M = NULL;
@@ -222,156 +227,157 @@ EmitExprForReferenceBinding(CodeGenFunction &CGF, const Expr *E,
return EmitExprForReferenceBinding(CGF, EWC->getSubExpr(),
ReferenceTemporary,
ReferenceTemporaryDtor,
+ ReferenceInitializerList,
ObjCARCReferenceLifetimeType,
InitializedDecl);
}
- RValue RV;
if (E->isGLValue()) {
// Emit the expression as an lvalue.
LValue LV = CGF.EmitLValue(E);
+ assert(LV.isSimple());
+ return LV.getAddress();
+ }
+
+ if (!ObjCARCReferenceLifetimeType.isNull()) {
+ ReferenceTemporary = CreateReferenceTemporary(CGF,
+ ObjCARCReferenceLifetimeType,
+ InitializedDecl);
- if (LV.isSimple())
- return LV.getAddress();
- // We have to load the lvalue.
- RV = CGF.EmitLoadOfLValue(LV);
- } else {
- if (!ObjCARCReferenceLifetimeType.isNull()) {
- ReferenceTemporary = CreateReferenceTemporary(CGF,
- ObjCARCReferenceLifetimeType,
- InitializedDecl);
-
-
- LValue RefTempDst = CGF.MakeAddrLValue(ReferenceTemporary,
- ObjCARCReferenceLifetimeType);
+ LValue RefTempDst = CGF.MakeAddrLValue(ReferenceTemporary,
+ ObjCARCReferenceLifetimeType);
- CGF.EmitScalarInit(E, dyn_cast_or_null<ValueDecl>(InitializedDecl),
- RefTempDst, false);
-
- bool ExtendsLifeOfTemporary = false;
- if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
- if (Var->extendsLifetimeOfTemporary())
- ExtendsLifeOfTemporary = true;
- } else if (InitializedDecl && isa<FieldDecl>(InitializedDecl)) {
+ CGF.EmitScalarInit(E, dyn_cast_or_null<ValueDecl>(InitializedDecl),
+ RefTempDst, false);
+
+ bool ExtendsLifeOfTemporary = false;
+ if (const VarDecl *Var = dyn_cast_or_null<VarDecl>(InitializedDecl)) {
+ if (Var->extendsLifetimeOfTemporary())
ExtendsLifeOfTemporary = true;
- }
-
- if (!ExtendsLifeOfTemporary) {
- // Since the lifetime of this temporary isn't going to be extended,
- // we need to clean it up ourselves at the end of the full expression.
- switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) {
- case Qualifiers::OCL_None:
- case Qualifiers::OCL_ExplicitNone:
- case Qualifiers::OCL_Autoreleasing:
- break;
-
- case Qualifiers::OCL_Strong: {
- assert(!ObjCARCReferenceLifetimeType->isArrayType());
- CleanupKind cleanupKind = CGF.getARCCleanupKind();
- CGF.pushDestroy(cleanupKind,
- ReferenceTemporary,
- ObjCARCReferenceLifetimeType,
- CodeGenFunction::destroyARCStrongImprecise,
- cleanupKind & EHCleanup);
- break;
- }
+ } else if (InitializedDecl && isa<FieldDecl>(InitializedDecl)) {
+ ExtendsLifeOfTemporary = true;
+ }
+
+ if (!ExtendsLifeOfTemporary) {
+ // Since the lifetime of this temporary isn't going to be extended,
+ // we need to clean it up ourselves at the end of the full expression.
+ switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) {
+ case Qualifiers::OCL_None:
+ case Qualifiers::OCL_ExplicitNone:
+ case Qualifiers::OCL_Autoreleasing:
+ break;
- case Qualifiers::OCL_Weak:
- assert(!ObjCARCReferenceLifetimeType->isArrayType());
- CGF.pushDestroy(NormalAndEHCleanup,
- ReferenceTemporary,
- ObjCARCReferenceLifetimeType,
- CodeGenFunction::destroyARCWeak,
- /*useEHCleanupForArray*/ true);
- break;
- }
+ case Qualifiers::OCL_Strong: {
+ assert(!ObjCARCReferenceLifetimeType->isArrayType());
+ CleanupKind cleanupKind = CGF.getARCCleanupKind();
+ CGF.pushDestroy(cleanupKind,
+ ReferenceTemporary,
+ ObjCARCReferenceLifetimeType,
+ CodeGenFunction::destroyARCStrongImprecise,
+ cleanupKind & EHCleanup);
+ break;
+ }
- ObjCARCReferenceLifetimeType = QualType();
+ case Qualifiers::OCL_Weak:
+ assert(!ObjCARCReferenceLifetimeType->isArrayType());
+ CGF.pushDestroy(NormalAndEHCleanup,
+ ReferenceTemporary,
+ ObjCARCReferenceLifetimeType,
+ CodeGenFunction::destroyARCWeak,
+ /*useEHCleanupForArray*/ true);
+ break;
}
- return ReferenceTemporary;
+ ObjCARCReferenceLifetimeType = QualType();
}
+
+ return ReferenceTemporary;
+ }
+
+ SmallVector<SubobjectAdjustment, 2> Adjustments;
+ E = E->skipRValueSubobjectAdjustments(Adjustments);
+ if (const OpaqueValueExpr *opaque = dyn_cast<OpaqueValueExpr>(E))
+ if (opaque->getType()->isRecordType())
+ return CGF.EmitOpaqueValueLValue(opaque).getAddress();
- SmallVector<SubobjectAdjustment, 2> Adjustments;
- E = E->skipRValueSubobjectAdjustments(Adjustments);
- if (const OpaqueValueExpr *opaque = dyn_cast<OpaqueValueExpr>(E))
- if (opaque->getType()->isRecordType())
- return CGF.EmitOpaqueValueLValue(opaque).getAddress();
-
- // Create a reference temporary if necessary.
- AggValueSlot AggSlot = AggValueSlot::ignored();
- if (CGF.hasAggregateEvaluationKind(E->getType())) {
- ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
- InitializedDecl);
- CharUnits Alignment = CGF.getContext().getTypeAlignInChars(E->getType());
- AggValueSlot::IsDestructed_t isDestructed
- = AggValueSlot::IsDestructed_t(InitializedDecl != 0);
- AggSlot = AggValueSlot::forAddr(ReferenceTemporary, Alignment,
- Qualifiers(), isDestructed,
- AggValueSlot::DoesNotNeedGCBarriers,
- AggValueSlot::IsNotAliased);
+ // Create a reference temporary if necessary.
+ AggValueSlot AggSlot = AggValueSlot::ignored();
+ if (CGF.hasAggregateEvaluationKind(E->getType())) {
+ ReferenceTemporary = CreateReferenceTemporary(CGF, E->getType(),
+ InitializedDecl);
+ CharUnits Alignment = CGF.getContext().getTypeAlignInChars(E->getType());
+ AggValueSlot::IsDestructed_t isDestructed
+ = AggValueSlot::IsDestructed_t(InitializedDecl != 0);
+ AggSlot = AggValueSlot::forAddr(ReferenceTemporary, Alignment,
+ Qualifiers(), isDestructed,
+ AggValueSlot::DoesNotNeedGCBarriers,
+ AggValueSlot::IsNotAliased);
+ }
+
+ if (InitializedDecl) {
+ if (const InitListExpr *ILE = dyn_cast<InitListExpr>(E)) {
+ if (ILE->initializesStdInitializerList()) {
+ ReferenceInitializerList = ILE;
+ }
}
-
- if (InitializedDecl) {
+ else if (const RecordType *RT =
+ E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()){
// Get the destructor for the reference temporary.
- if (const RecordType *RT =
- E->getType()->getBaseElementTypeUnsafe()->getAs<RecordType>()) {
- CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
- if (!ClassDecl->hasTrivialDestructor())
- ReferenceTemporaryDtor = ClassDecl->getDestructor();
- }
+ CXXRecordDecl *ClassDecl = cast<CXXRecordDecl>(RT->getDecl());
+ if (!ClassDecl->hasTrivialDestructor())
+ ReferenceTemporaryDtor = ClassDecl->getDestructor();
}
+ }
- RV = CGF.EmitAnyExpr(E, AggSlot);
-
- // Check if need to perform derived-to-base casts and/or field accesses, to
- // get from the temporary object we created (and, potentially, for which we
- // extended the lifetime) to the subobject we're binding the reference to.
- if (!Adjustments.empty()) {
- llvm::Value *Object = RV.getAggregateAddr();
- for (unsigned I = Adjustments.size(); I != 0; --I) {
- SubobjectAdjustment &Adjustment = Adjustments[I-1];
- switch (Adjustment.Kind) {
- case SubobjectAdjustment::DerivedToBaseAdjustment:
- Object =
- CGF.GetAddressOfBaseClass(Object,
- Adjustment.DerivedToBase.DerivedClass,
- Adjustment.DerivedToBase.BasePath->path_begin(),
- Adjustment.DerivedToBase.BasePath->path_end(),
- /*NullCheckValue=*/false);
- break;
-
- case SubobjectAdjustment::FieldAdjustment: {
- LValue LV = CGF.MakeAddrLValue(Object, E->getType());
- LV = CGF.EmitLValueForField(LV, Adjustment.Field);
- if (LV.isSimple()) {
- Object = LV.getAddress();
- break;
- }
+ RValue RV = CGF.EmitAnyExpr(E, AggSlot);
+
+ // Check if need to perform derived-to-base casts and/or field accesses, to
+ // get from the temporary object we created (and, potentially, for which we
+ // extended the lifetime) to the subobject we're binding the reference to.
+ if (!Adjustments.empty()) {
+ llvm::Value *Object = RV.getAggregateAddr();
+ for (unsigned I = Adjustments.size(); I != 0; --I) {
+ SubobjectAdjustment &Adjustment = Adjustments[I-1];
+ switch (Adjustment.Kind) {
+ case SubobjectAdjustment::DerivedToBaseAdjustment:
+ Object =
+ CGF.GetAddressOfBaseClass(Object,
+ Adjustment.DerivedToBase.DerivedClass,
+ Adjustment.DerivedToBase.BasePath->path_begin(),
+ Adjustment.DerivedToBase.BasePath->path_end(),
+ /*NullCheckValue=*/false);
+ break;
- // For non-simple lvalues, we actually have to create a copy of
- // the object we're binding to.
- QualType T = Adjustment.Field->getType().getNonReferenceType()
- .getUnqualifiedType();
- Object = CreateReferenceTemporary(CGF, T, InitializedDecl);
- LValue TempLV = CGF.MakeAddrLValue(Object,
- Adjustment.Field->getType());
- CGF.EmitStoreThroughLValue(CGF.EmitLoadOfLValue(LV), TempLV);
+ case SubobjectAdjustment::FieldAdjustment: {
+ LValue LV = CGF.MakeAddrLValue(Object, E->getType());
+ LV = CGF.EmitLValueForField(LV, Adjustment.Field);
+ if (LV.isSimple()) {
+ Object = LV.getAddress();
break;
}
-
- case SubobjectAdjustment::MemberPointerAdjustment: {
- llvm::Value *Ptr = CGF.EmitScalarExpr(Adjustment.Ptr.RHS);
- Object = CGF.CGM.getCXXABI().EmitMemberDataPointerAddress(
- CGF, Object, Ptr, Adjustment.Ptr.MPT);
- break;
- }
- }
+
+ // For non-simple lvalues, we actually have to create a copy of
+ // the object we're binding to.
+ QualType T = Adjustment.Field->getType().getNonReferenceType()
+ .getUnqualifiedType();
+ Object = CreateReferenceTemporary(CGF, T, InitializedDecl);
+ LValue TempLV = CGF.MakeAddrLValue(Object,
+ Adjustment.Field->getType());
+ CGF.EmitStoreThroughLValue(CGF.EmitLoadOfLValue(LV), TempLV);
+ break;
}
- return Object;
+ case SubobjectAdjustment::MemberPointerAdjustment: {
+ llvm::Value *Ptr = CGF.EmitScalarExpr(Adjustment.Ptr.RHS);
+ Object = CGF.CGM.getCXXABI().EmitMemberDataPointerAddress(
+ CGF, Object, Ptr, Adjustment.Ptr.MPT);
+ break;
+ }
+ }
}
+
+ return Object;
}
if (RV.isAggregate())
@@ -396,9 +402,11 @@ CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E,
const NamedDecl *InitializedDecl) {
llvm::Value *ReferenceTemporary = 0;
const CXXDestructorDecl *ReferenceTemporaryDtor = 0;
+ const InitListExpr *ReferenceInitializerList = 0;
QualType ObjCARCReferenceLifetimeType;
llvm::Value *Value = EmitExprForReferenceBinding(*this, E, ReferenceTemporary,
ReferenceTemporaryDtor,
+ ReferenceInitializerList,
ObjCARCReferenceLifetimeType,
InitializedDecl);
if (SanitizePerformTypeCheck && !E->getType()->isFunctionType()) {
@@ -410,7 +418,8 @@ CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E,
QualType Ty = E->getType();
EmitTypeCheck(TCK_ReferenceBinding, E->getExprLoc(), Value, Ty);
}
- if (!ReferenceTemporaryDtor && ObjCARCReferenceLifetimeType.isNull())
+ if (!ReferenceTemporaryDtor && !ReferenceInitializerList &&
+ ObjCARCReferenceLifetimeType.isNull())
return RValue::get(Value);
// Make sure to call the destructor for the reference temporary.
@@ -429,9 +438,15 @@ CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E,
CGM.GetAddrOfCXXDestructor(ReferenceTemporaryDtor, Dtor_Complete);
CleanupArg = cast<llvm::Constant>(ReferenceTemporary);
}
- CGM.getCXXABI().registerGlobalDtor(*this, CleanupFn, CleanupArg);
+ CGM.getCXXABI().registerGlobalDtor(*this, *VD, CleanupFn, CleanupArg);
+ } else if (ReferenceInitializerList) {
+ // FIXME: This is wrong. We need to register a global destructor to clean
+ // up the initializer_list object, rather than adding it as a local
+ // cleanup.
+ EmitStdInitializerListCleanup(ReferenceTemporary,
+ ReferenceInitializerList);
} else {
- assert(!ObjCARCReferenceLifetimeType.isNull());
+ assert(!ObjCARCReferenceLifetimeType.isNull() && !VD->getTLSKind());
// Note: We intentionally do not register a global "destructor" to
// release the object.
}
@@ -445,6 +460,9 @@ CodeGenFunction::EmitReferenceBindingToExpr(const Expr *E,
destroyCXXObject, getLangOpts().Exceptions);
else
PushDestructorCleanup(ReferenceTemporaryDtor, ReferenceTemporary);
+ } else if (ReferenceInitializerList) {
+ EmitStdInitializerListCleanup(ReferenceTemporary,
+ ReferenceInitializerList);
} else {
switch (ObjCARCReferenceLifetimeType.getObjCLifetime()) {
case Qualifiers::OCL_None:
@@ -885,6 +903,10 @@ LValue CodeGenFunction::EmitLValue(const Expr *E) {
return EmitNullInitializationLValue(cast<CXXScalarValueInitExpr>(E));
case Expr::CXXDefaultArgExprClass:
return EmitLValue(cast<CXXDefaultArgExpr>(E)->getExpr());
+ case Expr::CXXDefaultInitExprClass: {
+ CXXDefaultInitExprScope Scope(*this);
+ return EmitLValue(cast<CXXDefaultInitExpr>(E)->getExpr());
+ }
case Expr::CXXTypeidExprClass:
return EmitCXXTypeidLValue(cast<CXXTypeidExpr>(E));
@@ -1164,7 +1186,7 @@ llvm::Value *CodeGenFunction::EmitLoadOfScalar(llvm::Value *Addr, bool Volatile,
if (TBAAInfo) {
llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
TBAAOffset);
- CGM.DecorateInstruction(Load, TBAAPath);
+ CGM.DecorateInstruction(Load, TBAAPath, false/*ConvertTypeToTag*/);
}
if ((SanOpts->Bool && hasBooleanRepresentation(Ty)) ||
@@ -1278,7 +1300,7 @@ void CodeGenFunction::EmitStoreOfScalar(llvm::Value *Value, llvm::Value *Addr,
if (TBAAInfo) {
llvm::MDNode *TBAAPath = CGM.getTBAAStructTagInfo(TBAABaseType, TBAAInfo,
TBAAOffset);
- CGM.DecorateInstruction(Store, TBAAPath);
+ CGM.DecorateInstruction(Store, TBAAPath, false/*ConvertTypeToTag*/);
}
}
@@ -1656,7 +1678,7 @@ static void setObjCGCLValueClass(const ASTContext &Ctx, const Expr *E,
if (const VarDecl *VD = dyn_cast<VarDecl>(Exp->getDecl())) {
if (VD->hasGlobalStorage()) {
LV.setGlobalObjCRef(true);
- LV.setThreadLocalRef(VD->isThreadSpecified());
+ LV.setThreadLocalRef(VD->getTLSKind() != VarDecl::TLS_None);
}
}
LV.setObjCArray(E->getType()->isArrayType());
@@ -1806,8 +1828,12 @@ LValue CodeGenFunction::EmitDeclRefLValue(const DeclRefExpr *E) {
if (const VarDecl *VD = dyn_cast<VarDecl>(ND)) {
// Check if this is a global variable.
- if (VD->hasLinkage() || VD->isStaticDataMember())
+ if (VD->hasLinkage() || VD->isStaticDataMember()) {
+ // If it's thread_local, emit a call to its wrapper function instead.
+ if (VD->getTLSKind() == VarDecl::TLS_Dynamic)
+ return CGM.getCXXABI().EmitThreadLocalDeclRefExpr(*this, E);
return EmitGlobalVarDeclLValue(*this, E, VD);
+ }
bool isBlockVariable = VD->hasAttr<BlocksAttr>();
@@ -2469,6 +2495,17 @@ LValue CodeGenFunction::EmitMemberExpr(const MemberExpr *E) {
llvm_unreachable("Unhandled member declaration!");
}
+/// Given that we are currently emitting a lambda, emit an l-value for
+/// one of its members.
+LValue CodeGenFunction::EmitLValueForLambdaField(const FieldDecl *Field) {
+ assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent()->isLambda());
+ assert(cast<CXXMethodDecl>(CurCodeDecl)->getParent() == Field->getParent());
+ QualType LambdaTagType =
+ getContext().getTagDeclType(Field->getParent());
+ LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue, LambdaTagType);
+ return EmitLValueForField(LambdaLV, Field);
+}
+
LValue CodeGenFunction::EmitLValueForField(LValue base,
const FieldDecl *field) {
if (field->isBitField()) {
@@ -2562,8 +2599,8 @@ LValue CodeGenFunction::EmitLValueForField(LValue base,
getContext().getASTRecordLayout(field->getParent());
// Set the base type to be the base type of the base LValue and
// update offset to be relative to the base type.
- LV.setTBAABaseType(base.getTBAABaseType());
- LV.setTBAAOffset(base.getTBAAOffset() +
+ LV.setTBAABaseType(mayAlias ? getContext().CharTy : base.getTBAABaseType());
+ LV.setTBAAOffset(mayAlias ? 0 : base.getTBAAOffset() +
Layout.getFieldOffset(field->getFieldIndex()) /
getContext().getCharWidth());
}
diff --git a/lib/CodeGen/CGExprAgg.cpp b/lib/CodeGen/CGExprAgg.cpp
index 1ac13c01ed4e..b974e1dcc682 100644
--- a/lib/CodeGen/CGExprAgg.cpp
+++ b/lib/CodeGen/CGExprAgg.cpp
@@ -170,6 +170,10 @@ public:
void VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
Visit(DAE->getExpr());
}
+ void VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
+ CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
+ Visit(DIE->getExpr());
+ }
void VisitCXXBindTemporaryExpr(CXXBindTemporaryExpr *E);
void VisitCXXConstructExpr(const CXXConstructExpr *E);
void VisitLambdaExpr(LambdaExpr *E);
@@ -1189,7 +1193,10 @@ void AggExprEmitter::VisitInitListExpr(InitListExpr *E) {
// the optimizer, especially with bitfields.
unsigned NumInitElements = E->getNumInits();
RecordDecl *record = E->getType()->castAs<RecordType>()->getDecl();
-
+
+ // Prepare a 'this' for CXXDefaultInitExprs.
+ CodeGenFunction::FieldConstructionScope FCS(CGF, Dest.getAddr());
+
if (record->isUnion()) {
// Only initialize one field of a union. The field itself is
// specified by the initializer list.
@@ -1341,7 +1348,7 @@ static CharUnits GetNumNonZeroBytesInInit(const Expr *E, CodeGenFunction &CGF) {
// Reference values are always non-null and have the width of a pointer.
if (Field->getType()->isReferenceType())
NumNonZeroBytes += CGF.getContext().toCharUnitsFromBits(
- CGF.getContext().getTargetInfo().getPointerWidth(0));
+ CGF.getTarget().getPointerWidth(0));
else
NumNonZeroBytes += GetNumNonZeroBytesInInit(E, CGF);
}
diff --git a/lib/CodeGen/CGExprComplex.cpp b/lib/CodeGen/CGExprComplex.cpp
index 5fc73aa7901b..36f974a31329 100644
--- a/lib/CodeGen/CGExprComplex.cpp
+++ b/lib/CodeGen/CGExprComplex.cpp
@@ -182,6 +182,10 @@ public:
ComplexPairTy VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
return Visit(DAE->getExpr());
}
+ ComplexPairTy VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
+ CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
+ return Visit(DIE->getExpr());
+ }
ComplexPairTy VisitExprWithCleanups(ExprWithCleanups *E) {
CGF.enterFullExpression(E);
CodeGenFunction::RunCleanupsScope Scope(CGF);
diff --git a/lib/CodeGen/CGExprConstant.cpp b/lib/CodeGen/CGExprConstant.cpp
index faaf6468f1e3..f5c8187c26f4 100644
--- a/lib/CodeGen/CGExprConstant.cpp
+++ b/lib/CodeGen/CGExprConstant.cpp
@@ -757,6 +757,12 @@ public:
return Visit(DAE->getExpr());
}
+ llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
+ // No need for a DefaultInitExprScope: we don't handle 'this' in a
+ // constant expression.
+ return Visit(DIE->getExpr());
+ }
+
llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E) {
return Visit(E->GetTemporaryExpr());
}
diff --git a/lib/CodeGen/CGExprScalar.cpp b/lib/CodeGen/CGExprScalar.cpp
index ffd0eb5572db..c1c252d12b76 100644
--- a/lib/CodeGen/CGExprScalar.cpp
+++ b/lib/CodeGen/CGExprScalar.cpp
@@ -344,6 +344,10 @@ public:
Value *VisitCXXDefaultArgExpr(CXXDefaultArgExpr *DAE) {
return Visit(DAE->getExpr());
}
+ Value *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE) {
+ CodeGenFunction::CXXDefaultInitExprScope Scope(CGF);
+ return Visit(DIE->getExpr());
+ }
Value *VisitCXXThisExpr(CXXThisExpr *TE) {
return CGF.LoadCXXThis();
}
@@ -1634,8 +1638,8 @@ ScalarExprEmitter::EmitScalarPrePostIncDec(const UnaryOperator *E, LValue LV,
else {
llvm::APFloat F(static_cast<float>(amount));
bool ignored;
- F.convert(CGF.Target.getLongDoubleFormat(), llvm::APFloat::rmTowardZero,
- &ignored);
+ F.convert(CGF.getTarget().getLongDoubleFormat(),
+ llvm::APFloat::rmTowardZero, &ignored);
amt = llvm::ConstantFP::get(VMContext, F);
}
value = Builder.CreateFAdd(value, amt, isInc ? "inc" : "dec");
diff --git a/lib/CodeGen/CGObjC.cpp b/lib/CodeGen/CGObjC.cpp
index 79d97b99b40e..713509bf6738 100644
--- a/lib/CodeGen/CGObjC.cpp
+++ b/lib/CodeGen/CGObjC.cpp
@@ -21,6 +21,7 @@
#include "clang/AST/StmtObjC.h"
#include "clang/Basic/Diagnostic.h"
#include "llvm/ADT/STLExtras.h"
+#include "llvm/Support/CallSite.h"
#include "llvm/IR/DataLayout.h"
#include "llvm/IR/InlineAsm.h"
using namespace clang;
@@ -713,7 +714,7 @@ PropertyImplStrategy::PropertyImplStrategy(CodeGenModule &CGM,
}
llvm::Triple::ArchType arch =
- CGM.getContext().getTargetInfo().getTriple().getArch();
+ CGM.getTarget().getTriple().getArch();
// Most architectures require memory to fit within a single cache
// line, so the alignment has to be at least the size of the access.
@@ -1400,8 +1401,10 @@ bool CodeGenFunction::IvarTypeWithAggrGCObjects(QualType Ty) {
}
llvm::Value *CodeGenFunction::LoadObjCSelf() {
- const ObjCMethodDecl *OMD = cast<ObjCMethodDecl>(CurFuncDecl);
- return Builder.CreateLoad(LocalDeclMap[OMD->getSelfDecl()], "self");
+ VarDecl *Self = cast<ObjCMethodDecl>(CurFuncDecl)->getSelfDecl();
+ DeclRefExpr DRE(Self, /*is enclosing local*/ (CurFuncDecl != CurCodeDecl),
+ Self->getType(), VK_LValue, SourceLocation());
+ return EmitLoadOfScalar(EmitDeclRefLValue(&DRE));
}
QualType CodeGenFunction::TypeOfSelfObject() {
@@ -2256,7 +2259,8 @@ void CodeGenFunction::EmitObjCAutoreleasePoolPop(llvm::Value *value) {
fn = createARCRuntimeFunction(CGM, fnType, "objc_autoreleasePoolPop");
}
- EmitNounwindRuntimeCall(fn, value);
+ // objc_autoreleasePoolPop can throw.
+ EmitRuntimeCallOrInvoke(fn, value);
}
/// Produce the code to do an MRR version objc_autoreleasepool_push.
diff --git a/lib/CodeGen/CGObjCMac.cpp b/lib/CodeGen/CGObjCMac.cpp
index 6274e1bfe395..e8498b06ad2f 100644
--- a/lib/CodeGen/CGObjCMac.cpp
+++ b/lib/CodeGen/CGObjCMac.cpp
@@ -1949,8 +1949,8 @@ llvm::Constant *CGObjCCommonMac::BuildGCBlockLayout(CodeGenModule &CGM,
bool hasUnion = false;
SkipIvars.clear();
IvarsInfo.clear();
- unsigned WordSizeInBits = CGM.getContext().getTargetInfo().getPointerWidth(0);
- unsigned ByteSizeInBits = CGM.getContext().getTargetInfo().getCharWidth();
+ unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
+ unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
// __isa is the first field in block descriptor and must assume by runtime's
// convention that it is GC'able.
@@ -2077,7 +2077,7 @@ void CGObjCCommonMac::BuildRCRecordLayout(const llvm::StructLayout *RecLayout,
if (RecFields.empty())
return;
- unsigned ByteSizeInBits = CGM.getContext().getTargetInfo().getCharWidth();
+ unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
for (unsigned i = 0, e = RecFields.size(); i != e; ++i) {
const FieldDecl *Field = RecFields[i];
@@ -2316,8 +2316,8 @@ llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) {
llvm::Constant *nullPtr = llvm::Constant::getNullValue(CGM.Int8PtrTy);
if (RunSkipBlockVars.empty())
return nullPtr;
- unsigned WordSizeInBits = CGM.getContext().getTargetInfo().getPointerWidth(0);
- unsigned ByteSizeInBits = CGM.getContext().getTargetInfo().getCharWidth();
+ unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
+ unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits;
// Sort on byte position; captures might not be allocated in order,
@@ -2393,7 +2393,7 @@ llvm::Constant *CGObjCCommonMac::getBitmapBlockLayout(bool ComputeByrefLayout) {
printf("\n Inline instruction for BYREF variable layout: ");
else
printf("\n Inline instruction for block variable layout: ");
- printf("0x0%llx\n", (unsigned long long)Result);
+ printf("0x0%" PRIx64 "\n", Result);
}
if (WordSizeInBytes == 8) {
const llvm::APInt Instruction(64, Result);
@@ -2468,8 +2468,8 @@ llvm::Constant *CGObjCCommonMac::BuildRCBlockLayout(CodeGenModule &CGM,
RunSkipBlockVars.clear();
bool hasUnion = false;
- unsigned WordSizeInBits = CGM.getContext().getTargetInfo().getPointerWidth(0);
- unsigned ByteSizeInBits = CGM.getContext().getTargetInfo().getCharWidth();
+ unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
+ unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
unsigned WordSizeInBytes = WordSizeInBits/ByteSizeInBits;
const BlockDecl *blockDecl = blockInfo.getBlockDecl();
@@ -4537,8 +4537,8 @@ void CGObjCCommonMac::BuildAggrIvarLayout(const ObjCImplementationDecl *OI,
if (RecFields.empty())
return;
- unsigned WordSizeInBits = CGM.getContext().getTargetInfo().getPointerWidth(0);
- unsigned ByteSizeInBits = CGM.getContext().getTargetInfo().getCharWidth();
+ unsigned WordSizeInBits = CGM.getTarget().getPointerWidth(0);
+ unsigned ByteSizeInBits = CGM.getTarget().getCharWidth();
if (!RD && CGM.getLangOpts().ObjCAutoRefCount) {
const FieldDecl *FirstField = RecFields[0];
FirstFieldDelta =
diff --git a/lib/CodeGen/CGObjCRuntime.cpp b/lib/CodeGen/CGObjCRuntime.cpp
index abd10a29c9e2..9c0d5189f815 100644
--- a/lib/CodeGen/CGObjCRuntime.cpp
+++ b/lib/CodeGen/CGObjCRuntime.cpp
@@ -117,7 +117,7 @@ LValue CGObjCRuntime::EmitValueForIvarAtOffset(CodeGen::CodeGenFunction &CGF,
// a synthesized ivar can never be a bit-field, so this is safe.
uint64_t FieldBitOffset = LookupFieldBitOffset(CGF.CGM, OID, 0, Ivar);
uint64_t BitOffset = FieldBitOffset % CGF.CGM.getContext().getCharWidth();
- uint64_t AlignmentBits = CGF.CGM.getContext().getTargetInfo().getCharAlign();
+ uint64_t AlignmentBits = CGF.CGM.getTarget().getCharAlign();
uint64_t BitFieldSize = Ivar->getBitWidthValue(CGF.getContext());
CharUnits StorageSize =
CGF.CGM.getContext().toCharUnitsFromBits(
diff --git a/lib/CodeGen/CGRTTI.cpp b/lib/CodeGen/CGRTTI.cpp
index 869843cbd4e8..40dc6bfa3b0e 100644
--- a/lib/CodeGen/CGRTTI.cpp
+++ b/lib/CodeGen/CGRTTI.cpp
@@ -412,6 +412,9 @@ void RTTIBuilder::BuildVTablePointer(const Type *Ty) {
case Type::RValueReference:
llvm_unreachable("References shouldn't get here");
+ case Type::Auto:
+ llvm_unreachable("Undeduced auto type shouldn't get here");
+
case Type::Builtin:
// GCC treats vector and complex types as fundamental types.
case Type::Vector:
@@ -619,6 +622,9 @@ llvm::Constant *RTTIBuilder::BuildTypeInfo(QualType Ty, bool Force) {
case Type::RValueReference:
llvm_unreachable("References shouldn't get here");
+ case Type::Auto:
+ llvm_unreachable("Undeduced auto type shouldn't get here");
+
case Type::ConstantArray:
case Type::IncompleteArray:
case Type::VariableArray:
diff --git a/lib/CodeGen/CGRecordLayoutBuilder.cpp b/lib/CodeGen/CGRecordLayoutBuilder.cpp
index 2c6438b0b67c..30ab528ffbe4 100644
--- a/lib/CodeGen/CGRecordLayoutBuilder.cpp
+++ b/lib/CodeGen/CGRecordLayoutBuilder.cpp
@@ -276,7 +276,7 @@ bool CGRecordLayoutBuilder::LayoutBitfields(const ASTRecordLayout &Layout,
uint64_t FirstFieldOffset = Layout.getFieldOffset(FirstFieldNo);
uint64_t NextFieldOffsetInBits = Types.getContext().toBits(NextFieldOffset);
- unsigned CharAlign = Types.getContext().getTargetInfo().getCharAlign();
+ unsigned CharAlign = Types.getTarget().getCharAlign();
assert(FirstFieldOffset % CharAlign == 0 &&
"First field offset is misaligned");
CharUnits FirstFieldOffsetInBytes
@@ -352,7 +352,7 @@ bool CGRecordLayoutBuilder::LayoutBitfields(const ASTRecordLayout &Layout,
assert(EndOffset >= (FirstFieldOffset + TotalBits) &&
"End offset is not past the end of the known storage bits.");
uint64_t SpaceBits = EndOffset - FirstFieldOffset;
- uint64_t LongBits = Types.getContext().getTargetInfo().getLongWidth();
+ uint64_t LongBits = Types.getTarget().getLongWidth();
uint64_t WidenedBits = (StorageBits / LongBits) * LongBits +
llvm::NextPowerOf2(StorageBits % LongBits - 1);
assert(WidenedBits >= StorageBits && "Widening shrunk the bits!");
@@ -455,7 +455,7 @@ CGRecordLayoutBuilder::LayoutUnionField(const FieldDecl *Field,
return 0;
unsigned StorageBits = llvm::RoundUpToAlignment(
- FieldSize, Types.getContext().getTargetInfo().getCharAlign());
+ FieldSize, Types.getTarget().getCharAlign());
CharUnits NumBytesToAppend
= Types.getContext().toCharUnitsFromBits(StorageBits);
@@ -814,7 +814,7 @@ bool CGRecordLayoutBuilder::LayoutFields(const RecordDecl *D) {
// Lay out the virtual bases. The MS ABI uses a different
// algorithm here due to the lack of primary virtual bases.
- if (Types.getContext().getTargetInfo().getCXXABI().hasPrimaryVBases()) {
+ if (Types.getTarget().getCXXABI().hasPrimaryVBases()) {
RD->getIndirectPrimaryBases(IndirectPrimaryBases);
if (Layout.isPrimaryBaseVirtual())
IndirectPrimaryBases.insert(Layout.getPrimaryBase());
diff --git a/lib/CodeGen/CGStmt.cpp b/lib/CodeGen/CGStmt.cpp
index 3153ca8ca70f..5e2ebe0d9cd4 100644
--- a/lib/CodeGen/CGStmt.cpp
+++ b/lib/CodeGen/CGStmt.cpp
@@ -37,6 +37,9 @@ void CodeGenFunction::EmitStopPoint(const Stmt *S) {
else
Loc = S->getLocStart();
DI->EmitLocation(Builder, Loc);
+
+ //if (++NumStopPoints == 1)
+ LastStopPoint = Loc;
}
}
@@ -134,7 +137,9 @@ void CodeGenFunction::EmitStmt(const Stmt *S) {
case Stmt::SwitchStmtClass: EmitSwitchStmt(cast<SwitchStmt>(*S)); break;
case Stmt::GCCAsmStmtClass: // Intentional fall-through.
case Stmt::MSAsmStmtClass: EmitAsmStmt(cast<AsmStmt>(*S)); break;
-
+ case Stmt::CapturedStmtClass:
+ EmitCapturedStmt(cast<CapturedStmt>(*S));
+ break;
case Stmt::ObjCAtTryStmtClass:
EmitObjCAtTryStmt(cast<ObjCAtTryStmt>(*S));
break;
@@ -837,6 +842,10 @@ void CodeGenFunction::EmitReturnStmt(const ReturnStmt &S) {
}
}
+ NumReturnExprs += 1;
+ if (RV == 0 || RV->isEvaluatable(getContext()))
+ NumSimpleReturnExprs += 1;
+
cleanupScope.ForceCleanup();
EmitBranchThroughCleanup(ReturnBlock);
}
@@ -1449,7 +1458,7 @@ static llvm::MDNode *getAsmSrcLocInfo(const StringLiteral *Str,
for (unsigned i = 0, e = StrVal.size()-1; i != e; ++i) {
if (StrVal[i] != '\n') continue;
SourceLocation LineLoc = Str->getLocationOfByte(i+1, SM, LangOpts,
- CGF.Target);
+ CGF.getTarget());
Locs.push_back(llvm::ConstantInt::get(CGF.Int32Ty,
LineLoc.getRawEncoding()));
}
@@ -1467,18 +1476,23 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
for (unsigned i = 0, e = S.getNumOutputs(); i != e; i++) {
- TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i),
- S.getOutputName(i));
- bool IsValid = Target.validateOutputConstraint(Info); (void)IsValid;
+ StringRef Name;
+ if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
+ Name = GAS->getOutputName(i);
+ TargetInfo::ConstraintInfo Info(S.getOutputConstraint(i), Name);
+ bool IsValid = getTarget().validateOutputConstraint(Info); (void)IsValid;
assert(IsValid && "Failed to parse output constraint");
OutputConstraintInfos.push_back(Info);
}
for (unsigned i = 0, e = S.getNumInputs(); i != e; i++) {
- TargetInfo::ConstraintInfo Info(S.getInputConstraint(i),
- S.getInputName(i));
- bool IsValid = Target.validateInputConstraint(OutputConstraintInfos.data(),
- S.getNumOutputs(), Info);
+ StringRef Name;
+ if (const GCCAsmStmt *GAS = dyn_cast<GCCAsmStmt>(&S))
+ Name = GAS->getInputName(i);
+ TargetInfo::ConstraintInfo Info(S.getInputConstraint(i), Name);
+ bool IsValid =
+ getTarget().validateInputConstraint(OutputConstraintInfos.data(),
+ S.getNumOutputs(), Info);
assert(IsValid && "Failed to parse input constraint"); (void)IsValid;
InputConstraintInfos.push_back(Info);
}
@@ -1502,13 +1516,14 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
// Simplify the output constraint.
std::string OutputConstraint(S.getOutputConstraint(i));
- OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1, Target);
+ OutputConstraint = SimplifyConstraint(OutputConstraint.c_str() + 1,
+ getTarget());
const Expr *OutExpr = S.getOutputExpr(i);
OutExpr = OutExpr->IgnoreParenNoopCasts(getContext());
OutputConstraint = AddVariableConstraints(OutputConstraint, *OutExpr,
- Target, CGM, S);
+ getTarget(), CGM, S);
LValue Dest = EmitLValue(OutExpr);
if (!Constraints.empty())
@@ -1589,13 +1604,13 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
// Simplify the input constraint.
std::string InputConstraint(S.getInputConstraint(i));
- InputConstraint = SimplifyConstraint(InputConstraint.c_str(), Target,
+ InputConstraint = SimplifyConstraint(InputConstraint.c_str(), getTarget(),
&OutputConstraintInfos);
InputConstraint =
AddVariableConstraints(InputConstraint,
*InputExpr->IgnoreParenNoopCasts(getContext()),
- Target, CGM, S);
+ getTarget(), CGM, S);
llvm::Value *Arg = EmitAsmInput(Info, InputExpr, Constraints);
@@ -1647,7 +1662,7 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
StringRef Clobber = S.getClobber(i);
if (Clobber != "memory" && Clobber != "cc")
- Clobber = Target.getNormalizedGCCRegisterName(Clobber);
+ Clobber = getTarget().getNormalizedGCCRegisterName(Clobber);
if (i != 0 || NumConstraints != 0)
Constraints += ',';
@@ -1658,7 +1673,7 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
}
// Add machine specific clobbers
- std::string MachineClobbers = Target.getClobbers();
+ std::string MachineClobbers = getTarget().getClobbers();
if (!MachineClobbers.empty()) {
if (!Constraints.empty())
Constraints += ',';
@@ -1735,3 +1750,7 @@ void CodeGenFunction::EmitAsmStmt(const AsmStmt &S) {
EmitStoreThroughLValue(RValue::get(Tmp), ResultRegDests[i]);
}
}
+
+void CodeGenFunction::EmitCapturedStmt(const CapturedStmt &S) {
+ llvm_unreachable("not implemented yet");
+}
diff --git a/lib/CodeGen/CodeGenFunction.cpp b/lib/CodeGen/CodeGenFunction.cpp
index 2c3cabe98510..75c60edbba53 100644
--- a/lib/CodeGen/CodeGenFunction.cpp
+++ b/lib/CodeGen/CodeGenFunction.cpp
@@ -31,8 +31,7 @@ using namespace clang;
using namespace CodeGen;
CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
- : CodeGenTypeCache(cgm), CGM(cgm),
- Target(CGM.getContext().getTargetInfo()),
+ : CodeGenTypeCache(cgm), CGM(cgm), Target(cgm.getTarget()),
Builder(cgm.getModule().getContext()),
SanitizePerformTypeCheck(CGM.getSanOpts().Null |
CGM.getSanOpts().Alignment |
@@ -45,7 +44,9 @@ CodeGenFunction::CodeGenFunction(CodeGenModule &cgm, bool suppressNewContext)
DebugInfo(0), DisableDebugInfo(false), CalleeWithThisReturn(0),
DidCallStackSave(false),
IndirectBranch(0), SwitchInsn(0), CaseRangeBlock(0), UnreachableBlock(0),
+ NumReturnExprs(0), NumSimpleReturnExprs(0),
CXXABIThisDecl(0), CXXABIThisValue(0), CXXThisValue(0),
+ CXXDefaultInitExprThis(0),
CXXStructorImplicitParamDecl(0), CXXStructorImplicitParamValue(0),
OutermostConditional(0), CurLexicalScope(0), TerminateLandingPad(0),
TerminateHandler(0), TrapBB(0) {
@@ -91,6 +92,9 @@ TypeEvaluationKind CodeGenFunction::getEvaluationKind(QualType type) {
#include "clang/AST/TypeNodes.def"
llvm_unreachable("non-canonical or dependent type in IR-generation");
+ case Type::Auto:
+ llvm_unreachable("undeduced auto type in IR-generation");
+
// Various scalar types.
case Type::Builtin:
case Type::Pointer:
@@ -184,15 +188,36 @@ void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
assert(BreakContinueStack.empty() &&
"mismatched push/pop in break/continue stack!");
- if (CGDebugInfo *DI = getDebugInfo())
- DI->EmitLocation(Builder, EndLoc);
+ bool OnlySimpleReturnStmts = NumSimpleReturnExprs > 0
+ && NumSimpleReturnExprs == NumReturnExprs;
+ // If the function contains only a simple return statement, the
+ // cleanup code may become the first breakpoint in the function. To
+ // be safe, set the debug location for it to the location of the
+ // return statement. Otherwise point it to end of the function's
+ // lexical scope.
+ if (CGDebugInfo *DI = getDebugInfo()) {
+ if (OnlySimpleReturnStmts)
+ DI->EmitLocation(Builder, LastStopPoint);
+ else
+ DI->EmitLocation(Builder, EndLoc);
+ }
// Pop any cleanups that might have been associated with the
// parameters. Do this in whatever block we're currently in; it's
// important to do this before we enter the return block or return
// edges will be *really* confused.
- if (EHStack.stable_begin() != PrologueCleanupDepth)
- PopCleanupBlocks(PrologueCleanupDepth);
+ bool EmitRetDbgLoc = true;
+ if (EHStack.stable_begin() != PrologueCleanupDepth) {
+ PopCleanupBlocks(PrologueCleanupDepth, EndLoc);
+
+ // Make sure the line table doesn't jump back into the body for
+ // the ret after it's been at EndLoc.
+ EmitRetDbgLoc = false;
+
+ if (CGDebugInfo *DI = getDebugInfo())
+ if (OnlySimpleReturnStmts)
+ DI->EmitLocation(Builder, EndLoc);
+ }
// Emit function epilog (to return).
EmitReturnBlock();
@@ -205,7 +230,7 @@ void CodeGenFunction::FinishFunction(SourceLocation EndLoc) {
DI->EmitFunctionEnd(Builder);
}
- EmitFunctionEpilog(*CurFnInfo);
+ EmitFunctionEpilog(*CurFnInfo, EmitRetDbgLoc);
EmitEndEHSpec(CurCodeDecl);
assert(EHStack.empty() &&
@@ -279,8 +304,8 @@ void CodeGenFunction::EmitFunctionInstrumentation(const char *Fn) {
void CodeGenFunction::EmitMCountInstrumentation() {
llvm::FunctionType *FTy = llvm::FunctionType::get(VoidTy, false);
- llvm::Constant *MCountFn = CGM.CreateRuntimeFunction(FTy,
- Target.getMCountName());
+ llvm::Constant *MCountFn =
+ CGM.CreateRuntimeFunction(FTy, getTarget().getMCountName());
EmitNounwindRuntimeCall(MCountFn);
}
@@ -448,7 +473,8 @@ void CodeGenFunction::EmitOpenCLKernelMetadata(const FunctionDecl *FD,
OpenCLKernelMetadata->addOperand(kernelMDNode);
}
-void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
+void CodeGenFunction::StartFunction(GlobalDecl GD,
+ QualType RetTy,
llvm::Function *Fn,
const CGFunctionInfo &FnInfo,
const FunctionArgList &Args,
@@ -456,7 +482,8 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
const Decl *D = GD.getDecl();
DidCallStackSave = false;
- CurCodeDecl = CurFuncDecl = D;
+ CurCodeDecl = D;
+ CurFuncDecl = (D ? D->getNonClosureContext() : 0);
FnRetTy = RetTy;
CurFn = Fn;
CurFnInfo = &FnInfo;
@@ -555,12 +582,7 @@ void CodeGenFunction::StartFunction(GlobalDecl GD, QualType RetTy,
LambdaThisCaptureField);
if (LambdaThisCaptureField) {
// If this lambda captures this, load it.
- QualType LambdaTagType =
- getContext().getTagDeclType(LambdaThisCaptureField->getParent());
- LValue LambdaLV = MakeNaturalAlignAddrLValue(CXXABIThisValue,
- LambdaTagType);
- LValue ThisLValue = EmitLValueForField(LambdaLV,
- LambdaThisCaptureField);
+ LValue ThisLValue = EmitLValueForLambdaField(LambdaThisCaptureField);
CXXThisValue = EmitLoadOfLValue(ThisLValue).getScalarVal();
}
} else {
@@ -906,6 +928,16 @@ void CodeGenFunction::EmitBranchOnBoolExpr(const Expr *Cond,
return;
}
+ if (const CXXThrowExpr *Throw = dyn_cast<CXXThrowExpr>(Cond)) {
+ // Conditional operator handling can give us a throw expression as a
+ // condition for a case like:
+ // br(c ? throw x : y, t, f) -> br(c, br(throw x, t, f), br(y, t, f)
+ // Fold this to:
+ // br(c, throw x, br(y, t, f))
+ EmitCXXThrowExpr(Throw, /*KeepInsertionPoint*/false);
+ return;
+ }
+
// Emit the code with the fully general case.
llvm::Value *CondV = EvaluateExprAsBool(Cond);
Builder.CreateCondBr(CondV, TrueBlock, FalseBlock);
diff --git a/lib/CodeGen/CodeGenFunction.h b/lib/CodeGen/CodeGenFunction.h
index 645d5ff23785..ff74c15c38c3 100644
--- a/lib/CodeGen/CodeGenFunction.h
+++ b/lib/CodeGen/CodeGenFunction.h
@@ -579,8 +579,8 @@ public:
typedef std::pair<llvm::Value *, llvm::Value *> ComplexPairTy;
CGBuilderTy Builder;
- /// CurFuncDecl - Holds the Decl for the current function or ObjC method.
- /// This excludes BlockDecls.
+ /// CurFuncDecl - Holds the Decl for the current outermost
+ /// non-closure context.
const Decl *CurFuncDecl;
/// CurCodeDecl - This is the inner-most code context, which includes blocks.
const Decl *CurCodeDecl;
@@ -784,7 +784,9 @@ public:
/// PopCleanupBlock - Will pop the cleanup entry on the stack and
/// process all branch fixups.
- void PopCleanupBlock(bool FallThroughIsBranchThrough = false);
+ /// \param EHLoc - Optional debug location for EH code.
+ void PopCleanupBlock(bool FallThroughIsBranchThrough = false,
+ SourceLocation EHLoc=SourceLocation());
/// DeactivateCleanupBlock - Deactivates the given cleanup block.
/// The block cannot be reactivated. Pops it if it's the top of the
@@ -905,7 +907,9 @@ public:
/// PopCleanupBlocks - Takes the old cleanup stack size and emits
/// the cleanup blocks that have been added.
- void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize);
+ /// \param EHLoc - Optional debug location for EH code.
+ void PopCleanupBlocks(EHScopeStack::stable_iterator OldCleanupStackSize,
+ SourceLocation EHLoc=SourceLocation());
void ResolveBranchFixups(llvm::BasicBlock *Target);
@@ -1206,12 +1210,62 @@ private:
/// lazily by getUnreachableBlock().
llvm::BasicBlock *UnreachableBlock;
+ /// Counts of the number return expressions in the function.
+ unsigned NumReturnExprs;
+
+ /// Count the number of simple (constant) return expressions in the function.
+ unsigned NumSimpleReturnExprs;
+
+ /// The last regular (non-return) debug location (breakpoint) in the function.
+ SourceLocation LastStopPoint;
+
+public:
+ /// A scope within which we are constructing the fields of an object which
+ /// might use a CXXDefaultInitExpr. This stashes away a 'this' value to use
+ /// if we need to evaluate a CXXDefaultInitExpr within the evaluation.
+ class FieldConstructionScope {
+ public:
+ FieldConstructionScope(CodeGenFunction &CGF, llvm::Value *This)
+ : CGF(CGF), OldCXXDefaultInitExprThis(CGF.CXXDefaultInitExprThis) {
+ CGF.CXXDefaultInitExprThis = This;
+ }
+ ~FieldConstructionScope() {
+ CGF.CXXDefaultInitExprThis = OldCXXDefaultInitExprThis;
+ }
+
+ private:
+ CodeGenFunction &CGF;
+ llvm::Value *OldCXXDefaultInitExprThis;
+ };
+
+ /// The scope of a CXXDefaultInitExpr. Within this scope, the value of 'this'
+ /// is overridden to be the object under construction.
+ class CXXDefaultInitExprScope {
+ public:
+ CXXDefaultInitExprScope(CodeGenFunction &CGF)
+ : CGF(CGF), OldCXXThisValue(CGF.CXXThisValue) {
+ CGF.CXXThisValue = CGF.CXXDefaultInitExprThis;
+ }
+ ~CXXDefaultInitExprScope() {
+ CGF.CXXThisValue = OldCXXThisValue;
+ }
+
+ public:
+ CodeGenFunction &CGF;
+ llvm::Value *OldCXXThisValue;
+ };
+
+private:
/// CXXThisDecl - When generating code for a C++ member function,
/// this will hold the implicit 'this' declaration.
ImplicitParamDecl *CXXABIThisDecl;
llvm::Value *CXXABIThisValue;
llvm::Value *CXXThisValue;
+ /// The value of 'this' to use when evaluating CXXDefaultInitExprs within
+ /// this expression.
+ llvm::Value *CXXDefaultInitExprThis;
+
/// CXXStructorImplicitParamDecl - When generating code for a constructor or
/// destructor, this will hold the implicit argument (e.g. VTT).
ImplicitParamDecl *CXXStructorImplicitParamDecl;
@@ -1300,6 +1354,7 @@ public:
return getInvokeDestImpl();
}
+ const TargetInfo &getTarget() const { return Target; }
llvm::LLVMContext &getLLVMContext() { return CGM.getLLVMContext(); }
//===--------------------------------------------------------------------===//
@@ -1400,7 +1455,6 @@ public:
llvm::Function *GenerateBlockFunction(GlobalDecl GD,
const CGBlockInfo &Info,
- const Decl *OuterFuncDecl,
const DeclMapTy &ldm,
bool IsLambdaConversionToBlock);
@@ -1431,7 +1485,8 @@ public:
void GenerateCode(GlobalDecl GD, llvm::Function *Fn,
const CGFunctionInfo &FnInfo);
- void StartFunction(GlobalDecl GD, QualType RetTy,
+ void StartFunction(GlobalDecl GD,
+ QualType RetTy,
llvm::Function *Fn,
const CGFunctionInfo &FnInfo,
const FunctionArgList &Args,
@@ -1521,7 +1576,7 @@ public:
/// EmitFunctionEpilog - Emit the target specific LLVM code to return the
/// given temporary.
- void EmitFunctionEpilog(const CGFunctionInfo &FI);
+ void EmitFunctionEpilog(const CGFunctionInfo &FI, bool EmitRetDbgLoc);
/// EmitStartEHSpec - Emit the start of the exception spec.
void EmitStartEHSpec(const Decl *D);
@@ -2133,6 +2188,7 @@ public:
void EmitCaseStmt(const CaseStmt &S);
void EmitCaseStmtRange(const CaseStmt &S);
void EmitAsmStmt(const AsmStmt &S);
+ void EmitCapturedStmt(const CapturedStmt &S);
void EmitObjCForCollectionStmt(const ObjCForCollectionStmt &S);
void EmitObjCAtTryStmt(const ObjCAtTryStmt &S);
@@ -2327,6 +2383,7 @@ public:
llvm::Value *EmitIvarOffset(const ObjCInterfaceDecl *Interface,
const ObjCIvarDecl *Ivar);
LValue EmitLValueForField(LValue Base, const FieldDecl* Field);
+ LValue EmitLValueForLambdaField(const FieldDecl *Field);
/// EmitLValueForFieldInitialization - Like EmitLValueForField, except that
/// if the Field is a reference, this will return the address of the reference
@@ -2446,6 +2503,7 @@ public:
/// is unhandled by the current target.
llvm::Value *EmitTargetBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
+ llvm::Value *EmitAArch64BuiltinExpr(unsigned BuiltinID, const CallExpr *E);
llvm::Value *EmitARMBuiltinExpr(unsigned BuiltinID, const CallExpr *E);
llvm::Value *EmitNeonCall(llvm::Function *F,
SmallVectorImpl<llvm::Value*> &O,
@@ -2625,8 +2683,8 @@ public:
/// GenerateCXXGlobalInitFunc - Generates code for initializing global
/// variables.
void GenerateCXXGlobalInitFunc(llvm::Function *Fn,
- llvm::Constant **Decls,
- unsigned NumDecls);
+ ArrayRef<llvm::Constant *> Decls,
+ llvm::GlobalVariable *Guard = 0);
/// GenerateCXXGlobalDtorsFunc - Generates code for destroying global
/// variables.
@@ -2650,7 +2708,7 @@ public:
}
void enterNonTrivialFullExpression(const ExprWithCleanups *E);
- void EmitCXXThrowExpr(const CXXThrowExpr *E);
+ void EmitCXXThrowExpr(const CXXThrowExpr *E, bool KeepInsertionPoint = true);
void EmitLambdaExpr(const LambdaExpr *E, AggValueSlot Dest);
diff --git a/lib/CodeGen/CodeGenModule.cpp b/lib/CodeGen/CodeGenModule.cpp
index c518a5554e2a..0b03a3c4b67d 100644
--- a/lib/CodeGen/CodeGenModule.cpp
+++ b/lib/CodeGen/CodeGenModule.cpp
@@ -35,7 +35,6 @@
#include "clang/Basic/Module.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Basic/TargetInfo.h"
-#include "clang/Basic/TargetOptions.h"
#include "clang/Frontend/CodeGenOptions.h"
#include "llvm/ADT/APSInt.h"
#include "llvm/ADT/Triple.h"
@@ -55,7 +54,7 @@ using namespace CodeGen;
static const char AnnotationSection[] = "llvm.metadata";
static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
- switch (CGM.getContext().getTargetInfo().getCXXABI().getKind()) {
+ switch (CGM.getTarget().getCXXABI().getKind()) {
case TargetCXXABI::GenericAArch64:
case TargetCXXABI::GenericARM:
case TargetCXXABI::iOS:
@@ -70,19 +69,16 @@ static CGCXXABI &createCXXABI(CodeGenModule &CGM) {
CodeGenModule::CodeGenModule(ASTContext &C, const CodeGenOptions &CGO,
- const TargetOptions &TO, llvm::Module &M,
- const llvm::DataLayout &TD,
+ llvm::Module &M, const llvm::DataLayout &TD,
DiagnosticsEngine &diags)
- : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TargetOpts(TO),
- TheModule(M), TheDataLayout(TD), TheTargetCodeGenInfo(0), Diags(diags),
- ABI(createCXXABI(*this)),
- Types(*this),
- TBAA(0),
- VTables(*this), ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
+ : Context(C), LangOpts(C.getLangOpts()), CodeGenOpts(CGO), TheModule(M),
+ Diags(diags), TheDataLayout(TD), Target(C.getTargetInfo()),
+ ABI(createCXXABI(*this)), VMContext(M.getContext()), TBAA(0),
+ TheTargetCodeGenInfo(0), Types(*this), VTables(*this),
+ ObjCRuntime(0), OpenCLRuntime(0), CUDARuntime(0),
DebugInfo(0), ARCData(0), NoObjCARCExceptionsMetadata(0),
RRData(0), CFConstantStringClassRef(0),
ConstantStringClassRef(0), NSConstantStringType(0),
- VMContext(M.getContext()),
NSConcreteGlobalBlock(0), NSConcreteStackBlock(0),
BlockObjectAssign(0), BlockObjectDispose(0),
BlockDescriptorType(0), GenericBlockLiteralType(0),
@@ -180,15 +176,17 @@ void CodeGenModule::Release() {
EmitDeferred();
EmitCXXGlobalInitFunc();
EmitCXXGlobalDtorFunc();
+ EmitCXXThreadLocalInitFunc();
if (ObjCRuntime)
if (llvm::Function *ObjCInitFunction = ObjCRuntime->ModuleInitFunction())
AddGlobalCtor(ObjCInitFunction);
EmitCtorList(GlobalCtors, "llvm.global_ctors");
EmitCtorList(GlobalDtors, "llvm.global_dtors");
EmitGlobalAnnotations();
+ EmitStaticExternCAliases();
EmitLLVMUsed();
- if (CodeGenOpts.ModulesAutolink) {
+ if (CodeGenOpts.Autolink && Context.getLangOpts().Modules) {
EmitModuleLinkOptions();
}
@@ -241,13 +239,18 @@ llvm::MDNode *CodeGenModule::getTBAAStructTagInfo(QualType BaseTy,
return TBAA->getTBAAStructTagInfo(BaseTy, AccessN, O);
}
+/// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag
+/// is the same as the type. For struct-path aware TBAA, the tag
+/// is different from the type: base type, access type and offset.
+/// When ConvertTypeToTag is true, we create a tag based on the scalar type.
void CodeGenModule::DecorateInstruction(llvm::Instruction *Inst,
- llvm::MDNode *TBAAInfo) {
- Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
-}
-
-bool CodeGenModule::isTargetDarwin() const {
- return getContext().getTargetInfo().getTriple().isOSDarwin();
+ llvm::MDNode *TBAAInfo,
+ bool ConvertTypeToTag) {
+ if (ConvertTypeToTag && TBAA && CodeGenOpts.StructPathTBAA)
+ Inst->setMetadata(llvm::LLVMContext::MD_tbaa,
+ TBAA->getTBAAScalarTagInfo(TBAAInfo));
+ else
+ Inst->setMetadata(llvm::LLVMContext::MD_tbaa, TBAAInfo);
}
void CodeGenModule::Error(SourceLocation loc, StringRef error) {
@@ -323,7 +326,7 @@ static llvm::GlobalVariable::ThreadLocalMode GetLLVMTLSModel(
void CodeGenModule::setTLSMode(llvm::GlobalVariable *GV,
const VarDecl &D) const {
- assert(D.isThreadSpecified() && "setting TLS mode on non-TLS var!");
+ assert(D.getTLSKind() && "setting TLS mode on non-TLS var!");
llvm::GlobalVariable::ThreadLocalMode TLM;
TLM = GetLLVMTLSModel(CodeGenOpts.getDefaultTLSModel());
@@ -1475,8 +1478,11 @@ CodeGenModule::GetOrCreateLLVMGlobal(StringRef MangledName,
GV->setVisibility(GetLLVMVisibility(LV.getVisibility()));
}
- if (D->isThreadSpecified())
+ if (D->getTLSKind()) {
+ if (D->getTLSKind() == VarDecl::TLS_Dynamic)
+ CXXThreadLocals.push_back(std::make_pair(D, GV));
setTLSMode(GV, *D);
+ }
}
if (AddrSpace != Ty->getAddressSpace())
@@ -1617,6 +1623,7 @@ CodeGenModule::MaybeEmitGlobalStdInitializerListInitializer(const VarDecl *D,
D->getLocStart(), D->getLocation(),
name, arrayType, sourceInfo,
SC_Static);
+ backingArray->setTSCSpec(D->getTSCSpec());
// Now clone the InitListExpr to initialize the array instead.
// Incredible hack: we want to use the existing InitListExpr here, so we need
@@ -1707,6 +1714,39 @@ unsigned CodeGenModule::GetGlobalVarAddressSpace(const VarDecl *D,
return AddrSpace;
}
+template<typename SomeDecl>
+void CodeGenModule::MaybeHandleStaticInExternC(const SomeDecl *D,
+ llvm::GlobalValue *GV) {
+ if (!getLangOpts().CPlusPlus)
+ return;
+
+ // Must have 'used' attribute, or else inline assembly can't rely on
+ // the name existing.
+ if (!D->template hasAttr<UsedAttr>())
+ return;
+
+ // Must have internal linkage and an ordinary name.
+ if (!D->getIdentifier() || D->getLinkage() != InternalLinkage)
+ return;
+
+ // Must be in an extern "C" context. Entities declared directly within
+ // a record are not extern "C" even if the record is in such a context.
+ const SomeDecl *First = D->getFirstDeclaration();
+ if (First->getDeclContext()->isRecord() || !First->isInExternCContext())
+ return;
+
+ // OK, this is an internal linkage entity inside an extern "C" linkage
+ // specification. Make a note of that so we can give it the "expected"
+ // mangled name if nothing else is using that name.
+ std::pair<StaticExternCMap::iterator, bool> R =
+ StaticExternCValues.insert(std::make_pair(D->getIdentifier(), GV));
+
+ // If we have multiple internal linkage entities with the same name
+ // in extern "C" regions, none of them gets that name.
+ if (!R.second)
+ R.first->second = 0;
+}
+
void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
llvm::Constant *Init = 0;
QualType ASTTy = D->getType();
@@ -1805,6 +1845,8 @@ void CodeGenModule::EmitGlobalVarDefinition(const VarDecl *D) {
cast<llvm::GlobalValue>(Entry)->eraseFromParent();
}
+ MaybeHandleStaticInExternC(D, GV);
+
if (D->hasAttr<AnnotateAttr>())
AddGlobalAnnotations(D, GV);
@@ -1870,11 +1912,17 @@ CodeGenModule::GetLLVMLinkageVarDefinition(const VarDecl *D,
((!CodeGenOpts.NoCommon && !D->getAttr<NoCommonAttr>()) ||
D->getAttr<CommonAttr>()) &&
!D->hasExternalStorage() && !D->getInit() &&
- !D->getAttr<SectionAttr>() && !D->isThreadSpecified() &&
+ !D->getAttr<SectionAttr>() && !D->getTLSKind() &&
!D->getAttr<WeakImportAttr>()) {
// Thread local vars aren't considered common linkage.
return llvm::GlobalVariable::CommonLinkage;
- }
+ } else if (D->getTLSKind() == VarDecl::TLS_Dynamic &&
+ getTarget().getTriple().isMacOSX())
+ // On Darwin, the backing variable for a C++11 thread_local variable always
+ // has internal linkage; all accesses should just be calls to the
+ // Itanium-specified entry point, which has the normal linkage of the
+ // variable.
+ return llvm::GlobalValue::InternalLinkage;
return llvm::GlobalVariable::ExternalLinkage;
}
@@ -2083,6 +2131,8 @@ void CodeGenModule::EmitGlobalFunctionDefinition(GlobalDecl GD) {
// FIXME: this is redundant with part of SetFunctionDefinitionAttributes
setGlobalVisibility(Fn, D);
+ MaybeHandleStaticInExternC(D, Fn);
+
CodeGenFunction(*this).GenerateCode(D, Fn, FI);
SetFunctionDefinitionAttributes(D, Fn);
@@ -2231,7 +2281,8 @@ CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
llvm::Constant *Zeros[] = { Zero, Zero };
-
+ llvm::Value *V;
+
// If we don't already have it, get __CFConstantStringClassReference.
if (!CFConstantStringClassRef) {
llvm::Type *Ty = getTypes().ConvertType(getContext().IntTy);
@@ -2239,9 +2290,11 @@ CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
llvm::Constant *GV = CreateRuntimeVariable(Ty,
"__CFConstantStringClassReference");
// Decay array -> ptr
- CFConstantStringClassRef =
- llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
+ V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
+ CFConstantStringClassRef = V;
}
+ else
+ V = CFConstantStringClassRef;
QualType CFTy = getContext().getCFConstantStringType();
@@ -2251,7 +2304,7 @@ CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
llvm::Constant *Fields[4];
// Class pointer.
- Fields[0] = CFConstantStringClassRef;
+ Fields[0] = cast<llvm::ConstantExpr>(V);
// Flags.
llvm::Type *Ty = getTypes().ConvertType(getContext().UnsignedIntTy);
@@ -2286,6 +2339,8 @@ CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
new llvm::GlobalVariable(getModule(), C->getType(), /*isConstant=*/true,
Linkage, C, ".str");
GV->setUnnamedAddr(true);
+ // Don't enforce the target's minimum global alignment, since the only use
+ // of the string is via this class initializer.
if (isUTF16) {
CharUnits Align = getContext().getTypeAlignInChars(getContext().ShortTy);
GV->setAlignment(Align.getQuantity());
@@ -2310,7 +2365,7 @@ CodeGenModule::GetAddrOfConstantCFString(const StringLiteral *Literal) {
GV = new llvm::GlobalVariable(getModule(), C->getType(), true,
llvm::GlobalVariable::PrivateLinkage, C,
"_unnamed_cfstring_");
- if (const char *Sect = getContext().getTargetInfo().getCFStringSection())
+ if (const char *Sect = getTarget().getCFStringSection())
GV->setSection(Sect);
Entry.setValue(GV);
@@ -2338,7 +2393,7 @@ CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
llvm::Constant *Zero = llvm::Constant::getNullValue(Int32Ty);
llvm::Constant *Zeros[] = { Zero, Zero };
-
+ llvm::Value *V;
// If we don't already have it, get _NSConstantStringClassReference.
if (!ConstantStringClassRef) {
std::string StringClass(getLangOpts().ObjCConstantStringClass);
@@ -2351,8 +2406,8 @@ CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
GV = getObjCRuntime().GetClassGlobal(str);
// Make sure the result is of the correct type.
llvm::Type *PTy = llvm::PointerType::getUnqual(Ty);
- ConstantStringClassRef =
- llvm::ConstantExpr::getBitCast(GV, PTy);
+ V = llvm::ConstantExpr::getBitCast(GV, PTy);
+ ConstantStringClassRef = V;
} else {
std::string str =
StringClass.empty() ? "_NSConstantStringClassReference"
@@ -2360,10 +2415,12 @@ CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
llvm::Type *PTy = llvm::ArrayType::get(Ty, 0);
GV = CreateRuntimeVariable(PTy, str);
// Decay array -> ptr
- ConstantStringClassRef =
- llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
+ V = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
+ ConstantStringClassRef = V;
}
}
+ else
+ V = ConstantStringClassRef;
if (!NSConstantStringType) {
// Construct the type for a constant NSString.
@@ -2402,7 +2459,7 @@ CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
llvm::Constant *Fields[3];
// Class pointer.
- Fields[0] = ConstantStringClassRef;
+ Fields[0] = cast<llvm::ConstantExpr>(V);
// String pointer.
llvm::Constant *C =
@@ -2417,6 +2474,8 @@ CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
new llvm::GlobalVariable(getModule(), C->getType(), isConstant, Linkage, C,
".str");
GV->setUnnamedAddr(true);
+ // Don't enforce the target's minimum global alignment, since the only use
+ // of the string is via this class initializer.
CharUnits Align = getContext().getTypeAlignInChars(getContext().CharTy);
GV->setAlignment(Align.getQuantity());
Fields[1] = llvm::ConstantExpr::getGetElementPtr(GV, Zeros);
@@ -2433,8 +2492,8 @@ CodeGenModule::GetAddrOfConstantString(const StringLiteral *Literal) {
// FIXME. Fix section.
if (const char *Sect =
LangOpts.ObjCRuntime.isNonFragile()
- ? getContext().getTargetInfo().getNSStringNonFragileABISection()
- : getContext().getTargetInfo().getNSStringSection())
+ ? getTarget().getNSStringNonFragileABISection()
+ : getTarget().getNSStringSection())
GV->setSection(Sect);
Entry.setValue(GV);
@@ -2521,7 +2580,7 @@ CodeGenModule::GetConstantArrayFromStringLiteral(const StringLiteral *E) {
/// constant array for the given string literal.
llvm::Constant *
CodeGenModule::GetAddrOfConstantStringFromLiteral(const StringLiteral *S) {
- CharUnits Align = getContext().getTypeAlignInChars(S->getType());
+ CharUnits Align = getContext().getAlignOfGlobalVarInChars(S->getType());
if (S->isAscii() || S->isUTF8()) {
SmallString<64> Str(S->getString());
@@ -2590,6 +2649,10 @@ llvm::Constant *CodeGenModule::GetAddrOfConstantString(StringRef Str,
if (!GlobalName)
GlobalName = ".str";
+ if (Alignment == 0)
+ Alignment = getContext().getAlignOfGlobalVarInChars(getContext().CharTy)
+ .getQuantity();
+
// Don't share any string literals if strings aren't constant.
if (LangOpts.WritableStrings)
return GenerateStringLiteral(Str, false, *this, GlobalName, Alignment);
@@ -2770,7 +2833,6 @@ void CodeGenModule::EmitTopLevelDecl(Decl *D) {
// No code generation needed.
case Decl::UsingShadow:
case Decl::Using:
- case Decl::UsingDirective:
case Decl::ClassTemplate:
case Decl::FunctionTemplate:
case Decl::TypeAliasTemplate:
@@ -2778,6 +2840,10 @@ void CodeGenModule::EmitTopLevelDecl(Decl *D) {
case Decl::Block:
case Decl::Empty:
break;
+ case Decl::UsingDirective: // using namespace X; [C++]
+ if (CGDebugInfo *DI = getModuleDebugInfo())
+ DI->EmitUsingDirective(cast<UsingDirectiveDecl>(*D));
+ return;
case Decl::CXXConstructor:
// Skip function templates
if (cast<FunctionDecl>(D)->getDescribedFunctionTemplate() ||
@@ -2903,6 +2969,23 @@ static void EmitGlobalDeclMetadata(CodeGenModule &CGM,
GlobalMetadata->addOperand(llvm::MDNode::get(CGM.getLLVMContext(), Ops));
}
+/// For each function which is declared within an extern "C" region and marked
+/// as 'used', but has internal linkage, create an alias from the unmangled
+/// name to the mangled name if possible. People expect to be able to refer
+/// to such functions with an unmangled name from inline assembly within the
+/// same translation unit.
+void CodeGenModule::EmitStaticExternCAliases() {
+ for (StaticExternCMap::iterator I = StaticExternCValues.begin(),
+ E = StaticExternCValues.end();
+ I != E; ++I) {
+ IdentifierInfo *Name = I->first;
+ llvm::GlobalValue *Val = I->second;
+ if (Val && !getModule().getNamedValue(Name->getName()))
+ AddUsedGlobal(new llvm::GlobalAlias(Val->getType(), Val->getLinkage(),
+ Name->getName(), Val, &getModule()));
+ }
+}
+
/// Emits metadata nodes associating all the global values in the
/// current module with the Decls they came from. This is useful for
/// projects using IR gen as a subroutine.
diff --git a/lib/CodeGen/CodeGenModule.h b/lib/CodeGen/CodeGenModule.h
index 5b2153e5ff3f..91138c607c36 100644
--- a/lib/CodeGen/CodeGenModule.h
+++ b/lib/CodeGen/CodeGenModule.h
@@ -67,7 +67,6 @@ namespace clang {
class VarDecl;
class LangOptions;
class CodeGenOptions;
- class TargetOptions;
class DiagnosticsEngine;
class AnnotateAttr;
class CXXDestructorDecl;
@@ -233,15 +232,22 @@ class CodeGenModule : public CodeGenTypeCache {
ASTContext &Context;
const LangOptions &LangOpts;
const CodeGenOptions &CodeGenOpts;
- const TargetOptions &TargetOpts;
llvm::Module &TheModule;
- const llvm::DataLayout &TheDataLayout;
- mutable const TargetCodeGenInfo *TheTargetCodeGenInfo;
DiagnosticsEngine &Diags;
+ const llvm::DataLayout &TheDataLayout;
+ const TargetInfo &Target;
CGCXXABI &ABI;
- CodeGenTypes Types;
- CodeGenTBAA *TBAA;
+ llvm::LLVMContext &VMContext;
+ CodeGenTBAA *TBAA;
+
+ mutable const TargetCodeGenInfo *TheTargetCodeGenInfo;
+
+ // This should not be moved earlier, since its initialization depends on some
+ // of the previous reference members being already initialized and also checks
+ // if TheTargetCodeGenInfo is NULL
+ CodeGenTypes Types;
+
/// VTables - Holds information about C++ vtables.
CodeGenVTables VTables;
friend class CodeGenVTables;
@@ -255,8 +261,8 @@ class CodeGenModule : public CodeGenTypeCache {
RREntrypoints *RRData;
// WeakRefReferences - A set of references that have only been seen via
- // a weakref so far. This is used to remove the weak of the reference if we ever
- // see a direct reference or a definition.
+ // a weakref so far. This is used to remove the weak of the reference if we
+ // ever see a direct reference or a definition.
llvm::SmallPtrSet<llvm::GlobalValue*, 10> WeakRefReferences;
/// DeferredDecls - This contains all the decls which have definitions but
@@ -305,6 +311,20 @@ class CodeGenModule : public CodeGenTypeCache {
llvm::DenseMap<QualType, llvm::Constant *> AtomicSetterHelperFnMap;
llvm::DenseMap<QualType, llvm::Constant *> AtomicGetterHelperFnMap;
+ /// Map used to track internal linkage functions declared within
+ /// extern "C" regions.
+ typedef llvm::MapVector<IdentifierInfo *,
+ llvm::GlobalValue *> StaticExternCMap;
+ StaticExternCMap StaticExternCValues;
+
+ /// \brief thread_local variables defined or used in this TU.
+ std::vector<std::pair<const VarDecl *, llvm::GlobalVariable *> >
+ CXXThreadLocals;
+
+ /// \brief thread_local variables with initializers that need to run
+ /// before any thread_local variable in this TU is odr-used.
+ std::vector<llvm::Constant*> CXXThreadLocalInits;
+
/// CXXGlobalInits - Global variables with initializers that need to run
/// before main.
std::vector<llvm::Constant*> CXXGlobalInits;
@@ -340,11 +360,11 @@ class CodeGenModule : public CodeGenTypeCache {
/// CFConstantStringClassRef - Cached reference to the class for constant
/// strings. This value has type int * but is actually an Obj-C class pointer.
- llvm::Constant *CFConstantStringClassRef;
+ llvm::WeakVH CFConstantStringClassRef;
/// ConstantStringClassRef - Cached reference to the class for constant
/// strings. This value has type int * but is actually an Obj-C class pointer.
- llvm::Constant *ConstantStringClassRef;
+ llvm::WeakVH ConstantStringClassRef;
/// \brief The LLVM type corresponding to NSConstantString.
llvm::StructType *NSConstantStringType;
@@ -363,7 +383,6 @@ class CodeGenModule : public CodeGenTypeCache {
bool isTriviallyRecursive(const FunctionDecl *F);
bool shouldEmitFunction(const FunctionDecl *F);
- llvm::LLVMContext &VMContext;
/// @name Cache for Blocks Runtime Globals
/// @{
@@ -396,8 +415,8 @@ class CodeGenModule : public CodeGenTypeCache {
/// @}
public:
CodeGenModule(ASTContext &C, const CodeGenOptions &CodeGenOpts,
- const TargetOptions &TargetOpts, llvm::Module &M,
- const llvm::DataLayout &TD, DiagnosticsEngine &Diags);
+ llvm::Module &M, const llvm::DataLayout &TD,
+ DiagnosticsEngine &Diags);
~CodeGenModule();
@@ -427,9 +446,6 @@ public:
return *CUDARuntime;
}
- /// getCXXABI() - Return a reference to the configured C++ ABI.
- CGCXXABI &getCXXABI() { return ABI; }
-
ARCEntrypoints &getARCEntrypoints() const {
assert(getLangOpts().ObjCAutoRefCount && ARCData != 0);
return *ARCData;
@@ -483,21 +499,24 @@ public:
}
ASTContext &getContext() const { return Context; }
- const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
const LangOptions &getLangOpts() const { return LangOpts; }
+ const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
llvm::Module &getModule() const { return TheModule; }
- CodeGenTypes &getTypes() { return Types; }
- CodeGenVTables &getVTables() { return VTables; }
- VTableContext &getVTableContext() { return VTables.getVTableContext(); }
DiagnosticsEngine &getDiags() const { return Diags; }
const llvm::DataLayout &getDataLayout() const { return TheDataLayout; }
- const TargetInfo &getTarget() const { return Context.getTargetInfo(); }
+ const TargetInfo &getTarget() const { return Target; }
+ CGCXXABI &getCXXABI() { return ABI; }
llvm::LLVMContext &getLLVMContext() { return VMContext; }
- const TargetCodeGenInfo &getTargetCodeGenInfo();
- bool isTargetDarwin() const;
-
+
bool shouldUseTBAA() const { return TBAA != 0; }
+ const TargetCodeGenInfo &getTargetCodeGenInfo();
+
+ CodeGenTypes &getTypes() { return Types; }
+
+ CodeGenVTables &getVTables() { return VTables; }
+ VTableContext &getVTableContext() { return VTables.getVTableContext(); }
+
llvm::MDNode *getTBAAInfo(QualType QTy);
llvm::MDNode *getTBAAInfoForVTablePtr();
llvm::MDNode *getTBAAStructInfo(QualType QTy);
@@ -512,8 +531,13 @@ public:
bool isPaddedAtomicType(QualType type);
bool isPaddedAtomicType(const AtomicType *type);
- static void DecorateInstruction(llvm::Instruction *Inst,
- llvm::MDNode *TBAAInfo);
+ /// Decorate the instruction with a TBAA tag. For scalar TBAA, the tag
+ /// is the same as the type. For struct-path aware TBAA, the tag
+ /// is different from the type: base type, access type and offset.
+ /// When ConvertTypeToTag is true, we create a tag based on the scalar type.
+ void DecorateInstruction(llvm::Instruction *Inst,
+ llvm::MDNode *TBAAInfo,
+ bool ConvertTypeToTag = true);
/// getSize - Emit the given number of characters as a value of type size_t.
llvm::ConstantInt *getSize(CharUnits numChars);
@@ -563,8 +587,8 @@ public:
return GetAddrOfGlobalVar(cast<VarDecl>(GD.getDecl()));
}
- /// CreateOrReplaceCXXRuntimeVariable - Will return a global variable of the given
- /// type. If a variable with a different type already exists then a new
+ /// CreateOrReplaceCXXRuntimeVariable - Will return a global variable of the
+ /// given type. If a variable with a different type already exists then a new
/// variable with the right type will be created and all uses of the old
/// variable will be replaced with a bitcast to the new variable.
llvm::GlobalVariable *
@@ -689,7 +713,7 @@ public:
/// (if one is created).
llvm::Constant *GetAddrOfConstantString(StringRef Str,
const char *GlobalName=0,
- unsigned Alignment=1);
+ unsigned Alignment=0);
/// GetAddrOfConstantCString - Returns a pointer to a character array
/// containing the literal and a terminating '\0' character. The result has
@@ -699,7 +723,7 @@ public:
/// created).
llvm::Constant *GetAddrOfConstantCString(const std::string &str,
const char *GlobalName=0,
- unsigned Alignment=1);
+ unsigned Alignment=0);
/// GetAddrOfConstantCompoundLiteral - Returns a pointer to a constant global
/// variable for the given file-scope compound literal expression.
@@ -726,8 +750,7 @@ public:
llvm::Value *getBuiltinLibFunction(const FunctionDecl *FD,
unsigned BuiltinID);
- llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys =
- ArrayRef<llvm::Type*>());
+ llvm::Function *getIntrinsic(unsigned IID, ArrayRef<llvm::Type*> Tys = None);
/// EmitTopLevelDecl - Emit code for a single top level declaration.
void EmitTopLevelDecl(Decl *D);
@@ -736,6 +759,12 @@ public:
// variable has been instantiated.
void HandleCXXStaticMemberVarInstantiation(VarDecl *VD);
+ /// \brief If the declaration has internal linkage but is inside an
+ /// extern "C" linkage specification, prepare to emit an alias for it
+ /// to the expected name.
+ template<typename SomeDecl>
+ void MaybeHandleStaticInExternC(const SomeDecl *D, llvm::GlobalValue *GV);
+
/// AddUsedGlobal - Add a global which should be forced to be
/// present in the object file; these are emitted to the llvm.used
/// metadata global.
@@ -1004,6 +1033,9 @@ private:
/// a C++ destructor Decl.
void EmitCXXDestructor(const CXXDestructorDecl *D, CXXDtorType Type);
+ /// \brief Emit the function that initializes C++ thread_local variables.
+ void EmitCXXThreadLocalInitFunc();
+
/// EmitCXXGlobalInitFunc - Emit the function that initializes C++ globals.
void EmitCXXGlobalInitFunc();
@@ -1048,6 +1080,10 @@ private:
/// \brief Emit the link options introduced by imported modules.
void EmitModuleLinkOptions();
+ /// \brief Emit aliases for internal-linkage declarations inside "C" language
+ /// linkage specifications, giving them the "expected" name where possible.
+ void EmitStaticExternCAliases();
+
void EmitDeclMetadata();
/// EmitCoverageFile - Emit the llvm.gcov metadata used to tell LLVM where
diff --git a/lib/CodeGen/CodeGenTBAA.cpp b/lib/CodeGen/CodeGenTBAA.cpp
index 7e4d34ab8981..5ff1560a4886 100644
--- a/lib/CodeGen/CodeGenTBAA.cpp
+++ b/lib/CodeGen/CodeGenTBAA.cpp
@@ -50,13 +50,25 @@ llvm::MDNode *CodeGenTBAA::getRoot() {
return Root;
}
+// For struct-path aware TBAA, the scalar type has the same format as
+// the struct type: name, offset, pointer to another node in the type DAG.
+// For scalar TBAA, the scalar type is the same as the scalar tag:
+// name and a parent pointer.
+llvm::MDNode *CodeGenTBAA::createTBAAScalarType(StringRef Name,
+ llvm::MDNode *Parent) {
+ if (CodeGenOpts.StructPathTBAA)
+ return MDHelper.createTBAAScalarTypeNode(Name, Parent);
+ else
+ return MDHelper.createTBAANode(Name, Parent);
+}
+
llvm::MDNode *CodeGenTBAA::getChar() {
// Define the root of the tree for user-accessible memory. C and C++
// give special powers to char and certain similar types. However,
// these special powers only cover user-accessible memory, and doesn't
// include things like vtables.
if (!Char)
- Char = MDHelper.createTBAANode("omnipotent char", getRoot());
+ Char = createTBAAScalarType("omnipotent char", getRoot());
return Char;
}
@@ -124,7 +136,7 @@ CodeGenTBAA::getTBAAInfo(QualType QTy) {
// "underlying types".
default:
return MetadataCache[Ty] =
- MDHelper.createTBAANode(BTy->getName(Features), getChar());
+ createTBAAScalarType(BTy->getName(Features), getChar());
}
}
@@ -132,8 +144,8 @@ CodeGenTBAA::getTBAAInfo(QualType QTy) {
// TODO: Implement C++'s type "similarity" and consider dis-"similar"
// pointers distinct.
if (Ty->isPointerType())
- return MetadataCache[Ty] = MDHelper.createTBAANode("any pointer",
- getChar());
+ return MetadataCache[Ty] = createTBAAScalarType("any pointer",
+ getChar());
// Enum types are distinct types. In C++ they have "underlying types",
// however they aren't related for TBAA.
@@ -160,7 +172,7 @@ CodeGenTBAA::getTBAAInfo(QualType QTy) {
llvm::raw_svector_ostream Out(OutName);
MContext.mangleCXXRTTIName(QualType(ETy, 0), Out);
Out.flush();
- return MetadataCache[Ty] = MDHelper.createTBAANode(OutName, getChar());
+ return MetadataCache[Ty] = createTBAAScalarType(OutName, getChar());
}
// For now, handle any other kind of type conservatively.
@@ -168,7 +180,7 @@ CodeGenTBAA::getTBAAInfo(QualType QTy) {
}
llvm::MDNode *CodeGenTBAA::getTBAAInfoForVTablePtr() {
- return MDHelper.createTBAANode("vtable pointer", getRoot());
+ return createTBAAScalarType("vtable pointer", getRoot());
}
bool
@@ -192,8 +204,18 @@ CodeGenTBAA::CollectFields(uint64_t BaseOffset,
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
unsigned idx = 0;
+ const FieldDecl *LastFD = 0;
+ bool IsMsStruct = RD->isMsStruct(Context);
for (RecordDecl::field_iterator i = RD->field_begin(),
e = RD->field_end(); i != e; ++i, ++idx) {
+ if (IsMsStruct) {
+ // Zero-length bitfields following non-bitfield members are ignored.
+ if (Context.ZeroBitfieldFollowsNonBitfield(*i, LastFD)) {
+ --idx;
+ continue;
+ }
+ LastFD = *i;
+ }
uint64_t Offset = BaseOffset +
Layout.getFieldOffset(idx) / Context.getCharWidth();
QualType FieldQTy = i->getType();
@@ -208,7 +230,9 @@ CodeGenTBAA::CollectFields(uint64_t BaseOffset,
uint64_t Offset = BaseOffset;
uint64_t Size = Context.getTypeSizeInChars(QTy).getQuantity();
llvm::MDNode *TBAAInfo = MayAlias ? getChar() : getTBAAInfo(QTy);
- Fields.push_back(llvm::MDBuilder::TBAAStructField(Offset, Size, TBAAInfo));
+ llvm::MDNode *TBAATag = CodeGenOpts.StructPathTBAA ?
+ getTBAAScalarTagInfo(TBAAInfo) : TBAAInfo;
+ Fields.push_back(llvm::MDBuilder::TBAAStructField(Offset, Size, TBAATag));
return true;
}
@@ -231,9 +255,11 @@ CodeGenTBAA::getTBAAStructInfo(QualType QTy) {
static bool isTBAAPathStruct(QualType QTy) {
if (const RecordType *TTy = QTy->getAs<RecordType>()) {
const RecordDecl *RD = TTy->getDecl()->getDefinition();
+ if (RD->hasFlexibleArrayMember())
+ return false;
// RD can be struct, union, class, interface or enum.
- // For now, we only handle struct.
- if (RD->isStruct() && !RD->hasFlexibleArrayMember())
+ // For now, we only handle struct and class.
+ if (RD->isStruct() || RD->isClass())
return true;
}
return false;
@@ -251,29 +277,31 @@ CodeGenTBAA::getTBAAStructTypeInfo(QualType QTy) {
const RecordDecl *RD = TTy->getDecl()->getDefinition();
const ASTRecordLayout &Layout = Context.getASTRecordLayout(RD);
- SmallVector <std::pair<uint64_t, llvm::MDNode*>, 4> Fields;
- // To reduce the size of MDNode for a given struct type, we only output
- // once for all the fields with the same scalar types.
- // Offsets for scalar fields in the type DAG are not used.
- llvm::SmallSet <llvm::MDNode*, 4> ScalarFieldTypes;
+ SmallVector <std::pair<llvm::MDNode*, uint64_t>, 4> Fields;
unsigned idx = 0;
+ const FieldDecl *LastFD = 0;
+ bool IsMsStruct = RD->isMsStruct(Context);
for (RecordDecl::field_iterator i = RD->field_begin(),
e = RD->field_end(); i != e; ++i, ++idx) {
+ if (IsMsStruct) {
+ // Zero-length bitfields following non-bitfield members are ignored.
+ if (Context.ZeroBitfieldFollowsNonBitfield(*i, LastFD)) {
+ --idx;
+ continue;
+ }
+ LastFD = *i;
+ }
+
QualType FieldQTy = i->getType();
llvm::MDNode *FieldNode;
if (isTBAAPathStruct(FieldQTy))
FieldNode = getTBAAStructTypeInfo(FieldQTy);
- else {
+ else
FieldNode = getTBAAInfo(FieldQTy);
- // Ignore this field if the type already exists.
- if (ScalarFieldTypes.count(FieldNode))
- continue;
- ScalarFieldTypes.insert(FieldNode);
- }
if (!FieldNode)
return StructTypeMetadataCache[Ty] = NULL;
Fields.push_back(std::make_pair(
- Layout.getFieldOffset(idx) / Context.getCharWidth(), FieldNode));
+ FieldNode, Layout.getFieldOffset(idx) / Context.getCharWidth()));
}
// TODO: This is using the RTTI name. Is there a better way to get
@@ -305,8 +333,18 @@ CodeGenTBAA::getTBAAStructTagInfo(QualType BaseQTy, llvm::MDNode *AccessNode,
if (isTBAAPathStruct(BaseQTy))
BNode = getTBAAStructTypeInfo(BaseQTy);
if (!BNode)
- return StructTagMetadataCache[PathTag] = AccessNode;
+ return StructTagMetadataCache[PathTag] =
+ MDHelper.createTBAAStructTagNode(AccessNode, AccessNode, 0);
return StructTagMetadataCache[PathTag] =
MDHelper.createTBAAStructTagNode(BNode, AccessNode, Offset);
}
+
+llvm::MDNode *
+CodeGenTBAA::getTBAAScalarTagInfo(llvm::MDNode *AccessNode) {
+ if (llvm::MDNode *N = ScalarTagMetadataCache[AccessNode])
+ return N;
+
+ return ScalarTagMetadataCache[AccessNode] =
+ MDHelper.createTBAAStructTagNode(AccessNode, AccessNode, 0);
+}
diff --git a/lib/CodeGen/CodeGenTBAA.h b/lib/CodeGen/CodeGenTBAA.h
index 9ddc3aa97006..f0c9e06f02bd 100644
--- a/lib/CodeGen/CodeGenTBAA.h
+++ b/lib/CodeGen/CodeGenTBAA.h
@@ -61,6 +61,8 @@ class CodeGenTBAA {
llvm::DenseMap<const Type *, llvm::MDNode *> StructTypeMetadataCache;
/// This maps TBAAPathTags to a tag node.
llvm::DenseMap<TBAAPathTag, llvm::MDNode *> StructTagMetadataCache;
+ /// This maps a scalar type to a scalar tag node.
+ llvm::DenseMap<const llvm::MDNode *, llvm::MDNode *> ScalarTagMetadataCache;
/// StructMetadataCache - This maps clang::Types to llvm::MDNodes describing
/// them for struct assignments.
@@ -84,6 +86,11 @@ class CodeGenTBAA {
SmallVectorImpl<llvm::MDBuilder::TBAAStructField> &Fields,
bool MayAlias);
+ /// A wrapper function to create a scalar type. For struct-path aware TBAA,
+ /// the scalar type has the same format as the struct type: name, offset,
+ /// pointer to another node in the type DAG.
+ llvm::MDNode *createTBAAScalarType(StringRef Name, llvm::MDNode *Parent);
+
public:
CodeGenTBAA(ASTContext &Ctx, llvm::LLVMContext &VMContext,
const CodeGenOptions &CGO,
@@ -105,10 +112,13 @@ public:
/// Get the MDNode in the type DAG for given struct type QType.
llvm::MDNode *getTBAAStructTypeInfo(QualType QType);
- /// Get the tag MDNode for a given base type, the actual sclar access MDNode
+ /// Get the tag MDNode for a given base type, the actual scalar access MDNode
/// and offset into the base type.
llvm::MDNode *getTBAAStructTagInfo(QualType BaseQType,
llvm::MDNode *AccessNode, uint64_t Offset);
+
+ /// Get the sclar tag MDNode for a given scalar type.
+ llvm::MDNode *getTBAAScalarTagInfo(llvm::MDNode *AccessNode);
};
} // end namespace CodeGen
diff --git a/lib/CodeGen/CodeGenTypes.cpp b/lib/CodeGen/CodeGenTypes.cpp
index 8fc78e3de628..4240216b230c 100644
--- a/lib/CodeGen/CodeGenTypes.cpp
+++ b/lib/CodeGen/CodeGenTypes.cpp
@@ -28,12 +28,12 @@
using namespace clang;
using namespace CodeGen;
-CodeGenTypes::CodeGenTypes(CodeGenModule &CGM)
- : Context(CGM.getContext()), Target(Context.getTargetInfo()),
- TheModule(CGM.getModule()), TheDataLayout(CGM.getDataLayout()),
- TheABIInfo(CGM.getTargetCodeGenInfo().getABIInfo()),
- TheCXXABI(CGM.getCXXABI()),
- CodeGenOpts(CGM.getCodeGenOpts()), CGM(CGM) {
+CodeGenTypes::CodeGenTypes(CodeGenModule &cgm)
+ : CGM(cgm), Context(cgm.getContext()), TheModule(cgm.getModule()),
+ TheDataLayout(cgm.getDataLayout()),
+ Target(cgm.getTarget()), TheCXXABI(cgm.getCXXABI()),
+ CodeGenOpts(cgm.getCodeGenOpts()),
+ TheABIInfo(cgm.getTargetCodeGenInfo().getABIInfo()) {
SkippedLayout = false;
}
@@ -392,6 +392,8 @@ llvm::Type *CodeGenTypes::ConvertType(QualType T) {
}
break;
}
+ case Type::Auto:
+ llvm_unreachable("Unexpected undeduced auto type!");
case Type::Complex: {
llvm::Type *EltTy = ConvertType(cast<ComplexType>(Ty)->getElementType());
ResultType = llvm::StructType::get(EltTy, EltTy, NULL);
diff --git a/lib/CodeGen/CodeGenTypes.h b/lib/CodeGen/CodeGenTypes.h
index 11fd76fb19a9..452375f374c4 100644
--- a/lib/CodeGen/CodeGenTypes.h
+++ b/lib/CodeGen/CodeGenTypes.h
@@ -60,14 +60,17 @@ namespace CodeGen {
class CodeGenTypes {
public:
// Some of this stuff should probably be left on the CGM.
+ CodeGenModule &CGM;
ASTContext &Context;
- const TargetInfo &Target;
llvm::Module &TheModule;
const llvm::DataLayout &TheDataLayout;
- const ABIInfo &TheABIInfo;
+ const TargetInfo &Target;
CGCXXABI &TheCXXABI;
const CodeGenOptions &CodeGenOpts;
- CodeGenModule &CGM;
+
+ // This should not be moved earlier, since its initialization depends on some
+ // of the previous reference members being already initialized
+ const ABIInfo &TheABIInfo;
private:
/// The opaque type map for Objective-C interfaces. All direct
@@ -107,14 +110,14 @@ private:
llvm::DenseMap<const Type *, llvm::Type *> TypeCache;
public:
- CodeGenTypes(CodeGenModule &CGM);
+ CodeGenTypes(CodeGenModule &cgm);
~CodeGenTypes();
const llvm::DataLayout &getDataLayout() const { return TheDataLayout; }
- const TargetInfo &getTarget() const { return Target; }
ASTContext &getContext() const { return Context; }
const ABIInfo &getABIInfo() const { return TheABIInfo; }
const CodeGenOptions &getCodeGenOpts() const { return CodeGenOpts; }
+ const TargetInfo &getTarget() const { return Target; }
CGCXXABI &getCXXABI() const { return TheCXXABI; }
llvm::LLVMContext &getLLVMContext() { return TheModule.getContext(); }
diff --git a/lib/CodeGen/ItaniumCXXABI.cpp b/lib/CodeGen/ItaniumCXXABI.cpp
index e25d422d2367..e117e2867bdd 100644
--- a/lib/CodeGen/ItaniumCXXABI.cpp
+++ b/lib/CodeGen/ItaniumCXXABI.cpp
@@ -41,6 +41,20 @@ public:
ItaniumCXXABI(CodeGen::CodeGenModule &CGM, bool IsARM = false) :
CGCXXABI(CGM), IsARM(IsARM) { }
+ bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
+ // Structures with either a non-trivial destructor or a non-trivial
+ // copy constructor are always indirect.
+ return !RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor();
+ }
+
+ RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
+ // Structures with either a non-trivial destructor or a non-trivial
+ // copy constructor are always indirect.
+ if (!RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor())
+ return RAA_Indirect;
+ return RAA_Default;
+ }
+
bool isZeroInitializable(const MemberPointerType *MPT);
llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
@@ -130,8 +144,16 @@ public:
void EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
llvm::GlobalVariable *DeclPtr, bool PerformInit);
- void registerGlobalDtor(CodeGenFunction &CGF, llvm::Constant *dtor,
- llvm::Constant *addr);
+ void registerGlobalDtor(CodeGenFunction &CGF, const VarDecl &D,
+ llvm::Constant *dtor, llvm::Constant *addr);
+
+ llvm::Function *getOrCreateThreadLocalWrapper(const VarDecl *VD,
+ llvm::GlobalVariable *Var);
+ void EmitThreadLocalInitFuncs(
+ llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
+ llvm::Function *InitFunc);
+ LValue EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
+ const DeclRefExpr *DRE);
};
class ARMCXXABI : public ItaniumCXXABI {
@@ -177,7 +199,7 @@ public:
}
CodeGen::CGCXXABI *CodeGen::CreateItaniumCXXABI(CodeGenModule &CGM) {
- switch (CGM.getContext().getTargetInfo().getCXXABI().getKind()) {
+ switch (CGM.getTarget().getCXXABI().getKind()) {
// For IR-generation purposes, there's no significant difference
// between the ARM and iOS ABIs.
case TargetCXXABI::GenericARM:
@@ -1042,10 +1064,10 @@ void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
bool shouldPerformInit) {
CGBuilderTy &Builder = CGF.Builder;
- // We only need to use thread-safe statics for local variables;
+ // We only need to use thread-safe statics for local non-TLS variables;
// global initialization is always single-threaded.
- bool threadsafe =
- (getContext().getLangOpts().ThreadsafeStatics && D.isLocalVarDecl());
+ bool threadsafe = getContext().getLangOpts().ThreadsafeStatics &&
+ D.isLocalVarDecl() && !D.getTLSKind();
// If we have a global variable with internal linkage and thread-safe statics
// are disabled, we can just let the guard variable be of type i8.
@@ -1080,6 +1102,8 @@ void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
llvm::ConstantInt::get(guardTy, 0),
guardName.str());
guard->setVisibility(var->getVisibility());
+ // If the variable is thread-local, so is its guard variable.
+ guard->setThreadLocalMode(var->getThreadLocalMode());
CGM.setStaticLocalDeclGuardAddress(&D, guard);
}
@@ -1180,7 +1204,14 @@ void ItaniumCXXABI::EmitGuardedInit(CodeGenFunction &CGF,
/// Register a global destructor using __cxa_atexit.
static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
llvm::Constant *dtor,
- llvm::Constant *addr) {
+ llvm::Constant *addr,
+ bool TLS) {
+ const char *Name = "__cxa_atexit";
+ if (TLS) {
+ const llvm::Triple &T = CGF.getTarget().getTriple();
+ Name = T.isMacOSX() ? "_tlv_atexit" : "__cxa_thread_atexit";
+ }
+
// We're assuming that the destructor function is something we can
// reasonably call with the default CC. Go ahead and cast it to the
// right prototype.
@@ -1193,8 +1224,7 @@ static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
llvm::FunctionType::get(CGF.IntTy, paramTys, false);
// Fetch the actual function.
- llvm::Constant *atexit =
- CGF.CGM.CreateRuntimeFunction(atexitTy, "__cxa_atexit");
+ llvm::Constant *atexit = CGF.CGM.CreateRuntimeFunction(atexitTy, Name);
if (llvm::Function *fn = dyn_cast<llvm::Function>(atexit))
fn->setDoesNotThrow();
@@ -1212,12 +1242,15 @@ static void emitGlobalDtorWithCXAAtExit(CodeGenFunction &CGF,
/// Register a global destructor as best as we know how.
void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
+ const VarDecl &D,
llvm::Constant *dtor,
llvm::Constant *addr) {
// Use __cxa_atexit if available.
- if (CGM.getCodeGenOpts().CXAAtExit) {
- return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr);
- }
+ if (CGM.getCodeGenOpts().CXAAtExit)
+ return emitGlobalDtorWithCXAAtExit(CGF, dtor, addr, D.getTLSKind());
+
+ if (D.getTLSKind())
+ CGM.ErrorUnsupported(&D, "non-trivial TLS destruction");
// In Apple kexts, we want to add a global destructor entry.
// FIXME: shouldn't this be guarded by some variable?
@@ -1228,3 +1261,138 @@ void ItaniumCXXABI::registerGlobalDtor(CodeGenFunction &CGF,
CGF.registerGlobalDtorWithAtExit(dtor, addr);
}
+
+/// Get the appropriate linkage for the wrapper function. This is essentially
+/// the weak form of the variable's linkage; every translation unit which wneeds
+/// the wrapper emits a copy, and we want the linker to merge them.
+static llvm::GlobalValue::LinkageTypes getThreadLocalWrapperLinkage(
+ llvm::GlobalValue::LinkageTypes VarLinkage) {
+ if (llvm::GlobalValue::isLinkerPrivateLinkage(VarLinkage))
+ return llvm::GlobalValue::LinkerPrivateWeakLinkage;
+ // For internal linkage variables, we don't need an external or weak wrapper.
+ if (llvm::GlobalValue::isLocalLinkage(VarLinkage))
+ return VarLinkage;
+ return llvm::GlobalValue::WeakODRLinkage;
+}
+
+llvm::Function *
+ItaniumCXXABI::getOrCreateThreadLocalWrapper(const VarDecl *VD,
+ llvm::GlobalVariable *Var) {
+ // Mangle the name for the thread_local wrapper function.
+ SmallString<256> WrapperName;
+ {
+ llvm::raw_svector_ostream Out(WrapperName);
+ getMangleContext().mangleItaniumThreadLocalWrapper(VD, Out);
+ Out.flush();
+ }
+
+ if (llvm::Value *V = Var->getParent()->getNamedValue(WrapperName))
+ return cast<llvm::Function>(V);
+
+ llvm::Type *RetTy = Var->getType();
+ if (VD->getType()->isReferenceType())
+ RetTy = RetTy->getPointerElementType();
+
+ llvm::FunctionType *FnTy = llvm::FunctionType::get(RetTy, false);
+ llvm::Function *Wrapper = llvm::Function::Create(
+ FnTy, getThreadLocalWrapperLinkage(Var->getLinkage()), WrapperName.str(),
+ &CGM.getModule());
+ // Always resolve references to the wrapper at link time.
+ Wrapper->setVisibility(llvm::GlobalValue::HiddenVisibility);
+ return Wrapper;
+}
+
+void ItaniumCXXABI::EmitThreadLocalInitFuncs(
+ llvm::ArrayRef<std::pair<const VarDecl *, llvm::GlobalVariable *> > Decls,
+ llvm::Function *InitFunc) {
+ for (unsigned I = 0, N = Decls.size(); I != N; ++I) {
+ const VarDecl *VD = Decls[I].first;
+ llvm::GlobalVariable *Var = Decls[I].second;
+
+ // Mangle the name for the thread_local initialization function.
+ SmallString<256> InitFnName;
+ {
+ llvm::raw_svector_ostream Out(InitFnName);
+ getMangleContext().mangleItaniumThreadLocalInit(VD, Out);
+ Out.flush();
+ }
+
+ // If we have a definition for the variable, emit the initialization
+ // function as an alias to the global Init function (if any). Otherwise,
+ // produce a declaration of the initialization function.
+ llvm::GlobalValue *Init = 0;
+ bool InitIsInitFunc = false;
+ if (VD->hasDefinition()) {
+ InitIsInitFunc = true;
+ if (InitFunc)
+ Init =
+ new llvm::GlobalAlias(InitFunc->getType(), Var->getLinkage(),
+ InitFnName.str(), InitFunc, &CGM.getModule());
+ } else {
+ // Emit a weak global function referring to the initialization function.
+ // This function will not exist if the TU defining the thread_local
+ // variable in question does not need any dynamic initialization for
+ // its thread_local variables.
+ llvm::FunctionType *FnTy = llvm::FunctionType::get(CGM.VoidTy, false);
+ Init = llvm::Function::Create(
+ FnTy, llvm::GlobalVariable::ExternalWeakLinkage, InitFnName.str(),
+ &CGM.getModule());
+ }
+
+ if (Init)
+ Init->setVisibility(Var->getVisibility());
+
+ llvm::Function *Wrapper = getOrCreateThreadLocalWrapper(VD, Var);
+ llvm::LLVMContext &Context = CGM.getModule().getContext();
+ llvm::BasicBlock *Entry = llvm::BasicBlock::Create(Context, "", Wrapper);
+ CGBuilderTy Builder(Entry);
+ if (InitIsInitFunc) {
+ if (Init)
+ Builder.CreateCall(Init);
+ } else {
+ // Don't know whether we have an init function. Call it if it exists.
+ llvm::Value *Have = Builder.CreateIsNotNull(Init);
+ llvm::BasicBlock *InitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
+ llvm::BasicBlock *ExitBB = llvm::BasicBlock::Create(Context, "", Wrapper);
+ Builder.CreateCondBr(Have, InitBB, ExitBB);
+
+ Builder.SetInsertPoint(InitBB);
+ Builder.CreateCall(Init);
+ Builder.CreateBr(ExitBB);
+
+ Builder.SetInsertPoint(ExitBB);
+ }
+
+ // For a reference, the result of the wrapper function is a pointer to
+ // the referenced object.
+ llvm::Value *Val = Var;
+ if (VD->getType()->isReferenceType()) {
+ llvm::LoadInst *LI = Builder.CreateLoad(Val);
+ LI->setAlignment(CGM.getContext().getDeclAlign(VD).getQuantity());
+ Val = LI;
+ }
+
+ Builder.CreateRet(Val);
+ }
+}
+
+LValue ItaniumCXXABI::EmitThreadLocalDeclRefExpr(CodeGenFunction &CGF,
+ const DeclRefExpr *DRE) {
+ const VarDecl *VD = cast<VarDecl>(DRE->getDecl());
+ QualType T = VD->getType();
+ llvm::Type *Ty = CGF.getTypes().ConvertTypeForMem(T);
+ llvm::Value *Val = CGF.CGM.GetAddrOfGlobalVar(VD, Ty);
+ llvm::Function *Wrapper =
+ getOrCreateThreadLocalWrapper(VD, cast<llvm::GlobalVariable>(Val));
+
+ Val = CGF.Builder.CreateCall(Wrapper);
+
+ LValue LV;
+ if (VD->getType()->isReferenceType())
+ LV = CGF.MakeNaturalAlignAddrLValue(Val, T);
+ else
+ LV = CGF.MakeAddrLValue(Val, DRE->getType(),
+ CGF.getContext().getDeclAlign(VD));
+ // FIXME: need setObjCGCLValueClass?
+ return LV;
+}
diff --git a/lib/CodeGen/MicrosoftCXXABI.cpp b/lib/CodeGen/MicrosoftCXXABI.cpp
index 00b15c9a49c4..f5242eaaa2fb 100644
--- a/lib/CodeGen/MicrosoftCXXABI.cpp
+++ b/lib/CodeGen/MicrosoftCXXABI.cpp
@@ -28,6 +28,17 @@ class MicrosoftCXXABI : public CGCXXABI {
public:
MicrosoftCXXABI(CodeGenModule &CGM) : CGCXXABI(CGM) {}
+ bool isReturnTypeIndirect(const CXXRecordDecl *RD) const {
+ // Structures that are not C++03 PODs are always indirect.
+ return !RD->isPOD();
+ }
+
+ RecordArgABI getRecordArgABI(const CXXRecordDecl *RD) const {
+ if (RD->hasNonTrivialCopyConstructor())
+ return RAA_DirectInMemory;
+ return RAA_Default;
+ }
+
StringRef GetPureVirtualCallName() { return "_purecall"; }
// No known support for deleted functions in MSVC yet, so this choice is
// arbitrary.
@@ -111,21 +122,46 @@ public:
static bool needThisReturn(GlobalDecl GD);
private:
- llvm::Constant *getSimpleNullMemberPointer(const MemberPointerType *MPT);
-
- llvm::Constant *getZeroPtrDiff() {
- return llvm::ConstantInt::get(CGM.PtrDiffTy, 0);
+ llvm::Constant *getZeroInt() {
+ return llvm::ConstantInt::get(CGM.IntTy, 0);
}
- llvm::Constant *getAllOnesPtrDiff() {
- return llvm::Constant::getAllOnesValue(CGM.PtrDiffTy);
+ llvm::Constant *getAllOnesInt() {
+ return llvm::Constant::getAllOnesValue(CGM.IntTy);
}
+ void
+ GetNullMemberPointerFields(const MemberPointerType *MPT,
+ llvm::SmallVectorImpl<llvm::Constant *> &fields);
+
+ llvm::Value *AdjustVirtualBase(CodeGenFunction &CGF, const CXXRecordDecl *RD,
+ llvm::Value *Base,
+ llvm::Value *VirtualBaseAdjustmentOffset,
+ llvm::Value *VBPtrOffset /* optional */);
+
+ /// \brief Emits a full member pointer with the fields common to data and
+ /// function member pointers.
+ llvm::Constant *EmitFullMemberPointer(llvm::Constant *FirstField,
+ bool IsMemberFunction,
+ const CXXRecordDecl *RD);
+
public:
+ virtual llvm::Type *ConvertMemberPointerType(const MemberPointerType *MPT);
+
+ virtual bool isZeroInitializable(const MemberPointerType *MPT);
+
virtual llvm::Constant *EmitNullMemberPointer(const MemberPointerType *MPT);
virtual llvm::Constant *EmitMemberDataPointer(const MemberPointerType *MPT,
CharUnits offset);
+ virtual llvm::Constant *EmitMemberPointer(const CXXMethodDecl *MD);
+ virtual llvm::Constant *EmitMemberPointer(const APValue &MP, QualType MPT);
+
+ virtual llvm::Value *EmitMemberPointerComparison(CodeGenFunction &CGF,
+ llvm::Value *L,
+ llvm::Value *R,
+ const MemberPointerType *MPT,
+ bool Inequality);
virtual llvm::Value *EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
llvm::Value *MemPtr,
@@ -136,6 +172,12 @@ public:
llvm::Value *MemPtr,
const MemberPointerType *MPT);
+ virtual llvm::Value *
+ EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
+ llvm::Value *&This,
+ llvm::Value *MemPtr,
+ const MemberPointerType *MPT);
+
};
}
@@ -375,49 +417,259 @@ void MicrosoftCXXABI::EmitGuardedInit(CodeGenFunction &CGF, const VarDecl &D,
// Not sure whether we want thread-safe static local variables as VS
// doesn't make them thread-safe.
+ if (D.getTLSKind())
+ CGM.ErrorUnsupported(&D, "dynamic TLS initialization");
+
// Emit the initializer and add a global destructor if appropriate.
CGF.EmitCXXGlobalVarDeclInit(D, DeclPtr, PerformInit);
}
-// Returns true for member pointer types that we know how to represent with a
-// simple ptrdiff_t. Currently we only know how to emit, test, and load member
-// data pointers for complete single inheritance classes.
-static bool isSimpleMemberPointer(const MemberPointerType *MPT) {
+// Member pointer helpers.
+static bool hasVBPtrOffsetField(MSInheritanceModel Inheritance) {
+ return Inheritance == MSIM_Unspecified;
+}
+
+static bool hasOnlyOneField(MSInheritanceModel Inheritance) {
+ return Inheritance <= MSIM_SinglePolymorphic;
+}
+
+// Only member pointers to functions need a this adjustment, since it can be
+// combined with the field offset for data pointers.
+static bool hasNonVirtualBaseAdjustmentField(bool IsMemberFunction,
+ MSInheritanceModel Inheritance) {
+ return (IsMemberFunction && Inheritance >= MSIM_Multiple);
+}
+
+static bool hasVirtualBaseAdjustmentField(MSInheritanceModel Inheritance) {
+ return Inheritance >= MSIM_Virtual;
+}
+
+// Use zero for the field offset of a null data member pointer if we can
+// guarantee that zero is not a valid field offset, or if the member pointer has
+// multiple fields. Polymorphic classes have a vfptr at offset zero, so we can
+// use zero for null. If there are multiple fields, we can use zero even if it
+// is a valid field offset because null-ness testing will check the other
+// fields.
+static bool nullFieldOffsetIsZero(MSInheritanceModel Inheritance) {
+ return Inheritance != MSIM_Multiple && Inheritance != MSIM_Single;
+}
+
+bool MicrosoftCXXABI::isZeroInitializable(const MemberPointerType *MPT) {
+ // Null-ness for function memptrs only depends on the first field, which is
+ // the function pointer. The rest don't matter, so we can zero initialize.
+ if (MPT->isMemberFunctionPointer())
+ return true;
+
+ // The virtual base adjustment field is always -1 for null, so if we have one
+ // we can't zero initialize. The field offset is sometimes also -1 if 0 is a
+ // valid field offset.
const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
- return (MPT->isMemberDataPointer() &&
- !MPT->getClass()->isIncompleteType() &&
- RD->getNumVBases() == 0);
+ MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
+ return (!hasVirtualBaseAdjustmentField(Inheritance) &&
+ nullFieldOffsetIsZero(Inheritance));
}
-llvm::Constant *
-MicrosoftCXXABI::getSimpleNullMemberPointer(const MemberPointerType *MPT) {
- if (isSimpleMemberPointer(MPT)) {
- const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
- // A null member data pointer is represented as -1 if the class is not
- // polymorphic, and 0 otherwise.
- if (RD->isPolymorphic())
- return getZeroPtrDiff();
- return getAllOnesPtrDiff();
+llvm::Type *
+MicrosoftCXXABI::ConvertMemberPointerType(const MemberPointerType *MPT) {
+ const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
+ MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
+ llvm::SmallVector<llvm::Type *, 4> fields;
+ if (MPT->isMemberFunctionPointer())
+ fields.push_back(CGM.VoidPtrTy); // FunctionPointerOrVirtualThunk
+ else
+ fields.push_back(CGM.IntTy); // FieldOffset
+
+ if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
+ Inheritance))
+ fields.push_back(CGM.IntTy);
+ if (hasVBPtrOffsetField(Inheritance))
+ fields.push_back(CGM.IntTy);
+ if (hasVirtualBaseAdjustmentField(Inheritance))
+ fields.push_back(CGM.IntTy); // VirtualBaseAdjustmentOffset
+
+ if (fields.size() == 1)
+ return fields[0];
+ return llvm::StructType::get(CGM.getLLVMContext(), fields);
+}
+
+void MicrosoftCXXABI::
+GetNullMemberPointerFields(const MemberPointerType *MPT,
+ llvm::SmallVectorImpl<llvm::Constant *> &fields) {
+ assert(fields.empty());
+ const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
+ MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
+ if (MPT->isMemberFunctionPointer()) {
+ // FunctionPointerOrVirtualThunk
+ fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
+ } else {
+ if (nullFieldOffsetIsZero(Inheritance))
+ fields.push_back(getZeroInt()); // FieldOffset
+ else
+ fields.push_back(getAllOnesInt()); // FieldOffset
}
- return GetBogusMemberPointer(QualType(MPT, 0));
+
+ if (hasNonVirtualBaseAdjustmentField(MPT->isMemberFunctionPointer(),
+ Inheritance))
+ fields.push_back(getZeroInt());
+ if (hasVBPtrOffsetField(Inheritance))
+ fields.push_back(getZeroInt());
+ if (hasVirtualBaseAdjustmentField(Inheritance))
+ fields.push_back(getAllOnesInt());
}
llvm::Constant *
MicrosoftCXXABI::EmitNullMemberPointer(const MemberPointerType *MPT) {
- if (isSimpleMemberPointer(MPT))
- return getSimpleNullMemberPointer(MPT);
- // FIXME: Implement function member pointers.
- return GetBogusMemberPointer(QualType(MPT, 0));
+ llvm::SmallVector<llvm::Constant *, 4> fields;
+ GetNullMemberPointerFields(MPT, fields);
+ if (fields.size() == 1)
+ return fields[0];
+ llvm::Constant *Res = llvm::ConstantStruct::getAnon(fields);
+ assert(Res->getType() == ConvertMemberPointerType(MPT));
+ return Res;
+}
+
+llvm::Constant *
+MicrosoftCXXABI::EmitFullMemberPointer(llvm::Constant *FirstField,
+ bool IsMemberFunction,
+ const CXXRecordDecl *RD)
+{
+ MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
+
+ // Single inheritance class member pointer are represented as scalars instead
+ // of aggregates.
+ if (hasOnlyOneField(Inheritance))
+ return FirstField;
+
+ llvm::SmallVector<llvm::Constant *, 4> fields;
+ fields.push_back(FirstField);
+
+ if (hasNonVirtualBaseAdjustmentField(IsMemberFunction, Inheritance))
+ fields.push_back(getZeroInt());
+
+ if (hasVBPtrOffsetField(Inheritance)) {
+ int64_t VBPtrOffset =
+ getContext().getASTRecordLayout(RD).getVBPtrOffset().getQuantity();
+ if (VBPtrOffset == -1)
+ VBPtrOffset = 0;
+ fields.push_back(llvm::ConstantInt::get(CGM.IntTy, VBPtrOffset));
+ }
+
+ // The rest of the fields are adjusted by conversions to a more derived class.
+ if (hasVirtualBaseAdjustmentField(Inheritance))
+ fields.push_back(getZeroInt());
+
+ return llvm::ConstantStruct::getAnon(fields);
}
llvm::Constant *
MicrosoftCXXABI::EmitMemberDataPointer(const MemberPointerType *MPT,
CharUnits offset) {
- // Member data pointers are plain offsets when no virtual bases are involved.
- if (isSimpleMemberPointer(MPT))
- return llvm::ConstantInt::get(CGM.PtrDiffTy, offset.getQuantity());
- // FIXME: Implement member pointers other inheritance models.
- return GetBogusMemberPointer(QualType(MPT, 0));
+ const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
+ llvm::Constant *FirstField =
+ llvm::ConstantInt::get(CGM.IntTy, offset.getQuantity());
+ return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/false, RD);
+}
+
+llvm::Constant *
+MicrosoftCXXABI::EmitMemberPointer(const CXXMethodDecl *MD) {
+ assert(MD->isInstance() && "Member function must not be static!");
+ MD = MD->getCanonicalDecl();
+ const CXXRecordDecl *RD = MD->getParent();
+ CodeGenTypes &Types = CGM.getTypes();
+
+ llvm::Constant *FirstField;
+ if (MD->isVirtual()) {
+ // FIXME: We have to instantiate a thunk that loads the vftable and jumps to
+ // the right offset.
+ FirstField = llvm::Constant::getNullValue(CGM.VoidPtrTy);
+ } else {
+ const FunctionProtoType *FPT = MD->getType()->castAs<FunctionProtoType>();
+ llvm::Type *Ty;
+ // Check whether the function has a computable LLVM signature.
+ if (Types.isFuncTypeConvertible(FPT)) {
+ // The function has a computable LLVM signature; use the correct type.
+ Ty = Types.GetFunctionType(Types.arrangeCXXMethodDeclaration(MD));
+ } else {
+ // Use an arbitrary non-function type to tell GetAddrOfFunction that the
+ // function type is incomplete.
+ Ty = CGM.PtrDiffTy;
+ }
+ FirstField = CGM.GetAddrOfFunction(MD, Ty);
+ FirstField = llvm::ConstantExpr::getBitCast(FirstField, CGM.VoidPtrTy);
+ }
+
+ // The rest of the fields are common with data member pointers.
+ return EmitFullMemberPointer(FirstField, /*IsMemberFunction=*/true, RD);
+}
+
+llvm::Constant *
+MicrosoftCXXABI::EmitMemberPointer(const APValue &MP, QualType MPT) {
+ // FIXME PR15875: Implement member pointer conversions for Constants.
+ const CXXRecordDecl *RD = MPT->castAs<MemberPointerType>()->getClass()->getAsCXXRecordDecl();
+ return EmitFullMemberPointer(llvm::Constant::getNullValue(CGM.VoidPtrTy),
+ /*IsMemberFunction=*/true, RD);
+}
+
+/// Member pointers are the same if they're either bitwise identical *or* both
+/// null. Null-ness for function members is determined by the first field,
+/// while for data member pointers we must compare all fields.
+llvm::Value *
+MicrosoftCXXABI::EmitMemberPointerComparison(CodeGenFunction &CGF,
+ llvm::Value *L,
+ llvm::Value *R,
+ const MemberPointerType *MPT,
+ bool Inequality) {
+ CGBuilderTy &Builder = CGF.Builder;
+
+ // Handle != comparisons by switching the sense of all boolean operations.
+ llvm::ICmpInst::Predicate Eq;
+ llvm::Instruction::BinaryOps And, Or;
+ if (Inequality) {
+ Eq = llvm::ICmpInst::ICMP_NE;
+ And = llvm::Instruction::Or;
+ Or = llvm::Instruction::And;
+ } else {
+ Eq = llvm::ICmpInst::ICMP_EQ;
+ And = llvm::Instruction::And;
+ Or = llvm::Instruction::Or;
+ }
+
+ // If this is a single field member pointer (single inheritance), this is a
+ // single icmp.
+ const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
+ MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
+ if (hasOnlyOneField(Inheritance))
+ return Builder.CreateICmp(Eq, L, R);
+
+ // Compare the first field.
+ llvm::Value *L0 = Builder.CreateExtractValue(L, 0, "lhs.0");
+ llvm::Value *R0 = Builder.CreateExtractValue(R, 0, "rhs.0");
+ llvm::Value *Cmp0 = Builder.CreateICmp(Eq, L0, R0, "memptr.cmp.first");
+
+ // Compare everything other than the first field.
+ llvm::Value *Res = 0;
+ llvm::StructType *LType = cast<llvm::StructType>(L->getType());
+ for (unsigned I = 1, E = LType->getNumElements(); I != E; ++I) {
+ llvm::Value *LF = Builder.CreateExtractValue(L, I);
+ llvm::Value *RF = Builder.CreateExtractValue(R, I);
+ llvm::Value *Cmp = Builder.CreateICmp(Eq, LF, RF, "memptr.cmp.rest");
+ if (Res)
+ Res = Builder.CreateBinOp(And, Res, Cmp);
+ else
+ Res = Cmp;
+ }
+
+ // Check if the first field is 0 if this is a function pointer.
+ if (MPT->isMemberFunctionPointer()) {
+ // (l1 == r1 && ...) || l0 == 0
+ llvm::Value *Zero = llvm::Constant::getNullValue(L0->getType());
+ llvm::Value *IsZero = Builder.CreateICmp(Eq, L0, Zero, "memptr.cmp.iszero");
+ Res = Builder.CreateBinOp(Or, Res, IsZero);
+ }
+
+ // Combine the comparison of the first field, which must always be true for
+ // this comparison to succeeed.
+ return Builder.CreateBinOp(And, Res, Cmp0, "memptr.cmp");
}
llvm::Value *
@@ -425,16 +677,90 @@ MicrosoftCXXABI::EmitMemberPointerIsNotNull(CodeGenFunction &CGF,
llvm::Value *MemPtr,
const MemberPointerType *MPT) {
CGBuilderTy &Builder = CGF.Builder;
+ llvm::SmallVector<llvm::Constant *, 4> fields;
+ // We only need one field for member functions.
+ if (MPT->isMemberFunctionPointer())
+ fields.push_back(llvm::Constant::getNullValue(CGM.VoidPtrTy));
+ else
+ GetNullMemberPointerFields(MPT, fields);
+ assert(!fields.empty());
+ llvm::Value *FirstField = MemPtr;
+ if (MemPtr->getType()->isStructTy())
+ FirstField = Builder.CreateExtractValue(MemPtr, 0);
+ llvm::Value *Res = Builder.CreateICmpNE(FirstField, fields[0], "memptr.cmp0");
+
+ // For function member pointers, we only need to test the function pointer
+ // field. The other fields if any can be garbage.
+ if (MPT->isMemberFunctionPointer())
+ return Res;
+
+ // Otherwise, emit a series of compares and combine the results.
+ for (int I = 1, E = fields.size(); I < E; ++I) {
+ llvm::Value *Field = Builder.CreateExtractValue(MemPtr, I);
+ llvm::Value *Next = Builder.CreateICmpNE(Field, fields[I], "memptr.cmp");
+ Res = Builder.CreateAnd(Res, Next, "memptr.tobool");
+ }
+ return Res;
+}
- // For member data pointers, this is just a check against -1 or 0.
- if (isSimpleMemberPointer(MPT)) {
- llvm::Constant *Val = getSimpleNullMemberPointer(MPT);
- return Builder.CreateICmpNE(MemPtr, Val, "memptr.tobool");
+// Returns an adjusted base cast to i8*, since we do more address arithmetic on
+// it.
+llvm::Value *
+MicrosoftCXXABI::AdjustVirtualBase(CodeGenFunction &CGF,
+ const CXXRecordDecl *RD, llvm::Value *Base,
+ llvm::Value *VirtualBaseAdjustmentOffset,
+ llvm::Value *VBPtrOffset) {
+ CGBuilderTy &Builder = CGF.Builder;
+ Base = Builder.CreateBitCast(Base, CGM.Int8PtrTy);
+ llvm::BasicBlock *OriginalBB = 0;
+ llvm::BasicBlock *SkipAdjustBB = 0;
+ llvm::BasicBlock *VBaseAdjustBB = 0;
+
+ // In the unspecified inheritance model, there might not be a vbtable at all,
+ // in which case we need to skip the virtual base lookup. If there is a
+ // vbtable, the first entry is a no-op entry that gives back the original
+ // base, so look for a virtual base adjustment offset of zero.
+ if (VBPtrOffset) {
+ OriginalBB = Builder.GetInsertBlock();
+ VBaseAdjustBB = CGF.createBasicBlock("memptr.vadjust");
+ SkipAdjustBB = CGF.createBasicBlock("memptr.skip_vadjust");
+ llvm::Value *IsVirtual =
+ Builder.CreateICmpNE(VirtualBaseAdjustmentOffset, getZeroInt(),
+ "memptr.is_vbase");
+ Builder.CreateCondBr(IsVirtual, VBaseAdjustBB, SkipAdjustBB);
+ CGF.EmitBlock(VBaseAdjustBB);
}
- // FIXME: Implement member pointers other inheritance models.
- ErrorUnsupportedABI(CGF, "function member pointer tests");
- return GetBogusMemberPointer(QualType(MPT, 0));
+ // If we weren't given a dynamic vbptr offset, RD should be complete and we'll
+ // know the vbptr offset.
+ if (!VBPtrOffset) {
+ CharUnits offs = getContext().getASTRecordLayout(RD).getVBPtrOffset();
+ VBPtrOffset = llvm::ConstantInt::get(CGM.IntTy, offs.getQuantity());
+ }
+ // Load the vbtable pointer from the vbtable offset in the instance.
+ llvm::Value *VBPtr =
+ Builder.CreateInBoundsGEP(Base, VBPtrOffset, "memptr.vbptr");
+ llvm::Value *VBTable =
+ Builder.CreateBitCast(VBPtr, CGM.Int8PtrTy->getPointerTo(0));
+ VBTable = Builder.CreateLoad(VBTable, "memptr.vbtable");
+ // Load an i32 offset from the vb-table.
+ llvm::Value *VBaseOffs =
+ Builder.CreateInBoundsGEP(VBTable, VirtualBaseAdjustmentOffset);
+ VBaseOffs = Builder.CreateBitCast(VBaseOffs, CGM.Int32Ty->getPointerTo(0));
+ VBaseOffs = Builder.CreateLoad(VBaseOffs, "memptr.vbase_offs");
+ // Add it to VBPtr. GEP will sign extend the i32 value for us.
+ llvm::Value *AdjustedBase = Builder.CreateInBoundsGEP(VBPtr, VBaseOffs);
+
+ // Merge control flow with the case where we didn't have to adjust.
+ if (VBaseAdjustBB) {
+ Builder.CreateBr(SkipAdjustBB);
+ CGF.EmitBlock(SkipAdjustBB);
+ llvm::PHINode *Phi = Builder.CreatePHI(CGM.Int8PtrTy, 2, "memptr.base");
+ Phi->addIncoming(Base, OriginalBB);
+ Phi->addIncoming(AdjustedBase, VBaseAdjustBB);
+ return Phi;
+ }
+ return AdjustedBase;
}
llvm::Value *
@@ -442,32 +768,90 @@ MicrosoftCXXABI::EmitMemberDataPointerAddress(CodeGenFunction &CGF,
llvm::Value *Base,
llvm::Value *MemPtr,
const MemberPointerType *MPT) {
+ assert(MPT->isMemberDataPointer());
unsigned AS = Base->getType()->getPointerAddressSpace();
llvm::Type *PType =
CGF.ConvertTypeForMem(MPT->getPointeeType())->getPointerTo(AS);
CGBuilderTy &Builder = CGF.Builder;
-
- if (MPT->isMemberFunctionPointer()) {
- ErrorUnsupportedABI(CGF, "function member pointer address");
- return llvm::Constant::getNullValue(PType);
+ const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
+ MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
+
+ // Extract the fields we need, regardless of model. We'll apply them if we
+ // have them.
+ llvm::Value *FieldOffset = MemPtr;
+ llvm::Value *VirtualBaseAdjustmentOffset = 0;
+ llvm::Value *VBPtrOffset = 0;
+ if (MemPtr->getType()->isStructTy()) {
+ // We need to extract values.
+ unsigned I = 0;
+ FieldOffset = Builder.CreateExtractValue(MemPtr, I++);
+ if (hasVBPtrOffsetField(Inheritance))
+ VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
+ if (hasVirtualBaseAdjustmentField(Inheritance))
+ VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
}
- llvm::Value *Addr;
- if (isSimpleMemberPointer(MPT)) {
- // Add the offset with GEP and i8*.
- assert(MemPtr->getType() == CGM.PtrDiffTy);
- Base = Builder.CreateBitCast(Base, Builder.getInt8Ty()->getPointerTo(AS));
- Addr = Builder.CreateInBoundsGEP(Base, MemPtr, "memptr.offset");
- } else {
- ErrorUnsupportedABI(CGF, "non-scalar member pointers");
- return llvm::Constant::getNullValue(PType);
+ if (VirtualBaseAdjustmentOffset) {
+ Base = AdjustVirtualBase(CGF, RD, Base, VirtualBaseAdjustmentOffset,
+ VBPtrOffset);
}
+ llvm::Value *Addr =
+ Builder.CreateInBoundsGEP(Base, FieldOffset, "memptr.offset");
// Cast the address to the appropriate pointer type, adopting the address
// space of the base pointer.
return Builder.CreateBitCast(Addr, PType);
}
+llvm::Value *
+MicrosoftCXXABI::EmitLoadOfMemberFunctionPointer(CodeGenFunction &CGF,
+ llvm::Value *&This,
+ llvm::Value *MemPtr,
+ const MemberPointerType *MPT) {
+ assert(MPT->isMemberFunctionPointer());
+ const FunctionProtoType *FPT =
+ MPT->getPointeeType()->castAs<FunctionProtoType>();
+ const CXXRecordDecl *RD = MPT->getClass()->getAsCXXRecordDecl();
+ llvm::FunctionType *FTy =
+ CGM.getTypes().GetFunctionType(
+ CGM.getTypes().arrangeCXXMethodType(RD, FPT));
+ CGBuilderTy &Builder = CGF.Builder;
+
+ MSInheritanceModel Inheritance = RD->getMSInheritanceModel();
+
+ // Extract the fields we need, regardless of model. We'll apply them if we
+ // have them.
+ llvm::Value *FunctionPointer = MemPtr;
+ llvm::Value *NonVirtualBaseAdjustment = NULL;
+ llvm::Value *VirtualBaseAdjustmentOffset = NULL;
+ llvm::Value *VBPtrOffset = NULL;
+ if (MemPtr->getType()->isStructTy()) {
+ // We need to extract values.
+ unsigned I = 0;
+ FunctionPointer = Builder.CreateExtractValue(MemPtr, I++);
+ if (hasNonVirtualBaseAdjustmentField(MPT, Inheritance))
+ NonVirtualBaseAdjustment = Builder.CreateExtractValue(MemPtr, I++);
+ if (hasVBPtrOffsetField(Inheritance))
+ VBPtrOffset = Builder.CreateExtractValue(MemPtr, I++);
+ if (hasVirtualBaseAdjustmentField(Inheritance))
+ VirtualBaseAdjustmentOffset = Builder.CreateExtractValue(MemPtr, I++);
+ }
+
+ if (VirtualBaseAdjustmentOffset) {
+ This = AdjustVirtualBase(CGF, RD, This, VirtualBaseAdjustmentOffset,
+ VBPtrOffset);
+ }
+
+ if (NonVirtualBaseAdjustment) {
+ // Apply the adjustment and cast back to the original struct type.
+ llvm::Value *Ptr = Builder.CreateBitCast(This, Builder.getInt8PtrTy());
+ Ptr = Builder.CreateInBoundsGEP(Ptr, NonVirtualBaseAdjustment);
+ This = Builder.CreateBitCast(Ptr, This->getType(), "this.adjusted");
+ }
+
+ return Builder.CreateBitCast(FunctionPointer, FTy->getPointerTo());
+}
+
CGCXXABI *clang::CodeGen::CreateMicrosoftCXXABI(CodeGenModule &CGM) {
return new MicrosoftCXXABI(CGM);
}
diff --git a/lib/CodeGen/ModuleBuilder.cpp b/lib/CodeGen/ModuleBuilder.cpp
index d6e5f0673f82..69e5b323045c 100644
--- a/lib/CodeGen/ModuleBuilder.cpp
+++ b/lib/CodeGen/ModuleBuilder.cpp
@@ -31,15 +31,13 @@ namespace {
OwningPtr<const llvm::DataLayout> TD;
ASTContext *Ctx;
const CodeGenOptions CodeGenOpts; // Intentionally copied in.
- const TargetOptions TargetOpts; // Intentionally copied in.
protected:
OwningPtr<llvm::Module> M;
OwningPtr<CodeGen::CodeGenModule> Builder;
public:
CodeGeneratorImpl(DiagnosticsEngine &diags, const std::string& ModuleName,
- const CodeGenOptions &CGO, const TargetOptions &TO,
- llvm::LLVMContext& C)
- : Diags(diags), CodeGenOpts(CGO), TargetOpts(TO),
+ const CodeGenOptions &CGO, llvm::LLVMContext& C)
+ : Diags(diags), CodeGenOpts(CGO),
M(new llvm::Module(ModuleName, C)) {}
virtual ~CodeGeneratorImpl() {}
@@ -58,8 +56,8 @@ namespace {
M->setTargetTriple(Ctx->getTargetInfo().getTriple().getTriple());
M->setDataLayout(Ctx->getTargetInfo().getTargetDescription());
TD.reset(new llvm::DataLayout(Ctx->getTargetInfo().getTargetDescription()));
- Builder.reset(new CodeGen::CodeGenModule(Context, CodeGenOpts, TargetOpts,
- *M, *TD, Diags));
+ Builder.reset(new CodeGen::CodeGenModule(Context, CodeGenOpts, *M, *TD,
+ Diags));
}
virtual void HandleCXXStaticMemberVarInstantiation(VarDecl *VD) {
@@ -125,7 +123,7 @@ void CodeGenerator::anchor() { }
CodeGenerator *clang::CreateLLVMCodeGen(DiagnosticsEngine &Diags,
const std::string& ModuleName,
const CodeGenOptions &CGO,
- const TargetOptions &TO,
+ const TargetOptions &/*TO*/,
llvm::LLVMContext& C) {
- return new CodeGeneratorImpl(Diags, ModuleName, CGO, TO, C);
+ return new CodeGeneratorImpl(Diags, ModuleName, CGO, C);
}
diff --git a/lib/CodeGen/TargetInfo.cpp b/lib/CodeGen/TargetInfo.cpp
index 7cc63b7db15d..32b27b3172a6 100644
--- a/lib/CodeGen/TargetInfo.cpp
+++ b/lib/CodeGen/TargetInfo.cpp
@@ -14,6 +14,7 @@
#include "TargetInfo.h"
#include "ABIInfo.h"
+#include "CGCXXABI.h"
#include "CodeGenFunction.h"
#include "clang/AST/RecordLayout.h"
#include "clang/Frontend/CodeGenOptions.h"
@@ -43,6 +44,37 @@ static bool isAggregateTypeForABI(QualType T) {
ABIInfo::~ABIInfo() {}
+static bool isRecordReturnIndirect(const RecordType *RT, CodeGen::CodeGenTypes &CGT) {
+ const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
+ if (!RD)
+ return false;
+ return CGT.CGM.getCXXABI().isReturnTypeIndirect(RD);
+}
+
+
+static bool isRecordReturnIndirect(QualType T, CodeGen::CodeGenTypes &CGT) {
+ const RecordType *RT = T->getAs<RecordType>();
+ if (!RT)
+ return false;
+ return isRecordReturnIndirect(RT, CGT);
+}
+
+static CGCXXABI::RecordArgABI getRecordArgABI(const RecordType *RT,
+ CodeGen::CodeGenTypes &CGT) {
+ const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
+ if (!RD)
+ return CGCXXABI::RAA_Default;
+ return CGT.CGM.getCXXABI().getRecordArgABI(RD);
+}
+
+static CGCXXABI::RecordArgABI getRecordArgABI(QualType T,
+ CodeGen::CodeGenTypes &CGT) {
+ const RecordType *RT = T->getAs<RecordType>();
+ if (!RT)
+ return CGCXXABI::RAA_Default;
+ return getRecordArgABI(RT, CGT);
+}
+
ASTContext &ABIInfo::getContext() const {
return CGT.getContext();
}
@@ -55,6 +87,9 @@ const llvm::DataLayout &ABIInfo::getDataLayout() const {
return CGT.getDataLayout();
}
+const TargetInfo &ABIInfo::getTarget() const {
+ return CGT.getTarget();
+}
void ABIArgInfo::dump() const {
raw_ostream &OS = llvm::errs();
@@ -167,27 +202,6 @@ static bool isEmptyRecord(ASTContext &Context, QualType T, bool AllowArrays) {
return true;
}
-/// hasNonTrivialDestructorOrCopyConstructor - Determine if a type has either
-/// a non-trivial destructor or a non-trivial copy constructor.
-static bool hasNonTrivialDestructorOrCopyConstructor(const RecordType *RT) {
- const CXXRecordDecl *RD = dyn_cast<CXXRecordDecl>(RT->getDecl());
- if (!RD)
- return false;
-
- return !RD->hasTrivialDestructor() || RD->hasNonTrivialCopyConstructor();
-}
-
-/// isRecordWithNonTrivialDestructorOrCopyConstructor - Determine if a type is
-/// a record type with either a non-trivial destructor or a non-trivial copy
-/// constructor.
-static bool isRecordWithNonTrivialDestructorOrCopyConstructor(QualType T) {
- const RecordType *RT = T->getAs<RecordType>();
- if (!RT)
- return false;
-
- return hasNonTrivialDestructorOrCopyConstructor(RT);
-}
-
/// isSingleElementStruct - Determine if a structure is a "single
/// element struct", i.e. it has exactly one non-empty field or
/// exactly one field which is itself a single element
@@ -367,7 +381,7 @@ ABIArgInfo DefaultABIInfo::classifyArgumentType(QualType Ty) const {
if (isAggregateTypeForABI(Ty)) {
// Records with non trivial destructors/constructors should not be passed
// by value.
- if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
+ if (isRecordReturnIndirect(Ty, CGT))
return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
return ABIArgInfo::getIndirect(0);
@@ -398,6 +412,9 @@ ABIArgInfo DefaultABIInfo::classifyReturnType(QualType RetTy) const {
//===----------------------------------------------------------------------===//
// le32/PNaCl bitcode ABI Implementation
+//
+// This is a simplified version of the x86_32 ABI. Arguments and return values
+// are always passed on the stack.
//===----------------------------------------------------------------------===//
class PNaClABIInfo : public ABIInfo {
@@ -405,7 +422,7 @@ class PNaClABIInfo : public ABIInfo {
PNaClABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
ABIArgInfo classifyReturnType(QualType RetTy) const;
- ABIArgInfo classifyArgumentType(QualType RetTy, unsigned &FreeRegs) const;
+ ABIArgInfo classifyArgumentType(QualType RetTy) const;
virtual void computeInfo(CGFunctionInfo &FI) const;
virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
@@ -421,13 +438,9 @@ class PNaClTargetCodeGenInfo : public TargetCodeGenInfo {
void PNaClABIInfo::computeInfo(CGFunctionInfo &FI) const {
FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
- // Obtain the initial number of registers available for passing integers
- // from the function's regparm attribute.
- unsigned FreeRegs = FI.getHasRegParm() ? FI.getRegParm() : 0;
-
for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
it != ie; ++it)
- it->info = classifyArgumentType(it->type, FreeRegs);
+ it->info = classifyArgumentType(it->type);
}
llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
@@ -435,42 +448,22 @@ llvm::Value *PNaClABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
return 0;
}
-// \brief Classify argument of given type \p Ty. \p FreeRegs is the number of
-// registers available for passing arguments - it can be updated by this
-// method.
-ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty,
- unsigned &FreeRegs) const {
+/// \brief Classify argument of given type \p Ty.
+ABIArgInfo PNaClABIInfo::classifyArgumentType(QualType Ty) const {
if (isAggregateTypeForABI(Ty)) {
- // In the PNaCl ABI we always pass records/structures on the stack. The
- // byval attribute can be used if the record doesn't have non-trivial
- // constructors/destructors.
- FreeRegs = 0;
- if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
- return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
+ if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT))
+ return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
return ABIArgInfo::getIndirect(0);
- }
-
- // Treat an enum type as its underlying type.
- if (const EnumType *EnumTy = Ty->getAs<EnumType>())
+ } else if (const EnumType *EnumTy = Ty->getAs<EnumType>()) {
+ // Treat an enum type as its underlying type.
Ty = EnumTy->getDecl()->getIntegerType();
+ } else if (Ty->isFloatingType()) {
+ // Floating-point types don't go inreg.
+ return ABIArgInfo::getDirect();
+ }
- ABIArgInfo BaseInfo = (Ty->isPromotableIntegerType() ?
+ return (Ty->isPromotableIntegerType() ?
ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
-
- // Figure out how many of the free registers can be occupied by this type.
- // regparm registers are 32-bit.
- unsigned NumRegsRequired = (getContext().getTypeSize(Ty) + 31) / 32;
- if (NumRegsRequired == 0) return BaseInfo;
- if (NumRegsRequired > FreeRegs) {
- // If this type needs more registers than we have available, no more
- // passing in-registers can happen.
- FreeRegs = 0;
- return BaseInfo;
- }
- FreeRegs -= NumRegsRequired;
- return BaseInfo.isDirect() ?
- ABIArgInfo::getDirectInReg(BaseInfo.getCoerceToType()) :
- ABIArgInfo::getExtendInReg(BaseInfo.getCoerceToType());
}
ABIArgInfo PNaClABIInfo::classifyReturnType(QualType RetTy) const {
@@ -520,7 +513,7 @@ class X86_32ABIInfo : public ABIInfo {
bool IsDarwinVectorABI;
bool IsSmallStructInRegABI;
- bool IsWin32FloatStructABI;
+ bool IsWin32StructABI;
unsigned DefaultNumRegisterParameters;
static bool isRegisterSize(unsigned Size) {
@@ -555,7 +548,7 @@ public:
X86_32ABIInfo(CodeGen::CodeGenTypes &CGT, bool d, bool p, bool w,
unsigned r)
: ABIInfo(CGT), IsDarwinVectorABI(d), IsSmallStructInRegABI(p),
- IsWin32FloatStructABI(w), DefaultNumRegisterParameters(r) {}
+ IsWin32StructABI(w), DefaultNumRegisterParameters(r) {}
};
class X86_32TargetCodeGenInfo : public TargetCodeGenInfo {
@@ -569,8 +562,7 @@ public:
int getDwarfEHStackPointer(CodeGen::CodeGenModule &CGM) const {
// Darwin uses different dwarf register numbers for EH.
- if (CGM.isTargetDarwin()) return 5;
-
+ if (CGM.getTarget().getTriple().isOSDarwin()) return 5;
return 4;
}
@@ -682,9 +674,7 @@ ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
if (isAggregateTypeForABI(RetTy)) {
if (const RecordType *RT = RetTy->getAs<RecordType>()) {
- // Structures with either a non-trivial destructor or a non-trivial
- // copy constructor are always indirect.
- if (hasNonTrivialDestructorOrCopyConstructor(RT))
+ if (isRecordReturnIndirect(RT, CGT))
return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
// Structures with flexible arrays are always indirect.
@@ -708,7 +698,7 @@ ABIArgInfo X86_32ABIInfo::classifyReturnType(QualType RetTy,
// We apply a similar transformation for pointer types to improve the
// quality of the generated IR.
if (const Type *SeltTy = isSingleElementStruct(RetTy, getContext()))
- if ((!IsWin32FloatStructABI && SeltTy->isRealFloatingType())
+ if ((!IsWin32StructABI && SeltTy->isRealFloatingType())
|| SeltTy->hasPointerRepresentation())
return ABIArgInfo::getDirect(CGT.ConvertType(QualType(SeltTy, 0)));
@@ -865,13 +855,14 @@ ABIArgInfo X86_32ABIInfo::classifyArgumentType(QualType Ty,
bool IsFastCall) const {
// FIXME: Set alignment on indirect arguments.
if (isAggregateTypeForABI(Ty)) {
- // Structures with flexible arrays are always indirect.
if (const RecordType *RT = Ty->getAs<RecordType>()) {
- // Structures with either a non-trivial destructor or a non-trivial
- // copy constructor are always indirect.
- if (hasNonTrivialDestructorOrCopyConstructor(RT))
- return getIndirectResult(Ty, false, FreeRegs);
+ if (IsWin32StructABI)
+ return getIndirectResult(Ty, true, FreeRegs);
+
+ if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, CGT))
+ return getIndirectResult(Ty, RAA == CGCXXABI::RAA_DirectInMemory, FreeRegs);
+ // Structures with flexible arrays are always indirect.
if (RT->getDecl()->hasFlexibleArrayMember())
return getIndirectResult(Ty, true, FreeRegs);
}
@@ -1038,7 +1029,7 @@ bool X86_32TargetCodeGenInfo::initDwarfEHRegSizeTable(
// 8 is %eip.
AssignToArrayRange(Builder, Address, Four8, 0, 8);
- if (CGF.CGM.isTargetDarwin()) {
+ if (CGF.CGM.getTarget().getTriple().isOSDarwin()) {
// 12-16 are st(0..4). Not sure why we stop at 4.
// These have size 16, which is sizeof(long double) on
// platforms with 8-byte alignment for that type.
@@ -1163,7 +1154,7 @@ class X86_64ABIInfo : public ABIInfo {
/// required strict binary compatibility with older versions of GCC
/// may need to exempt themselves.
bool honorsRevision0_98() const {
- return !getContext().getTargetInfo().getTriple().isOSDarwin();
+ return !getTarget().getTriple().isOSDarwin();
}
bool HasAVX;
@@ -1198,7 +1189,7 @@ public:
/// WinX86_64ABIInfo - The Windows X86_64 ABI information.
class WinX86_64ABIInfo : public ABIInfo {
- ABIArgInfo classify(QualType Ty) const;
+ ABIArgInfo classify(QualType Ty, bool IsReturnType) const;
public:
WinX86_64ABIInfo(CodeGen::CodeGenTypes &CGT) : ABIInfo(CGT) {}
@@ -1387,8 +1378,7 @@ void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Current = Integer;
} else if ((k == BuiltinType::Float || k == BuiltinType::Double) ||
(k == BuiltinType::LongDouble &&
- getContext().getTargetInfo().getTriple().getOS() ==
- llvm::Triple::NaCl)) {
+ getTarget().getTriple().getOS() == llvm::Triple::NaCl)) {
Current = SSE;
} else if (k == BuiltinType::LongDouble) {
Lo = X87;
@@ -1476,8 +1466,7 @@ void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
Current = SSE;
else if (ET == getContext().DoubleTy ||
(ET == getContext().LongDoubleTy &&
- getContext().getTargetInfo().getTriple().getOS() ==
- llvm::Triple::NaCl))
+ getTarget().getTriple().getOS() == llvm::Triple::NaCl))
Lo = Hi = SSE;
else if (ET == getContext().LongDoubleTy)
Current = ComplexX87;
@@ -1546,7 +1535,7 @@ void X86_64ABIInfo::classify(QualType Ty, uint64_t OffsetBase,
// AMD64-ABI 3.2.3p2: Rule 2. If a C++ object has either a non-trivial
// copy constructor or a non-trivial destructor, it is passed by invisible
// reference.
- if (hasNonTrivialDestructorOrCopyConstructor(RT))
+ if (getRecordArgABI(RT, CGT))
return;
const RecordDecl *RD = RT->getDecl();
@@ -1696,8 +1685,8 @@ ABIArgInfo X86_64ABIInfo::getIndirectResult(QualType Ty,
ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
}
- if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
- return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
+ if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT))
+ return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
// Compute the byval alignment. We specify the alignment of the byval in all
// cases so that the mid-level optimizer knows the alignment of the byval.
@@ -2185,7 +2174,7 @@ ABIArgInfo X86_64ABIInfo::classifyArgumentType(
// COMPLEX_X87, it is passed in memory.
case X87:
case ComplexX87:
- if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
+ if (getRecordArgABI(Ty, CGT) == CGCXXABI::RAA_Indirect)
++neededInt;
return getIndirectResult(Ty, freeIntRegs);
@@ -2516,7 +2505,7 @@ llvm::Value *X86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
return ResAddr;
}
-ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty) const {
+ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty, bool IsReturnType) const {
if (Ty->isVoidType())
return ABIArgInfo::getIgnore();
@@ -2527,14 +2516,19 @@ ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty) const {
uint64_t Size = getContext().getTypeSize(Ty);
if (const RecordType *RT = Ty->getAs<RecordType>()) {
- if (hasNonTrivialDestructorOrCopyConstructor(RT) ||
- RT->getDecl()->hasFlexibleArrayMember())
+ if (IsReturnType) {
+ if (isRecordReturnIndirect(RT, CGT))
+ return ABIArgInfo::getIndirect(0, false);
+ } else {
+ if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(RT, CGT))
+ return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
+ }
+
+ if (RT->getDecl()->hasFlexibleArrayMember())
return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
// FIXME: mingw-w64-gcc emits 128-bit struct as i128
- if (Size == 128 &&
- getContext().getTargetInfo().getTriple().getOS()
- == llvm::Triple::MinGW32)
+ if (Size == 128 && getTarget().getTriple().getOS() == llvm::Triple::MinGW32)
return ABIArgInfo::getDirect(llvm::IntegerType::get(getVMContext(),
Size));
@@ -2557,11 +2551,11 @@ ABIArgInfo WinX86_64ABIInfo::classify(QualType Ty) const {
void WinX86_64ABIInfo::computeInfo(CGFunctionInfo &FI) const {
QualType RetTy = FI.getReturnType();
- FI.getReturnInfo() = classify(RetTy);
+ FI.getReturnInfo() = classify(RetTy, true);
for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
it != ie; ++it)
- it->info = classify(it->type);
+ it->info = classify(it->type, false);
}
llvm::Value *WinX86_64ABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
@@ -2788,10 +2782,8 @@ PPC64_SVR4_ABIInfo::classifyArgumentType(QualType Ty) const {
return ABIArgInfo::getDirect();
if (isAggregateTypeForABI(Ty)) {
- // Records with non trivial destructors/constructors should not be passed
- // by value.
- if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
- return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
+ if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT))
+ return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
return ABIArgInfo::getIndirect(0);
}
@@ -2964,8 +2956,7 @@ public:
}
bool isEABI() const {
- StringRef Env =
- getContext().getTargetInfo().getTriple().getEnvironmentName();
+ StringRef Env = getTarget().getTriple().getEnvironmentName();
return (Env == "gnueabi" || Env == "eabi" ||
Env == "android" || Env == "androideabi");
}
@@ -3064,7 +3055,7 @@ void ARMABIInfo::computeInfo(CGFunctionInfo &FI) const {
/// Return the default calling convention that LLVM will use.
llvm::CallingConv::ID ARMABIInfo::getLLVMDefaultCC() const {
// The default calling convention that LLVM will infer.
- if (getContext().getTargetInfo().getTriple().getEnvironmentName()=="gnueabihf")
+ if (getTarget().getTriple().getEnvironmentName()=="gnueabihf")
return llvm::CallingConv::ARM_AAPCS_VFP;
else if (isEABI())
return llvm::CallingConv::ARM_AAPCS;
@@ -3256,10 +3247,8 @@ ABIArgInfo ARMABIInfo::classifyArgumentType(QualType Ty, int *VFPRegs,
if (isEmptyRecord(getContext(), Ty, true))
return ABIArgInfo::getIgnore();
- // Structures with either a non-trivial destructor or a non-trivial
- // copy constructor are always indirect.
- if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
- return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
+ if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT))
+ return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
if (getABIKind() == ARMABIInfo::AAPCS_VFP) {
// Homogeneous Aggregates need to be expanded when we can fit the aggregate
@@ -3422,7 +3411,7 @@ ABIArgInfo ARMABIInfo::classifyReturnType(QualType RetTy) const {
// Structures with either a non-trivial destructor or a non-trivial
// copy constructor are always indirect.
- if (isRecordWithNonTrivialDestructorOrCopyConstructor(RetTy))
+ if (isRecordReturnIndirect(RetTy, CGT))
return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
// Are we following APCS?
@@ -3746,12 +3735,10 @@ ABIArgInfo AArch64ABIInfo::classifyGenericType(QualType Ty,
return tryUseRegs(Ty, FreeIntRegs, RegsNeeded, /*IsInt=*/ true);
}
- // Structures with either a non-trivial destructor or a non-trivial
- // copy constructor are always indirect.
- if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty)) {
- if (FreeIntRegs > 0)
+ if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT)) {
+ if (FreeIntRegs > 0 && RAA == CGCXXABI::RAA_Indirect)
--FreeIntRegs;
- return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
+ return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
}
if (isEmptyRecord(getContext(), Ty, true)) {
@@ -4130,6 +4117,293 @@ void NVPTXTargetCodeGenInfo::addKernelMetadata(llvm::Function *F) {
}
//===----------------------------------------------------------------------===//
+// SystemZ ABI Implementation
+//===----------------------------------------------------------------------===//
+
+namespace {
+
+class SystemZABIInfo : public ABIInfo {
+public:
+ SystemZABIInfo(CodeGenTypes &CGT) : ABIInfo(CGT) {}
+
+ bool isPromotableIntegerType(QualType Ty) const;
+ bool isCompoundType(QualType Ty) const;
+ bool isFPArgumentType(QualType Ty) const;
+
+ ABIArgInfo classifyReturnType(QualType RetTy) const;
+ ABIArgInfo classifyArgumentType(QualType ArgTy) const;
+
+ virtual void computeInfo(CGFunctionInfo &FI) const {
+ FI.getReturnInfo() = classifyReturnType(FI.getReturnType());
+ for (CGFunctionInfo::arg_iterator it = FI.arg_begin(), ie = FI.arg_end();
+ it != ie; ++it)
+ it->info = classifyArgumentType(it->type);
+ }
+
+ virtual llvm::Value *EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
+ CodeGenFunction &CGF) const;
+};
+
+class SystemZTargetCodeGenInfo : public TargetCodeGenInfo {
+public:
+ SystemZTargetCodeGenInfo(CodeGenTypes &CGT)
+ : TargetCodeGenInfo(new SystemZABIInfo(CGT)) {}
+};
+
+}
+
+bool SystemZABIInfo::isPromotableIntegerType(QualType Ty) const {
+ // Treat an enum type as its underlying type.
+ if (const EnumType *EnumTy = Ty->getAs<EnumType>())
+ Ty = EnumTy->getDecl()->getIntegerType();
+
+ // Promotable integer types are required to be promoted by the ABI.
+ if (Ty->isPromotableIntegerType())
+ return true;
+
+ // 32-bit values must also be promoted.
+ if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
+ switch (BT->getKind()) {
+ case BuiltinType::Int:
+ case BuiltinType::UInt:
+ return true;
+ default:
+ return false;
+ }
+ return false;
+}
+
+bool SystemZABIInfo::isCompoundType(QualType Ty) const {
+ return Ty->isAnyComplexType() || isAggregateTypeForABI(Ty);
+}
+
+bool SystemZABIInfo::isFPArgumentType(QualType Ty) const {
+ if (const BuiltinType *BT = Ty->getAs<BuiltinType>())
+ switch (BT->getKind()) {
+ case BuiltinType::Float:
+ case BuiltinType::Double:
+ return true;
+ default:
+ return false;
+ }
+
+ if (const RecordType *RT = Ty->getAsStructureType()) {
+ const RecordDecl *RD = RT->getDecl();
+ bool Found = false;
+
+ // If this is a C++ record, check the bases first.
+ if (const CXXRecordDecl *CXXRD = dyn_cast<CXXRecordDecl>(RD))
+ for (CXXRecordDecl::base_class_const_iterator I = CXXRD->bases_begin(),
+ E = CXXRD->bases_end(); I != E; ++I) {
+ QualType Base = I->getType();
+
+ // Empty bases don't affect things either way.
+ if (isEmptyRecord(getContext(), Base, true))
+ continue;
+
+ if (Found)
+ return false;
+ Found = isFPArgumentType(Base);
+ if (!Found)
+ return false;
+ }
+
+ // Check the fields.
+ for (RecordDecl::field_iterator I = RD->field_begin(),
+ E = RD->field_end(); I != E; ++I) {
+ const FieldDecl *FD = *I;
+
+ // Empty bitfields don't affect things either way.
+ // Unlike isSingleElementStruct(), empty structure and array fields
+ // do count. So do anonymous bitfields that aren't zero-sized.
+ if (FD->isBitField() && FD->getBitWidthValue(getContext()) == 0)
+ return true;
+
+ // Unlike isSingleElementStruct(), arrays do not count.
+ // Nested isFPArgumentType structures still do though.
+ if (Found)
+ return false;
+ Found = isFPArgumentType(FD->getType());
+ if (!Found)
+ return false;
+ }
+
+ // Unlike isSingleElementStruct(), trailing padding is allowed.
+ // An 8-byte aligned struct s { float f; } is passed as a double.
+ return Found;
+ }
+
+ return false;
+}
+
+llvm::Value *SystemZABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
+ CodeGenFunction &CGF) const {
+ // Assume that va_list type is correct; should be pointer to LLVM type:
+ // struct {
+ // i64 __gpr;
+ // i64 __fpr;
+ // i8 *__overflow_arg_area;
+ // i8 *__reg_save_area;
+ // };
+
+ // Every argument occupies 8 bytes and is passed by preference in either
+ // GPRs or FPRs.
+ Ty = CGF.getContext().getCanonicalType(Ty);
+ ABIArgInfo AI = classifyArgumentType(Ty);
+ bool InFPRs = isFPArgumentType(Ty);
+
+ llvm::Type *APTy = llvm::PointerType::getUnqual(CGF.ConvertTypeForMem(Ty));
+ bool IsIndirect = AI.isIndirect();
+ unsigned UnpaddedBitSize;
+ if (IsIndirect) {
+ APTy = llvm::PointerType::getUnqual(APTy);
+ UnpaddedBitSize = 64;
+ } else
+ UnpaddedBitSize = getContext().getTypeSize(Ty);
+ unsigned PaddedBitSize = 64;
+ assert((UnpaddedBitSize <= PaddedBitSize) && "Invalid argument size.");
+
+ unsigned PaddedSize = PaddedBitSize / 8;
+ unsigned Padding = (PaddedBitSize - UnpaddedBitSize) / 8;
+
+ unsigned MaxRegs, RegCountField, RegSaveIndex, RegPadding;
+ if (InFPRs) {
+ MaxRegs = 4; // Maximum of 4 FPR arguments
+ RegCountField = 1; // __fpr
+ RegSaveIndex = 16; // save offset for f0
+ RegPadding = 0; // floats are passed in the high bits of an FPR
+ } else {
+ MaxRegs = 5; // Maximum of 5 GPR arguments
+ RegCountField = 0; // __gpr
+ RegSaveIndex = 2; // save offset for r2
+ RegPadding = Padding; // values are passed in the low bits of a GPR
+ }
+
+ llvm::Value *RegCountPtr =
+ CGF.Builder.CreateStructGEP(VAListAddr, RegCountField, "reg_count_ptr");
+ llvm::Value *RegCount = CGF.Builder.CreateLoad(RegCountPtr, "reg_count");
+ llvm::Type *IndexTy = RegCount->getType();
+ llvm::Value *MaxRegsV = llvm::ConstantInt::get(IndexTy, MaxRegs);
+ llvm::Value *InRegs = CGF.Builder.CreateICmpULT(RegCount, MaxRegsV,
+ "fits_in_regs");
+
+ llvm::BasicBlock *InRegBlock = CGF.createBasicBlock("vaarg.in_reg");
+ llvm::BasicBlock *InMemBlock = CGF.createBasicBlock("vaarg.in_mem");
+ llvm::BasicBlock *ContBlock = CGF.createBasicBlock("vaarg.end");
+ CGF.Builder.CreateCondBr(InRegs, InRegBlock, InMemBlock);
+
+ // Emit code to load the value if it was passed in registers.
+ CGF.EmitBlock(InRegBlock);
+
+ // Work out the address of an argument register.
+ llvm::Value *PaddedSizeV = llvm::ConstantInt::get(IndexTy, PaddedSize);
+ llvm::Value *ScaledRegCount =
+ CGF.Builder.CreateMul(RegCount, PaddedSizeV, "scaled_reg_count");
+ llvm::Value *RegBase =
+ llvm::ConstantInt::get(IndexTy, RegSaveIndex * PaddedSize + RegPadding);
+ llvm::Value *RegOffset =
+ CGF.Builder.CreateAdd(ScaledRegCount, RegBase, "reg_offset");
+ llvm::Value *RegSaveAreaPtr =
+ CGF.Builder.CreateStructGEP(VAListAddr, 3, "reg_save_area_ptr");
+ llvm::Value *RegSaveArea =
+ CGF.Builder.CreateLoad(RegSaveAreaPtr, "reg_save_area");
+ llvm::Value *RawRegAddr =
+ CGF.Builder.CreateGEP(RegSaveArea, RegOffset, "raw_reg_addr");
+ llvm::Value *RegAddr =
+ CGF.Builder.CreateBitCast(RawRegAddr, APTy, "reg_addr");
+
+ // Update the register count
+ llvm::Value *One = llvm::ConstantInt::get(IndexTy, 1);
+ llvm::Value *NewRegCount =
+ CGF.Builder.CreateAdd(RegCount, One, "reg_count");
+ CGF.Builder.CreateStore(NewRegCount, RegCountPtr);
+ CGF.EmitBranch(ContBlock);
+
+ // Emit code to load the value if it was passed in memory.
+ CGF.EmitBlock(InMemBlock);
+
+ // Work out the address of a stack argument.
+ llvm::Value *OverflowArgAreaPtr =
+ CGF.Builder.CreateStructGEP(VAListAddr, 2, "overflow_arg_area_ptr");
+ llvm::Value *OverflowArgArea =
+ CGF.Builder.CreateLoad(OverflowArgAreaPtr, "overflow_arg_area");
+ llvm::Value *PaddingV = llvm::ConstantInt::get(IndexTy, Padding);
+ llvm::Value *RawMemAddr =
+ CGF.Builder.CreateGEP(OverflowArgArea, PaddingV, "raw_mem_addr");
+ llvm::Value *MemAddr =
+ CGF.Builder.CreateBitCast(RawMemAddr, APTy, "mem_addr");
+
+ // Update overflow_arg_area_ptr pointer
+ llvm::Value *NewOverflowArgArea =
+ CGF.Builder.CreateGEP(OverflowArgArea, PaddedSizeV, "overflow_arg_area");
+ CGF.Builder.CreateStore(NewOverflowArgArea, OverflowArgAreaPtr);
+ CGF.EmitBranch(ContBlock);
+
+ // Return the appropriate result.
+ CGF.EmitBlock(ContBlock);
+ llvm::PHINode *ResAddr = CGF.Builder.CreatePHI(APTy, 2, "va_arg.addr");
+ ResAddr->addIncoming(RegAddr, InRegBlock);
+ ResAddr->addIncoming(MemAddr, InMemBlock);
+
+ if (IsIndirect)
+ return CGF.Builder.CreateLoad(ResAddr, "indirect_arg");
+
+ return ResAddr;
+}
+
+
+ABIArgInfo SystemZABIInfo::classifyReturnType(QualType RetTy) const {
+ if (RetTy->isVoidType())
+ return ABIArgInfo::getIgnore();
+ if (isCompoundType(RetTy) || getContext().getTypeSize(RetTy) > 64)
+ return ABIArgInfo::getIndirect(0);
+ return (isPromotableIntegerType(RetTy) ?
+ ABIArgInfo::getExtend() : ABIArgInfo::getDirect());
+}
+
+ABIArgInfo SystemZABIInfo::classifyArgumentType(QualType Ty) const {
+ // Handle the generic C++ ABI.
+ if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT))
+ return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
+
+ // Integers and enums are extended to full register width.
+ if (isPromotableIntegerType(Ty))
+ return ABIArgInfo::getExtend();
+
+ // Values that are not 1, 2, 4 or 8 bytes in size are passed indirectly.
+ uint64_t Size = getContext().getTypeSize(Ty);
+ if (Size != 8 && Size != 16 && Size != 32 && Size != 64)
+ return ABIArgInfo::getIndirect(0);
+
+ // Handle small structures.
+ if (const RecordType *RT = Ty->getAs<RecordType>()) {
+ // Structures with flexible arrays have variable length, so really
+ // fail the size test above.
+ const RecordDecl *RD = RT->getDecl();
+ if (RD->hasFlexibleArrayMember())
+ return ABIArgInfo::getIndirect(0);
+
+ // The structure is passed as an unextended integer, a float, or a double.
+ llvm::Type *PassTy;
+ if (isFPArgumentType(Ty)) {
+ assert(Size == 32 || Size == 64);
+ if (Size == 32)
+ PassTy = llvm::Type::getFloatTy(getVMContext());
+ else
+ PassTy = llvm::Type::getDoubleTy(getVMContext());
+ } else
+ PassTy = llvm::IntegerType::get(getVMContext(), Size);
+ return ABIArgInfo::getDirect(PassTy);
+ }
+
+ // Non-structure compounds are passed indirectly.
+ if (isCompoundType(Ty))
+ return ABIArgInfo::getIndirect(0);
+
+ return ABIArgInfo::getDirect(0);
+}
+
+//===----------------------------------------------------------------------===//
// MBlaze ABI Implementation
//===----------------------------------------------------------------------===//
@@ -4436,11 +4710,9 @@ MipsABIInfo::classifyArgumentType(QualType Ty, uint64_t &Offset) const {
if (TySize == 0)
return ABIArgInfo::getIgnore();
- // Records with non trivial destructors/constructors should not be passed
- // by value.
- if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty)) {
+ if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT)) {
Offset = OrigOffset + MinABIStackAlignInBytes;
- return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
+ return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
}
// If we have reached here, aggregates are passed directly by coercing to
@@ -4510,6 +4782,9 @@ ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
return ABIArgInfo::getIgnore();
if (isAggregateTypeForABI(RetTy) || RetTy->isVectorType()) {
+ if (isRecordReturnIndirect(RetTy, CGT))
+ return ABIArgInfo::getIndirect(0);
+
if (Size <= 128) {
if (RetTy->isAnyComplexType())
return ABIArgInfo::getDirect();
@@ -4518,7 +4793,7 @@ ABIArgInfo MipsABIInfo::classifyReturnType(QualType RetTy) const {
if (IsO32 && RetTy->isVectorType() && !RetTy->hasFloatingRepresentation())
return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
- if (!IsO32 && !isRecordWithNonTrivialDestructorOrCopyConstructor(RetTy))
+ if (!IsO32)
return ABIArgInfo::getDirect(returnAggregateInRegs(RetTy, Size));
}
@@ -4556,7 +4831,7 @@ llvm::Value* MipsABIInfo::EmitVAArg(llvm::Value *VAListAddr, QualType Ty,
int64_t TypeAlign = getContext().getTypeAlign(Ty) / 8;
llvm::Type *PTy = llvm::PointerType::getUnqual(CGF.ConvertType(Ty));
llvm::Value *AddrTyped;
- unsigned PtrWidth = getContext().getTargetInfo().getPointerWidth(0);
+ unsigned PtrWidth = getTarget().getPointerWidth(0);
llvm::IntegerType *IntTy = (PtrWidth == 32) ? CGF.Int32Ty : CGF.Int64Ty;
if (TypeAlign > MinABIStackAlignInBytes) {
@@ -4728,10 +5003,8 @@ ABIArgInfo HexagonABIInfo::classifyArgumentType(QualType Ty) const {
if (isEmptyRecord(getContext(), Ty, true))
return ABIArgInfo::getIgnore();
- // Structures with either a non-trivial destructor or a non-trivial
- // copy constructor are always indirect.
- if (isRecordWithNonTrivialDestructorOrCopyConstructor(Ty))
- return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
+ if (CGCXXABI::RecordArgABI RAA = getRecordArgABI(Ty, CGT))
+ return ABIArgInfo::getIndirect(0, RAA == CGCXXABI::RAA_DirectInMemory);
uint64_t Size = getContext().getTypeSize(Ty);
if (Size > 64)
@@ -4766,7 +5039,7 @@ ABIArgInfo HexagonABIInfo::classifyReturnType(QualType RetTy) const {
// Structures with either a non-trivial destructor or a non-trivial
// copy constructor are always indirect.
- if (isRecordWithNonTrivialDestructorOrCopyConstructor(RetTy))
+ if (isRecordReturnIndirect(RetTy, CGT))
return ABIArgInfo::getIndirect(0, /*ByVal=*/false);
if (isEmptyRecord(getContext(), RetTy, true))
@@ -4817,7 +5090,7 @@ const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
if (TheTargetCodeGenInfo)
return *TheTargetCodeGenInfo;
- const llvm::Triple &Triple = getContext().getTargetInfo().getTriple();
+ const llvm::Triple &Triple = getTarget().getTriple();
switch (Triple.getArch()) {
default:
return *(TheTargetCodeGenInfo = new DefaultTargetCodeGenInfo(Types));
@@ -4839,10 +5112,11 @@ const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
case llvm::Triple::thumb:
{
ARMABIInfo::ABIKind Kind = ARMABIInfo::AAPCS;
- if (strcmp(getContext().getTargetInfo().getABI(), "apcs-gnu") == 0)
+ if (strcmp(getTarget().getABI(), "apcs-gnu") == 0)
Kind = ARMABIInfo::APCS;
else if (CodeGenOpts.FloatABI == "hard" ||
- (CodeGenOpts.FloatABI != "soft" && Triple.getEnvironment()==llvm::Triple::GNUEABIHF))
+ (CodeGenOpts.FloatABI != "soft" &&
+ Triple.getEnvironment() == llvm::Triple::GNUEABIHF))
Kind = ARMABIInfo::AAPCS_VFP;
switch (Triple.getOS()) {
@@ -4873,6 +5147,9 @@ const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
case llvm::Triple::msp430:
return *(TheTargetCodeGenInfo = new MSP430TargetCodeGenInfo(Types));
+ case llvm::Triple::systemz:
+ return *(TheTargetCodeGenInfo = new SystemZTargetCodeGenInfo(Types));
+
case llvm::Triple::tce:
return *(TheTargetCodeGenInfo = new TCETargetCodeGenInfo(Types));
@@ -4907,7 +5184,7 @@ const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
}
case llvm::Triple::x86_64: {
- bool HasAVX = strcmp(getContext().getTargetInfo().getABI(), "avx") == 0;
+ bool HasAVX = strcmp(getTarget().getABI(), "avx") == 0;
switch (Triple.getOS()) {
case llvm::Triple::Win32:
@@ -4915,7 +5192,8 @@ const TargetCodeGenInfo &CodeGenModule::getTargetCodeGenInfo() {
case llvm::Triple::Cygwin:
return *(TheTargetCodeGenInfo = new WinX86_64TargetCodeGenInfo(Types));
case llvm::Triple::NaCl:
- return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types, HasAVX));
+ return *(TheTargetCodeGenInfo = new NaClX86_64TargetCodeGenInfo(Types,
+ HasAVX));
default:
return *(TheTargetCodeGenInfo = new X86_64TargetCodeGenInfo(Types,
HasAVX));
diff --git a/lib/Driver/ArgList.cpp b/lib/Driver/ArgList.cpp
index 6c57b622b8d2..4b8d151d195a 100644
--- a/lib/Driver/ArgList.cpp
+++ b/lib/Driver/ArgList.cpp
@@ -206,6 +206,13 @@ bool ArgList::hasFlag(OptSpecifier Pos, OptSpecifier Neg, bool Default) const {
return Default;
}
+bool ArgList::hasFlag(OptSpecifier Pos, OptSpecifier PosAlias, OptSpecifier Neg,
+ bool Default) const {
+ if (Arg *A = getLastArg(Pos, PosAlias, Neg))
+ return A->getOption().matches(Pos) || A->getOption().matches(PosAlias);
+ return Default;
+}
+
StringRef ArgList::getLastArgValue(OptSpecifier Id,
StringRef Default) const {
if (Arg *A = getLastArg(Id))
@@ -241,6 +248,14 @@ void ArgList::AddLastArg(ArgStringList &Output, OptSpecifier Id) const {
}
}
+void ArgList::AddLastArg(ArgStringList &Output, OptSpecifier Id0,
+ OptSpecifier Id1) const {
+ if (Arg *A = getLastArg(Id0, Id1)) {
+ A->claim();
+ A->render(*this, Output);
+ }
+}
+
void ArgList::AddAllArgs(ArgStringList &Output, OptSpecifier Id0,
OptSpecifier Id1, OptSpecifier Id2) const {
for (arg_iterator it = filtered_begin(Id0, Id1, Id2),
diff --git a/lib/Driver/Driver.cpp b/lib/Driver/Driver.cpp
index ad1921b838e3..1dbbc9a342bb 100644
--- a/lib/Driver/Driver.cpp
+++ b/lib/Driver/Driver.cpp
@@ -491,9 +491,8 @@ void Driver::generateCompilationDiagnostics(Compilation &C,
<< "\n\n********************";
} else {
// Failure, remove preprocessed files.
- if (!C.getArgs().hasArg(options::OPT_save_temps)) {
+ if (!C.getArgs().hasArg(options::OPT_save_temps))
C.CleanupFileList(C.getTempFiles(), true);
- }
Diag(clang::diag::note_drv_command_failed_diag_msg)
<< "Error generating preprocessed source(s).";
@@ -825,17 +824,6 @@ void Driver::BuildUniversalActions(const ToolChain &TC,
if (!Archs.size())
Archs.push_back(Args.MakeArgString(TC.getDefaultUniversalArchName()));
- // FIXME: We killed off some others but these aren't yet detected in a
- // functional manner. If we added information to jobs about which "auxiliary"
- // files they wrote then we could detect the conflict these cause downstream.
- if (Archs.size() > 1) {
- // No recovery needed, the point of this is just to prevent
- // overwriting the same files.
- if (const Arg *A = Args.getLastArg(options::OPT_save_temps))
- Diag(clang::diag::err_drv_invalid_opt_with_multiple_archs)
- << A->getAsString(Args);
- }
-
ActionList SingleActions;
BuildActions(TC, Args, BAInputs, SingleActions);
@@ -1221,6 +1209,17 @@ void Driver::BuildJobs(Compilation &C) const {
}
}
+ // Collect the list of architectures.
+ llvm::StringSet<> ArchNames;
+ if (C.getDefaultToolChain().getTriple().isOSDarwin()) {
+ for (ArgList::const_iterator it = C.getArgs().begin(), ie = C.getArgs().end();
+ it != ie; ++it) {
+ Arg *A = *it;
+ if (A->getOption().matches(options::OPT_arch))
+ ArchNames.insert(A->getValue());
+ }
+ }
+
for (ActionList::const_iterator it = C.getActions().begin(),
ie = C.getActions().end(); it != ie; ++it) {
Action *A = *it;
@@ -1243,6 +1242,7 @@ void Driver::BuildJobs(Compilation &C) const {
BuildJobsForAction(C, A, &C.getDefaultToolChain(),
/*BoundArch*/0,
/*AtTopLevel*/ true,
+ /*MultipleArchs*/ ArchNames.size() > 1,
/*LinkingOutput*/ LinkingOutput,
II);
}
@@ -1337,6 +1337,7 @@ void Driver::BuildJobsForAction(Compilation &C,
const ToolChain *TC,
const char *BoundArch,
bool AtTopLevel,
+ bool MultipleArchs,
const char *LinkingOutput,
InputInfo &Result) const {
llvm::PrettyStackTraceString CrashInfo("Building compilation jobs");
@@ -1364,7 +1365,7 @@ void Driver::BuildJobsForAction(Compilation &C,
TC = &C.getDefaultToolChain();
BuildJobsForAction(C, *BAA->begin(), TC, BAA->getArchName(),
- AtTopLevel, LinkingOutput, Result);
+ AtTopLevel, MultipleArchs, LinkingOutput, Result);
return;
}
@@ -1387,8 +1388,8 @@ void Driver::BuildJobsForAction(Compilation &C,
SubJobAtTopLevel = true;
InputInfo II;
- BuildJobsForAction(C, *it, TC, BoundArch,
- SubJobAtTopLevel, LinkingOutput, II);
+ BuildJobsForAction(C, *it, TC, BoundArch, SubJobAtTopLevel, MultipleArchs,
+ LinkingOutput, II);
InputInfos.push_back(II);
}
@@ -1404,7 +1405,8 @@ void Driver::BuildJobsForAction(Compilation &C,
if (JA->getType() == types::TY_Nothing)
Result = InputInfo(A->getType(), BaseInput);
else
- Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, AtTopLevel),
+ Result = InputInfo(GetNamedOutputPath(C, *JA, BaseInput, BoundArch,
+ AtTopLevel, MultipleArchs),
A->getType(), BaseInput);
if (CCCPrintBindings && !CCGenDiagnostics) {
@@ -1425,7 +1427,9 @@ void Driver::BuildJobsForAction(Compilation &C,
const char *Driver::GetNamedOutputPath(Compilation &C,
const JobAction &JA,
const char *BaseInput,
- bool AtTopLevel) const {
+ const char *BoundArch,
+ bool AtTopLevel,
+ bool MultipleArchs) const {
llvm::PrettyStackTraceString CrashInfo("Computing output path");
// Output to a user requested destination?
if (AtTopLevel && !isa<DsymutilJobAction>(JA) &&
@@ -1460,8 +1464,14 @@ const char *Driver::GetNamedOutputPath(Compilation &C,
// Determine what the derived output name should be.
const char *NamedOutput;
- if (JA.getType() == types::TY_Image) {
- NamedOutput = DefaultImageName.c_str();
+ if (JA.getType() == types::TY_Image) {
+ if (MultipleArchs && BoundArch) {
+ SmallString<128> Output(DefaultImageName.c_str());
+ Output += "-";
+ Output.append(BoundArch);
+ NamedOutput = C.getArgs().MakeArgString(Output.c_str());
+ } else
+ NamedOutput = DefaultImageName.c_str();
} else {
const char *Suffix = types::getTypeTempSuffix(JA.getType());
assert(Suffix && "All types used for output should have a suffix.");
@@ -1469,7 +1479,11 @@ const char *Driver::GetNamedOutputPath(Compilation &C,
std::string::size_type End = std::string::npos;
if (!types::appendSuffixForType(JA.getType()))
End = BaseName.rfind('.');
- std::string Suffixed(BaseName.substr(0, End));
+ SmallString<128> Suffixed(BaseName.substr(0, End));
+ if (MultipleArchs && BoundArch) {
+ Suffixed += "-";
+ Suffixed.append(BoundArch);
+ }
Suffixed += '.';
Suffixed += Suffix;
NamedOutput = C.getArgs().MakeArgString(Suffixed.c_str());
diff --git a/lib/Driver/SanitizerArgs.h b/lib/Driver/SanitizerArgs.h
index e61f15ad624f..326d80db72e1 100644
--- a/lib/Driver/SanitizerArgs.h
+++ b/lib/Driver/SanitizerArgs.h
@@ -38,7 +38,8 @@ class SanitizerArgs {
NeedsTsanRt = Thread,
NeedsMsanRt = Memory,
NeedsUbsanRt = Undefined | Integer,
- NotAllowedWithTrap = Vptr
+ NotAllowedWithTrap = Vptr,
+ HasZeroBaseShadow = Thread | Memory
};
unsigned Kind;
std::string BlacklistFile;
@@ -50,7 +51,7 @@ class SanitizerArgs {
SanitizerArgs() : Kind(0), BlacklistFile(""), MsanTrackOrigins(false),
AsanZeroBaseShadow(false), UbsanTrapOnError(false) {}
/// Parses the sanitizer arguments from an argument list.
- SanitizerArgs(const Driver &D, const ArgList &Args);
+ SanitizerArgs(const ToolChain &TC, const ArgList &Args);
bool needsAsanRt() const { return Kind & NeedsAsanRt; }
bool needsTsanRt() const { return Kind & NeedsTsanRt; }
@@ -63,6 +64,9 @@ class SanitizerArgs {
bool sanitizesVptr() const { return Kind & Vptr; }
bool notAllowedWithTrap() const { return Kind & NotAllowedWithTrap; }
+ bool hasZeroBaseShadow() const {
+ return (Kind & HasZeroBaseShadow) || AsanZeroBaseShadow;
+ }
void addArgs(const ArgList &Args, ArgStringList &CmdArgs) const {
if (!Kind)
diff --git a/lib/Driver/ToolChain.cpp b/lib/Driver/ToolChain.cpp
index 19270b2aa33f..71f53933e2af 100644
--- a/lib/Driver/ToolChain.cpp
+++ b/lib/Driver/ToolChain.cpp
@@ -19,6 +19,7 @@
#include "clang/Driver/Options.h"
#include "llvm/ADT/StringSwitch.h"
#include "llvm/Support/ErrorHandling.h"
+#include "llvm/Support/FileSystem.h"
using namespace clang::driver;
using namespace clang;
@@ -333,6 +334,13 @@ ToolChain::CXXStdlibType ToolChain::GetCXXStdlibType(const ArgList &Args) const{
CC1Args.push_back(DriverArgs.MakeArgString(Path));
}
+void ToolChain::addExternCSystemIncludeIfExists(const ArgList &DriverArgs,
+ ArgStringList &CC1Args,
+ const Twine &Path) {
+ if (llvm::sys::fs::exists(Path))
+ addExternCSystemInclude(DriverArgs, CC1Args, Path);
+}
+
/// \brief Utility function to add a list of system include directories to CC1.
/*static*/ void ToolChain::addSystemIncludes(const ArgList &DriverArgs,
ArgStringList &CC1Args,
diff --git a/lib/Driver/ToolChains.cpp b/lib/Driver/ToolChains.cpp
index bcfe51ef7bbb..fffba0e4e50f 100644
--- a/lib/Driver/ToolChains.cpp
+++ b/lib/Driver/ToolChains.cpp
@@ -294,7 +294,7 @@ void DarwinClang::AddLinkRuntimeLibArgs(const ArgList &Args,
}
}
- SanitizerArgs Sanitize(getDriver(), Args);
+ SanitizerArgs Sanitize(*this, Args);
// Add Ubsan runtime library, if required.
if (Sanitize.needsUbsanRt()) {
@@ -878,6 +878,10 @@ bool Darwin::isPICDefault() const {
return true;
}
+bool Darwin::isPIEDefault() const {
+ return false;
+}
+
bool Darwin::isPICDefaultForced() const {
return getArch() == llvm::Triple::x86_64;
}
@@ -1082,6 +1086,7 @@ Generic_GCC::GCCInstallationDetector::GCCInstallationDetector(
};
static const char *const ARMHFTriples[] = {
"arm-linux-gnueabihf",
+ "armv7hl-redhat-linux-gnueabi"
};
static const char *const X86_64LibDirs[] = { "/lib64", "/lib" };
@@ -1116,7 +1121,8 @@ Generic_GCC::GCCInstallationDetector::GCCInstallationDetector(
static const char *const MIPSELLibDirs[] = { "/lib" };
static const char *const MIPSELTriples[] = {
"mipsel-linux-gnu",
- "mipsel-linux-android"
+ "mipsel-linux-android",
+ "mips-linux-gnu"
};
static const char *const MIPS64LibDirs[] = { "/lib64", "/lib" };
@@ -1140,6 +1146,15 @@ Generic_GCC::GCCInstallationDetector::GCCInstallationDetector(
"ppc64-redhat-linux"
};
+ static const char *const SystemZLibDirs[] = { "/lib64", "/lib" };
+ static const char *const SystemZTriples[] = {
+ "s390x-linux-gnu",
+ "s390x-unknown-linux-gnu",
+ "s390x-ibm-linux-gnu",
+ "s390x-suse-linux",
+ "s390x-redhat-linux"
+ };
+
switch (TargetTriple.getArch()) {
case llvm::Triple::aarch64:
LibDirs.append(AArch64LibDirs, AArch64LibDirs
@@ -1240,6 +1255,12 @@ Generic_GCC::GCCInstallationDetector::GCCInstallationDetector(
MultiarchTripleAliases.append(
PPCTriples, PPCTriples + llvm::array_lengthof(PPCTriples));
break;
+ case llvm::Triple::systemz:
+ LibDirs.append(
+ SystemZLibDirs, SystemZLibDirs + llvm::array_lengthof(SystemZLibDirs));
+ TripleAliases.append(
+ SystemZTriples, SystemZTriples + llvm::array_lengthof(SystemZTriples));
+ break;
default:
// By default, just rely on the standard lib directories and the original
@@ -1256,29 +1277,102 @@ Generic_GCC::GCCInstallationDetector::GCCInstallationDetector(
MultiarchTripleAliases.push_back(MultiarchTriple.str());
}
+static bool isSoftFloatABI(const ArgList &Args) {
+ Arg *A = Args.getLastArg(options::OPT_msoft_float,
+ options::OPT_mhard_float,
+ options::OPT_mfloat_abi_EQ);
+ if (!A) return false;
+
+ return A->getOption().matches(options::OPT_msoft_float) ||
+ (A->getOption().matches(options::OPT_mfloat_abi_EQ) &&
+ A->getValue() == StringRef("soft"));
+}
+
+static bool isMipsArch(llvm::Triple::ArchType Arch) {
+ return Arch == llvm::Triple::mips ||
+ Arch == llvm::Triple::mipsel ||
+ Arch == llvm::Triple::mips64 ||
+ Arch == llvm::Triple::mips64el;
+}
+
+static bool isMips16(const ArgList &Args) {
+ Arg *A = Args.getLastArg(options::OPT_mips16,
+ options::OPT_mno_mips16);
+ return A && A->getOption().matches(options::OPT_mips16);
+}
+
+static bool isMicroMips(const ArgList &Args) {
+ Arg *A = Args.getLastArg(options::OPT_mmicromips,
+ options::OPT_mno_micromips);
+ return A && A->getOption().matches(options::OPT_mmicromips);
+}
+
// FIXME: There is the same routine in the Tools.cpp.
static bool hasMipsN32ABIArg(const ArgList &Args) {
Arg *A = Args.getLastArg(options::OPT_mabi_EQ);
return A && (A->getValue() == StringRef("n32"));
}
-static StringRef getTargetMultiarchSuffix(llvm::Triple::ArchType TargetArch,
- const ArgList &Args) {
- if (TargetArch == llvm::Triple::x86_64 ||
- TargetArch == llvm::Triple::ppc64)
- return "/64";
+static void appendMipsTargetSuffix(std::string &Path,
+ llvm::Triple::ArchType TargetArch,
+ const ArgList &Args) {
+ if (isMips16(Args))
+ Path += "/mips16";
+ else if (isMicroMips(Args))
+ Path += "/micromips";
+
+ if (isSoftFloatABI(Args))
+ Path += "/soft-float";
+ if (TargetArch == llvm::Triple::mipsel ||
+ TargetArch == llvm::Triple::mips64el)
+ Path += "/el";
+}
+
+static StringRef getMipsTargetABISuffix(llvm::Triple::ArchType TargetArch,
+ const ArgList &Args) {
if (TargetArch == llvm::Triple::mips64 ||
- TargetArch == llvm::Triple::mips64el) {
- if (hasMipsN32ABIArg(Args))
- return "/n32";
- else
- return "/64";
- }
+ TargetArch == llvm::Triple::mips64el)
+ return hasMipsN32ABIArg(Args) ? "/n32" : "/64";
return "/32";
}
+static bool findTargetMultiarchSuffix(std::string &Suffix,
+ StringRef Path,
+ llvm::Triple::ArchType TargetArch,
+ const ArgList &Args) {
+ if (isMipsArch(TargetArch)) {
+ StringRef ABISuffix = getMipsTargetABISuffix(TargetArch, Args);
+
+ // First build and check a complex path to crtbegin.o
+ // depends on command line options (-mips16, -msoft-float, ...)
+ // like mips-linux-gnu/4.7/mips16/soft-float/el/crtbegin.o
+ appendMipsTargetSuffix(Suffix, TargetArch, Args);
+
+ if (TargetArch == llvm::Triple::mips64 ||
+ TargetArch == llvm::Triple::mips64el)
+ Suffix += ABISuffix;
+
+ if (llvm::sys::fs::exists(Path + Suffix + "/crtbegin.o"))
+ return true;
+
+ // Then fall back and probe a simple case like
+ // mips-linux-gnu/4.7/32/crtbegin.o
+ Suffix = ABISuffix;
+ return llvm::sys::fs::exists(Path + Suffix + "/crtbegin.o");
+ }
+
+ if (TargetArch == llvm::Triple::x86_64 ||
+ TargetArch == llvm::Triple::ppc64 ||
+ TargetArch == llvm::Triple::systemz)
+ Suffix = "/64";
+ else
+ Suffix = "/32";
+
+ return llvm::sys::fs::exists(Path + Suffix + "/crtbegin.o");
+}
+
void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
llvm::Triple::ArchType TargetArch, const ArgList &Args,
const std::string &LibDir,
@@ -1328,9 +1422,11 @@ void Generic_GCC::GCCInstallationDetector::ScanLibDirForGCCTriple(
// *if* there is a subdirectory of the right name with crtbegin.o in it,
// we use that. If not, and if not a multiarch triple, we look for
// crtbegin.o without the subdirectory.
- StringRef MultiarchSuffix = getTargetMultiarchSuffix(TargetArch, Args);
- if (llvm::sys::fs::exists(LI->path() + MultiarchSuffix + "/crtbegin.o")) {
- GCCMultiarchSuffix = MultiarchSuffix.str();
+
+ std::string MultiarchSuffix;
+ if (findTargetMultiarchSuffix(MultiarchSuffix,
+ LI->path(), TargetArch, Args)) {
+ GCCMultiarchSuffix = MultiarchSuffix;
} else {
if (NeedsMultiarchSuffix ||
!llvm::sys::fs::exists(LI->path() + "/crtbegin.o"))
@@ -1396,6 +1492,10 @@ bool Generic_GCC::isPICDefault() const {
return false;
}
+bool Generic_GCC::isPIEDefault() const {
+ return false;
+}
+
bool Generic_GCC::isPICDefaultForced() const {
return false;
}
@@ -1630,6 +1730,10 @@ bool TCEToolChain::isPICDefault() const {
return false;
}
+bool TCEToolChain::isPIEDefault() const {
+ return false;
+}
+
bool TCEToolChain::isPICDefaultForced() const {
return false;
}
@@ -1773,6 +1877,42 @@ Tool *NetBSD::buildLinker() const {
return new tools::netbsd::Link(*this);
}
+ToolChain::CXXStdlibType
+NetBSD::GetCXXStdlibType(const ArgList &Args) const {
+ if (Arg *A = Args.getLastArg(options::OPT_stdlib_EQ)) {
+ StringRef Value = A->getValue();
+ if (Value == "libstdc++")
+ return ToolChain::CST_Libstdcxx;
+ if (Value == "libc++")
+ return ToolChain::CST_Libcxx;
+
+ getDriver().Diag(diag::err_drv_invalid_stdlib_name)
+ << A->getAsString(Args);
+ }
+
+ return ToolChain::CST_Libstdcxx;
+}
+
+void NetBSD::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
+ ArgStringList &CC1Args) const {
+ if (DriverArgs.hasArg(options::OPT_nostdlibinc) ||
+ DriverArgs.hasArg(options::OPT_nostdincxx))
+ return;
+
+ switch (GetCXXStdlibType(DriverArgs)) {
+ case ToolChain::CST_Libcxx:
+ addSystemInclude(DriverArgs, CC1Args,
+ getDriver().SysRoot + "/usr/include/c++/");
+ break;
+ case ToolChain::CST_Libstdcxx:
+ addSystemInclude(DriverArgs, CC1Args,
+ getDriver().SysRoot + "/usr/include/g++");
+ addSystemInclude(DriverArgs, CC1Args,
+ getDriver().SysRoot + "/usr/include/g++/backward");
+ break;
+ }
+}
+
/// Minix - Minix tool chain which can call as(1) and ld(1) directly.
Minix::Minix(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
@@ -2036,13 +2176,6 @@ static void addPathIfExists(Twine Path, ToolChain::path_list &Paths) {
if (llvm::sys::fs::exists(Path)) Paths.push_back(Path.str());
}
-static bool isMipsArch(llvm::Triple::ArchType Arch) {
- return Arch == llvm::Triple::mips ||
- Arch == llvm::Triple::mipsel ||
- Arch == llvm::Triple::mips64 ||
- Arch == llvm::Triple::mips64el;
-}
-
static bool isMipsR2Arch(llvm::Triple::ArchType Arch,
const ArgList &Args) {
if (Arch != llvm::Triple::mips &&
@@ -2079,7 +2212,7 @@ static StringRef getMultilibDir(const llvm::Triple &Triple,
Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
: Generic_ELF(D, Triple, Args) {
llvm::Triple::ArchType Arch = Triple.getArch();
- const std::string &SysRoot = getDriver().SysRoot;
+ std::string SysRoot = computeSysRoot(Args);
// OpenSuse stores the linker with the compiler, add that to the search
// path.
@@ -2100,13 +2233,17 @@ Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
ExtraOpts.push_back("-X");
const bool IsAndroid = Triple.getEnvironment() == llvm::Triple::Android;
+ const bool IsMips = isMipsArch(Arch);
+
+ if (IsMips && !SysRoot.empty())
+ ExtraOpts.push_back("--sysroot=" + SysRoot);
// Do not use 'gnu' hash style for Mips targets because .gnu.hash
// and the MIPS ABI require .dynsym to be sorted in different ways.
// .gnu.hash needs symbols to be grouped by hash code whereas the MIPS
// ABI requires a mapping between the GOT and the symbol table.
// Android loader does not support .gnu.hash.
- if (!isMipsArch(Arch) && !IsAndroid) {
+ if (!IsMips && !IsAndroid) {
if (IsRedhat(Distro) || IsOpenSuse(Distro) ||
(IsUbuntu(Distro) && Distro >= UbuntuMaverick))
ExtraOpts.push_back("--hash-style=gnu");
@@ -2171,6 +2308,15 @@ Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
if (IsAndroid) {
addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib", Paths);
}
+ // Sourcery CodeBench MIPS toolchain holds some libraries under
+ // the parent prefix of the GCC installation.
+ if (IsMips) {
+ std::string Suffix;
+ appendMipsTargetSuffix(Suffix, Arch, Args);
+ addPathIfExists(LibPath + "/../" + GCCTriple.str() + "/lib/../" +
+ Multilib + Suffix,
+ Paths);
+ }
}
addPathIfExists(SysRoot + "/lib/" + MultiarchTriple, Paths);
addPathIfExists(SysRoot + "/lib/../" + Multilib, Paths);
@@ -2197,6 +2343,8 @@ Linux::Linux(const Driver &D, const llvm::Triple &Triple, const ArgList &Args)
}
addPathIfExists(SysRoot + "/lib", Paths);
addPathIfExists(SysRoot + "/usr/lib", Paths);
+
+ IsPIEDefault = SanitizerArgs(*this, Args).hasZeroBaseShadow();
}
bool Linux::HasNativeLLVMSupport() const {
@@ -2224,15 +2372,31 @@ void Linux::addClangTargetOptions(const ArgList &DriverArgs,
CC1Args.push_back("-fuse-init-array");
}
+std::string Linux::computeSysRoot(const ArgList &Args) const {
+ if (!getDriver().SysRoot.empty())
+ return getDriver().SysRoot;
+
+ if (!GCCInstallation.isValid() || !isMipsArch(getTriple().getArch()))
+ return std::string();
+
+ std::string Path =
+ (GCCInstallation.getInstallPath() +
+ "/../../../../" + GCCInstallation.getTriple().str() + "/libc").str();
+ appendMipsTargetSuffix(Path, getTriple().getArch(), Args);
+
+ return llvm::sys::fs::exists(Path) ? Path : "";
+}
+
void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
ArgStringList &CC1Args) const {
const Driver &D = getDriver();
+ std::string SysRoot = computeSysRoot(DriverArgs);
if (DriverArgs.hasArg(options::OPT_nostdinc))
return;
if (!DriverArgs.hasArg(options::OPT_nostdlibinc))
- addSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/usr/local/include");
+ addSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/local/include");
if (!DriverArgs.hasArg(options::OPT_nobuiltininc)) {
llvm::sys::Path P(D.ResourceDir);
@@ -2250,7 +2414,7 @@ void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
CIncludeDirs.split(dirs, ":");
for (SmallVectorImpl<StringRef>::iterator I = dirs.begin(), E = dirs.end();
I != E; ++I) {
- StringRef Prefix = llvm::sys::path::is_absolute(*I) ? D.SysRoot : "";
+ StringRef Prefix = llvm::sys::path::is_absolute(*I) ? SysRoot : "";
addExternCSystemInclude(DriverArgs, CC1Args, Prefix + *I);
}
return;
@@ -2259,6 +2423,20 @@ void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
// Lacking those, try to detect the correct set of system includes for the
// target triple.
+ // Sourcery CodeBench and modern FSF Mips toolchains put extern C
+ // system includes under three additional directories.
+ if (GCCInstallation.isValid() && isMipsArch(getTriple().getArch())) {
+ addExternCSystemIncludeIfExists(DriverArgs, CC1Args,
+ GCCInstallation.getInstallPath() +
+ "/include");
+
+ addExternCSystemIncludeIfExists(DriverArgs, CC1Args,
+ GCCInstallation.getInstallPath() +
+ "/../../../../" +
+ GCCInstallation.getTriple().str() +
+ "/libc/usr/include");
+ }
+
// Implement generic Debian multiarch support.
const StringRef X86_64MultiarchIncludeDirs[] = {
"/usr/include/x86_64-linux-gnu",
@@ -2324,8 +2502,8 @@ void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
for (ArrayRef<StringRef>::iterator I = MultiarchIncludeDirs.begin(),
E = MultiarchIncludeDirs.end();
I != E; ++I) {
- if (llvm::sys::fs::exists(D.SysRoot + *I)) {
- addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + *I);
+ if (llvm::sys::fs::exists(SysRoot + *I)) {
+ addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + *I);
break;
}
}
@@ -2336,9 +2514,9 @@ void Linux::AddClangSystemIncludeArgs(const ArgList &DriverArgs,
// Add an include of '/include' directly. This isn't provided by default by
// system GCCs, but is often used with cross-compiling GCCs, and harmless to
// add even when Clang is acting as-if it were a system compiler.
- addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/include");
+ addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/include");
- addExternCSystemInclude(DriverArgs, CC1Args, D.SysRoot + "/usr/include");
+ addExternCSystemInclude(DriverArgs, CC1Args, SysRoot + "/usr/include");
}
/// \brief Helper to add the three variant paths for a libstdc++ installation.
@@ -2422,6 +2600,10 @@ void Linux::AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
}
}
+bool Linux::isPIEDefault() const {
+ return IsPIEDefault;
+}
+
/// DragonFly - DragonFly tool chain which can call as(1) and ld(1) directly.
DragonFly::DragonFly(const Driver &D, const llvm::Triple& Triple, const ArgList &Args)
@@ -2434,7 +2616,10 @@ DragonFly::DragonFly(const Driver &D, const llvm::Triple& Triple, const ArgList
getFilePaths().push_back(getDriver().Dir + "/../lib");
getFilePaths().push_back("/usr/lib");
- getFilePaths().push_back("/usr/lib/gcc41");
+ if (llvm::sys::fs::exists("/usr/lib/gcc47"))
+ getFilePaths().push_back("/usr/lib/gcc47");
+ else
+ getFilePaths().push_back("/usr/lib/gcc44");
}
Tool *DragonFly::buildAssembler() const {
diff --git a/lib/Driver/ToolChains.h b/lib/Driver/ToolChains.h
index 3421c53eb236..3afd8dd228b6 100644
--- a/lib/Driver/ToolChains.h
+++ b/lib/Driver/ToolChains.h
@@ -123,6 +123,7 @@ public:
virtual bool IsUnwindTablesDefault() const;
virtual bool isPICDefault() const;
+ virtual bool isPIEDefault() const;
virtual bool isPICDefaultForced() const;
protected:
@@ -332,6 +333,7 @@ public:
return ToolChain::RLT_CompilerRT;
}
virtual bool isPICDefault() const;
+ virtual bool isPIEDefault() const;
virtual bool isPICDefaultForced() const;
virtual bool SupportsProfiling() const;
@@ -472,6 +474,11 @@ public:
virtual bool IsMathErrnoDefault() const { return false; }
virtual bool IsObjCNonFragileABIDefault() const { return true; }
+ virtual CXXStdlibType GetCXXStdlibType(const ArgList &Args) const;
+
+ virtual void AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
+ ArgStringList &CC1Args) const;
+
protected:
virtual Tool *buildAssembler() const;
virtual Tool *buildLinker() const;
@@ -509,9 +516,11 @@ public:
ArgStringList &CC1Args) const;
virtual void AddClangCXXStdlibIncludeArgs(const ArgList &DriverArgs,
ArgStringList &CC1Args) const;
+ virtual bool isPIEDefault() const;
std::string Linker;
std::vector<std::string> ExtraOpts;
+ bool IsPIEDefault;
protected:
virtual Tool *buildAssembler() const;
@@ -526,6 +535,8 @@ private:
static bool addLibStdCXXIncludePaths(Twine Base, Twine TargetArchDir,
const ArgList &DriverArgs,
ArgStringList &CC1Args);
+
+ std::string computeSysRoot(const ArgList &Args) const;
};
class LLVM_LIBRARY_VISIBILITY Hexagon_TC : public Linux {
@@ -562,6 +573,7 @@ public:
bool IsMathErrnoDefault() const;
bool isPICDefault() const;
+ bool isPIEDefault() const;
bool isPICDefaultForced() const;
};
@@ -572,6 +584,7 @@ public:
virtual bool IsIntegratedAssemblerDefault() const;
virtual bool IsUnwindTablesDefault() const;
virtual bool isPICDefault() const;
+ virtual bool isPIEDefault() const;
virtual bool isPICDefaultForced() const;
virtual void AddClangSystemIncludeArgs(const ArgList &DriverArgs,
diff --git a/lib/Driver/Tools.cpp b/lib/Driver/Tools.cpp
index 77a72ba33a5e..aba1fe4d2d9e 100644
--- a/lib/Driver/Tools.cpp
+++ b/lib/Driver/Tools.cpp
@@ -7,6 +7,7 @@
//
//===----------------------------------------------------------------------===//
+#include <sys/stat.h>
#include "Tools.h"
#include "InputInfo.h"
#include "SanitizerArgs.h"
@@ -544,6 +545,9 @@ static bool isSignedCharDefault(const llvm::Triple &Triple) {
if (Triple.isOSDarwin())
return true;
return false;
+
+ case llvm::Triple::systemz:
+ return false;
}
}
@@ -815,7 +819,9 @@ void Clang::AddARMTargetArgs(const ArgList &Args,
CmdArgs.push_back("-mno-global-merge");
}
- if (Args.hasArg(options::OPT_mno_implicit_float))
+ if (!Args.hasFlag(options::OPT_mimplicit_float,
+ options::OPT_mno_implicit_float,
+ true))
CmdArgs.push_back("-no-implicit-float");
}
@@ -851,8 +857,15 @@ static void getMipsCPUAndABI(const ArgList &Args,
CPUName = A->getValue();
}
- if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ))
+ if (Arg *A = Args.getLastArg(options::OPT_mabi_EQ)) {
ABIName = A->getValue();
+ // Convert a GNU style Mips ABI name to the name
+ // accepted by LLVM Mips backend.
+ ABIName = llvm::StringSwitch<llvm::StringRef>(ABIName)
+ .Case("32", "o32")
+ .Case("64", "n64")
+ .Default(ABIName);
+ }
// Setup default CPU and ABI names.
if (CPUName.empty() && ABIName.empty()) {
@@ -899,8 +912,6 @@ static StringRef getGnuCompatibleMipsABIName(StringRef ABI) {
// Select the MIPS float ABI as determined by -msoft-float, -mhard-float,
// and -mfloat-abi=.
static StringRef getMipsFloatABI(const Driver &D, const ArgList &Args) {
- // Select the float ABI as determined by -msoft-float, -mhard-float,
- // and -mfloat-abi=.
StringRef FloatABI;
if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
options::OPT_mhard_float,
@@ -911,7 +922,7 @@ static StringRef getMipsFloatABI(const Driver &D, const ArgList &Args) {
FloatABI = "hard";
else {
FloatABI = A->getValue();
- if (FloatABI != "soft" && FloatABI != "single" && FloatABI != "hard") {
+ if (FloatABI != "soft" && FloatABI != "hard") {
D.Diag(diag::err_drv_invalid_mfloat_abi) << A->getAsString(Args);
FloatABI = "hard";
}
@@ -944,7 +955,7 @@ static void AddTargetFeature(const ArgList &Args,
}
void Clang::AddMIPSTargetArgs(const ArgList &Args,
- ArgStringList &CmdArgs) const {
+ ArgStringList &CmdArgs) const {
const Driver &D = getToolChain().getDriver();
StringRef CPUName;
StringRef ABIName;
@@ -977,12 +988,6 @@ void Clang::AddMIPSTargetArgs(const ArgList &Args,
CmdArgs.push_back("-mips16-hard-float");
}
}
- else if (FloatABI == "single") {
- // Restrict the use of hardware floating-point
- // instructions to 32-bit operations.
- CmdArgs.push_back("-target-feature");
- CmdArgs.push_back("+single-float");
- }
else {
// Floating point operations and argument passing are hard.
assert(FloatABI == "hard" && "Invalid float abi!");
@@ -991,9 +996,15 @@ void Clang::AddMIPSTargetArgs(const ArgList &Args,
}
AddTargetFeature(Args, CmdArgs,
+ options::OPT_msingle_float, options::OPT_mdouble_float,
+ "single-float");
+ AddTargetFeature(Args, CmdArgs,
options::OPT_mips16, options::OPT_mno_mips16,
"mips16");
AddTargetFeature(Args, CmdArgs,
+ options::OPT_mmicromips, options::OPT_mno_micromips,
+ "micromips");
+ AddTargetFeature(Args, CmdArgs,
options::OPT_mdsp, options::OPT_mno_dsp,
"dsp");
AddTargetFeature(Args, CmdArgs,
@@ -1127,11 +1138,11 @@ static std::string getR600TargetGPU(const ArgList &Args) {
if (Arg *A = Args.getLastArg(options::OPT_mcpu_EQ)) {
std::string GPUName = A->getValue();
return llvm::StringSwitch<const char *>(GPUName)
- .Cases("rv610", "rv620", "rv630", "r600")
- .Cases("rv635", "rs780", "rs880", "r600")
+ .Cases("rv630", "rv635", "r600")
+ .Cases("rv610", "rv620", "rs780", "rs880")
.Case("rv740", "rv770")
.Case("palm", "cedar")
- .Cases("sumo", "sumo2", "redwood")
+ .Cases("sumo", "sumo2", "sumo")
.Case("hemlock", "cypress")
.Case("aruba", "cayman")
.Default(GPUName.c_str());
@@ -1255,6 +1266,7 @@ void Clang::AddX86TargetArgs(const ArgList &Args,
Args.hasArg(options::OPT_fapple_kext));
if (Arg *A = Args.getLastArg(options::OPT_msoft_float,
options::OPT_mno_soft_float,
+ options::OPT_mimplicit_float,
options::OPT_mno_implicit_float)) {
const Option &O = A->getOption();
NoImplicitFloat = (O.matches(options::OPT_mno_implicit_float) ||
@@ -1452,6 +1464,18 @@ static void addExceptionArgs(const ArgList &Args, types::ID InputType,
CmdArgs.push_back("-fexceptions");
}
+static bool ShouldDisableAutolink(const ArgList &Args,
+ const ToolChain &TC) {
+ bool Default = true;
+ if (TC.getTriple().isOSDarwin()) {
+ // The native darwin assembler doesn't support the linker_option directives,
+ // so we disable them if we think the .s file will be passed to it.
+ Default = TC.useIntegratedAs();
+ }
+ return !Args.hasFlag(options::OPT_fautolink, options::OPT_fno_autolink,
+ Default);
+}
+
static bool ShouldDisableCFI(const ArgList &Args,
const ToolChain &TC) {
bool Default = true;
@@ -1508,11 +1532,12 @@ static bool UseRelaxAll(Compilation &C, const ArgList &Args) {
RelaxDefault);
}
-SanitizerArgs::SanitizerArgs(const Driver &D, const ArgList &Args)
+SanitizerArgs::SanitizerArgs(const ToolChain &TC, const ArgList &Args)
: Kind(0), BlacklistFile(""), MsanTrackOrigins(false),
AsanZeroBaseShadow(false) {
unsigned AllKinds = 0; // All kinds of sanitizers that were turned on
// at least once (possibly, disabled further).
+ const Driver &D = TC.getDriver();
for (ArgList::const_iterator I = Args.begin(), E = Args.end(); I != E; ++I) {
unsigned Add, Remove;
if (!parse(D, Args, *I, Add, Remove, true))
@@ -1604,11 +1629,20 @@ SanitizerArgs::SanitizerArgs(const Driver &D, const ArgList &Args)
/* Default */false);
// Parse -f(no-)sanitize-address-zero-base-shadow options.
- if (NeedsAsan)
+ if (NeedsAsan) {
+ bool IsAndroid = (TC.getTriple().getEnvironment() == llvm::Triple::Android);
+ bool ZeroBaseShadowDefault = IsAndroid;
AsanZeroBaseShadow =
- Args.hasFlag(options::OPT_fsanitize_address_zero_base_shadow,
- options::OPT_fno_sanitize_address_zero_base_shadow,
- /* Default */false);
+ Args.hasFlag(options::OPT_fsanitize_address_zero_base_shadow,
+ options::OPT_fno_sanitize_address_zero_base_shadow,
+ ZeroBaseShadowDefault);
+ // Zero-base shadow is a requirement on Android.
+ if (IsAndroid && !AsanZeroBaseShadow) {
+ D.Diag(diag::err_drv_argument_not_allowed_with)
+ << "-fno-sanitize-address-zero-base-shadow"
+ << lastArgumentForKind(D, Args, Address);
+ }
+ }
}
static void addSanitizerRTLinkFlagsLinux(
@@ -1637,6 +1671,7 @@ static void addSanitizerRTLinkFlagsLinux(
LibSanitizerArgs.begin(), LibSanitizerArgs.end());
CmdArgs.push_back("-lpthread");
+ CmdArgs.push_back("-lrt");
CmdArgs.push_back("-ldl");
// If possible, use a dynamic symbols file to export the symbols from the
@@ -1656,11 +1691,6 @@ static void addSanitizerRTLinkFlagsLinux(
static void addAsanRTLinux(const ToolChain &TC, const ArgList &Args,
ArgStringList &CmdArgs) {
if(TC.getTriple().getEnvironment() == llvm::Triple::Android) {
- if (!Args.hasArg(options::OPT_shared)) {
- if (!Args.hasArg(options::OPT_pie))
- TC.getDriver().Diag(diag::err_drv_asan_android_requires_pie);
- }
-
SmallString<128> LibAsan(TC.getDriver().ResourceDir);
llvm::sys::path::append(LibAsan, "lib", "linux",
(Twine("libclang_rt.asan-") +
@@ -1668,13 +1698,6 @@ static void addAsanRTLinux(const ToolChain &TC, const ArgList &Args,
CmdArgs.insert(CmdArgs.begin(), Args.MakeArgString(LibAsan));
} else {
if (!Args.hasArg(options::OPT_shared)) {
- bool ZeroBaseShadow = Args.hasFlag(
- options::OPT_fsanitize_address_zero_base_shadow,
- options::OPT_fno_sanitize_address_zero_base_shadow, false);
- if (ZeroBaseShadow && !Args.hasArg(options::OPT_pie)) {
- TC.getDriver().Diag(diag::err_drv_argument_only_allowed_with) <<
- "-fsanitize-address-zero-base-shadow" << "-pie";
- }
addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "asan", true);
}
}
@@ -1685,9 +1708,6 @@ static void addAsanRTLinux(const ToolChain &TC, const ArgList &Args,
static void addTsanRTLinux(const ToolChain &TC, const ArgList &Args,
ArgStringList &CmdArgs) {
if (!Args.hasArg(options::OPT_shared)) {
- if (!Args.hasArg(options::OPT_pie))
- TC.getDriver().Diag(diag::err_drv_argument_only_allowed_with) <<
- "-fsanitize=thread" << "-pie";
addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "tsan", true);
}
}
@@ -1697,9 +1717,6 @@ static void addTsanRTLinux(const ToolChain &TC, const ArgList &Args,
static void addMsanRTLinux(const ToolChain &TC, const ArgList &Args,
ArgStringList &CmdArgs) {
if (!Args.hasArg(options::OPT_shared)) {
- if (!Args.hasArg(options::OPT_pie))
- TC.getDriver().Diag(diag::err_drv_argument_only_allowed_with) <<
- "-fsanitize=memory" << "-pie";
addSanitizerRTLinkFlagsLinux(TC, Args, CmdArgs, "msan", true);
}
}
@@ -1764,14 +1781,27 @@ static bool shouldUseLeafFramePointer(const ArgList &Args,
/// If the PWD environment variable is set, add a CC1 option to specify the
/// debug compilation directory.
static void addDebugCompDirArg(const ArgList &Args, ArgStringList &CmdArgs) {
- if (const char *pwd = ::getenv("PWD")) {
- // GCC also verifies that stat(pwd) and stat(".") have the same inode
- // number. Not doing those because stats are slow, but we could.
- if (llvm::sys::path::is_absolute(pwd)) {
- std::string CompDir = pwd;
- CmdArgs.push_back("-fdebug-compilation-dir");
- CmdArgs.push_back(Args.MakeArgString(CompDir));
- }
+ struct stat StatPWDBuf, StatDotBuf;
+
+ const char *pwd = ::getenv("PWD");
+ if (!pwd)
+ return;
+
+ if (llvm::sys::path::is_absolute(pwd) &&
+ stat(pwd, &StatPWDBuf) == 0 &&
+ stat(".", &StatDotBuf) == 0 &&
+ StatPWDBuf.st_ino == StatDotBuf.st_ino &&
+ StatPWDBuf.st_dev == StatDotBuf.st_dev) {
+ CmdArgs.push_back("-fdebug-compilation-dir");
+ CmdArgs.push_back(Args.MakeArgString(pwd));
+ return;
+ }
+
+ // Fall back to using getcwd.
+ SmallString<128> cwd;
+ if (!llvm::sys::fs::current_path(cwd)) {
+ CmdArgs.push_back("-fdebug-compilation-dir");
+ CmdArgs.push_back(Args.MakeArgString(cwd));
}
}
@@ -1817,6 +1847,13 @@ static void SplitDebugInfo(const ToolChain &TC, Compilation &C,
C.addCommand(new Command(JA, T, Exec, StripArgs));
}
+static bool isOptimizationLevelFast(const ArgList &Args) {
+ if (Arg *A = Args.getLastArg(options::OPT_O_Group))
+ if (A->getOption().matches(options::OPT_Ofast))
+ return true;
+ return false;
+}
+
void Clang::ConstructJob(Compilation &C, const JobAction &JA,
const InputInfo &Output,
const InputInfoList &Inputs,
@@ -1969,6 +2006,9 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
CmdArgs.push_back("-analyzer-checker=deadcode");
+ if (types::isCXX(Inputs[0].getType()))
+ CmdArgs.push_back("-analyzer-checker=cplusplus");
+
// Enable the following experimental checkers for testing.
CmdArgs.push_back("-analyzer-checker=security.insecureAPI.UncheckedReturn");
CmdArgs.push_back("-analyzer-checker=security.insecureAPI.getpw");
@@ -1997,37 +2037,38 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
CheckCodeGenerationOptions(D, Args);
- // For the PIC and PIE flag options, this logic is different from the legacy
- // logic in very old versions of GCC, as that logic was just a bug no one had
- // ever fixed. This logic is both more rational and consistent with GCC's new
- // logic now that the bugs are fixed. The last argument relating to either
- // PIC or PIE wins, and no other argument is used. If the last argument is
- // any flavor of the '-fno-...' arguments, both PIC and PIE are disabled. Any
- // PIE option implicitly enables PIC at the same level.
- bool PIE = false;
- bool PIC = getToolChain().isPICDefault();
+ bool PIE = getToolChain().isPIEDefault();
+ bool PIC = PIE || getToolChain().isPICDefault();
bool IsPICLevelTwo = PIC;
- if (Arg *A = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
- options::OPT_fpic, options::OPT_fno_pic,
- options::OPT_fPIE, options::OPT_fno_PIE,
- options::OPT_fpie, options::OPT_fno_pie)) {
- Option O = A->getOption();
- if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
- O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
- PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
- PIC = PIE || O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic);
- IsPICLevelTwo = O.matches(options::OPT_fPIE) ||
- O.matches(options::OPT_fPIC);
- } else {
- PIE = PIC = false;
- }
- }
+
+ // For the PIC and PIE flag options, this logic is different from the
+ // legacy logic in very old versions of GCC, as that logic was just
+ // a bug no one had ever fixed. This logic is both more rational and
+ // consistent with GCC's new logic now that the bugs are fixed. The last
+ // argument relating to either PIC or PIE wins, and no other argument is
+ // used. If the last argument is any flavor of the '-fno-...' arguments,
+ // both PIC and PIE are disabled. Any PIE option implicitly enables PIC
+ // at the same level.
+ Arg *LastPICArg =Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
+ options::OPT_fpic, options::OPT_fno_pic,
+ options::OPT_fPIE, options::OPT_fno_PIE,
+ options::OPT_fpie, options::OPT_fno_pie);
// Check whether the tool chain trumps the PIC-ness decision. If the PIC-ness
// is forced, then neither PIC nor PIE flags will have no effect.
- if (getToolChain().isPICDefaultForced()) {
- PIE = false;
- PIC = getToolChain().isPICDefault();
- IsPICLevelTwo = PIC;
+ if (!getToolChain().isPICDefaultForced()) {
+ if (LastPICArg) {
+ Option O = LastPICArg->getOption();
+ if (O.matches(options::OPT_fPIC) || O.matches(options::OPT_fpic) ||
+ O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie)) {
+ PIE = O.matches(options::OPT_fPIE) || O.matches(options::OPT_fpie);
+ PIC = PIE || O.matches(options::OPT_fPIC) ||
+ O.matches(options::OPT_fpic);
+ IsPICLevelTwo = O.matches(options::OPT_fPIE) ||
+ O.matches(options::OPT_fPIC);
+ } else {
+ PIE = PIC = false;
+ }
+ }
}
// Inroduce a Darwin-specific hack. If the default is PIC but the flags
@@ -2101,7 +2142,13 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
if (!Args.hasFlag(options::OPT_fzero_initialized_in_bss,
options::OPT_fno_zero_initialized_in_bss))
CmdArgs.push_back("-mno-zero-initialized-in-bss");
- if (!Args.hasFlag(options::OPT_fstrict_aliasing,
+
+ bool OFastEnabled = isOptimizationLevelFast(Args);
+ // If -Ofast is the optimization level, then -fstrict-aliasing should be
+ // enabled. This alias option is being used to simplify the hasFlag logic.
+ OptSpecifier StrictAliasingAliasOption = OFastEnabled ? options::OPT_Ofast :
+ options::OPT_fstrict_aliasing;
+ if (!Args.hasFlag(options::OPT_fstrict_aliasing, StrictAliasingAliasOption,
options::OPT_fno_strict_aliasing,
getToolChain().IsStrictAliasingDefault()))
CmdArgs.push_back("-relaxed-aliasing");
@@ -2117,13 +2164,18 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
// Handle segmented stacks.
if (Args.hasArg(options::OPT_fsplit_stack))
CmdArgs.push_back("-split-stacks");
+
+ // If -Ofast is the optimization level, then -ffast-math should be enabled.
+ // This alias option is being used to simplify the getLastArg logic.
+ OptSpecifier FastMathAliasOption = OFastEnabled ? options::OPT_Ofast :
+ options::OPT_ffast_math;
// Handle various floating point optimization flags, mapping them to the
// appropriate LLVM code generation flags. The pattern for all of these is to
// default off the codegen optimizations, and if any flag enables them and no
// flag disables them after the flag enabling them, enable the codegen
// optimization. This is complicated by several "umbrella" flags.
- if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
+ if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
options::OPT_fno_fast_math,
options::OPT_ffinite_math_only,
options::OPT_fno_finite_math_only,
@@ -2133,7 +2185,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
A->getOption().getID() != options::OPT_fno_finite_math_only &&
A->getOption().getID() != options::OPT_fhonor_infinities)
CmdArgs.push_back("-menable-no-infs");
- if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
+ if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
options::OPT_fno_fast_math,
options::OPT_ffinite_math_only,
options::OPT_fno_finite_math_only,
@@ -2146,7 +2198,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
// -fmath-errno is the default on some platforms, e.g. BSD-derived OSes.
bool MathErrno = getToolChain().IsMathErrnoDefault();
- if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
+ if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
options::OPT_fno_fast_math,
options::OPT_fmath_errno,
options::OPT_fno_math_errno))
@@ -2159,7 +2211,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
// entire set of LLVM optimizations, so collect them through all the flag
// madness.
bool AssociativeMath = false;
- if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
+ if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
options::OPT_fno_fast_math,
options::OPT_funsafe_math_optimizations,
options::OPT_fno_unsafe_math_optimizations,
@@ -2170,7 +2222,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
A->getOption().getID() != options::OPT_fno_associative_math)
AssociativeMath = true;
bool ReciprocalMath = false;
- if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
+ if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
options::OPT_fno_fast_math,
options::OPT_funsafe_math_optimizations,
options::OPT_fno_unsafe_math_optimizations,
@@ -2181,7 +2233,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
A->getOption().getID() != options::OPT_fno_reciprocal_math)
ReciprocalMath = true;
bool SignedZeros = true;
- if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
+ if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
options::OPT_fno_fast_math,
options::OPT_funsafe_math_optimizations,
options::OPT_fno_unsafe_math_optimizations,
@@ -2192,7 +2244,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
A->getOption().getID() != options::OPT_fsigned_zeros)
SignedZeros = false;
bool TrappingMath = true;
- if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
+ if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
options::OPT_fno_fast_math,
options::OPT_funsafe_math_optimizations,
options::OPT_fno_unsafe_math_optimizations,
@@ -2208,7 +2260,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
// Validate and pass through -fp-contract option.
- if (Arg *A = Args.getLastArg(options::OPT_ffast_math,
+ if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
options::OPT_fno_fast_math,
options::OPT_ffp_contract)) {
if (A->getOption().getID() == options::OPT_ffp_contract) {
@@ -2219,7 +2271,8 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
D.Diag(diag::err_drv_unsupported_option_argument)
<< A->getOption().getName() << Val;
}
- } else if (A->getOption().getID() == options::OPT_ffast_math) {
+ } else if (A->getOption().matches(options::OPT_ffast_math) ||
+ (OFastEnabled && A->getOption().matches(options::OPT_Ofast))) {
// If fast-math is set then set the fp-contract mode to fast.
CmdArgs.push_back(Args.MakeArgString("-ffp-contract=fast"));
}
@@ -2230,9 +2283,10 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
// preprocessor macros. This is distinct from enabling any optimizations as
// these options induce language changes which must survive serialization
// and deserialization, etc.
- if (Arg *A = Args.getLastArg(options::OPT_ffast_math, options::OPT_fno_fast_math))
- if (A->getOption().matches(options::OPT_ffast_math))
- CmdArgs.push_back("-ffast-math");
+ if (Arg *A = Args.getLastArg(options::OPT_ffast_math, FastMathAliasOption,
+ options::OPT_fno_fast_math))
+ if (!A->getOption().matches(options::OPT_fno_fast_math))
+ CmdArgs.push_back("-ffast-math");
if (Arg *A = Args.getLastArg(options::OPT_ffinite_math_only, options::OPT_fno_fast_math))
if (A->getOption().matches(options::OPT_ffinite_math_only))
CmdArgs.push_back("-ffinite-math-only");
@@ -2597,6 +2651,9 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
if (ShouldDisableDwarfDirectory(Args, getToolChain()))
CmdArgs.push_back("-fno-dwarf-directory-asm");
+ if (ShouldDisableAutolink(Args, getToolChain()))
+ CmdArgs.push_back("-fno-autolink");
+
// Add in -fdebug-compilation-dir if necessary.
addDebugCompDirArg(Args, CmdArgs);
@@ -2705,7 +2762,7 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
Args.AddLastArg(CmdArgs, options::OPT_fdiagnostics_show_template_tree);
Args.AddLastArg(CmdArgs, options::OPT_fno_elide_type);
- SanitizerArgs Sanitize(D, Args);
+ SanitizerArgs Sanitize(getToolChain(), Args);
Sanitize.addArgs(Args, CmdArgs);
if (!Args.hasFlag(options::OPT_fsanitize_recover,
@@ -2892,16 +2949,6 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_interval);
Args.AddLastArg(CmdArgs, options::OPT_fmodules_prune_after);
- // -fmodules-autolink (on by default when modules is enabled) automatically
- // links against libraries for imported modules. This requires the
- // integrated assembler.
- if (HaveModules && getToolChain().useIntegratedAs() &&
- Args.hasFlag(options::OPT_fmodules_autolink,
- options::OPT_fno_modules_autolink,
- true)) {
- CmdArgs.push_back("-fmodules-autolink");
- }
-
// -faccess-control is default.
if (Args.hasFlag(options::OPT_fno_access_control,
options::OPT_faccess_control,
@@ -3198,9 +3245,42 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
// Color diagnostics are the default, unless the terminal doesn't support
// them.
- if (Args.hasFlag(options::OPT_fcolor_diagnostics,
- options::OPT_fno_color_diagnostics,
- llvm::sys::Process::StandardErrHasColors()))
+ // Support both clang's -f[no-]color-diagnostics and gcc's
+ // -f[no-]diagnostics-colors[=never|always|auto].
+ enum { Colors_On, Colors_Off, Colors_Auto } ShowColors = Colors_Auto;
+ for (ArgList::const_iterator it = Args.begin(), ie = Args.end();
+ it != ie; ++it) {
+ const Option &O = (*it)->getOption();
+ if (!O.matches(options::OPT_fcolor_diagnostics) &&
+ !O.matches(options::OPT_fdiagnostics_color) &&
+ !O.matches(options::OPT_fno_color_diagnostics) &&
+ !O.matches(options::OPT_fno_diagnostics_color) &&
+ !O.matches(options::OPT_fdiagnostics_color_EQ))
+ continue;
+
+ (*it)->claim();
+ if (O.matches(options::OPT_fcolor_diagnostics) ||
+ O.matches(options::OPT_fdiagnostics_color)) {
+ ShowColors = Colors_On;
+ } else if (O.matches(options::OPT_fno_color_diagnostics) ||
+ O.matches(options::OPT_fno_diagnostics_color)) {
+ ShowColors = Colors_Off;
+ } else {
+ assert(O.matches(options::OPT_fdiagnostics_color_EQ));
+ StringRef value((*it)->getValue());
+ if (value == "always")
+ ShowColors = Colors_On;
+ else if (value == "never")
+ ShowColors = Colors_Off;
+ else if (value == "auto")
+ ShowColors = Colors_Auto;
+ else
+ getToolChain().getDriver().Diag(diag::err_drv_clang_unsupported)
+ << ("-fdiagnostics-color=" + value).str();
+ }
+ }
+ if (ShowColors == Colors_On ||
+ (ShowColors == Colors_Auto && llvm::sys::Process::StandardErrHasColors()))
CmdArgs.push_back("-fcolor-diagnostics");
if (!Args.hasFlag(options::OPT_fshow_source_location,
@@ -3222,8 +3302,13 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
false))
CmdArgs.push_back("-fasm-blocks");
+ // If -Ofast is the optimization level, then -fvectorize should be enabled.
+ // This alias option is being used to simplify the hasFlag logic.
+ OptSpecifier VectorizeAliasOption = OFastEnabled ? options::OPT_Ofast :
+ options::OPT_fvectorize;
+
// -fvectorize is default.
- if (Args.hasFlag(options::OPT_fvectorize,
+ if (Args.hasFlag(options::OPT_fvectorize, VectorizeAliasOption,
options::OPT_fno_vectorize, true)) {
CmdArgs.push_back("-backend-option");
CmdArgs.push_back("-vectorize-loops");
@@ -3233,7 +3318,14 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
if (Args.hasFlag(options::OPT_fslp_vectorize,
options::OPT_fno_slp_vectorize, false)) {
CmdArgs.push_back("-backend-option");
- CmdArgs.push_back("-vectorize");
+ CmdArgs.push_back("-vectorize-slp");
+ }
+
+ // -fno-slp-vectorize-aggressive is default.
+ if (Args.hasFlag(options::OPT_fslp_vectorize_aggressive,
+ options::OPT_fno_slp_vectorize_aggressive, false)) {
+ CmdArgs.push_back("-backend-option");
+ CmdArgs.push_back("-vectorize-slp-aggressive");
}
if (Arg *A = Args.getLastArg(options::OPT_fshow_overloads_EQ))
@@ -3298,6 +3390,8 @@ void Clang::ConstructJob(Compilation &C, const JobAction &JA,
// Forward -fcomment-block-commands to -cc1.
Args.AddAllArgs(CmdArgs, options::OPT_fcomment_block_commands);
+ // Forward -fparse-all-comments to -cc1.
+ Args.AddAllArgs(CmdArgs, options::OPT_fparse_all_comments);
// Forward -Xclang arguments to -cc1, and -mllvm arguments to the LLVM option
// parser.
@@ -3673,6 +3767,14 @@ void ClangAs::ConstructJob(Compilation &C, const JobAction &JA,
const char *Exec = getToolChain().getDriver().getClangProgramPath();
C.addCommand(new Command(JA, *this, Exec, CmdArgs));
+
+ // Handle the debug info splitting at object creation time if we're
+ // creating an object.
+ // TODO: Currently only works on linux with newer objcopy.
+ if (Args.hasArg(options::OPT_gsplit_dwarf) &&
+ (getToolChain().getTriple().getOS() == llvm::Triple::Linux))
+ SplitDebugInfo(getToolChain(), C, *this, JA, Args, Output,
+ SplitDebugName(Args, Inputs));
}
void gcc::Common::ConstructJob(Compilation &C, const JobAction &JA,
@@ -3867,7 +3969,6 @@ void hexagon::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
CmdArgs.push_back(
Args.MakeArgString(std::string("-G") + SmallDataThreshold));
- Args.AddAllArgs(CmdArgs, options::OPT_g_Group);
Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
options::OPT_Xassembler);
@@ -4579,7 +4680,7 @@ void darwin::Link::ConstructJob(Compilation &C, const JobAction &JA,
Args.AddAllArgs(CmdArgs, options::OPT_L);
- SanitizerArgs Sanitize(getToolChain().getDriver(), Args);
+ SanitizerArgs Sanitize(getToolChain(), Args);
// If we're building a dynamic lib with -fsanitize=address,
// unresolved symbols may appear. Mark all
// of them as dynamic_lookup. Linking executables is handled in
@@ -5706,6 +5807,12 @@ void gnutools::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
else
CmdArgs.push_back("-EL");
+ Args.AddLastArg(CmdArgs, options::OPT_mips16, options::OPT_mno_mips16);
+ Args.AddLastArg(CmdArgs, options::OPT_mmicromips,
+ options::OPT_mno_micromips);
+ Args.AddLastArg(CmdArgs, options::OPT_mdsp, options::OPT_mno_dsp);
+ Args.AddLastArg(CmdArgs, options::OPT_mdspr2, options::OPT_mno_dspr2);
+
Arg *LastPICArg = Args.getLastArg(options::OPT_fPIC, options::OPT_fno_PIC,
options::OPT_fpic, options::OPT_fno_pic,
options::OPT_fPIE, options::OPT_fno_PIE,
@@ -5717,6 +5824,9 @@ void gnutools::Assemble::ConstructJob(Compilation &C, const JobAction &JA,
LastPICArg->getOption().matches(options::OPT_fpie))) {
CmdArgs.push_back("-KPIC");
}
+ } else if (getToolChain().getArch() == llvm::Triple::systemz) {
+ // At the moment we always produce z10 code.
+ CmdArgs.push_back("-march=z10");
}
Args.AddAllArgValues(CmdArgs, options::OPT_Wa_COMMA,
@@ -5784,6 +5894,10 @@ void gnutools::Link::ConstructJob(Compilation &C, const JobAction &JA,
const Driver &D = ToolChain.getDriver();
const bool isAndroid =
ToolChain.getTriple().getEnvironment() == llvm::Triple::Android;
+ SanitizerArgs Sanitize(getToolChain(), Args);
+ const bool IsPIE =
+ !Args.hasArg(options::OPT_shared) &&
+ (Args.hasArg(options::OPT_pie) || Sanitize.hasZeroBaseShadow());
ArgStringList CmdArgs;
@@ -5798,7 +5912,7 @@ void gnutools::Link::ConstructJob(Compilation &C, const JobAction &JA,
if (!D.SysRoot.empty())
CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
- if (Args.hasArg(options::OPT_pie) && !Args.hasArg(options::OPT_shared))
+ if (IsPIE)
CmdArgs.push_back("-pie");
if (Args.hasArg(options::OPT_rdynamic))
@@ -5844,6 +5958,8 @@ void gnutools::Link::ConstructJob(Compilation &C, const JobAction &JA,
else
CmdArgs.push_back("elf64ltsmip");
}
+ else if (ToolChain.getArch() == llvm::Triple::systemz)
+ CmdArgs.push_back("elf64_s390");
else
CmdArgs.push_back("elf_x86_64");
@@ -5890,7 +6006,8 @@ void gnutools::Link::ConstructJob(Compilation &C, const JobAction &JA,
}
else if (ToolChain.getArch() == llvm::Triple::ppc)
CmdArgs.push_back("/lib/ld.so.1");
- else if (ToolChain.getArch() == llvm::Triple::ppc64)
+ else if (ToolChain.getArch() == llvm::Triple::ppc64 ||
+ ToolChain.getArch() == llvm::Triple::systemz)
CmdArgs.push_back("/lib64/ld64.so.1");
else
CmdArgs.push_back("/lib64/ld-linux-x86-64.so.2");
@@ -5904,7 +6021,7 @@ void gnutools::Link::ConstructJob(Compilation &C, const JobAction &JA,
if (!isAndroid) {
const char *crt1 = NULL;
if (!Args.hasArg(options::OPT_shared)){
- if (Args.hasArg(options::OPT_pie))
+ if (IsPIE)
crt1 = "Scrt1.o";
else
crt1 = "crt1.o";
@@ -5920,7 +6037,7 @@ void gnutools::Link::ConstructJob(Compilation &C, const JobAction &JA,
crtbegin = isAndroid ? "crtbegin_static.o" : "crtbeginT.o";
else if (Args.hasArg(options::OPT_shared))
crtbegin = isAndroid ? "crtbegin_so.o" : "crtbeginS.o";
- else if (Args.hasArg(options::OPT_pie))
+ else if (IsPIE)
crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbeginS.o";
else
crtbegin = isAndroid ? "crtbegin_dynamic.o" : "crtbegin.o";
@@ -5971,8 +6088,6 @@ void gnutools::Link::ConstructJob(Compilation &C, const JobAction &JA,
AddLinkerInputs(ToolChain, Inputs, Args, CmdArgs);
- SanitizerArgs Sanitize(D, Args);
-
// Call these before we add the C++ ABI library.
if (Sanitize.needsUbsanRt())
addUbsanRTLinux(getToolChain(), Args, CmdArgs, D.CCCIsCXX,
@@ -6030,7 +6145,7 @@ void gnutools::Link::ConstructJob(Compilation &C, const JobAction &JA,
const char *crtend;
if (Args.hasArg(options::OPT_shared))
crtend = isAndroid ? "crtend_so.o" : "crtendS.o";
- else if (Args.hasArg(options::OPT_pie))
+ else if (IsPIE)
crtend = isAndroid ? "crtend_android.o" : "crtendS.o";
else
crtend = isAndroid ? "crtend_android.o" : "crtend.o";
@@ -6162,21 +6277,29 @@ void dragonfly::Link::ConstructJob(Compilation &C, const JobAction &JA,
const InputInfoList &Inputs,
const ArgList &Args,
const char *LinkingOutput) const {
+ bool UseGCC47 = false;
const Driver &D = getToolChain().getDriver();
ArgStringList CmdArgs;
+ if (llvm::sys::fs::exists("/usr/lib/gcc47", UseGCC47))
+ UseGCC47 = false;
+
if (!D.SysRoot.empty())
CmdArgs.push_back(Args.MakeArgString("--sysroot=" + D.SysRoot));
+ CmdArgs.push_back("--eh-frame-hdr");
if (Args.hasArg(options::OPT_static)) {
CmdArgs.push_back("-Bstatic");
} else {
+ if (Args.hasArg(options::OPT_rdynamic))
+ CmdArgs.push_back("-export-dynamic");
if (Args.hasArg(options::OPT_shared))
CmdArgs.push_back("-Bshareable");
else {
CmdArgs.push_back("-dynamic-linker");
CmdArgs.push_back("/usr/libexec/ld-elf.so.2");
}
+ CmdArgs.push_back("--hash-style=both");
}
// When building 32-bit code on DragonFly/pc64, we have to explicitly
@@ -6196,18 +6319,26 @@ void dragonfly::Link::ConstructJob(Compilation &C, const JobAction &JA,
if (!Args.hasArg(options::OPT_nostdlib) &&
!Args.hasArg(options::OPT_nostartfiles)) {
if (!Args.hasArg(options::OPT_shared)) {
- CmdArgs.push_back(
- Args.MakeArgString(getToolChain().GetFilePath("crt1.o")));
- CmdArgs.push_back(
- Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
- CmdArgs.push_back(
- Args.MakeArgString(getToolChain().GetFilePath("crtbegin.o")));
- } else {
- CmdArgs.push_back(
- Args.MakeArgString(getToolChain().GetFilePath("crti.o")));
- CmdArgs.push_back(
- Args.MakeArgString(getToolChain().GetFilePath("crtbeginS.o")));
+ if (Args.hasArg(options::OPT_pg))
+ CmdArgs.push_back(Args.MakeArgString(
+ getToolChain().GetFilePath("gcrt1.o")));
+ else {
+ if (Args.hasArg(options::OPT_pie))
+ CmdArgs.push_back(Args.MakeArgString(
+ getToolChain().GetFilePath("Scrt1.o")));
+ else
+ CmdArgs.push_back(Args.MakeArgString(
+ getToolChain().GetFilePath("crt1.o")));
+ }
}
+ CmdArgs.push_back(Args.MakeArgString(
+ getToolChain().GetFilePath("crti.o")));
+ if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
+ CmdArgs.push_back(Args.MakeArgString(
+ getToolChain().GetFilePath("crtbeginS.o")));
+ else
+ CmdArgs.push_back(Args.MakeArgString(
+ getToolChain().GetFilePath("crtbegin.o")));
}
Args.AddAllArgs(CmdArgs, options::OPT_L);
@@ -6220,20 +6351,19 @@ void dragonfly::Link::ConstructJob(Compilation &C, const JobAction &JA,
!Args.hasArg(options::OPT_nodefaultlibs)) {
// FIXME: GCC passes on -lgcc, -lgcc_pic and a whole lot of
// rpaths
- CmdArgs.push_back("-L/usr/lib/gcc41");
+ if (UseGCC47)
+ CmdArgs.push_back("-L/usr/lib/gcc47");
+ else
+ CmdArgs.push_back("-L/usr/lib/gcc44");
if (!Args.hasArg(options::OPT_static)) {
- CmdArgs.push_back("-rpath");
- CmdArgs.push_back("/usr/lib/gcc41");
-
- CmdArgs.push_back("-rpath-link");
- CmdArgs.push_back("/usr/lib/gcc41");
-
- CmdArgs.push_back("-rpath");
- CmdArgs.push_back("/usr/lib");
-
- CmdArgs.push_back("-rpath-link");
- CmdArgs.push_back("/usr/lib");
+ if (UseGCC47) {
+ CmdArgs.push_back("-rpath");
+ CmdArgs.push_back("/usr/lib/gcc47");
+ } else {
+ CmdArgs.push_back("-rpath");
+ CmdArgs.push_back("/usr/lib/gcc44");
+ }
}
if (D.CCCIsCXX) {
@@ -6241,13 +6371,6 @@ void dragonfly::Link::ConstructJob(Compilation &C, const JobAction &JA,
CmdArgs.push_back("-lm");
}
- if (Args.hasArg(options::OPT_shared)) {
- CmdArgs.push_back("-lgcc_pic");
- } else {
- CmdArgs.push_back("-lgcc");
- }
-
-
if (Args.hasArg(options::OPT_pthread))
CmdArgs.push_back("-lpthread");
@@ -6255,23 +6378,42 @@ void dragonfly::Link::ConstructJob(Compilation &C, const JobAction &JA,
CmdArgs.push_back("-lc");
}
- if (Args.hasArg(options::OPT_shared)) {
- CmdArgs.push_back("-lgcc_pic");
+ if (UseGCC47) {
+ if (Args.hasArg(options::OPT_static) ||
+ Args.hasArg(options::OPT_static_libgcc)) {
+ CmdArgs.push_back("-lgcc");
+ CmdArgs.push_back("-lgcc_eh");
+ } else {
+ if (Args.hasArg(options::OPT_shared_libgcc)) {
+ CmdArgs.push_back("-lgcc_pic");
+ if (!Args.hasArg(options::OPT_shared))
+ CmdArgs.push_back("-lgcc");
+ } else {
+ CmdArgs.push_back("-lgcc");
+ CmdArgs.push_back("--as-needed");
+ CmdArgs.push_back("-lgcc_pic");
+ CmdArgs.push_back("--no-as-needed");
+ }
+ }
} else {
- CmdArgs.push_back("-lgcc");
+ if (Args.hasArg(options::OPT_shared)) {
+ CmdArgs.push_back("-lgcc_pic");
+ } else {
+ CmdArgs.push_back("-lgcc");
+ }
}
}
if (!Args.hasArg(options::OPT_nostdlib) &&
!Args.hasArg(options::OPT_nostartfiles)) {
- if (!Args.hasArg(options::OPT_shared))
+ if (Args.hasArg(options::OPT_shared) || Args.hasArg(options::OPT_pie))
CmdArgs.push_back(Args.MakeArgString(
- getToolChain().GetFilePath("crtend.o")));
+ getToolChain().GetFilePath("crtendS.o")));
else
CmdArgs.push_back(Args.MakeArgString(
- getToolChain().GetFilePath("crtendS.o")));
+ getToolChain().GetFilePath("crtend.o")));
CmdArgs.push_back(Args.MakeArgString(
- getToolChain().GetFilePath("crtn.o")));
+ getToolChain().GetFilePath("crtn.o")));
}
addProfileRT(getToolChain(), Args, CmdArgs, getToolChain().getTriple());
diff --git a/lib/Driver/WindowsToolChain.cpp b/lib/Driver/WindowsToolChain.cpp
index dac7e77d608e..622c49296de8 100644
--- a/lib/Driver/WindowsToolChain.cpp
+++ b/lib/Driver/WindowsToolChain.cpp
@@ -60,6 +60,10 @@ bool Windows::isPICDefault() const {
return getArch() == llvm::Triple::x86_64;
}
+bool Windows::isPIEDefault() const {
+ return false;
+}
+
bool Windows::isPICDefaultForced() const {
return getArch() == llvm::Triple::x86_64;
}
diff --git a/lib/Edit/EditedSource.cpp b/lib/Edit/EditedSource.cpp
index dd99ca928019..34b5e62333ad 100644
--- a/lib/Edit/EditedSource.cpp
+++ b/lib/Edit/EditedSource.cpp
@@ -188,6 +188,8 @@ void EditedSource::commitRemove(SourceLocation OrigLoc,
unsigned diff = EndOffs.getOffset() - TopEnd.getOffset();
TopEnd = EndOffs;
TopFA->RemoveLen += diff;
+ if (B == BeginOffs)
+ TopFA->Text = StringRef();
++I;
}
diff --git a/lib/Format/BreakableToken.cpp b/lib/Format/BreakableToken.cpp
new file mode 100644
index 000000000000..3e2e0ce7cf3d
--- /dev/null
+++ b/lib/Format/BreakableToken.cpp
@@ -0,0 +1,179 @@
+//===--- BreakableToken.cpp - Format C++ code -----------------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// \brief Contains implementation of BreakableToken class and classes derived
+/// from it.
+///
+//===----------------------------------------------------------------------===//
+
+#include "BreakableToken.h"
+#include "llvm/ADT/STLExtras.h"
+#include <algorithm>
+
+namespace clang {
+namespace format {
+
+BreakableToken::Split BreakableComment::getSplit(unsigned LineIndex,
+ unsigned TailOffset,
+ unsigned ColumnLimit) const {
+ StringRef Text = getLine(LineIndex).substr(TailOffset);
+ unsigned ContentStartColumn = getContentStartColumn(LineIndex, TailOffset);
+ if (ColumnLimit <= ContentStartColumn + 1)
+ return Split(StringRef::npos, 0);
+
+ unsigned MaxSplit = ColumnLimit - ContentStartColumn + 1;
+ StringRef::size_type SpaceOffset = Text.rfind(' ', MaxSplit);
+ if (SpaceOffset == StringRef::npos ||
+ Text.find_last_not_of(' ', SpaceOffset) == StringRef::npos) {
+ SpaceOffset = Text.find(' ', MaxSplit);
+ }
+ if (SpaceOffset != StringRef::npos && SpaceOffset != 0) {
+ StringRef BeforeCut = Text.substr(0, SpaceOffset).rtrim();
+ StringRef AfterCut = Text.substr(SpaceOffset).ltrim();
+ return BreakableToken::Split(BeforeCut.size(),
+ AfterCut.begin() - BeforeCut.end());
+ }
+ return BreakableToken::Split(StringRef::npos, 0);
+}
+
+void BreakableComment::insertBreak(unsigned LineIndex, unsigned TailOffset,
+ Split Split, bool InPPDirective,
+ WhitespaceManager &Whitespaces) {
+ StringRef Text = getLine(LineIndex).substr(TailOffset);
+ StringRef AdditionalPrefix = Decoration;
+ if (Text.size() == Split.first + Split.second) {
+ // For all but the last line handle trailing space in trimLine.
+ if (LineIndex < Lines.size() - 1)
+ return;
+ // For the last line we need to break before "*/", but not to add "* ".
+ AdditionalPrefix = "";
+ }
+
+ unsigned WhitespaceStartColumn =
+ getContentStartColumn(LineIndex, TailOffset) + Split.first;
+ unsigned BreakOffset = Text.data() - TokenText.data() + Split.first;
+ unsigned CharsToRemove = Split.second;
+ Whitespaces.breakToken(Tok, BreakOffset, CharsToRemove, "", AdditionalPrefix,
+ InPPDirective, IndentAtLineBreak,
+ WhitespaceStartColumn);
+}
+
+BreakableBlockComment::BreakableBlockComment(const SourceManager &SourceMgr,
+ const AnnotatedToken &Token,
+ unsigned StartColumn)
+ : BreakableComment(SourceMgr, Token.FormatTok, StartColumn + 2) {
+ assert(TokenText.startswith("/*") && TokenText.endswith("*/"));
+
+ OriginalStartColumn =
+ SourceMgr.getSpellingColumnNumber(Tok.getStartOfNonWhitespace()) - 1;
+
+ TokenText.substr(2, TokenText.size() - 4).split(Lines, "\n");
+
+ bool NeedsStar = true;
+ CommonPrefixLength = UINT_MAX;
+ if (Lines.size() == 1) {
+ if (Token.Parent == 0) {
+ // Standalone block comments will be aligned and prefixed with *s.
+ CommonPrefixLength = OriginalStartColumn + 1;
+ } else {
+ // Trailing comments can start on arbitrary column, and available
+ // horizontal space can be too small to align consecutive lines with
+ // the first one. We could, probably, align them to current
+ // indentation level, but now we just wrap them without indentation
+ // and stars.
+ CommonPrefixLength = 0;
+ NeedsStar = false;
+ }
+ } else {
+ for (size_t i = 1; i < Lines.size(); ++i) {
+ size_t FirstNonWhitespace = Lines[i].find_first_not_of(" ");
+ if (FirstNonWhitespace != StringRef::npos) {
+ NeedsStar = NeedsStar && (Lines[i][FirstNonWhitespace] == '*');
+ CommonPrefixLength =
+ std::min<unsigned>(CommonPrefixLength, FirstNonWhitespace);
+ }
+ }
+ }
+ if (CommonPrefixLength == UINT_MAX)
+ CommonPrefixLength = 0;
+
+ Decoration = NeedsStar ? "* " : "";
+
+ IndentAtLineBreak =
+ std::max<int>(StartColumn - OriginalStartColumn + CommonPrefixLength, 0);
+}
+
+void BreakableBlockComment::alignLines(WhitespaceManager &Whitespaces) {
+ SourceLocation TokenLoc = Tok.getStartOfNonWhitespace();
+ int IndentDelta = (StartColumn - 2) - OriginalStartColumn;
+ if (IndentDelta > 0) {
+ std::string WhiteSpace(IndentDelta, ' ');
+ for (size_t i = 1; i < Lines.size(); ++i) {
+ Whitespaces.addReplacement(
+ TokenLoc.getLocWithOffset(Lines[i].data() - TokenText.data()), 0,
+ WhiteSpace);
+ }
+ } else if (IndentDelta < 0) {
+ std::string WhiteSpace(-IndentDelta, ' ');
+ // Check that the line is indented enough.
+ for (size_t i = 1; i < Lines.size(); ++i) {
+ if (!Lines[i].startswith(WhiteSpace))
+ return;
+ }
+ for (size_t i = 1; i < Lines.size(); ++i) {
+ Whitespaces.addReplacement(
+ TokenLoc.getLocWithOffset(Lines[i].data() - TokenText.data()),
+ -IndentDelta, "");
+ }
+ }
+
+ for (unsigned i = 1; i < Lines.size(); ++i)
+ Lines[i] = Lines[i].substr(CommonPrefixLength + Decoration.size());
+}
+
+void BreakableBlockComment::trimLine(unsigned LineIndex, unsigned TailOffset,
+ unsigned InPPDirective,
+ WhitespaceManager &Whitespaces) {
+ if (LineIndex == Lines.size() - 1)
+ return;
+ StringRef Text = Lines[LineIndex].substr(TailOffset);
+ if (!Text.endswith(" ") && !InPPDirective)
+ return;
+
+ StringRef TrimmedLine = Text.rtrim();
+ unsigned WhitespaceStartColumn =
+ getLineLengthAfterSplit(LineIndex, TailOffset);
+ unsigned BreakOffset = TrimmedLine.end() - TokenText.data();
+ unsigned CharsToRemove = Text.size() - TrimmedLine.size() + 1;
+ Whitespaces.breakToken(Tok, BreakOffset, CharsToRemove, "", "", InPPDirective,
+ 0, WhitespaceStartColumn);
+}
+
+BreakableLineComment::BreakableLineComment(const SourceManager &SourceMgr,
+ const AnnotatedToken &Token,
+ unsigned StartColumn)
+ : BreakableComment(SourceMgr, Token.FormatTok, StartColumn) {
+ assert(TokenText.startswith("//"));
+ Decoration = getLineCommentPrefix(TokenText);
+ Lines.push_back(TokenText.substr(Decoration.size()));
+ IndentAtLineBreak = StartColumn;
+ this->StartColumn += Decoration.size(); // Start column of the contents.
+}
+
+StringRef BreakableLineComment::getLineCommentPrefix(StringRef Comment) {
+ const char *KnownPrefixes[] = { "/// ", "///", "// ", "//" };
+ for (size_t i = 0; i < llvm::array_lengthof(KnownPrefixes); ++i)
+ if (Comment.startswith(KnownPrefixes[i]))
+ return KnownPrefixes[i];
+ return "";
+}
+
+} // namespace format
+} // namespace clang
diff --git a/lib/Format/BreakableToken.h b/lib/Format/BreakableToken.h
new file mode 100644
index 000000000000..c1303183d312
--- /dev/null
+++ b/lib/Format/BreakableToken.h
@@ -0,0 +1,240 @@
+//===--- BreakableToken.h - Format C++ code -------------------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// \brief Declares BreakableToken, BreakableStringLiteral, and
+/// BreakableBlockComment classes, that contain token type-specific logic to
+/// break long lines in tokens.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_FORMAT_BREAKABLETOKEN_H
+#define LLVM_CLANG_FORMAT_BREAKABLETOKEN_H
+
+#include "TokenAnnotator.h"
+#include "WhitespaceManager.h"
+#include <utility>
+
+namespace clang {
+namespace format {
+
+class BreakableToken {
+public:
+ BreakableToken(const SourceManager &SourceMgr, const FormatToken &Tok,
+ unsigned StartColumn)
+ : Tok(Tok), StartColumn(StartColumn),
+ TokenText(SourceMgr.getCharacterData(Tok.getStartOfNonWhitespace()),
+ Tok.TokenLength) {}
+ virtual ~BreakableToken() {}
+ virtual unsigned getLineCount() const = 0;
+ virtual unsigned getLineSize(unsigned Index) const = 0;
+ virtual unsigned getLineLengthAfterSplit(unsigned LineIndex,
+ unsigned TailOffset) const = 0;
+
+ // Contains starting character index and length of split.
+ typedef std::pair<StringRef::size_type, unsigned> Split;
+ virtual Split getSplit(unsigned LineIndex, unsigned TailOffset,
+ unsigned ColumnLimit) const = 0;
+ virtual void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split,
+ bool InPPDirective,
+ WhitespaceManager &Whitespaces) = 0;
+ virtual void trimLine(unsigned LineIndex, unsigned TailOffset,
+ unsigned InPPDirective,
+ WhitespaceManager &Whitespaces) {}
+protected:
+ const FormatToken &Tok;
+ unsigned StartColumn;
+ StringRef TokenText;
+};
+
+class BreakableStringLiteral : public BreakableToken {
+public:
+ BreakableStringLiteral(const SourceManager &SourceMgr, const FormatToken &Tok,
+ unsigned StartColumn)
+ : BreakableToken(SourceMgr, Tok, StartColumn) {
+ assert(TokenText.startswith("\"") && TokenText.endswith("\""));
+ }
+
+ virtual unsigned getLineCount() const { return 1; }
+
+ virtual unsigned getLineSize(unsigned Index) const {
+ return Tok.TokenLength - 2; // Should be in sync with getLine
+ }
+
+ virtual unsigned getLineLengthAfterSplit(unsigned LineIndex,
+ unsigned TailOffset) const {
+ return getDecorationLength() + getLine().size() - TailOffset;
+ }
+
+ virtual Split getSplit(unsigned LineIndex, unsigned TailOffset,
+ unsigned ColumnLimit) const {
+ StringRef Text = getLine().substr(TailOffset);
+ if (ColumnLimit <= getDecorationLength())
+ return Split(StringRef::npos, 0);
+ unsigned MaxSplit = ColumnLimit - getDecorationLength();
+ assert(MaxSplit < Text.size());
+ StringRef::size_type SpaceOffset = Text.rfind(' ', MaxSplit);
+ if (SpaceOffset != StringRef::npos && SpaceOffset != 0)
+ return Split(SpaceOffset + 1, 0);
+ StringRef::size_type SlashOffset = Text.rfind('/', MaxSplit);
+ if (SlashOffset != StringRef::npos && SlashOffset != 0)
+ return Split(SlashOffset + 1, 0);
+ StringRef::size_type SplitPoint = getStartOfCharacter(Text, MaxSplit);
+ if (SplitPoint != StringRef::npos && SplitPoint > 1)
+ // Do not split at 0.
+ return Split(SplitPoint, 0);
+ return Split(StringRef::npos, 0);
+ }
+
+ virtual void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split,
+ bool InPPDirective, WhitespaceManager &Whitespaces) {
+ unsigned WhitespaceStartColumn = StartColumn + Split.first + 2;
+ Whitespaces.breakToken(Tok, 1 + TailOffset + Split.first, Split.second,
+ "\"", "\"", InPPDirective, StartColumn,
+ WhitespaceStartColumn);
+ }
+
+private:
+ StringRef getLine() const {
+ // Get string without quotes.
+ // FIXME: Handle string prefixes.
+ return TokenText.substr(1, TokenText.size() - 2);
+ }
+
+ unsigned getDecorationLength() const { return StartColumn + 2; }
+
+ static StringRef::size_type getStartOfCharacter(StringRef Text,
+ StringRef::size_type Offset) {
+ StringRef::size_type NextEscape = Text.find('\\');
+ while (NextEscape != StringRef::npos && NextEscape < Offset) {
+ StringRef::size_type SequenceLength =
+ getEscapeSequenceLength(Text.substr(NextEscape));
+ if (Offset < NextEscape + SequenceLength)
+ return NextEscape;
+ NextEscape = Text.find('\\', NextEscape + SequenceLength);
+ }
+ return Offset;
+ }
+
+ static unsigned getEscapeSequenceLength(StringRef Text) {
+ assert(Text[0] == '\\');
+ if (Text.size() < 2)
+ return 1;
+
+ switch (Text[1]) {
+ case 'u':
+ return 6;
+ case 'U':
+ return 10;
+ case 'x':
+ return getHexLength(Text);
+ default:
+ if (Text[1] >= '0' && Text[1] <= '7')
+ return getOctalLength(Text);
+ return 2;
+ }
+ }
+
+ static unsigned getHexLength(StringRef Text) {
+ unsigned I = 2; // Point after '\x'.
+ while (I < Text.size() && ((Text[I] >= '0' && Text[I] <= '9') ||
+ (Text[I] >= 'a' && Text[I] <= 'f') ||
+ (Text[I] >= 'A' && Text[I] <= 'F'))) {
+ ++I;
+ }
+ return I;
+ }
+
+ static unsigned getOctalLength(StringRef Text) {
+ unsigned I = 1;
+ while (I < Text.size() && I < 4 && (Text[I] >= '0' && Text[I] <= '7')) {
+ ++I;
+ }
+ return I;
+ }
+
+};
+
+class BreakableComment : public BreakableToken {
+public:
+ virtual unsigned getLineSize(unsigned Index) const {
+ return getLine(Index).size();
+ }
+
+ virtual unsigned getLineCount() const { return Lines.size(); }
+
+ virtual unsigned getLineLengthAfterSplit(unsigned LineIndex,
+ unsigned TailOffset) const {
+ return getContentStartColumn(LineIndex, TailOffset) +
+ getLine(LineIndex).size() - TailOffset;
+ }
+
+ virtual Split getSplit(unsigned LineIndex, unsigned TailOffset,
+ unsigned ColumnLimit) const;
+ virtual void insertBreak(unsigned LineIndex, unsigned TailOffset, Split Split,
+ bool InPPDirective, WhitespaceManager &Whitespaces);
+
+protected:
+ BreakableComment(const SourceManager &SourceMgr, const FormatToken &Tok,
+ unsigned StartColumn)
+ : BreakableToken(SourceMgr, Tok, StartColumn) {}
+
+ // Get comment lines without /* */, common prefix and trailing whitespace.
+ // Last line is not trimmed, as it is terminated by */, so its trailing
+ // whitespace is not really trailing.
+ StringRef getLine(unsigned Index) const {
+ return Index < Lines.size() - 1 ? Lines[Index].rtrim() : Lines[Index];
+ }
+
+ unsigned getContentStartColumn(unsigned LineIndex,
+ unsigned TailOffset) const {
+ return (TailOffset == 0 && LineIndex == 0)
+ ? StartColumn
+ : IndentAtLineBreak + Decoration.size();
+ }
+
+ unsigned IndentAtLineBreak;
+ StringRef Decoration;
+ SmallVector<StringRef, 16> Lines;
+};
+
+class BreakableBlockComment : public BreakableComment {
+public:
+ BreakableBlockComment(const SourceManager &SourceMgr,
+ const AnnotatedToken &Token, unsigned StartColumn);
+
+ void alignLines(WhitespaceManager &Whitespaces);
+
+ virtual unsigned getLineLengthAfterSplit(unsigned LineIndex,
+ unsigned TailOffset) const {
+ return BreakableComment::getLineLengthAfterSplit(LineIndex, TailOffset) +
+ (LineIndex + 1 < Lines.size() ? 0 : 2);
+ }
+
+ virtual void trimLine(unsigned LineIndex, unsigned TailOffset,
+ unsigned InPPDirective, WhitespaceManager &Whitespaces);
+
+private:
+ unsigned OriginalStartColumn;
+ unsigned CommonPrefixLength;
+};
+
+class BreakableLineComment : public BreakableComment {
+public:
+ BreakableLineComment(const SourceManager &SourceMgr,
+ const AnnotatedToken &Token, unsigned StartColumn);
+
+private:
+ static StringRef getLineCommentPrefix(StringRef Comment);
+};
+
+} // namespace format
+} // namespace clang
+
+#endif // LLVM_CLANG_FORMAT_BREAKABLETOKEN_H
diff --git a/lib/Format/CMakeLists.txt b/lib/Format/CMakeLists.txt
index d8630eeeead3..560e38b4bfaa 100644
--- a/lib/Format/CMakeLists.txt
+++ b/lib/Format/CMakeLists.txt
@@ -1,9 +1,11 @@
set(LLVM_LINK_COMPONENTS support)
add_clang_library(clangFormat
+ BreakableToken.cpp
+ Format.cpp
TokenAnnotator.cpp
UnwrappedLineParser.cpp
- Format.cpp
+ WhitespaceManager.cpp
)
add_dependencies(clangFormat
diff --git a/lib/Format/Format.cpp b/lib/Format/Format.cpp
index 101b16f1a18c..a0557f781824 100644
--- a/lib/Format/Format.cpp
+++ b/lib/Format/Format.cpp
@@ -15,8 +15,10 @@
#define DEBUG_TYPE "format-formatter"
+#include "BreakableToken.h"
#include "TokenAnnotator.h"
#include "UnwrappedLineParser.h"
+#include "WhitespaceManager.h"
#include "clang/Basic/Diagnostic.h"
#include "clang/Basic/OperatorPrecedence.h"
#include "clang/Basic/SourceManager.h"
@@ -34,62 +36,66 @@ namespace format {
FormatStyle getLLVMStyle() {
FormatStyle LLVMStyle;
- LLVMStyle.ColumnLimit = 80;
- LLVMStyle.MaxEmptyLinesToKeep = 1;
- LLVMStyle.PointerBindsToType = false;
- LLVMStyle.DerivePointerBinding = false;
LLVMStyle.AccessModifierOffset = -2;
- LLVMStyle.Standard = FormatStyle::LS_Cpp03;
- LLVMStyle.IndentCaseLabels = false;
- LLVMStyle.SpacesBeforeTrailingComments = 1;
- LLVMStyle.BinPackParameters = true;
+ LLVMStyle.AlignEscapedNewlinesLeft = false;
LLVMStyle.AllowAllParametersOfDeclarationOnNextLine = true;
- LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
LLVMStyle.AllowShortIfStatementsOnASingleLine = false;
+ LLVMStyle.BinPackParameters = true;
+ LLVMStyle.ColumnLimit = 80;
+ LLVMStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = false;
+ LLVMStyle.DerivePointerBinding = false;
+ LLVMStyle.IndentCaseLabels = false;
+ LLVMStyle.MaxEmptyLinesToKeep = 1;
LLVMStyle.ObjCSpaceBeforeProtocolList = true;
LLVMStyle.PenaltyExcessCharacter = 1000000;
- LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 5;
+ LLVMStyle.PenaltyReturnTypeOnItsOwnLine = 75;
+ LLVMStyle.PointerBindsToType = false;
+ LLVMStyle.SpacesBeforeTrailingComments = 1;
+ LLVMStyle.Standard = FormatStyle::LS_Cpp03;
return LLVMStyle;
}
FormatStyle getGoogleStyle() {
FormatStyle GoogleStyle;
- GoogleStyle.ColumnLimit = 80;
- GoogleStyle.MaxEmptyLinesToKeep = 1;
- GoogleStyle.PointerBindsToType = true;
- GoogleStyle.DerivePointerBinding = true;
GoogleStyle.AccessModifierOffset = -1;
- GoogleStyle.Standard = FormatStyle::LS_Auto;
- GoogleStyle.IndentCaseLabels = true;
- GoogleStyle.SpacesBeforeTrailingComments = 2;
- GoogleStyle.BinPackParameters = true;
+ GoogleStyle.AlignEscapedNewlinesLeft = true;
GoogleStyle.AllowAllParametersOfDeclarationOnNextLine = true;
+ GoogleStyle.AllowShortIfStatementsOnASingleLine = true;
+ GoogleStyle.BinPackParameters = true;
+ GoogleStyle.ColumnLimit = 80;
GoogleStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
- GoogleStyle.AllowShortIfStatementsOnASingleLine = false;
+ GoogleStyle.DerivePointerBinding = true;
+ GoogleStyle.IndentCaseLabels = true;
+ GoogleStyle.MaxEmptyLinesToKeep = 1;
GoogleStyle.ObjCSpaceBeforeProtocolList = false;
GoogleStyle.PenaltyExcessCharacter = 1000000;
- GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 100;
+ GoogleStyle.PenaltyReturnTypeOnItsOwnLine = 200;
+ GoogleStyle.PointerBindsToType = true;
+ GoogleStyle.SpacesBeforeTrailingComments = 2;
+ GoogleStyle.Standard = FormatStyle::LS_Auto;
return GoogleStyle;
}
FormatStyle getChromiumStyle() {
FormatStyle ChromiumStyle = getGoogleStyle();
ChromiumStyle.AllowAllParametersOfDeclarationOnNextLine = false;
+ ChromiumStyle.AllowShortIfStatementsOnASingleLine = false;
ChromiumStyle.BinPackParameters = false;
ChromiumStyle.Standard = FormatStyle::LS_Cpp03;
ChromiumStyle.DerivePointerBinding = false;
return ChromiumStyle;
}
-static bool isTrailingComment(const AnnotatedToken &Tok) {
- return Tok.is(tok::comment) &&
- (Tok.Children.empty() || Tok.Children[0].MustBreakBefore);
-}
-
-static bool isComparison(const AnnotatedToken &Tok) {
- prec::Level Precedence = getPrecedence(Tok);
- return Tok.Type == TT_BinaryOperator &&
- (Precedence == prec::Equality || Precedence == prec::Relational);
+FormatStyle getMozillaStyle() {
+ FormatStyle MozillaStyle = getLLVMStyle();
+ MozillaStyle.AllowAllParametersOfDeclarationOnNextLine = false;
+ MozillaStyle.ConstructorInitializerAllOnOneLineOrOnePerLine = true;
+ MozillaStyle.DerivePointerBinding = true;
+ MozillaStyle.IndentCaseLabels = true;
+ MozillaStyle.ObjCSpaceBeforeProtocolList = false;
+ MozillaStyle.PenaltyReturnTypeOnItsOwnLine = 200;
+ MozillaStyle.PointerBindsToType = true;
+ return MozillaStyle;
}
// Returns the length of everything up to the first possible line break after
@@ -104,373 +110,12 @@ static unsigned getLengthToMatchingParen(const AnnotatedToken &Tok) {
return End->TotalLength - Tok.TotalLength + 1;
}
-static size_t
-calculateColumnLimit(const FormatStyle &Style, bool InPPDirective) {
- // In preprocessor directives reserve two chars for trailing " \"
- return Style.ColumnLimit - (InPPDirective ? 2 : 0);
-}
-
-/// \brief Manages the whitespaces around tokens and their replacements.
-///
-/// This includes special handling for certain constructs, e.g. the alignment of
-/// trailing line comments.
-class WhitespaceManager {
-public:
- WhitespaceManager(SourceManager &SourceMgr, const FormatStyle &Style)
- : SourceMgr(SourceMgr), Style(Style) {}
-
- /// \brief Replaces the whitespace in front of \p Tok. Only call once for
- /// each \c AnnotatedToken.
- void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
- unsigned Spaces, unsigned WhitespaceStartColumn) {
- // 2+ newlines mean an empty line separating logic scopes.
- if (NewLines >= 2)
- alignComments();
-
- SourceLocation TokenLoc = Tok.FormatTok.Tok.getLocation();
- bool LineExceedsColumnLimit = Spaces + WhitespaceStartColumn +
- Tok.FormatTok.TokenLength > Style.ColumnLimit;
-
- // Align line comments if they are trailing or if they continue other
- // trailing comments.
- if (isTrailingComment(Tok)) {
- // Remove the comment's trailing whitespace.
- if (Tok.FormatTok.Tok.getLength() != Tok.FormatTok.TokenLength)
- Replaces.insert(tooling::Replacement(
- SourceMgr, TokenLoc.getLocWithOffset(Tok.FormatTok.TokenLength),
- Tok.FormatTok.Tok.getLength() - Tok.FormatTok.TokenLength, ""));
-
- // Align comment with other comments.
- if ((Tok.Parent != NULL || !Comments.empty()) &&
- !LineExceedsColumnLimit) {
- StoredComment Comment;
- Comment.Tok = Tok.FormatTok;
- Comment.Spaces = Spaces;
- Comment.NewLines = NewLines;
- Comment.MinColumn =
- NewLines > 0 ? Spaces : WhitespaceStartColumn + Spaces;
- Comment.MaxColumn = Style.ColumnLimit - Tok.FormatTok.TokenLength;
- Comment.Untouchable = false;
- Comments.push_back(Comment);
- return;
- }
- }
-
- // If this line does not have a trailing comment, align the stored comments.
- if (Tok.Children.empty() && !isTrailingComment(Tok))
- alignComments();
-
- if (Tok.Type == TT_BlockComment) {
- indentBlockComment(Tok, Spaces, WhitespaceStartColumn, NewLines, false);
- } else if (Tok.Type == TT_LineComment && LineExceedsColumnLimit) {
- StringRef Line(SourceMgr.getCharacterData(TokenLoc),
- Tok.FormatTok.TokenLength);
- int StartColumn = Spaces + (NewLines == 0 ? WhitespaceStartColumn : 0);
- StringRef Prefix = getLineCommentPrefix(Line);
- std::string NewPrefix = std::string(StartColumn, ' ') + Prefix.str();
- splitLineInComment(Tok.FormatTok, Line.substr(Prefix.size()),
- StartColumn + Prefix.size(), NewPrefix,
- /*InPPDirective=*/ false,
- /*CommentHasMoreLines=*/ false);
- }
-
- storeReplacement(Tok.FormatTok, getNewLineText(NewLines, Spaces));
- }
-
- /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
- /// backslashes to escape newlines inside a preprocessor directive.
- ///
- /// This function and \c replaceWhitespace have the same behavior if
- /// \c Newlines == 0.
- void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
- unsigned Spaces, unsigned WhitespaceStartColumn) {
- if (Tok.Type == TT_BlockComment)
- indentBlockComment(Tok, Spaces, WhitespaceStartColumn, NewLines, true);
-
- storeReplacement(Tok.FormatTok,
- getNewLineText(NewLines, Spaces, WhitespaceStartColumn));
- }
-
- /// \brief Inserts a line break into the middle of a token.
- ///
- /// Will break at \p Offset inside \p Tok, putting \p Prefix before the line
- /// break and \p Postfix before the rest of the token starts in the next line.
- ///
- /// \p InPPDirective, \p Spaces, \p WhitespaceStartColumn and \p Style are
- /// used to generate the correct line break.
- void breakToken(const FormatToken &Tok, unsigned Offset,
- unsigned ReplaceChars, StringRef Prefix, StringRef Postfix,
- bool InPPDirective, unsigned Spaces,
- unsigned WhitespaceStartColumn) {
- std::string NewLineText;
- if (!InPPDirective)
- NewLineText = getNewLineText(1, Spaces);
- else
- NewLineText = getNewLineText(1, Spaces, WhitespaceStartColumn);
- std::string ReplacementText = (Prefix + NewLineText + Postfix).str();
- SourceLocation Location = Tok.Tok.getLocation().getLocWithOffset(Offset);
- Replaces.insert(tooling::Replacement(SourceMgr, Location, ReplaceChars,
- ReplacementText));
- }
-
- /// \brief Returns all the \c Replacements created during formatting.
- const tooling::Replacements &generateReplacements() {
- alignComments();
- return Replaces;
- }
-
- void addUntouchableComment(unsigned Column) {
- StoredComment Comment;
- Comment.MinColumn = Column;
- Comment.MaxColumn = Column;
- Comment.Untouchable = true;
- Comments.push_back(Comment);
- }
-
-private:
- static StringRef getLineCommentPrefix(StringRef Comment) {
- const char *KnownPrefixes[] = { "/// ", "///", "// ", "//" };
- for (size_t i = 0; i < llvm::array_lengthof(KnownPrefixes); ++i)
- if (Comment.startswith(KnownPrefixes[i]))
- return KnownPrefixes[i];
- return "";
- }
-
- /// \brief Finds a common prefix of lines of a block comment to properly
- /// indent (and possibly decorate with '*'s) added lines.
- ///
- /// The first line is ignored (it's special and starts with /*). The number of
- /// lines should be more than one.
- static StringRef findCommentLinesPrefix(ArrayRef<StringRef> Lines,
- const char *PrefixChars = " *") {
- assert(Lines.size() > 1);
- StringRef Prefix(Lines[1].data(), Lines[1].find_first_not_of(PrefixChars));
- for (size_t i = 2; i < Lines.size(); ++i) {
- for (size_t j = 0; j < Prefix.size() && j < Lines[i].size(); ++j) {
- if (Prefix[j] != Lines[i][j]) {
- Prefix = Prefix.substr(0, j);
- break;
- }
- }
- }
- return Prefix;
- }
-
- /// \brief Splits one line in a line or block comment, if it doesn't fit to
- /// provided column limit. Removes trailing whitespace in each line.
- ///
- /// \param Line points to the line contents without leading // or /*.
- ///
- /// \param StartColumn is the column where the first character of Line will be
- /// located after formatting.
- ///
- /// \param LinePrefix is inserted after each line break.
- ///
- /// When \param InPPDirective is true, each line break will be preceded by a
- /// backslash in the last column to make line breaks inside the comment
- /// visually consistent with line breaks outside the comment. This only makes
- /// sense for block comments.
- ///
- /// When \param CommentHasMoreLines is false, no line breaks/trailing
- /// backslashes will be inserted after it.
- void splitLineInComment(const FormatToken &Tok, StringRef Line,
- size_t StartColumn, StringRef LinePrefix,
- bool InPPDirective, bool CommentHasMoreLines,
- const char *WhiteSpaceChars = " ") {
- size_t ColumnLimit = calculateColumnLimit(Style, InPPDirective);
- const char *TokenStart = SourceMgr.getCharacterData(Tok.Tok.getLocation());
-
- StringRef TrimmedLine = Line.rtrim();
- int TrailingSpaceLength = Line.size() - TrimmedLine.size();
-
- // Don't touch leading whitespace.
- Line = TrimmedLine.ltrim();
- StartColumn += TrimmedLine.size() - Line.size();
-
- while (Line.size() + StartColumn > ColumnLimit) {
- // Try to break at the last whitespace before the column limit.
- size_t SpacePos =
- Line.find_last_of(WhiteSpaceChars, ColumnLimit - StartColumn + 1);
- if (SpacePos == StringRef::npos) {
- // Try to find any whitespace in the line.
- SpacePos = Line.find_first_of(WhiteSpaceChars);
- if (SpacePos == StringRef::npos) // No whitespace found, give up.
- break;
- }
-
- StringRef NextCut = Line.substr(0, SpacePos).rtrim();
- StringRef RemainingLine = Line.substr(SpacePos).ltrim();
- if (RemainingLine.empty())
- break;
-
- if (RemainingLine == "*/" && LinePrefix.endswith("* "))
- LinePrefix = LinePrefix.substr(0, LinePrefix.size() - 2);
-
- Line = RemainingLine;
-
- size_t ReplaceChars = Line.begin() - NextCut.end();
- breakToken(Tok, NextCut.end() - TokenStart, ReplaceChars, "", LinePrefix,
- InPPDirective, 0, NextCut.size() + StartColumn);
- StartColumn = LinePrefix.size();
- }
-
- if (TrailingSpaceLength > 0 || (InPPDirective && CommentHasMoreLines)) {
- // Remove trailing whitespace/insert backslash. + 1 is for \n
- breakToken(Tok, Line.end() - TokenStart, TrailingSpaceLength + 1, "", "",
- InPPDirective, 0, Line.size() + StartColumn);
- }
- }
-
- /// \brief Changes indentation of all lines in a block comment by Indent,
- /// removes trailing whitespace from each line, splits lines that end up
- /// exceeding the column limit.
- void indentBlockComment(const AnnotatedToken &Tok, int Indent,
- int WhitespaceStartColumn, int NewLines,
- bool InPPDirective) {
- assert(Tok.Type == TT_BlockComment);
- int StartColumn = Indent + (NewLines == 0 ? WhitespaceStartColumn : 0);
- const SourceLocation TokenLoc = Tok.FormatTok.Tok.getLocation();
- const int CurrentIndent = SourceMgr.getSpellingColumnNumber(TokenLoc) - 1;
- const int IndentDelta = Indent - CurrentIndent;
- const StringRef Text(SourceMgr.getCharacterData(TokenLoc),
- Tok.FormatTok.TokenLength);
- assert(Text.startswith("/*") && Text.endswith("*/"));
-
- SmallVector<StringRef, 16> Lines;
- Text.split(Lines, "\n");
-
- if (IndentDelta > 0) {
- std::string WhiteSpace(IndentDelta, ' ');
- for (size_t i = 1; i < Lines.size(); ++i) {
- Replaces.insert(tooling::Replacement(
- SourceMgr, TokenLoc.getLocWithOffset(Lines[i].data() - Text.data()),
- 0, WhiteSpace));
- }
- } else if (IndentDelta < 0) {
- std::string WhiteSpace(-IndentDelta, ' ');
- // Check that the line is indented enough.
- for (size_t i = 1; i < Lines.size(); ++i) {
- if (!Lines[i].startswith(WhiteSpace))
- return;
- }
- for (size_t i = 1; i < Lines.size(); ++i) {
- Replaces.insert(tooling::Replacement(
- SourceMgr, TokenLoc.getLocWithOffset(Lines[i].data() - Text.data()),
- -IndentDelta, ""));
- }
- }
-
- // Split long lines in comments.
- size_t OldPrefixSize = 0;
- std::string NewPrefix;
- if (Lines.size() > 1) {
- StringRef CurrentPrefix = findCommentLinesPrefix(Lines);
- OldPrefixSize = CurrentPrefix.size();
- NewPrefix = (IndentDelta < 0)
- ? CurrentPrefix.substr(-IndentDelta).str()
- : std::string(IndentDelta, ' ') + CurrentPrefix.str();
- if (CurrentPrefix.endswith("*")) {
- NewPrefix += " ";
- ++OldPrefixSize;
- }
- } else if (Tok.Parent == 0) {
- NewPrefix = std::string(StartColumn, ' ') + " * ";
- }
-
- StartColumn += 2;
- for (size_t i = 0; i < Lines.size(); ++i) {
- StringRef Line = Lines[i].substr(i == 0 ? 2 : OldPrefixSize);
- splitLineInComment(Tok.FormatTok, Line, StartColumn, NewPrefix,
- InPPDirective, i != Lines.size() - 1);
- StartColumn = NewPrefix.size();
- }
- }
-
- std::string getNewLineText(unsigned NewLines, unsigned Spaces) {
- return std::string(NewLines, '\n') + std::string(Spaces, ' ');
- }
-
- std::string getNewLineText(unsigned NewLines, unsigned Spaces,
- unsigned WhitespaceStartColumn) {
- std::string NewLineText;
- if (NewLines > 0) {
- unsigned Offset =
- std::min<int>(Style.ColumnLimit - 1, WhitespaceStartColumn);
- for (unsigned i = 0; i < NewLines; ++i) {
- NewLineText += std::string(Style.ColumnLimit - Offset - 1, ' ');
- NewLineText += "\\\n";
- Offset = 0;
- }
- }
- return NewLineText + std::string(Spaces, ' ');
- }
-
- /// \brief Structure to store a comment for later layout and alignment.
- struct StoredComment {
- FormatToken Tok;
- unsigned MinColumn;
- unsigned MaxColumn;
- unsigned NewLines;
- unsigned Spaces;
- bool Untouchable;
- };
- SmallVector<StoredComment, 16> Comments;
- typedef SmallVector<StoredComment, 16>::iterator comment_iterator;
-
- /// \brief Try to align all stashed comments.
- void alignComments() {
- unsigned MinColumn = 0;
- unsigned MaxColumn = UINT_MAX;
- comment_iterator Start = Comments.begin();
- for (comment_iterator I = Start, E = Comments.end(); I != E; ++I) {
- if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
- alignComments(Start, I, MinColumn);
- MinColumn = I->MinColumn;
- MaxColumn = I->MaxColumn;
- Start = I;
- } else {
- MinColumn = std::max(MinColumn, I->MinColumn);
- MaxColumn = std::min(MaxColumn, I->MaxColumn);
- }
- }
- alignComments(Start, Comments.end(), MinColumn);
- Comments.clear();
- }
-
- /// \brief Put all the comments between \p I and \p E into \p Column.
- void alignComments(comment_iterator I, comment_iterator E, unsigned Column) {
- while (I != E) {
- if (!I->Untouchable) {
- unsigned Spaces = I->Spaces + Column - I->MinColumn;
- storeReplacement(I->Tok, getNewLineText(I->NewLines, Spaces));
- }
- ++I;
- }
- }
-
- /// \brief Stores \p Text as the replacement for the whitespace in front of
- /// \p Tok.
- void storeReplacement(const FormatToken &Tok, const std::string Text) {
- // Don't create a replacement, if it does not change anything.
- if (StringRef(SourceMgr.getCharacterData(Tok.WhiteSpaceStart),
- Tok.WhiteSpaceLength) == Text)
- return;
-
- Replaces.insert(tooling::Replacement(SourceMgr, Tok.WhiteSpaceStart,
- Tok.WhiteSpaceLength, Text));
- }
-
- SourceManager &SourceMgr;
- tooling::Replacements Replaces;
- const FormatStyle &Style;
-};
-
class UnwrappedLineFormatter {
public:
UnwrappedLineFormatter(const FormatStyle &Style, SourceManager &SourceMgr,
const AnnotatedLine &Line, unsigned FirstIndent,
const AnnotatedToken &RootToken,
- WhitespaceManager &Whitespaces, bool StructuralError)
+ WhitespaceManager &Whitespaces)
: Style(Style), SourceMgr(SourceMgr), Line(Line),
FirstIndent(FirstIndent), RootToken(RootToken),
Whitespaces(Whitespaces), Count(0) {}
@@ -486,16 +131,12 @@ public:
State.NextToken = &RootToken;
State.Stack.push_back(
ParenState(FirstIndent, FirstIndent, !Style.BinPackParameters,
- /*HasMultiParameterLine=*/ false));
+ /*NoLineBreak=*/ false));
State.LineContainsContinuedForLoopSection = false;
State.ParenLevel = 0;
State.StartOfStringLiteral = 0;
State.StartOfLineLevel = State.ParenLevel;
- DEBUG({
- DebugTokenState(*State.NextToken);
- });
-
// The first token has already been indented and thus consumed.
moveStateToNextToken(State, /*DryRun=*/ false);
@@ -530,13 +171,13 @@ private:
struct ParenState {
ParenState(unsigned Indent, unsigned LastSpace, bool AvoidBinPacking,
- bool HasMultiParameterLine)
+ bool NoLineBreak)
: Indent(Indent), LastSpace(LastSpace), FirstLessLess(0),
BreakBeforeClosingBrace(false), QuestionColumn(0),
AvoidBinPacking(AvoidBinPacking), BreakBeforeParameter(false),
- HasMultiParameterLine(HasMultiParameterLine), ColonPos(0),
- StartOfFunctionCall(0), NestedNameSpecifierContinuation(0),
- CallContinuation(0), VariablePos(0) {}
+ NoLineBreak(NoLineBreak), ColonPos(0), StartOfFunctionCall(0),
+ NestedNameSpecifierContinuation(0), CallContinuation(0),
+ VariablePos(0) {}
/// \brief The position to which a specific parenthesis level needs to be
/// indented.
@@ -573,8 +214,8 @@ private:
/// \c AvoidBinPacking is \c true).
bool BreakBeforeParameter;
- /// \brief This context already has a line with more than one parameter.
- bool HasMultiParameterLine;
+ /// \brief Line breaking in this context would break a formatting rule.
+ bool NoLineBreak;
/// \brief The position of the colon in an ObjC method declaration/call.
unsigned ColonPos;
@@ -610,14 +251,14 @@ private:
return AvoidBinPacking;
if (BreakBeforeParameter != Other.BreakBeforeParameter)
return BreakBeforeParameter;
- if (HasMultiParameterLine != Other.HasMultiParameterLine)
- return HasMultiParameterLine;
+ if (NoLineBreak != Other.NoLineBreak)
+ return NoLineBreak;
if (ColonPos != Other.ColonPos)
return ColonPos < Other.ColonPos;
if (StartOfFunctionCall != Other.StartOfFunctionCall)
return StartOfFunctionCall < Other.StartOfFunctionCall;
if (NestedNameSpecifierContinuation !=
- Other.NestedNameSpecifierContinuation)
+ Other.NestedNameSpecifierContinuation)
return NestedNameSpecifierContinuation <
Other.NestedNameSpecifierContinuation;
if (CallContinuation != Other.CallContinuation)
@@ -662,7 +303,7 @@ private:
if (Column != Other.Column)
return Column < Other.Column;
if (LineContainsContinuedForLoopSection !=
- Other.LineContainsContinuedForLoopSection)
+ Other.LineContainsContinuedForLoopSection)
return LineContainsContinuedForLoopSection;
if (ParenLevel != Other.ParenLevel)
return ParenLevel < Other.ParenLevel;
@@ -730,7 +371,8 @@ private:
State.Stack.back().VariablePos != 0) {
State.Column = State.Stack.back().VariablePos;
} else if (Previous.ClosesTemplateDeclaration ||
- (Current.Type == TT_StartOfName && State.ParenLevel == 0)) {
+ (Current.Type == TT_StartOfName && State.ParenLevel == 0 &&
+ Line.StartsDefinition)) {
State.Column = State.Stack.back().Indent;
} else if (Current.Type == TT_ObjCSelectorName) {
if (State.Stack.back().ColonPos > Current.FormatTok.TokenLength) {
@@ -741,8 +383,7 @@ private:
State.Stack.back().ColonPos =
State.Column + Current.FormatTok.TokenLength;
}
- } else if (Current.Type == TT_StartOfName || Current.is(tok::question) ||
- Previous.is(tok::equal) || isComparison(Previous) ||
+ } else if (Current.Type == TT_StartOfName || Previous.is(tok::equal) ||
Previous.Type == TT_ObjCMethodExpr) {
State.Column = ContinuationIndent;
} else {
@@ -781,7 +422,9 @@ private:
for (unsigned i = 0, e = State.Stack.size() - 1; i != e; ++i) {
State.Stack[i].BreakBeforeParameter = true;
}
- if (Current.isOneOf(tok::period, tok::arrow))
+ const AnnotatedToken *TokenBefore = Current.getPreviousNoneComment();
+ if (TokenBefore && !TokenBefore->isOneOf(tok::comma, tok::semi) &&
+ !TokenBefore->opensScope())
State.Stack.back().BreakBeforeParameter = true;
// If we break after {, we should also break before the corresponding }.
@@ -822,7 +465,7 @@ private:
if (Current.Type == TT_ObjCSelectorName &&
State.Stack.back().ColonPos == 0) {
if (State.Stack.back().Indent + Current.LongestObjCSelectorName >
- State.Column + Spaces + Current.FormatTok.TokenLength)
+ State.Column + Spaces + Current.FormatTok.TokenLength)
State.Stack.back().ColonPos =
State.Stack.back().Indent + Current.LongestObjCSelectorName;
else
@@ -830,12 +473,12 @@ private:
State.Column + Spaces + Current.FormatTok.TokenLength;
}
- if (Current.Type != TT_LineComment &&
- (Previous.isOneOf(tok::l_paren, tok::l_brace) ||
- State.NextToken->Parent->Type == TT_TemplateOpener))
+ if (Previous.opensScope() && Previous.Type != TT_ObjCMethodExpr &&
+ Current.Type != TT_LineComment)
State.Stack.back().Indent = State.Column + Spaces;
- if (Previous.is(tok::comma) && !isTrailingComment(Current))
- State.Stack.back().HasMultiParameterLine = true;
+ if (Previous.is(tok::comma) && !Current.isTrailingComment() &&
+ State.Stack.back().AvoidBinPacking)
+ State.Stack.back().NoLineBreak = true;
State.Column += Spaces;
if (Current.is(tok::l_paren) && Previous.isOneOf(tok::kw_if, tok::kw_for))
@@ -851,9 +494,7 @@ private:
State.Stack.back().LastSpace = State.Column;
else if (Previous.Type == TT_InheritanceColon)
State.Stack.back().Indent = State.Column;
- else if (Previous.ParameterCount > 1 &&
- (Previous.isOneOf(tok::l_paren, tok::l_square, tok::l_brace) ||
- Previous.Type == TT_TemplateOpener))
+ else if (Previous.opensScope() && Previous.ParameterCount > 1)
// If this function has multiple parameters, indent nested calls from
// the start of the first parameter.
State.Stack.back().LastSpace = State.Column;
@@ -879,28 +520,55 @@ private:
State.Stack.back().StartOfFunctionCall =
Current.LastInChainOfCalls ? 0 : State.Column;
if (Current.Type == TT_CtorInitializerColon) {
+ State.Stack.back().Indent = State.Column + 2;
if (Style.ConstructorInitializerAllOnOneLineOrOnePerLine)
State.Stack.back().AvoidBinPacking = true;
State.Stack.back().BreakBeforeParameter = false;
}
+ // If return returns a binary expression, align after it.
+ if (Current.is(tok::kw_return) && !Current.FakeLParens.empty())
+ State.Stack.back().LastSpace = State.Column + 7;
+
// In ObjC method declaration we align on the ":" of parameters, but we need
// to ensure that we indent parameters on subsequent lines by at least 4.
if (Current.Type == TT_ObjCMethodSpecifier)
State.Stack.back().Indent += 4;
// Insert scopes created by fake parenthesis.
- for (unsigned i = 0, e = Current.FakeLParens; i != e; ++i) {
+ const AnnotatedToken *Previous = Current.getPreviousNoneComment();
+ // Don't add extra indentation for the first fake parenthesis after
+ // 'return', assignements or opening <({[. The indentation for these cases
+ // is special cased.
+ bool SkipFirstExtraIndent =
+ Current.is(tok::kw_return) ||
+ (Previous && (Previous->opensScope() ||
+ getPrecedence(*Previous) == prec::Assignment));
+ for (SmallVector<prec::Level, 4>::const_reverse_iterator
+ I = Current.FakeLParens.rbegin(),
+ E = Current.FakeLParens.rend();
+ I != E; ++I) {
ParenState NewParenState = State.Stack.back();
- NewParenState.Indent = std::max(State.Column, State.Stack.back().Indent);
- NewParenState.BreakBeforeParameter = false;
+ NewParenState.Indent =
+ std::max(std::max(State.Column, NewParenState.Indent),
+ State.Stack.back().LastSpace);
+
+ // Always indent conditional expressions. Never indent expression where
+ // the 'operator' is ',', ';' or an assignment (i.e. *I <=
+ // prec::Assignment) as those have different indentation rules. Indent
+ // other expression, unless the indentation needs to be skipped.
+ if (*I == prec::Conditional ||
+ (!SkipFirstExtraIndent && *I > prec::Assignment))
+ NewParenState.Indent += 4;
+ if (Previous && !Previous->opensScope())
+ NewParenState.BreakBeforeParameter = false;
State.Stack.push_back(NewParenState);
+ SkipFirstExtraIndent = false;
}
// If we encounter an opening (, [, { or <, we add a level to our stacks to
// prepare for the following tokens.
- if (Current.isOneOf(tok::l_paren, tok::l_square, tok::l_brace) ||
- State.NextToken->Type == TT_TemplateOpener) {
+ if (Current.opensScope()) {
unsigned NewIndent;
bool AvoidBinPacking;
if (Current.is(tok::l_brace)) {
@@ -909,12 +577,20 @@ private:
} else {
NewIndent = 4 + std::max(State.Stack.back().LastSpace,
State.Stack.back().StartOfFunctionCall);
- AvoidBinPacking =
- !Style.BinPackParameters || State.Stack.back().AvoidBinPacking;
+ AvoidBinPacking = !Style.BinPackParameters;
}
State.Stack.push_back(
ParenState(NewIndent, State.Stack.back().LastSpace, AvoidBinPacking,
- State.Stack.back().HasMultiParameterLine));
+ State.Stack.back().NoLineBreak));
+
+ if (Current.NoMoreTokensOnLevel && Current.FakeLParens.empty()) {
+ // This parenthesis was the last token possibly making use of Indent and
+ // LastSpace of the next higher ParenLevel. Thus, erase them to acieve
+ // better memoization results.
+ State.Stack[State.Stack.size() - 2].Indent = 0;
+ State.Stack[State.Stack.size() - 2].LastSpace = 0;
+ }
+
++State.ParenLevel;
}
@@ -962,115 +638,74 @@ private:
/// it if possible.
unsigned breakProtrudingToken(const AnnotatedToken &Current, LineState &State,
bool DryRun) {
- if (Current.isNot(tok::string_literal))
- return 0;
- // Only break up default narrow strings.
- const char *LiteralData = Current.FormatTok.Tok.getLiteralData();
- if (!LiteralData || *LiteralData != '"')
+ llvm::OwningPtr<BreakableToken> Token;
+ unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
+ if (Current.is(tok::string_literal)) {
+ // Only break up default narrow strings.
+ const char *LiteralData = SourceMgr.getCharacterData(
+ Current.FormatTok.getStartOfNonWhitespace());
+ if (!LiteralData || *LiteralData != '"')
+ return 0;
+
+ Token.reset(new BreakableStringLiteral(SourceMgr, Current.FormatTok,
+ StartColumn));
+ } else if (Current.Type == TT_BlockComment) {
+ BreakableBlockComment *BBC =
+ new BreakableBlockComment(SourceMgr, Current, StartColumn);
+ if (!DryRun)
+ BBC->alignLines(Whitespaces);
+ Token.reset(BBC);
+ } else if (Current.Type == TT_LineComment &&
+ (Current.Parent == NULL ||
+ Current.Parent->Type != TT_ImplicitStringLiteral)) {
+ Token.reset(new BreakableLineComment(SourceMgr, Current, StartColumn));
+ } else {
return 0;
+ }
+ bool BreakInserted = false;
unsigned Penalty = 0;
- unsigned TailOffset = 0;
- unsigned TailLength = Current.FormatTok.TokenLength;
- unsigned StartColumn = State.Column - Current.FormatTok.TokenLength;
- unsigned OffsetFromStart = 0;
- while (StartColumn + TailLength > getColumnLimit()) {
- StringRef Text = StringRef(LiteralData + TailOffset, TailLength);
- if (StartColumn + OffsetFromStart + 1 > getColumnLimit())
- break;
- StringRef::size_type SplitPoint = getSplitPoint(
- Text, getColumnLimit() - StartColumn - OffsetFromStart - 1);
- if (SplitPoint == StringRef::npos)
- break;
- assert(SplitPoint != 0);
- // +2, because 'Text' starts after the opening quotes, and does not
- // include the closing quote we need to insert.
- unsigned WhitespaceStartColumn =
- StartColumn + OffsetFromStart + SplitPoint + 2;
- State.Stack.back().LastSpace = StartColumn;
+ for (unsigned LineIndex = 0; LineIndex < Token->getLineCount();
+ ++LineIndex) {
+ unsigned TailOffset = 0;
+ unsigned RemainingLength =
+ Token->getLineLengthAfterSplit(LineIndex, TailOffset);
+ while (RemainingLength > getColumnLimit()) {
+ BreakableToken::Split Split =
+ Token->getSplit(LineIndex, TailOffset, getColumnLimit());
+ if (Split.first == StringRef::npos)
+ break;
+ assert(Split.first != 0);
+ unsigned NewRemainingLength = Token->getLineLengthAfterSplit(
+ LineIndex, TailOffset + Split.first + Split.second);
+ if (NewRemainingLength >= RemainingLength)
+ break;
+ if (!DryRun) {
+ Token->insertBreak(LineIndex, TailOffset, Split, Line.InPPDirective,
+ Whitespaces);
+ }
+ TailOffset += Split.first + Split.second;
+ RemainingLength = NewRemainingLength;
+ Penalty += Style.PenaltyExcessCharacter;
+ BreakInserted = true;
+ }
+ State.Column = RemainingLength;
if (!DryRun) {
- Whitespaces.breakToken(Current.FormatTok, TailOffset + SplitPoint + 1,
- 0, "\"", "\"", Line.InPPDirective, StartColumn,
- WhitespaceStartColumn);
+ Token->trimLine(LineIndex, TailOffset, Line.InPPDirective, Whitespaces);
}
- TailOffset += SplitPoint + 1;
- TailLength -= SplitPoint + 1;
- OffsetFromStart = 1;
- Penalty += Style.PenaltyExcessCharacter;
+ }
+
+ if (BreakInserted) {
for (unsigned i = 0, e = State.Stack.size(); i != e; ++i)
State.Stack[i].BreakBeforeParameter = true;
+ State.Stack.back().LastSpace = StartColumn;
}
- State.Column = StartColumn + TailLength;
return Penalty;
}
- StringRef::size_type
- getSplitPoint(StringRef Text, StringRef::size_type Offset) {
- StringRef::size_type SpaceOffset = Text.rfind(' ', Offset);
- if (SpaceOffset != StringRef::npos && SpaceOffset != 0)
- return SpaceOffset;
- StringRef::size_type SlashOffset = Text.rfind('/', Offset);
- if (SlashOffset != StringRef::npos && SlashOffset != 0)
- return SlashOffset;
- StringRef::size_type Split = getStartOfCharacter(Text, Offset);
- if (Split != StringRef::npos && Split > 1)
- // Do not split at 0.
- return Split - 1;
- return StringRef::npos;
- }
-
- StringRef::size_type
- getStartOfCharacter(StringRef Text, StringRef::size_type Offset) {
- StringRef::size_type NextEscape = Text.find('\\');
- while (NextEscape != StringRef::npos && NextEscape < Offset) {
- StringRef::size_type SequenceLength =
- getEscapeSequenceLength(Text.substr(NextEscape));
- if (Offset < NextEscape + SequenceLength)
- return NextEscape;
- NextEscape = Text.find('\\', NextEscape + SequenceLength);
- }
- return Offset;
- }
-
- unsigned getEscapeSequenceLength(StringRef Text) {
- assert(Text[0] == '\\');
- if (Text.size() < 2)
- return 1;
-
- switch (Text[1]) {
- case 'u':
- return 6;
- case 'U':
- return 10;
- case 'x':
- return getHexLength(Text);
- default:
- if (Text[1] >= '0' && Text[1] <= '7')
- return getOctalLength(Text);
- return 2;
- }
- }
-
- unsigned getHexLength(StringRef Text) {
- unsigned I = 2; // Point after '\x'.
- while (I < Text.size() && ((Text[I] >= '0' && Text[I] <= '9') ||
- (Text[I] >= 'a' && Text[I] <= 'f') ||
- (Text[I] >= 'A' && Text[I] <= 'F'))) {
- ++I;
- }
- return I;
- }
-
- unsigned getOctalLength(StringRef Text) {
- unsigned I = 1;
- while (I < Text.size() && I < 4 && (Text[I] >= '0' && Text[I] <= '7')) {
- ++I;
- }
- return I;
- }
-
unsigned getColumnLimit() {
- return calculateColumnLimit(Style, Line.InPPDirective);
+ // In preprocessor directives reserve two chars for trailing " \"
+ return Style.ColumnLimit - (Line.InPPDirective ? 2 : 0);
}
/// \brief An edge in the solution space from \c Previous->State to \c State,
@@ -1194,12 +829,7 @@ private:
!(State.NextToken->is(tok::r_brace) &&
State.Stack.back().BreakBeforeClosingBrace))
return false;
- // Trying to insert a parameter on a new line if there are already more than
- // one parameter on the current line is bin packing.
- if (State.Stack.back().HasMultiParameterLine &&
- State.Stack.back().AvoidBinPacking)
- return false;
- return true;
+ return !State.Stack.back().NoLineBreak;
}
/// \brief Returns \c true, if a line break after \p State is mandatory.
@@ -1216,7 +846,7 @@ private:
State.NextToken->is(tok::question) ||
State.NextToken->Type == TT_ConditionalExpr) &&
State.Stack.back().BreakBeforeParameter &&
- !isTrailingComment(*State.NextToken) &&
+ !State.NextToken->isTrailingComment() &&
State.NextToken->isNot(tok::r_paren) &&
State.NextToken->isNot(tok::r_brace))
return true;
@@ -1310,6 +940,11 @@ public:
// Now FormatTok is the next non-whitespace token.
FormatTok.TokenLength = Text.size();
+ if (FormatTok.Tok.is(tok::comment)) {
+ FormatTok.TrailingWhiteSpaceLength = Text.size() - Text.rtrim().size();
+ FormatTok.TokenLength -= FormatTok.TrailingWhiteSpaceLength;
+ }
+
// In case the token starts with escaped newlines, we want to
// take them into account as whitespace - this pattern is quite frequent
// in macro definitions.
@@ -1336,11 +971,6 @@ public:
GreaterStashed = true;
}
- // If we reformat comments, we remove trailing whitespace. Update the length
- // accordingly.
- if (FormatTok.Tok.is(tok::comment))
- FormatTok.TokenLength = Text.rtrim().size();
-
return FormatTok;
}
@@ -1373,7 +1003,7 @@ public:
tooling::Replacements format() {
LexerBasedFormatTokenSource Tokens(Lex, SourceMgr);
UnwrappedLineParser Parser(Diag, Style, Tokens, *this);
- StructuralError = Parser.parse();
+ bool StructuralError = Parser.parse();
unsigned PreviousEndOfLineColumn = 0;
TokenAnnotator Annotator(Style, SourceMgr, Lex,
Tokens.getIdentTable().get("in"));
@@ -1383,14 +1013,21 @@ public:
deriveLocalStyle();
for (unsigned i = 0, e = AnnotatedLines.size(); i != e; ++i) {
Annotator.calculateFormattingInformation(AnnotatedLines[i]);
+ }
- // Adapt level to the next line if this is a comment.
- // FIXME: Can/should this be done in the UnwrappedLineParser?
- if (i + 1 != e && AnnotatedLines[i].First.is(tok::comment) &&
- AnnotatedLines[i].First.Children.empty() &&
- AnnotatedLines[i + 1].First.isNot(tok::r_brace))
- AnnotatedLines[i].Level = AnnotatedLines[i + 1].Level;
+ // Adapt level to the next line if this is a comment.
+ // FIXME: Can/should this be done in the UnwrappedLineParser?
+ const AnnotatedLine *NextNoneCommentLine = NULL;
+ for (unsigned i = AnnotatedLines.size() - 1; i > 0; --i) {
+ if (NextNoneCommentLine && AnnotatedLines[i].First.is(tok::comment) &&
+ AnnotatedLines[i].First.Children.empty())
+ AnnotatedLines[i].Level = NextNoneCommentLine->Level;
+ else
+ NextNoneCommentLine =
+ AnnotatedLines[i].First.isNot(tok::r_brace) ? &AnnotatedLines[i]
+ : NULL;
}
+
std::vector<int> IndentForLevel;
bool PreviousLineWasTouched = false;
const AnnotatedToken *PreviousLineLastToken = 0;
@@ -1416,17 +1053,19 @@ public:
unsigned Indent = LevelIndent;
if (static_cast<int>(Indent) + Offset >= 0)
Indent += Offset;
- if (!FirstTok.WhiteSpaceStart.isValid() || StructuralError) {
- Indent = LevelIndent =
- SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
- } else {
+ if (FirstTok.WhiteSpaceStart.isValid() &&
+ // Insert a break even if there is a structural error in case where
+ // we break apart a line consisting of multiple unwrapped lines.
+ (FirstTok.NewlinesBefore == 0 || !StructuralError)) {
formatFirstToken(TheLine.First, PreviousLineLastToken, Indent,
TheLine.InPPDirective, PreviousEndOfLineColumn);
+ } else {
+ Indent = LevelIndent =
+ SourceMgr.getSpellingColumnNumber(FirstTok.Tok.getLocation()) - 1;
}
tryFitMultipleLinesInOne(Indent, I, E);
UnwrappedLineFormatter Formatter(Style, SourceMgr, TheLine, Indent,
- TheLine.First, Whitespaces,
- StructuralError);
+ TheLine.First, Whitespaces);
PreviousEndOfLineColumn =
Formatter.format(I + 1 != E ? &*(I + 1) : NULL);
IndentForLevel[TheLine.Level] = LevelIndent;
@@ -1457,6 +1096,8 @@ public:
if (TheLine.Last->is(tok::comment))
Whitespaces.addUntouchableComment(SourceMgr.getSpellingColumnNumber(
TheLine.Last->FormatTok.Tok.getLocation()) - 1);
+ else
+ Whitespaces.alignComments();
}
PreviousLineLastToken = I->Last;
}
@@ -1727,12 +1368,12 @@ private:
WhitespaceManager Whitespaces;
std::vector<CharSourceRange> Ranges;
std::vector<AnnotatedLine> AnnotatedLines;
- bool StructuralError;
};
-tooling::Replacements
-reformat(const FormatStyle &Style, Lexer &Lex, SourceManager &SourceMgr,
- std::vector<CharSourceRange> Ranges, DiagnosticConsumer *DiagClient) {
+tooling::Replacements reformat(const FormatStyle &Style, Lexer &Lex,
+ SourceManager &SourceMgr,
+ std::vector<CharSourceRange> Ranges,
+ DiagnosticConsumer *DiagClient) {
IntrusiveRefCntPtr<DiagnosticOptions> DiagOpts = new DiagnosticOptions();
OwningPtr<DiagnosticConsumer> DiagPrinter;
if (DiagClient == 0) {
diff --git a/lib/Format/TokenAnnotator.cpp b/lib/Format/TokenAnnotator.cpp
index 427157e3322d..17abb01d181d 100644
--- a/lib/Format/TokenAnnotator.cpp
+++ b/lib/Format/TokenAnnotator.cpp
@@ -16,12 +16,13 @@
#include "TokenAnnotator.h"
#include "clang/Basic/SourceManager.h"
#include "clang/Lex/Lexer.h"
+#include "llvm/Support/Debug.h"
namespace clang {
namespace format {
-static bool isUnaryOperator(const AnnotatedToken &Tok) {
- switch (Tok.FormatTok.Tok.getKind()) {
+bool AnnotatedToken::isUnaryOperator() const {
+ switch (FormatTok.Tok.getKind()) {
case tok::plus:
case tok::plusplus:
case tok::minus:
@@ -36,49 +37,38 @@ static bool isUnaryOperator(const AnnotatedToken &Tok) {
}
}
-static bool isBinaryOperator(const AnnotatedToken &Tok) {
+bool AnnotatedToken::isBinaryOperator() const {
// Comma is a binary operator, but does not behave as such wrt. formatting.
- return getPrecedence(Tok) > prec::Comma;
+ return getPrecedence(*this) > prec::Comma;
}
-// Returns the previous token ignoring comments.
-static AnnotatedToken *getPreviousToken(AnnotatedToken &Tok) {
- AnnotatedToken *PrevToken = Tok.Parent;
- while (PrevToken != NULL && PrevToken->is(tok::comment))
- PrevToken = PrevToken->Parent;
- return PrevToken;
-}
-static const AnnotatedToken *getPreviousToken(const AnnotatedToken &Tok) {
- return getPreviousToken(const_cast<AnnotatedToken &>(Tok));
+bool AnnotatedToken::isTrailingComment() const {
+ return is(tok::comment) &&
+ (Children.empty() || Children[0].FormatTok.NewlinesBefore > 0);
}
-static bool isTrailingComment(AnnotatedToken *Tok) {
- return Tok != NULL && Tok->is(tok::comment) &&
- (Tok->Children.empty() ||
- Tok->Children[0].FormatTok.NewlinesBefore > 0);
+AnnotatedToken *AnnotatedToken::getPreviousNoneComment() const {
+ AnnotatedToken *Tok = Parent;
+ while (Tok != NULL && Tok->is(tok::comment))
+ Tok = Tok->Parent;
+ return Tok;
}
-// Returns the next token ignoring comments.
-static const AnnotatedToken *getNextToken(const AnnotatedToken &Tok) {
- if (Tok.Children.empty())
- return NULL;
- const AnnotatedToken *NextToken = &Tok.Children[0];
- while (NextToken->is(tok::comment)) {
- if (NextToken->Children.empty())
- return NULL;
- NextToken = &NextToken->Children[0];
- }
- return NextToken;
+const AnnotatedToken *AnnotatedToken::getNextNoneComment() const {
+ const AnnotatedToken *Tok = Children.empty() ? NULL : &Children[0];
+ while (Tok != NULL && Tok->is(tok::comment))
+ Tok = Tok->Children.empty() ? NULL : &Tok->Children[0];
+ return Tok;
}
-static bool closesScope(const AnnotatedToken &Tok) {
- return Tok.isOneOf(tok::r_paren, tok::r_brace, tok::r_square) ||
- Tok.Type == TT_TemplateCloser;
+bool AnnotatedToken::closesScope() const {
+ return isOneOf(tok::r_paren, tok::r_brace, tok::r_square) ||
+ Type == TT_TemplateCloser;
}
-static bool opensScope(const AnnotatedToken &Tok) {
- return Tok.isOneOf(tok::l_paren, tok::l_brace, tok::l_square) ||
- Tok.Type == TT_TemplateOpener;
+bool AnnotatedToken::opensScope() const {
+ return isOneOf(tok::l_paren, tok::l_brace, tok::l_square) ||
+ Type == TT_TemplateOpener;
}
/// \brief A parser that gathers additional information about tokens.
@@ -91,7 +81,7 @@ public:
AnnotatingParser(SourceManager &SourceMgr, Lexer &Lex, AnnotatedLine &Line,
IdentifierInfo &Ident_in)
: SourceMgr(SourceMgr), Lex(Lex), Line(Line), CurrentToken(&Line.First),
- KeywordVirtualFound(false), Ident_in(Ident_in) {
+ KeywordVirtualFound(false), NameFound(false), Ident_in(Ident_in) {
Contexts.push_back(Context(tok::unknown, 1, /*IsExpression=*/ false));
}
@@ -165,6 +155,8 @@ private:
}
if (CurrentToken->is(tok::r_paren)) {
+ if (CurrentToken->Parent->closesScope())
+ CurrentToken->Parent->MatchingParen->NoMoreTokensOnLevel = true;
Left->MatchingParen = CurrentToken;
CurrentToken->MatchingParen = Left;
@@ -196,12 +188,12 @@ private:
// ')' or ']'), it could be the start of an Objective-C method
// expression, or it could the the start of an Objective-C array literal.
AnnotatedToken *Left = CurrentToken->Parent;
- AnnotatedToken *Parent = getPreviousToken(*Left);
+ AnnotatedToken *Parent = Left->getPreviousNoneComment();
bool StartsObjCMethodExpr =
Contexts.back().CanBeExpression &&
(!Parent || Parent->isOneOf(tok::colon, tok::l_square, tok::l_paren,
tok::kw_return, tok::kw_throw) ||
- isUnaryOperator(*Parent) || Parent->Type == TT_ObjCForIn ||
+ Parent->isUnaryOperator() || Parent->Type == TT_ObjCForIn ||
Parent->Type == TT_CastRParen ||
getBinOpPrecedence(Parent->FormatTok.Tok.getKind(), true, true) >
prec::Unknown);
@@ -253,24 +245,25 @@ private:
}
bool parseBrace() {
- // Lines are fine to end with '{'.
- if (CurrentToken == NULL)
- return true;
- ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
- AnnotatedToken *Left = CurrentToken->Parent;
- while (CurrentToken != NULL) {
- if (CurrentToken->is(tok::r_brace)) {
- Left->MatchingParen = CurrentToken;
- CurrentToken->MatchingParen = Left;
- next();
- return true;
+ if (CurrentToken != NULL) {
+ ScopedContextCreator ContextCreator(*this, tok::l_brace, 1);
+ AnnotatedToken *Left = CurrentToken->Parent;
+ while (CurrentToken != NULL) {
+ if (CurrentToken->is(tok::r_brace)) {
+ Left->MatchingParen = CurrentToken;
+ CurrentToken->MatchingParen = Left;
+ next();
+ return true;
+ }
+ if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
+ return false;
+ updateParameterCount(Left, CurrentToken);
+ if (!consumeToken())
+ return false;
}
- if (CurrentToken->isOneOf(tok::r_paren, tok::r_square))
- return false;
- updateParameterCount(Left, CurrentToken);
- if (!consumeToken())
- return false;
}
+ // No closing "}" found, this probably starts a definition.
+ Line.StartsDefinition = true;
return true;
}
@@ -357,7 +350,7 @@ private:
case tok::l_paren:
if (!parseParens())
return false;
- if (Line.MustBeDeclaration)
+ if (Line.MustBeDeclaration && NameFound && !Contexts.back().IsExpression)
Line.MightBeFunctionDecl = true;
break;
case tok::l_square:
@@ -467,6 +460,10 @@ private:
case tok::pp_warning:
parseWarningOrError();
break;
+ case tok::pp_if:
+ case tok::pp_elif:
+ parseLine();
+ break;
default:
break;
}
@@ -573,7 +570,8 @@ private:
};
void determineTokenType(AnnotatedToken &Current) {
- if (getPrecedence(Current) == prec::Assignment) {
+ if (getPrecedence(Current) == prec::Assignment &&
+ (!Current.Parent || Current.Parent->isNot(tok::kw_operator))) {
Contexts.back().IsExpression = true;
for (AnnotatedToken *Previous = Current.Parent;
Previous && Previous->isNot(tok::comma);
@@ -599,6 +597,9 @@ private:
Contexts.back().IsExpression = true;
} else if (Current.is(tok::kw_new)) {
Contexts.back().CanBeExpression = false;
+ } else if (Current.is(tok::semi)) {
+ // This should be the condition or increment in a for-loop.
+ Contexts.back().IsExpression = true;
}
if (Current.Type == TT_Unknown) {
@@ -611,6 +612,7 @@ private:
Current.Parent->Type == TT_TemplateCloser)) {
Contexts.back().FirstStartOfName = &Current;
Current.Type = TT_StartOfName;
+ NameFound = true;
} else if (Current.isOneOf(tok::star, tok::amp, tok::ampamp)) {
Current.Type =
determineStarAmpUsage(Current, Contexts.back().IsExpression);
@@ -620,7 +622,7 @@ private:
Current.Type = determineIncrementUsage(Current);
} else if (Current.is(tok::exclaim)) {
Current.Type = TT_UnaryOperator;
- } else if (isBinaryOperator(Current)) {
+ } else if (Current.isBinaryOperator()) {
Current.Type = TT_BinaryOperator;
} else if (Current.is(tok::comment)) {
std::string Data(Lexer::getSpelling(Current.FormatTok.Tok, SourceMgr,
@@ -664,11 +666,11 @@ private:
/// \brief Return the type of the given token assuming it is * or &.
TokenType
determineStarAmpUsage(const AnnotatedToken &Tok, bool IsExpression) {
- const AnnotatedToken *PrevToken = getPreviousToken(Tok);
+ const AnnotatedToken *PrevToken = Tok.getPreviousNoneComment();
if (PrevToken == NULL)
return TT_UnaryOperator;
- const AnnotatedToken *NextToken = getNextToken(Tok);
+ const AnnotatedToken *NextToken = Tok.getNextNoneComment();
if (NextToken == NULL)
return TT_Unknown;
@@ -687,7 +689,7 @@ private:
if (PrevToken->FormatTok.Tok.isLiteral() ||
PrevToken->isOneOf(tok::r_paren, tok::r_square) ||
- NextToken->FormatTok.Tok.isLiteral() || isUnaryOperator(*NextToken))
+ NextToken->FormatTok.Tok.isLiteral() || NextToken->isUnaryOperator())
return TT_BinaryOperator;
// It is very unlikely that we are going to find a pointer or reference type
@@ -699,7 +701,7 @@ private:
}
TokenType determinePlusMinusCaretUsage(const AnnotatedToken &Tok) {
- const AnnotatedToken *PrevToken = getPreviousToken(Tok);
+ const AnnotatedToken *PrevToken = Tok.getPreviousNoneComment();
if (PrevToken == NULL)
return TT_UnaryOperator;
@@ -719,7 +721,7 @@ private:
/// \brief Determine whether ++/-- are pre- or post-increments/-decrements.
TokenType determineIncrementUsage(const AnnotatedToken &Tok) {
- const AnnotatedToken *PrevToken = getPreviousToken(Tok);
+ const AnnotatedToken *PrevToken = Tok.getPreviousNoneComment();
if (PrevToken == NULL)
return TT_UnaryOperator;
if (PrevToken->isOneOf(tok::r_paren, tok::r_square, tok::identifier))
@@ -768,6 +770,7 @@ private:
AnnotatedLine &Line;
AnnotatedToken *CurrentToken;
bool KeywordVirtualFound;
+ bool NameFound;
IdentifierInfo &Ident_in;
};
@@ -782,12 +785,8 @@ public:
if (Precedence > prec::PointerToMember || Current == NULL)
return;
- // Skip over "return" until we can properly parse it.
- if (Current->is(tok::kw_return))
- next();
-
// Eagerly consume trailing comments.
- while (isTrailingComment(Current)) {
+ while (Current && Current->isTrailingComment()) {
next();
}
@@ -796,14 +795,13 @@ public:
while (Current) {
// Consume operators with higher precedence.
- parse(prec::Level(Precedence + 1));
+ parse(Precedence + 1);
int CurrentPrecedence = 0;
if (Current) {
if (Current->Type == TT_ConditionalExpr)
CurrentPrecedence = 1 + (int) prec::Conditional;
- else if (Current->is(tok::semi) || Current->Type == TT_InlineASMColon ||
- Current->Type == TT_CtorInitializerColon)
+ else if (Current->is(tok::semi) || Current->Type == TT_InlineASMColon)
CurrentPrecedence = 1;
else if (Current->Type == TT_BinaryOperator || Current->is(tok::comma))
CurrentPrecedence = 1 + (int) getPrecedence(*Current);
@@ -811,10 +809,10 @@ public:
// At the end of the line or when an operator with higher precedence is
// found, insert fake parenthesis and return.
- if (Current == NULL || closesScope(*Current) ||
+ if (Current == NULL || Current->closesScope() ||
(CurrentPrecedence != 0 && CurrentPrecedence < Precedence)) {
if (OperatorFound) {
- ++Start->FakeLParens;
+ Start->FakeLParens.push_back(prec::Level(Precedence - 1));
if (Current)
++Current->Parent->FakeRParens;
}
@@ -822,18 +820,11 @@ public:
}
// Consume scopes: (), [], <> and {}
- if (opensScope(*Current)) {
- AnnotatedToken *Left = Current;
- while (Current && !closesScope(*Current)) {
+ if (Current->opensScope()) {
+ while (Current && !Current->closesScope()) {
next();
parse();
}
- // Remove fake parens that just duplicate the real parens.
- if (Current && Left->Children[0].FakeLParens > 0 &&
- Current->Parent->FakeRParens > 0) {
- --Left->Children[0].FakeLParens;
- --Current->Parent->FakeRParens;
- }
next();
} else {
// Operator found.
@@ -892,7 +883,7 @@ void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
Current->MustBreakBefore = true;
} else if (Current->Type == TT_LineComment) {
Current->MustBreakBefore = Current->FormatTok.NewlinesBefore > 0;
- } else if (isTrailingComment(Current->Parent) ||
+ } else if (Current->Parent->isTrailingComment() ||
(Current->is(tok::string_literal) &&
Current->Parent->is(tok::string_literal))) {
Current->MustBreakBefore = true;
@@ -919,6 +910,10 @@ void TokenAnnotator::calculateFormattingInformation(AnnotatedLine &Line) {
Current = Current->Children.empty() ? NULL : &Current->Children[0];
}
+
+ DEBUG({
+ printDebugInfo(Line);
+ });
}
unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
@@ -933,12 +928,14 @@ unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
// FIXME: Clean up hack of using BindingStrength to find top-level names.
return Style.PenaltyReturnTypeOnItsOwnLine;
else
- return 100;
+ return 200;
}
if (Left.is(tok::equal) && Right.is(tok::l_brace))
return 150;
if (Left.is(tok::coloncolon))
return 500;
+ if (Left.isOneOf(tok::kw_class, tok::kw_struct))
+ return 5000;
if (Left.Type == TT_RangeBasedForLoopColon ||
Left.Type == TT_InheritanceColon)
@@ -969,7 +966,9 @@ unsigned TokenAnnotator::splitPenalty(const AnnotatedLine &Line,
if (Left.is(tok::colon) && Left.Type == TT_ObjCMethodExpr)
return 20;
- if (opensScope(Left))
+ if (Left.is(tok::l_paren) && Line.MightBeFunctionDecl)
+ return 100;
+ if (Left.opensScope())
return Left.ParameterCount > 1 ? prec::Comma : 20;
if (Right.is(tok::lessless)) {
@@ -1050,13 +1049,15 @@ bool TokenAnnotator::spaceRequiredBetween(const AnnotatedLine &Line,
return Line.Type == LT_ObjCDecl ||
Left.isOneOf(tok::kw_if, tok::kw_for, tok::kw_while, tok::kw_switch,
tok::kw_return, tok::kw_catch, tok::kw_new,
- tok::kw_delete);
+ tok::kw_delete, tok::semi);
}
if (Left.is(tok::at) &&
Right.FormatTok.Tok.getObjCKeywordID() != tok::objc_not_keyword)
return false;
if (Left.is(tok::l_brace) && Right.is(tok::r_brace))
return false;
+ if (Right.is(tok::ellipsis))
+ return false;
return true;
}
@@ -1088,7 +1089,7 @@ bool TokenAnnotator::spaceRequiredBefore(const AnnotatedLine &Line,
return false;
if (Tok.is(tok::colon))
return !Line.First.isOneOf(tok::kw_case, tok::kw_default) &&
- !Tok.Children.empty() && Tok.Type != TT_ObjCMethodExpr;
+ Tok.getNextNoneComment() != NULL && Tok.Type != TT_ObjCMethodExpr;
if (Tok.is(tok::l_paren) && !Tok.Children.empty() &&
Tok.Children[0].Type == TT_PointerOrReference &&
!Tok.Children[0].Children.empty() &&
@@ -1137,10 +1138,9 @@ bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
if (Right.Type == TT_ConditionalExpr || Right.is(tok::question))
return true;
if (Right.Type == TT_RangeBasedForLoopColon ||
- Right.Type == TT_InheritanceColon)
+ Right.Type == TT_OverloadedOperatorLParen)
return false;
- if (Left.Type == TT_RangeBasedForLoopColon ||
- Left.Type == TT_InheritanceColon)
+ if (Left.Type == TT_RangeBasedForLoopColon)
return true;
if (Right.Type == TT_RangeBasedForLoopColon)
return false;
@@ -1174,8 +1174,9 @@ bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
return false;
if (Left.is(tok::identifier) && Right.is(tok::string_literal))
return true;
- return (isBinaryOperator(Left) && Left.isNot(tok::lessless)) ||
- Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace) ||
+ return (Left.isBinaryOperator() && Left.isNot(tok::lessless)) ||
+ Left.isOneOf(tok::comma, tok::coloncolon, tok::semi, tok::l_brace,
+ tok::kw_class, tok::kw_struct) ||
Right.isOneOf(tok::lessless, tok::arrow, tok::period, tok::colon) ||
(Left.is(tok::r_paren) && Left.Type != TT_CastRParen &&
Right.isOneOf(tok::identifier, tok::kw___attribute)) ||
@@ -1183,5 +1184,22 @@ bool TokenAnnotator::canBreakBefore(const AnnotatedLine &Line,
(Left.is(tok::l_square) && !Right.is(tok::r_square));
}
+void TokenAnnotator::printDebugInfo(const AnnotatedLine &Line) {
+ llvm::errs() << "AnnotatedTokens:\n";
+ const AnnotatedToken *Tok = &Line.First;
+ while (Tok) {
+ llvm::errs() << " M=" << Tok->MustBreakBefore
+ << " C=" << Tok->CanBreakBefore << " T=" << Tok->Type
+ << " S=" << Tok->SpacesRequiredBefore
+ << " P=" << Tok->SplitPenalty
+ << " Name=" << Tok->FormatTok.Tok.getName() << " FakeLParens=";
+ for (unsigned i = 0, e = Tok->FakeLParens.size(); i != e; ++i)
+ llvm::errs() << Tok->FakeLParens[i] << "/";
+ llvm::errs() << " FakeRParens=" << Tok->FakeRParens << "\n";
+ Tok = Tok->Children.empty() ? NULL : &Tok->Children[0];
+ }
+ llvm::errs() << "----\n";
+}
+
} // namespace format
} // namespace clang
diff --git a/lib/Format/TokenAnnotator.h b/lib/Format/TokenAnnotator.h
index c41ee33c439b..b364082391f8 100644
--- a/lib/Format/TokenAnnotator.h
+++ b/lib/Format/TokenAnnotator.h
@@ -75,9 +75,9 @@ public:
CanBreakBefore(false), MustBreakBefore(false),
ClosesTemplateDeclaration(false), MatchingParen(NULL),
ParameterCount(0), BindingStrength(0), SplitPenalty(0),
- LongestObjCSelectorName(0), Parent(NULL), FakeLParens(0),
+ LongestObjCSelectorName(0), Parent(NULL),
FakeRParens(0), LastInChainOfCalls(false),
- PartOfMultiVariableDeclStmt(false) {}
+ PartOfMultiVariableDeclStmt(false), NoMoreTokensOnLevel(false) {}
bool is(tok::TokenKind Kind) const { return FormatTok.Tok.is(Kind); }
@@ -121,6 +121,15 @@ public:
Children[0].isObjCAtKeyword(tok::objc_private));
}
+ /// \brief Returns whether \p Tok is ([{ or a template opening <.
+ bool opensScope() const;
+ /// \brief Returns whether \p Tok is )]} or a template opening >.
+ bool closesScope() const;
+
+ bool isUnaryOperator() const;
+ bool isBinaryOperator() const;
+ bool isTrailingComment() const;
+
FormatToken FormatTok;
TokenType Type;
@@ -158,8 +167,12 @@ public:
std::vector<AnnotatedToken> Children;
AnnotatedToken *Parent;
- /// \brief Insert this many fake ( before this token for correct indentation.
- unsigned FakeLParens;
+ /// \brief Stores the number of required fake parentheses and the
+ /// corresponding operator precedence.
+ ///
+ /// If multiple fake parentheses start at a token, this vector stores them in
+ /// reverse order, i.e. inner fake parenthesis first.
+ SmallVector<prec::Level, 4> FakeLParens;
/// \brief Insert this many fake ) after this token for correct indentation.
unsigned FakeRParens;
@@ -171,12 +184,24 @@ public:
/// Only set if \c Type == \c TT_StartOfName.
bool PartOfMultiVariableDeclStmt;
- const AnnotatedToken *getPreviousNoneComment() const {
- AnnotatedToken *Tok = Parent;
- while (Tok != NULL && Tok->is(tok::comment))
- Tok = Tok->Parent;
- return Tok;
- }
+ /// \brief Set to \c true for "("-tokens if this is the last token other than
+ /// ")" in the next higher parenthesis level.
+ ///
+ /// If this is \c true, no more formatting decisions have to be made on the
+ /// next higher parenthesis level, enabling optimizations.
+ ///
+ /// Example:
+ /// \code
+ /// aaaaaa(aaaaaa());
+ /// ^ // Set to true for this parenthesis.
+ /// \endcode
+ bool NoMoreTokensOnLevel;
+
+ /// \brief Returns the previous token ignoring comments.
+ AnnotatedToken *getPreviousNoneComment() const;
+
+ /// \brief Returns the next token ignoring comments.
+ const AnnotatedToken *getNextNoneComment() const;
};
class AnnotatedLine {
@@ -184,8 +209,8 @@ public:
AnnotatedLine(const UnwrappedLine &Line)
: First(Line.Tokens.front()), Level(Line.Level),
InPPDirective(Line.InPPDirective),
- MustBeDeclaration(Line.MustBeDeclaration),
- MightBeFunctionDecl(false) {
+ MustBeDeclaration(Line.MustBeDeclaration), MightBeFunctionDecl(false),
+ StartsDefinition(false) {
assert(!Line.Tokens.empty());
AnnotatedToken *Current = &First;
for (std::list<FormatToken>::const_iterator I = ++Line.Tokens.begin(),
@@ -201,7 +226,8 @@ public:
: First(Other.First), Type(Other.Type), Level(Other.Level),
InPPDirective(Other.InPPDirective),
MustBeDeclaration(Other.MustBeDeclaration),
- MightBeFunctionDecl(Other.MightBeFunctionDecl) {
+ MightBeFunctionDecl(Other.MightBeFunctionDecl),
+ StartsDefinition(Other.StartsDefinition) {
Last = &First;
while (!Last->Children.empty()) {
Last->Children[0].Parent = Last;
@@ -217,6 +243,7 @@ public:
bool InPPDirective;
bool MustBeDeclaration;
bool MightBeFunctionDecl;
+ bool StartsDefinition;
};
inline prec::Level getPrecedence(const AnnotatedToken &Tok) {
@@ -248,6 +275,8 @@ private:
bool canBreakBefore(const AnnotatedLine &Line, const AnnotatedToken &Right);
+ void printDebugInfo(const AnnotatedLine &Line);
+
const FormatStyle &Style;
SourceManager &SourceMgr;
Lexer &Lex;
diff --git a/lib/Format/UnwrappedLineParser.cpp b/lib/Format/UnwrappedLineParser.cpp
index 89a391bd1928..722af5d2b763 100644
--- a/lib/Format/UnwrappedLineParser.cpp
+++ b/lib/Format/UnwrappedLineParser.cpp
@@ -45,9 +45,11 @@ private:
class ScopedMacroState : public FormatTokenSource {
public:
ScopedMacroState(UnwrappedLine &Line, FormatTokenSource *&TokenSource,
- FormatToken &ResetToken)
+ FormatToken &ResetToken, bool &StructuralError)
: Line(Line), TokenSource(TokenSource), ResetToken(ResetToken),
- PreviousLineLevel(Line.Level), PreviousTokenSource(TokenSource) {
+ PreviousLineLevel(Line.Level), PreviousTokenSource(TokenSource),
+ StructuralError(StructuralError),
+ PreviousStructuralError(StructuralError) {
TokenSource = this;
Line.Level = 0;
Line.InPPDirective = true;
@@ -58,6 +60,7 @@ public:
ResetToken = Token;
Line.InPPDirective = false;
Line.Level = PreviousLineLevel;
+ StructuralError = PreviousStructuralError;
}
virtual FormatToken getNextToken() {
@@ -71,7 +74,7 @@ public:
}
private:
- bool eof() { return Token.NewlinesBefore > 0 && Token.HasUnescapedNewline; }
+ bool eof() { return Token.HasUnescapedNewline; }
FormatToken createEOF() {
FormatToken FormatTok;
@@ -85,6 +88,8 @@ private:
FormatToken &ResetToken;
unsigned PreviousLineLevel;
FormatTokenSource *PreviousTokenSource;
+ bool &StructuralError;
+ bool PreviousStructuralError;
FormatToken Token;
};
@@ -124,13 +129,13 @@ UnwrappedLineParser::UnwrappedLineParser(
clang::DiagnosticsEngine &Diag, const FormatStyle &Style,
FormatTokenSource &Tokens, UnwrappedLineConsumer &Callback)
: Line(new UnwrappedLine), MustBreakBeforeNextToken(false),
- CurrentLines(&Lines), Diag(Diag), Style(Style), Tokens(&Tokens),
- Callback(Callback) {}
+ CurrentLines(&Lines), StructuralError(false), Diag(Diag), Style(Style),
+ Tokens(&Tokens), Callback(Callback) {}
bool UnwrappedLineParser::parse() {
DEBUG(llvm::dbgs() << "----\n");
readToken();
- bool Error = parseFile();
+ parseFile();
for (std::vector<UnwrappedLine>::iterator I = Lines.begin(), E = Lines.end();
I != E; ++I) {
Callback.consumeUnwrappedLine(*I);
@@ -139,23 +144,20 @@ bool UnwrappedLineParser::parse() {
// Create line with eof token.
pushToken(FormatTok);
Callback.consumeUnwrappedLine(*Line);
-
- return Error;
+ return StructuralError;
}
-bool UnwrappedLineParser::parseFile() {
+void UnwrappedLineParser::parseFile() {
ScopedDeclarationState DeclarationState(
*Line, DeclarationScopeStack,
/*MustBeDeclaration=*/ !Line->InPPDirective);
- bool Error = parseLevel(/*HasOpeningBrace=*/ false);
+ parseLevel(/*HasOpeningBrace=*/ false);
// Make sure to format the remaining tokens.
flushComments(true);
addUnwrappedLine();
- return Error;
}
-bool UnwrappedLineParser::parseLevel(bool HasOpeningBrace) {
- bool Error = false;
+void UnwrappedLineParser::parseLevel(bool HasOpeningBrace) {
do {
switch (FormatTok.Tok.getKind()) {
case tok::comment:
@@ -165,30 +167,27 @@ bool UnwrappedLineParser::parseLevel(bool HasOpeningBrace) {
case tok::l_brace:
// FIXME: Add parameter whether this can happen - if this happens, we must
// be in a non-declaration context.
- Error |= parseBlock(/*MustBeDeclaration=*/ false);
+ parseBlock(/*MustBeDeclaration=*/ false);
addUnwrappedLine();
break;
case tok::r_brace:
- if (HasOpeningBrace) {
- return false;
- } else {
- Diag.Report(FormatTok.Tok.getLocation(),
- Diag.getCustomDiagID(clang::DiagnosticsEngine::Error,
- "unexpected '}'"));
- Error = true;
- nextToken();
- addUnwrappedLine();
- }
+ if (HasOpeningBrace)
+ return;
+ Diag.Report(FormatTok.Tok.getLocation(),
+ Diag.getCustomDiagID(clang::DiagnosticsEngine::Error,
+ "unexpected '}'"));
+ StructuralError = true;
+ nextToken();
+ addUnwrappedLine();
break;
default:
parseStructuralElement();
break;
}
} while (!eof());
- return Error;
}
-bool UnwrappedLineParser::parseBlock(bool MustBeDeclaration,
+void UnwrappedLineParser::parseBlock(bool MustBeDeclaration,
unsigned AddLevels) {
assert(FormatTok.Tok.is(tok::l_brace) && "'{' expected");
nextToken();
@@ -202,17 +201,17 @@ bool UnwrappedLineParser::parseBlock(bool MustBeDeclaration,
if (!FormatTok.Tok.is(tok::r_brace)) {
Line->Level -= AddLevels;
- return true;
+ StructuralError = true;
+ return;
}
nextToken(); // Munch the closing brace.
Line->Level -= AddLevels;
- return false;
}
void UnwrappedLineParser::parsePPDirective() {
assert(FormatTok.Tok.is(tok::hash) && "'#' expected");
- ScopedMacroState MacroState(*Line, Tokens, FormatTok);
+ ScopedMacroState MacroState(*Line, Tokens, FormatTok, StructuralError);
nextToken();
if (FormatTok.Tok.getIdentifierInfo() == NULL) {
@@ -260,9 +259,35 @@ void UnwrappedLineParser::parsePPUnknown() {
addUnwrappedLine();
}
+// Here we blacklist certain tokens that are not usually the first token in an
+// unwrapped line. This is used in attempt to distinguish macro calls without
+// trailing semicolons from other constructs split to several lines.
+bool tokenCanStartNewLine(clang::Token Tok) {
+ // Semicolon can be a null-statement, l_square can be a start of a macro or
+ // a C++11 attribute, but this doesn't seem to be common.
+ return Tok.isNot(tok::semi) && Tok.isNot(tok::l_brace) &&
+ Tok.isNot(tok::l_square) &&
+ // Tokens that can only be used as binary operators and a part of
+ // overloaded operator names.
+ Tok.isNot(tok::period) && Tok.isNot(tok::periodstar) &&
+ Tok.isNot(tok::arrow) && Tok.isNot(tok::arrowstar) &&
+ Tok.isNot(tok::less) && Tok.isNot(tok::greater) &&
+ Tok.isNot(tok::slash) && Tok.isNot(tok::percent) &&
+ Tok.isNot(tok::lessless) && Tok.isNot(tok::greatergreater) &&
+ Tok.isNot(tok::equal) && Tok.isNot(tok::plusequal) &&
+ Tok.isNot(tok::minusequal) && Tok.isNot(tok::starequal) &&
+ Tok.isNot(tok::slashequal) && Tok.isNot(tok::percentequal) &&
+ Tok.isNot(tok::ampequal) && Tok.isNot(tok::pipeequal) &&
+ Tok.isNot(tok::caretequal) && Tok.isNot(tok::greatergreaterequal) &&
+ Tok.isNot(tok::lesslessequal) &&
+ // Colon is used in labels, base class lists, initializer lists,
+ // range-based for loops, ternary operator, but should never be the
+ // first token in an unwrapped line.
+ Tok.isNot(tok::colon);
+}
+
void UnwrappedLineParser::parseStructuralElement() {
assert(!FormatTok.Tok.is(tok::l_brace));
- int TokenNumber = 0;
switch (FormatTok.Tok.getKind()) {
case tok::at:
nextToken();
@@ -297,7 +322,6 @@ void UnwrappedLineParser::parseStructuralElement() {
return;
case tok::kw_inline:
nextToken();
- TokenNumber++;
if (FormatTok.Tok.is(tok::kw_namespace)) {
parseNamespace();
return;
@@ -347,7 +371,6 @@ void UnwrappedLineParser::parseStructuralElement() {
break;
}
do {
- ++TokenNumber;
switch (FormatTok.Tok.getKind()) {
case tok::at:
nextToken();
@@ -384,9 +407,20 @@ void UnwrappedLineParser::parseStructuralElement() {
return;
case tok::identifier:
nextToken();
- if (TokenNumber == 1 && FormatTok.Tok.is(tok::colon)) {
- parseLabel();
- return;
+ if (Line->Tokens.size() == 1) {
+ if (FormatTok.Tok.is(tok::colon)) {
+ parseLabel();
+ return;
+ }
+ // Recognize function-like macro usages without trailing semicolon.
+ if (FormatTok.Tok.is(tok::l_paren)) {
+ parseParens();
+ if (FormatTok.HasUnescapedNewline &&
+ tokenCanStartNewLine(FormatTok.Tok)) {
+ addUnwrappedLine();
+ return;
+ }
+ }
}
break;
case tok::equal:
@@ -405,16 +439,36 @@ void UnwrappedLineParser::parseStructuralElement() {
void UnwrappedLineParser::parseBracedList() {
nextToken();
+ // FIXME: Once we have an expression parser in the UnwrappedLineParser,
+ // replace this by using parseAssigmentExpression() inside.
+ bool StartOfExpression = true;
do {
+ // FIXME: When we start to support lambdas, we'll want to parse them away
+ // here, otherwise our bail-out scenarios below break. The better solution
+ // might be to just implement a more or less complete expression parser.
switch (FormatTok.Tok.getKind()) {
case tok::l_brace:
+ if (!StartOfExpression) {
+ // Probably a missing closing brace. Bail out.
+ addUnwrappedLine();
+ return;
+ }
parseBracedList();
+ StartOfExpression = false;
break;
case tok::r_brace:
nextToken();
return;
+ case tok::semi:
+ // Probably a missing closing brace. Bail out.
+ return;
+ case tok::comma:
+ nextToken();
+ StartOfExpression = true;
+ break;
default:
nextToken();
+ StartOfExpression = false;
break;
}
} while (!eof());
@@ -427,6 +481,11 @@ void UnwrappedLineParser::parseReturn() {
switch (FormatTok.Tok.getKind()) {
case tok::l_brace:
parseBracedList();
+ if (FormatTok.Tok.isNot(tok::semi)) {
+ // Assume missing ';'.
+ addUnwrappedLine();
+ return;
+ }
break;
case tok::l_paren:
parseParens();
@@ -820,8 +879,7 @@ void UnwrappedLineParser::readToken() {
do {
FormatTok = Tokens->getNextToken();
while (!Line->InPPDirective && FormatTok.Tok.is(tok::hash) &&
- ((FormatTok.NewlinesBefore > 0 && FormatTok.HasUnescapedNewline) ||
- FormatTok.IsFirst)) {
+ (FormatTok.HasUnescapedNewline || FormatTok.IsFirst)) {
// If there is an unfinished unwrapped line, we flush the preprocessor
// directives only after that unwrapped line was finished later.
bool SwitchToPreprocessorLines =
diff --git a/lib/Format/UnwrappedLineParser.h b/lib/Format/UnwrappedLineParser.h
index f4fecc5ef0ac..0c618e24d44e 100644
--- a/lib/Format/UnwrappedLineParser.h
+++ b/lib/Format/UnwrappedLineParser.h
@@ -34,7 +34,7 @@ struct FormatToken {
FormatToken()
: NewlinesBefore(0), HasUnescapedNewline(false), WhiteSpaceLength(0),
LastNewlineOffset(0), TokenLength(0), IsFirst(false),
- MustBreakBefore(false) {}
+ MustBreakBefore(false), TrailingWhiteSpaceLength(0) {}
/// \brief The \c Token.
Token Tok;
@@ -76,6 +76,18 @@ struct FormatToken {
/// This happens for example when a preprocessor directive ended directly
/// before the token.
bool MustBreakBefore;
+
+ /// \brief Number of characters of trailing whitespace.
+ unsigned TrailingWhiteSpaceLength;
+
+ /// \brief Returns actual token start location without leading escaped
+ /// newlines and whitespace.
+ ///
+ /// This can be different to Tok.getLocation(), which includes leading escaped
+ /// newlines.
+ SourceLocation getStartOfNonWhitespace() const {
+ return WhiteSpaceStart.getLocWithOffset(WhiteSpaceLength);
+ }
};
/// \brief An unwrapped line is a sequence of \c Token, that we would like to
@@ -125,9 +137,9 @@ public:
bool parse();
private:
- bool parseFile();
- bool parseLevel(bool HasOpeningBrace);
- bool parseBlock(bool MustBeDeclaration, unsigned AddLevels = 1);
+ void parseFile();
+ void parseLevel(bool HasOpeningBrace);
+ void parseBlock(bool MustBeDeclaration, unsigned AddLevels = 1);
void parsePPDirective();
void parsePPDefine();
void parsePPUnknown();
@@ -187,6 +199,10 @@ private:
// whether we are in a compound statement or not.
std::vector<bool> DeclarationScopeStack;
+ // Will be true if we encounter an error that leads to possibily incorrect
+ // indentation levels.
+ bool StructuralError;
+
clang::DiagnosticsEngine &Diag;
const FormatStyle &Style;
FormatTokenSource *Tokens;
diff --git a/lib/Format/WhitespaceManager.cpp b/lib/Format/WhitespaceManager.cpp
new file mode 100644
index 000000000000..a75c592bfeda
--- /dev/null
+++ b/lib/Format/WhitespaceManager.cpp
@@ -0,0 +1,211 @@
+//===--- WhitespaceManager.cpp - Format C++ code --------------------------===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// \brief This file implements WhitespaceManager class.
+///
+//===----------------------------------------------------------------------===//
+
+#include "WhitespaceManager.h"
+#include "llvm/ADT/STLExtras.h"
+
+namespace clang {
+namespace format {
+
+void WhitespaceManager::replaceWhitespace(const AnnotatedToken &Tok,
+ unsigned NewLines, unsigned Spaces,
+ unsigned WhitespaceStartColumn) {
+ if (NewLines > 0)
+ alignEscapedNewlines();
+
+ // 2+ newlines mean an empty line separating logic scopes.
+ if (NewLines >= 2)
+ alignComments();
+
+ // Align line comments if they are trailing or if they continue other
+ // trailing comments.
+ if (Tok.isTrailingComment()) {
+ SourceLocation TokenEndLoc = Tok.FormatTok.getStartOfNonWhitespace()
+ .getLocWithOffset(Tok.FormatTok.TokenLength);
+ // Remove the comment's trailing whitespace.
+ if (Tok.FormatTok.TrailingWhiteSpaceLength != 0)
+ Replaces.insert(tooling::Replacement(
+ SourceMgr, TokenEndLoc, Tok.FormatTok.TrailingWhiteSpaceLength, ""));
+
+ bool LineExceedsColumnLimit =
+ Spaces + WhitespaceStartColumn + Tok.FormatTok.TokenLength >
+ Style.ColumnLimit;
+ // Align comment with other comments.
+ if ((Tok.Parent != NULL || !Comments.empty()) &&
+ !LineExceedsColumnLimit) {
+ unsigned MinColumn =
+ NewLines > 0 ? Spaces : WhitespaceStartColumn + Spaces;
+ unsigned MaxColumn = Style.ColumnLimit - Tok.FormatTok.TokenLength;
+ Comments.push_back(StoredToken(
+ Tok.FormatTok.WhiteSpaceStart, Tok.FormatTok.WhiteSpaceLength,
+ MinColumn, MaxColumn, NewLines, Spaces));
+ return;
+ }
+ }
+
+ // If this line does not have a trailing comment, align the stored comments.
+ if (Tok.Children.empty() && !Tok.isTrailingComment())
+ alignComments();
+
+ storeReplacement(Tok.FormatTok.WhiteSpaceStart,
+ Tok.FormatTok.WhiteSpaceLength,
+ getNewLineText(NewLines, Spaces));
+}
+
+void WhitespaceManager::replacePPWhitespace(const AnnotatedToken &Tok,
+ unsigned NewLines, unsigned Spaces,
+ unsigned WhitespaceStartColumn) {
+ if (NewLines == 0) {
+ replaceWhitespace(Tok, NewLines, Spaces, WhitespaceStartColumn);
+ } else {
+ // The earliest position for "\" is 2 after the last token.
+ unsigned MinColumn = WhitespaceStartColumn + 2;
+ unsigned MaxColumn = Style.ColumnLimit;
+ EscapedNewlines.push_back(StoredToken(
+ Tok.FormatTok.WhiteSpaceStart, Tok.FormatTok.WhiteSpaceLength,
+ MinColumn, MaxColumn, NewLines, Spaces));
+ }
+}
+
+void WhitespaceManager::breakToken(const FormatToken &Tok, unsigned Offset,
+ unsigned ReplaceChars, StringRef Prefix,
+ StringRef Postfix, bool InPPDirective,
+ unsigned Spaces,
+ unsigned WhitespaceStartColumn) {
+ SourceLocation Location =
+ Tok.getStartOfNonWhitespace().getLocWithOffset(Offset);
+ if (InPPDirective) {
+ // The earliest position for "\" is 2 after the last token.
+ unsigned MinColumn = WhitespaceStartColumn + 2;
+ unsigned MaxColumn = Style.ColumnLimit;
+ StoredToken StoredTok = StoredToken(Location, ReplaceChars, MinColumn,
+ MaxColumn, /*NewLines=*/ 1, Spaces);
+ StoredTok.Prefix = Prefix;
+ StoredTok.Postfix = Postfix;
+ EscapedNewlines.push_back(StoredTok);
+ } else {
+ std::string ReplacementText =
+ (Prefix + getNewLineText(1, Spaces) + Postfix).str();
+ Replaces.insert(tooling::Replacement(SourceMgr, Location, ReplaceChars,
+ ReplacementText));
+ }
+}
+
+const tooling::Replacements &WhitespaceManager::generateReplacements() {
+ alignComments();
+ alignEscapedNewlines();
+ return Replaces;
+}
+
+void WhitespaceManager::addReplacement(const SourceLocation &SourceLoc,
+ unsigned ReplaceChars, StringRef Text) {
+ Replaces.insert(
+ tooling::Replacement(SourceMgr, SourceLoc, ReplaceChars, Text));
+}
+
+void WhitespaceManager::addUntouchableComment(unsigned Column) {
+ StoredToken Tok = StoredToken(SourceLocation(), 0, Column, Column, 0, 0);
+ Tok.Untouchable = true;
+ Comments.push_back(Tok);
+}
+
+std::string WhitespaceManager::getNewLineText(unsigned NewLines,
+ unsigned Spaces) {
+ return std::string(NewLines, '\n') + std::string(Spaces, ' ');
+}
+
+std::string WhitespaceManager::getNewLineText(unsigned NewLines,
+ unsigned Spaces,
+ unsigned WhitespaceStartColumn,
+ unsigned EscapedNewlineColumn) {
+ std::string NewLineText;
+ if (NewLines > 0) {
+ unsigned Offset =
+ std::min<int>(EscapedNewlineColumn - 1, WhitespaceStartColumn);
+ for (unsigned i = 0; i < NewLines; ++i) {
+ NewLineText += std::string(EscapedNewlineColumn - Offset - 1, ' ');
+ NewLineText += "\\\n";
+ Offset = 0;
+ }
+ }
+ return NewLineText + std::string(Spaces, ' ');
+}
+
+void WhitespaceManager::alignComments() {
+ unsigned MinColumn = 0;
+ unsigned MaxColumn = UINT_MAX;
+ token_iterator Start = Comments.begin();
+ for (token_iterator I = Start, E = Comments.end(); I != E; ++I) {
+ if (I->MinColumn > MaxColumn || I->MaxColumn < MinColumn) {
+ alignComments(Start, I, MinColumn);
+ MinColumn = I->MinColumn;
+ MaxColumn = I->MaxColumn;
+ Start = I;
+ } else {
+ MinColumn = std::max(MinColumn, I->MinColumn);
+ MaxColumn = std::min(MaxColumn, I->MaxColumn);
+ }
+ }
+ alignComments(Start, Comments.end(), MinColumn);
+ Comments.clear();
+}
+
+void WhitespaceManager::alignComments(token_iterator I, token_iterator E,
+ unsigned Column) {
+ while (I != E) {
+ if (!I->Untouchable) {
+ unsigned Spaces = I->Spaces + Column - I->MinColumn;
+ storeReplacement(I->ReplacementLoc, I->ReplacementLength,
+ getNewLineText(I->NewLines, Spaces));
+ }
+ ++I;
+ }
+}
+
+void WhitespaceManager::alignEscapedNewlines() {
+ unsigned MinColumn;
+ if (Style.AlignEscapedNewlinesLeft) {
+ MinColumn = 0;
+ for (token_iterator I = EscapedNewlines.begin(), E = EscapedNewlines.end();
+ I != E; ++I) {
+ if (I->MinColumn > MinColumn)
+ MinColumn = I->MinColumn;
+ }
+ } else {
+ MinColumn = Style.ColumnLimit;
+ }
+
+ for (token_iterator I = EscapedNewlines.begin(), E = EscapedNewlines.end();
+ I != E; ++I) {
+ // I->MinColumn - 2 is the end of the previous token (i.e. the
+ // WhitespaceStartColumn).
+ storeReplacement(
+ I->ReplacementLoc, I->ReplacementLength,
+ I->Prefix + getNewLineText(I->NewLines, I->Spaces, I->MinColumn - 2,
+ MinColumn) + I->Postfix);
+
+ }
+ EscapedNewlines.clear();
+}
+
+void WhitespaceManager::storeReplacement(SourceLocation Loc, unsigned Length,
+ const std::string Text) {
+ // Don't create a replacement, if it does not change anything.
+ if (StringRef(SourceMgr.getCharacterData(Loc), Length) == Text)
+ return;
+ Replaces.insert(tooling::Replacement(SourceMgr, Loc, Length, Text));
+}
+
+} // namespace format
+} // namespace clang
diff --git a/lib/Format/WhitespaceManager.h b/lib/Format/WhitespaceManager.h
new file mode 100644
index 000000000000..5f3dc55edacc
--- /dev/null
+++ b/lib/Format/WhitespaceManager.h
@@ -0,0 +1,119 @@
+//===--- WhitespaceManager.h - Format C++ code ------------------*- C++ -*-===//
+//
+// The LLVM Compiler Infrastructure
+//
+// This file is distributed under the University of Illinois Open Source
+// License. See LICENSE.TXT for details.
+//
+//===----------------------------------------------------------------------===//
+///
+/// \file
+/// \brief WhitespaceManager class manages whitespace around tokens and their
+/// replacements.
+///
+//===----------------------------------------------------------------------===//
+
+#ifndef LLVM_CLANG_FORMAT_WHITESPACEMANAGER_H
+#define LLVM_CLANG_FORMAT_WHITESPACEMANAGER_H
+
+#include "TokenAnnotator.h"
+#include "clang/Basic/SourceManager.h"
+#include "clang/Format/Format.h"
+#include <string>
+
+namespace clang {
+namespace format {
+
+/// \brief Manages the whitespaces around tokens and their replacements.
+///
+/// This includes special handling for certain constructs, e.g. the alignment of
+/// trailing line comments.
+class WhitespaceManager {
+public:
+ WhitespaceManager(SourceManager &SourceMgr, const FormatStyle &Style)
+ : SourceMgr(SourceMgr), Style(Style) {}
+
+ /// \brief Replaces the whitespace in front of \p Tok. Only call once for
+ /// each \c AnnotatedToken.
+ void replaceWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
+ unsigned Spaces, unsigned WhitespaceStartColumn);
+
+ /// \brief Like \c replaceWhitespace, but additionally adds right-aligned
+ /// backslashes to escape newlines inside a preprocessor directive.
+ ///
+ /// This function and \c replaceWhitespace have the same behavior if
+ /// \c Newlines == 0.
+ void replacePPWhitespace(const AnnotatedToken &Tok, unsigned NewLines,
+ unsigned Spaces, unsigned WhitespaceStartColumn);
+
+ /// \brief Inserts a line break into the middle of a token.
+ ///
+ /// Will break at \p Offset inside \p Tok, putting \p Prefix before the line
+ /// break and \p Postfix before the rest of the token starts