Skip to content

Archive attributes and runtime support for it #9432

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 10 commits into from
May 11, 2017
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
13 changes: 13 additions & 0 deletions include/swift/AST/Attr.def
Original file line number Diff line number Diff line change
Expand Up @@ -273,6 +273,19 @@ DECL_ATTR(_implements, Implements,
| NotSerialized | UserInaccessible,
/* Not serialized */ 67)

DECL_ATTR(NSKeyedArchiveLegacy, NSKeyedArchiveLegacy,
OnClass | NotSerialized | LongAttribute,
/*Not serialized */ 68)

SIMPLE_DECL_ATTR(_staticInitializeObjCMetadata, StaticInitializeObjCMetadata,
OnClass | NotSerialized | LongAttribute | UserInaccessible,
/*Not serialized */ 69)

SIMPLE_DECL_ATTR(NSKeyedArchiveSubclassesOnly,
NSKeyedArchiveSubclassesOnly,
OnClass | NotSerialized | LongAttribute,
/*Not serialized */ 70)

#undef TYPE_ATTR
#undef DECL_ATTR_ALIAS
#undef SIMPLE_DECL_ATTR
Expand Down
18 changes: 18 additions & 0 deletions include/swift/AST/Attr.h
Original file line number Diff line number Diff line change
Expand Up @@ -1158,6 +1158,24 @@ class ImplementsAttr : public DeclAttribute {
}
};

/// Defines the @NSKeyedArchiveLegacyAttr attribute.
class NSKeyedArchiveLegacyAttr : public DeclAttribute {
public:
NSKeyedArchiveLegacyAttr(StringRef Name, SourceLoc AtLoc, SourceRange Range, bool Implicit)
: DeclAttribute(DAK_NSKeyedArchiveLegacy, AtLoc, Range, Implicit),
Name(Name) {}

NSKeyedArchiveLegacyAttr(StringRef Name, bool Implicit)
: NSKeyedArchiveLegacyAttr(Name, SourceLoc(), SourceRange(), /*Implicit=*/true) {}

/// The legacy mangled name.
const StringRef Name;

static bool classof(const DeclAttribute *DA) {
return DA->getKind() == DAK_NSKeyedArchiveLegacy;
}
};

/// \brief Attributes that may be applied to declarations.
class DeclAttributes {
/// Linked list of declaration attributes.
Expand Down
22 changes: 22 additions & 0 deletions include/swift/AST/DiagnosticsSema.def
Original file line number Diff line number Diff line change
Expand Up @@ -1212,6 +1212,28 @@ ERROR(pattern_binds_no_variables,none,
"variables",
(unsigned))

ERROR(nscoding_unstable_mangled_name,none,
"%select{private|fileprivate|nested|local|generic}0 class %1 has an "
"unstable name when archiving via 'NSCoding'",
(unsigned, Type))
WARNING(nscoding_unstable_mangled_name_warn,none,
"%select{private|fileprivate|nested|local|generic}0 class %1 has an "
"unstable name when archiving via 'NSCoding'",
(unsigned, Type))
NOTE(unstable_mangled_name_add_objc,none,
"for new classes, add '@objc' to specify a unique, prefixed Objective-C "
"runtime name", ())
NOTE(unstable_mangled_name_add_nskeyedarchivelegacy,none,
"for compatibility with existing archives, use '@NSKeyedArchiveLegacy' "
"to record the Swift 3 mangled name", ())
NOTE(add_nskeyedarchivesubclassesonly_attr,none,
"generic classes should not be archived directly; "
"add @NSKeyedArchiveSubclassesOnly "
"and only archive specific subclasses of this class", (Type))

ERROR(attr_nskeyedarchivelegacy_generic,none,
"'@NSKeyedArchiveLegacy' cannot be applied to generic class %0",
(Type))

// Generic types
ERROR(unsupported_type_nested_in_generic_function,none,
Expand Down
8 changes: 8 additions & 0 deletions include/swift/Runtime/RuntimeFunctions.def
Original file line number Diff line number Diff line change
Expand Up @@ -1217,6 +1217,14 @@ FUNCTION(GetKeyPath, swift_getKeyPath, C_CC,
ARGS(Int8PtrTy, Int8PtrTy),
ATTRS(NoUnwind))

// func _registerClassNameForArchiving(_ nameOrNull: UnsafePointer<CChar>?,
// _ c: AnyClass)
FUNCTION(RegisterClassNameForArchiving, swift_registerClassNameForArchiving,
SwiftCC,
RETURNS(VoidTy),
ARGS(Int8PtrTy, TypeMetadataPtrTy),
ATTRS(NoUnwind))

#if SWIFT_OBJC_INTEROP || !defined(SWIFT_RUNTIME_GENERATE_GLOBAL_SYMBOLS)

// Put here all definitions of runtime functions which are:
Expand Down
2 changes: 2 additions & 0 deletions include/swift/Serialization/ModuleFormat.h
Original file line number Diff line number Diff line change
Expand Up @@ -1314,6 +1314,8 @@ namespace decls_block {
using SynthesizedProtocolDeclAttrLayout
= BCRecordLayout<SynthesizedProtocol_DECL_ATTR>;
using ImplementsDeclAttrLayout = BCRecordLayout<Implements_DECL_ATTR>;
using NSKeyedArchiveLegacyDeclAttrLayout
= BCRecordLayout<NSKeyedArchiveLegacy_DECL_ATTR>;

using InlineDeclAttrLayout = BCRecordLayout<
Inline_DECL_ATTR,
Expand Down
2 changes: 2 additions & 0 deletions lib/AST/ASTDumper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -855,6 +855,8 @@ namespace {

void visitClassDecl(ClassDecl *CD) {
printCommon(CD, "class_decl");
if (CD->getAttrs().hasAttribute<StaticInitializeObjCMetadataAttr>())
OS << " @_staticInitializeObjCMetadata";
printInherited(CD->getInherited());
for (Decl *D : CD->getMembers()) {
OS << '\n';
Expand Down
15 changes: 15 additions & 0 deletions lib/AST/Attr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -493,6 +493,19 @@ bool DeclAttribute::printImpl(ASTPrinter &Printer, const PrintOptions &Options,
break;
}

case DAK_NSKeyedArchiveLegacy: {
Printer.printAttrName("@NSKeyedArchiveLegacy");
Printer << "(";
auto *attr = cast<NSKeyedArchiveLegacyAttr>(this);
Printer << "\"" << attr->Name << "\"";
Printer << ")";
break;
}

case DAK_StaticInitializeObjCMetadata:
Printer.printAttrName("@_staticInitializeObjCMetadata");
break;

case DAK_Count:
llvm_unreachable("exceed declaration attribute kinds");

Expand Down Expand Up @@ -609,6 +622,8 @@ StringRef DeclAttribute::getAttrName() const {
return "_specialize";
case DAK_Implements:
return "_implements";
case DAK_NSKeyedArchiveLegacy:
return "NSKeyedArchiveLegacy";
}
llvm_unreachable("bad DeclAttrKind");
}
Expand Down
3 changes: 3 additions & 0 deletions lib/IRGen/GenClass.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -960,6 +960,9 @@ void IRGenModule::emitClassDecl(ClassDecl *D) {
emitClassMetadata(*this, D,
classTI.getLayout(*this, selfType),
classTI.getClassLayout(*this, selfType));

IRGen.addClassForArchiveNameRegistration(D);

emitNestedTypeDecls(D->getMembers());
emitFieldMetadataRecord(D);
}
Expand Down
52 changes: 52 additions & 0 deletions lib/IRGen/GenDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -41,9 +41,11 @@
#include "llvm/IR/Module.h"
#include "llvm/IR/TypeBuilder.h"
#include "llvm/IR/Value.h"
#include "llvm/IR/InlineAsm.h"
#include "llvm/Support/Compiler.h"
#include "llvm/Support/ConvertUTF.h"
#include "llvm/Support/Path.h"
#include "llvm/Transforms/Utils/ModuleUtils.h"

#include "ConstantBuilder.h"
#include "Explosion.h"
Expand Down Expand Up @@ -947,6 +949,56 @@ void IRGenerator::emitLazyDefinitions() {
}
}

void IRGenerator::emitNSArchiveClassNameRegistration() {
if (ClassesForArchiveNameRegistration.empty())
return;

// Emit the register function in the primary module.
IRGenModule *IGM = getPrimaryIGM();

llvm::Function *RegisterFn = llvm::Function::Create(
llvm::FunctionType::get(IGM->VoidTy, false),
llvm::GlobalValue::InternalLinkage,
"_swift_register_class_names_for_archives");
IRGenFunction RegisterIGF(*IGM, RegisterFn);
RegisterFn->setAttributes(IGM->constructInitialAttributes());
IGM->Module.getFunctionList().push_back(RegisterFn);
RegisterFn->setCallingConv(IGM->DefaultCC);

for (ClassDecl *CD : ClassesForArchiveNameRegistration) {
Type Ty = CD->getDeclaredType();
llvm::Value *MetaData = RegisterIGF.emitTypeMetadataRef(getAsCanType(Ty));
if (auto *LegacyAttr = CD->getAttrs().
getAttribute<NSKeyedArchiveLegacyAttr>()) {
// Register the name for the class in the NSKeyed(Un)Archiver.
llvm::Value *NameStr = IGM->getAddrOfGlobalString(LegacyAttr->Name);
RegisterIGF.Builder.CreateCall(IGM->getRegisterClassNameForArchivingFn(),
{NameStr, MetaData});
} else {
assert(CD->getAttrs().hasAttribute<StaticInitializeObjCMetadataAttr>());

// In this case we don't add a name mapping, but just get the metadata
// to make sure that the class is registered. But: we need to add a use
// (empty inline asm instruction) for the metadata. Otherwise
// llvm would optimize the metadata accessor call away because it's
// defined as "readnone".
llvm::FunctionType *asmFnTy =
llvm::FunctionType::get(IGM->VoidTy, {MetaData->getType()},
false /* = isVarArg */);
llvm::InlineAsm *inlineAsm =
llvm::InlineAsm::get(asmFnTy, "", "r", true /* = SideEffects */);
RegisterIGF.Builder.CreateCall(inlineAsm, MetaData);
}
}
RegisterIGF.Builder.CreateRetVoid();

// Add the registration function as a static initializer. We use a priority
// slightly lower than used for C++ global constructors, so that the code is
// executed before C++ global constructors (in case someone uses archives
// from a C++ global constructor).
llvm::appendToGlobalCtors(IGM->Module, RegisterFn, 60000, nullptr);
}

/// Emit symbols for eliminated dead methods, which can still be referenced
/// from other modules. This happens e.g. if a public class contains a (dead)
/// private method.
Expand Down
3 changes: 3 additions & 0 deletions lib/IRGen/IRGen.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -715,6 +715,7 @@ static std::unique_ptr<llvm::Module> performIRGeneration(IRGenOptions &Opts,
IGM.emitTypeMetadataRecords();
IGM.emitBuiltinReflectionMetadata();
IGM.emitReflectionMetadataVersion();
irgen.emitNSArchiveClassNameRegistration();
}

// Emit symbols for eliminated dead methods.
Expand Down Expand Up @@ -893,6 +894,8 @@ static void performParallelIRGeneration(IRGenOptions &Opts,

irgen.emitReflectionMetadataVersion();

irgen.emitNSArchiveClassNameRegistration();

// Emit reflection metadata for builtin and imported types.
irgen.emitBuiltinReflectionMetadata();

Expand Down
23 changes: 23 additions & 0 deletions lib/IRGen/IRGenModule.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -558,6 +558,9 @@ llvm::Constant *swift::getWrapperFn(llvm::Module &Module,
#define FUNCTION_FOR_CONV_C_CC(ID, NAME, CC, RETURNS, ARGS, ATTRS) \
FUNCTION_IMPL(ID, NAME, CC, QUOTE(RETURNS), QUOTE(ARGS), QUOTE(ATTRS))

#define FUNCTION_FOR_CONV_SwiftCC(ID, NAME, CC, RETURNS, ARGS, ATTRS) \
FUNCTION_IMPL(ID, NAME, CC, QUOTE(RETURNS), QUOTE(ARGS), QUOTE(ATTRS))

#define FUNCTION_FOR_CONV_RegisterPreservingCC(ID, NAME, CC, RETURNS, ARGS, \
ATTRS) \
FUNCTION_WITH_GLOBAL_SYMBOL_IMPL(ID, NAME, SWIFT_RT_ENTRY_REF(NAME), CC, \
Expand Down Expand Up @@ -748,6 +751,26 @@ void IRGenerator::addLazyWitnessTable(const ProtocolConformance *Conf) {
}
}

void IRGenerator::addClassForArchiveNameRegistration(ClassDecl *ClassDecl) {

// Those two attributes are interesting to us
if (!ClassDecl->getAttrs().hasAttribute<NSKeyedArchiveLegacyAttr>() &&
!ClassDecl->getAttrs().hasAttribute<StaticInitializeObjCMetadataAttr>())
return;

// Exclude some classes where those attributes make no sense but could be set
// for some reason. Just to be on the safe side.
Type ClassTy = ClassDecl->getDeclaredType();
if (ClassTy->is<UnboundGenericType>())
return;
if (ClassTy->hasArchetype())
return;
if (ClassDecl->hasClangNode())
return;

ClassesForArchiveNameRegistration.push_back(ClassDecl);
}

llvm::AttributeSet IRGenModule::getAllocAttrs() {
if (AllocAttrs.isEmpty()) {
AllocAttrs = llvm::AttributeSet::get(LLVMContext,
Expand Down
8 changes: 7 additions & 1 deletion lib/IRGen/IRGenModule.h
Original file line number Diff line number Diff line change
Expand Up @@ -222,6 +222,8 @@ class IRGenerator {
/// The queue of lazy witness tables to emit.
llvm::SmallVector<SILWitnessTable *, 4> LazyWitnessTables;

llvm::SmallVector<ClassDecl *, 4> ClassesForArchiveNameRegistration;

/// The order in which all the SIL function definitions should
/// appear in the translation unit.
llvm::DenseMap<SILFunction*, unsigned> FunctionOrder;
Expand Down Expand Up @@ -296,6 +298,8 @@ class IRGenerator {
/// Emit a symbol identifying the reflection metadata version.
void emitReflectionMetadataVersion();

void emitNSArchiveClassNameRegistration();

/// Checks if the metadata of \p Nominal can be emitted lazily.
///
/// If yes, \p Nominal is added to eligibleLazyMetadata and true is returned.
Expand Down Expand Up @@ -333,7 +337,9 @@ class IRGenerator {
{fieldTypes.begin(), fieldTypes.end()},
fn, IGM});
}


void addClassForArchiveNameRegistration(ClassDecl *ClassDecl);

unsigned getFunctionOrder(SILFunction *F) {
auto it = FunctionOrder.find(F);
assert(it != FunctionOrder.end() &&
Expand Down
7 changes: 6 additions & 1 deletion lib/Parse/ParseDecl.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -743,7 +743,8 @@ bool Parser::parseNewDeclAttribute(DeclAttributes &Attributes, SourceLoc AtLoc,
}

case DAK_CDecl:
case DAK_SILGenName: {
case DAK_SILGenName:
case DAK_NSKeyedArchiveLegacy: {
if (!consumeIf(tok::l_paren)) {
diagnose(Loc, diag::attr_expected_lparen, AttrName,
DeclAttribute::isDeclModifier(DK));
Expand Down Expand Up @@ -786,6 +787,10 @@ bool Parser::parseNewDeclAttribute(DeclAttributes &Attributes, SourceLoc AtLoc,
else if (DK == DAK_CDecl)
Attributes.add(new (Context) CDeclAttr(AsmName.getValue(), AtLoc,
AttrRange, /*Implicit=*/false));
else if (DK == DAK_NSKeyedArchiveLegacy)
Attributes.add(new (Context) NSKeyedArchiveLegacyAttr(
AsmName.getValue(), AtLoc,
AttrRange, /*Implicit=*/false));
else
llvm_unreachable("out of sync with switch");
}
Expand Down
Loading