Skip to content

Commit 1da10c3

Browse files
committed
ClangImporter: enhance the importer to alias declarations
Import simple CPP macro aliases as aliases in Swift. Extend the macro importer to import the following construct: ``` #define alias aliasee ``` as the following Swift construct: ``` @_transparent @inline(__always) var alias: type(of: aliasee) { aliasee } ``` This improves the QoI for Windows where there is a universal define (`UNICODE`) which normally is used for translating APIs between ANSI and Unicode variants, e.g.: ``` #if defined(UNICODE) #define MessageBox MessageBoxW #else #define MessageBox MessageBoxA #endif ``` Global variables which are non-const also have a setter synthesized: ``` @_transparent @inline(__always) var alias: type(of: aliasee) { get { return aliasee } set { aliasee = newValue } } ```
1 parent 68524a8 commit 1da10c3

File tree

5 files changed

+224
-1
lines changed

5 files changed

+224
-1
lines changed

lib/ClangImporter/ImportMacro.cpp

Lines changed: 102 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,6 +20,7 @@
2020
#include "swift/AST/ASTContext.h"
2121
#include "swift/AST/DiagnosticsClangImporter.h"
2222
#include "swift/AST/Expr.h"
23+
#include "swift/AST/ParameterList.h"
2324
#include "swift/AST/Stmt.h"
2425
#include "swift/AST/Types.h"
2526
#include "swift/Basic/Assertions.h"
@@ -31,6 +32,7 @@
3132
#include "clang/Lex/MacroInfo.h"
3233
#include "clang/Lex/Preprocessor.h"
3334
#include "clang/Sema/DelayedDiagnostic.h"
35+
#include "clang/Sema/Lookup.h"
3436
#include "clang/Sema/Sema.h"
3537
#include "clang/StaticAnalyzer/Core/PathSensitive/APSIntType.h"
3638
#include "llvm/ADT/SmallString.h"
@@ -371,6 +373,98 @@ getIntegerConstantForMacroToken(ClangImporter::Implementation &impl,
371373
return std::nullopt;
372374
}
373375

376+
namespace {
377+
ValueDecl *importDeclAlias(ClangImporter::Implementation &clang,
378+
swift::DeclContext *DC, const clang::ValueDecl *D,
379+
Identifier alias) {
380+
// Ignore self-referential macros.
381+
if (D->getName() == alias.str())
382+
return nullptr;
383+
384+
swift::ValueDecl *VD =
385+
dyn_cast_or_null<ValueDecl>(clang.importDecl(D, clang.CurrentVersion));
386+
if (VD == nullptr)
387+
return nullptr;
388+
389+
// If the imported decl is named identically, avoid the aliasing.
390+
if (VD->getBaseIdentifier().str() == alias.str())
391+
return nullptr;
392+
393+
swift::ASTContext &Ctx = DC->getASTContext();
394+
ImportedType Ty =
395+
clang.importType(D->getType(), ImportTypeKind::Abstract,
396+
[&clang, &D](Diagnostic &&Diag) {
397+
clang.addImportDiagnostic(D, std::move(Diag),
398+
D->getLocation());
399+
}, /*AllowsNSUIntegerAsInt*/true,
400+
Bridgeability::None, { });
401+
swift::Type GetterTy = FunctionType::get({}, Ty.getType(), ASTExtInfo{});
402+
swift::Type SetterTy =
403+
FunctionType::get({AnyFunctionType::Param(Ty.getType())},
404+
Ctx.TheEmptyTupleType, ASTExtInfo{});
405+
406+
/* Storage */
407+
swift::VarDecl *V =
408+
new (Ctx) VarDecl(/*IsStatic*/false, VarDecl::Introducer::Var,
409+
SourceLoc(), alias, DC);
410+
V->setAccess(swift::AccessLevel::Public);
411+
V->setInterfaceType(Ty.getType());
412+
V->getAttrs().add(new (Ctx) TransparentAttr(/*Implicit*/true));
413+
V->getAttrs().add(new (Ctx) InlineAttr(InlineKind::Always));
414+
415+
/* Accessor */
416+
swift::AccessorDecl *G = nullptr;
417+
{
418+
G = AccessorDecl::createImplicit(Ctx, AccessorKind::Get, V, false, false,
419+
TypeLoc(), GetterTy, DC);
420+
G->setAccess(swift::AccessLevel::Public);
421+
G->setInterfaceType(GetterTy);
422+
G->setIsTransparent(true);
423+
G->setParameters(ParameterList::createEmpty(Ctx));
424+
425+
DeclRefExpr *DRE =
426+
new (Ctx) DeclRefExpr(ConcreteDeclRef(VD), {}, /*Implicit*/true,
427+
AccessSemantics::Ordinary, Ty.getType());
428+
ReturnStmt *RS = ReturnStmt::createImplicit(Ctx, DRE);
429+
430+
G->setBody(BraceStmt::createImplicit(Ctx, {RS}),
431+
AbstractFunctionDecl::BodyKind::TypeChecked);
432+
}
433+
434+
swift::AccessorDecl *S = nullptr;
435+
if (isa<clang::VarDecl>(D) &&
436+
!cast<clang::VarDecl>(D)->getType().isConstQualified()) {
437+
S = AccessorDecl::createImplicit(Ctx, AccessorKind::Set, V, false, false,
438+
TypeLoc(), Ctx.TheEmptyTupleType, DC);
439+
S->setAccess(swift::AccessLevel::Public);
440+
S->setInterfaceType(SetterTy);
441+
S->setIsTransparent(true);
442+
S->setParameters(ParameterList::create(Ctx, {
443+
ParamDecl::createImplicit(Ctx, Identifier(), Ctx.getIdentifier("newValue"),
444+
Ty.getType(), DC)
445+
}));
446+
447+
DeclRefExpr *LHS =
448+
new (Ctx) DeclRefExpr(ConcreteDeclRef(VD), {}, /*Implicit*/true,
449+
AccessSemantics::Ordinary, Ty.getType());
450+
DeclRefExpr *RHS =
451+
new (Ctx) DeclRefExpr(S->getParameters()->get(0), {}, /*Implicit*/true,
452+
AccessSemantics::Ordinary, Ty.getType());
453+
AssignExpr *AE = new (Ctx) AssignExpr(LHS, SourceLoc(), RHS, true);
454+
AE->setType(Ctx.TheEmptyTupleType);
455+
S->setBody(BraceStmt::createImplicit(Ctx, {AE}),
456+
AbstractFunctionDecl::BodyKind::TypeChecked);
457+
}
458+
459+
/* Bind */
460+
V->setImplInfo(S ? StorageImplInfo::getMutableComputed()
461+
: StorageImplInfo::getImmutableComputed());
462+
V->setAccessors(SourceLoc(), S ? ArrayRef{G,S} : ArrayRef{G}, SourceLoc());
463+
464+
return V;
465+
}
466+
}
467+
374468
static ValueDecl *importMacro(ClangImporter::Implementation &impl,
375469
llvm::SmallSet<StringRef, 4> &visitedMacros,
376470
DeclContext *DC, Identifier name,
@@ -509,7 +603,14 @@ static ValueDecl *importMacro(ClangImporter::Implementation &impl,
509603
}
510604
}
511605

512-
// FIXME: If the identifier refers to a declaration, alias it?
606+
/* Create an alias for any Decl */
607+
clang::Sema &S = impl.getClangSema();
608+
clang::LookupResult R(S, {{tok.getIdentifierInfo()}, {}},
609+
clang::Sema::LookupAnyName);
610+
if (S.LookupName(R, S.TUScope))
611+
if (R.getResultKind() == clang::LookupResult::LookupResultKind::Found)
612+
if (const auto *VD = dyn_cast<clang::ValueDecl>(R.getFoundDecl()))
613+
return importDeclAlias(impl, DC, VD, name);
513614
}
514615

515616
// TODO(https://github.com/apple/swift/issues/57735): Seems rare to have a single token that is neither a literal nor an identifier, but add diagnosis.
Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,42 @@
1+
#pragma once
2+
3+
#if defined(UNICODE)
4+
#define F FW
5+
#define V VW
6+
#else
7+
#define F FA
8+
#define V VA
9+
#endif
10+
11+
#if defined(_WIN32)
12+
#define ALIASES_ABI /**/
13+
#else
14+
#define ALIASES_ABI __attribute__((__visibility__("default")))
15+
#endif
16+
17+
extern ALIASES_ABI const unsigned int VA;
18+
extern ALIASES_ABI const unsigned long long VW;
19+
20+
ALIASES_ABI void FA(unsigned int);
21+
ALIASES_ABI void FW(unsigned long long);
22+
23+
#define InvalidCall DoesNotExist
24+
25+
extern ALIASES_ABI float UIA;
26+
extern ALIASES_ABI double UIW;
27+
28+
#if defined(UNICODE)
29+
#define UI UIW
30+
#else
31+
#define UI UIA
32+
#endif
33+
34+
enum {
35+
ALPHA = 0,
36+
#define ALPHA ALPHA
37+
BETA = 1,
38+
#define BETA BETA
39+
};
40+
41+
extern ALIASES_ABI double RA __attribute__((__swift_name__("RAW")));
42+
#define RAW RA

test/ClangImporter/Inputs/custom-modules/module.modulemap

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -275,3 +275,7 @@ module CommonName {
275275
module "Weird C Module" {
276276
header "WeirdCModule.h"
277277
}
278+
279+
module Aliases {
280+
header "Aliases.h"
281+
}
Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,12 @@
1+
// RUN: %empty-directory(%t)
2+
// RUN: %target-typecheck-verify-swift -I %S/Inputs/custom-modules
3+
4+
import Aliases
5+
6+
func f() {
7+
InvalidCall() // expected-error{{cannot find 'InvalidCall' in scope}}
8+
}
9+
10+
func g() {
11+
V = 32 // expected-error{{cannot assign to value: 'V' is a get-only property}}
12+
}

test/ClangImporter/alias.swift

Lines changed: 64 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,64 @@
1+
// RUN: %target-typecheck-verify-swift -I %S/Inputs/custom-modules %s
2+
// RUN: %target-swift-frontend -I %S/Inputs/custom-modules -parse-as-library -module-name Alias -Osize -emit-ir -o - %s | %FileCheck %s -check-prefix CHECK-ANSI-IR
3+
// RUN: %target-typecheck-verify-swift -I %S/Inputs/custom-modules %s -Xcc -DUNICODE
4+
// RUN: %target-swift-frontend -I %S/Inputs/custom-modules -parse-as-library -module-name Alias -Osize -emit-ir -o - %s -Xcc -DUNICODE | %FileCheck %s -check-prefix CHECK-UNICODE-IR
5+
// RUN: not %target-swift-frontend -I %S/Inputs/custom-modules -parse-as-library -module-name Alias -c %s -DINVALID -o /dev/null 2>&1 | %FileCheck --dry-run %s -check-prefix CHECK-INVALID
6+
7+
// expected-no-diagnostics
8+
9+
import Aliases
10+
11+
public func f() {
12+
F(V)
13+
}
14+
15+
public func g() {
16+
UI = 32
17+
}
18+
19+
// CHECK-ANSI-IR: @VA = external {{(dso_local )?}}local_unnamed_addr constant i32
20+
// CHECK-ANSI-IR: @UIA = external {{(dso_local )?}}local_unnamed_addr global float
21+
22+
// CHECK-ANSI-IR: define {{.*}}swiftcc void @"$s5Alias1fyyF"(){{.*}}{
23+
// CHECK-ANSI-IR: entry:
24+
// CHECK-ANSI-IR: %0 = load i32, ptr @VA
25+
// CHECK-ANSI-IR: tail call void @FA(i32 %0)
26+
// CHECK-ANSI-IR: ret void
27+
// CHECK-ANSI-IR: }
28+
29+
// CHECK-ANSI-IR: declare {{.*}}void @FA(i32 noundef)
30+
// CHECK-ANSI-IR-NOT: declare {{.*}}void @FW(i64 noundef)
31+
32+
// CHECK-ANSI-IR: define {{.*}}swiftcc void @"$s5Alias1gyyF"(){{.*}}{
33+
// CHECK-ANSI-IR: entry:
34+
// CHECK-ANSI-IR: store float 3.200000e+01, ptr @UIA
35+
// CHECK-ANSI-IR: ret void
36+
// CHECK-ANSI-IR: }
37+
38+
// CHECK-UNICODE-IR: @VW = external {{(dso_local )?}}local_unnamed_addr constant i64
39+
// CHECK-UNICODE-IR: @UIW = external {{(dso_local )?}}local_unnamed_addr global double
40+
41+
// CHECK-UNICODE-IR: define {{.*}}swiftcc void @"$s5Alias1fyyF"(){{.*}}{
42+
// CHECK-UNICODE-IR: entry:
43+
// CHECK-UNICODE-IR: %0 = load i64, ptr @VW
44+
// CHECK-UNICODE-IR: tail call void @FW(i64 %0)
45+
// CHECK-UNICODE-IR: ret void
46+
// CHECK-UNICODE-IR: }
47+
48+
// CHECK-UNICODE-IR: declare {{(dso_local )?}}void @FW(i64 noundef)
49+
// CHECK-UNICODE-IR-NOT: declare {{(dso_local )?}}void @FA(i32 noundef)
50+
51+
// CHECK-UNICODE-IR: define {{.*}}swiftcc void @"$s5Alias1gyyF"(){{.*}}{
52+
// CHECK-UNICODE-IR: entry:
53+
// CHECK-UNICODE-IR: store double 3.200000e+01, ptr @UIW
54+
// CHECK-UNICODE-IR: ret void
55+
// CHECK-UNICODE-IR: }
56+
57+
func h() {
58+
let _ = RAW
59+
}
60+
61+
#if INVALID
62+
let _ = ALPHA
63+
// CHECK-INVALID: error: global variable declaration does not bind any variables
64+
#endif

0 commit comments

Comments
 (0)