Skip to content

Commit dba9103

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 ```
1 parent 9753d23 commit dba9103

File tree

5 files changed

+191
-1
lines changed

5 files changed

+191
-1
lines changed

lib/ClangImporter/ImportMacro.cpp

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

512-
// FIXME: If the identifier refers to a declaration, alias it?
598+
/* Create an alias for any Decl */
599+
clang::Sema &S = impl.getClangSema();
600+
clang::LookupResult R(S, {{tok.getIdentifierInfo()}, {}},
601+
clang::Sema::LookupAnyName);
602+
if (S.LookupName(R, S.TUScope))
603+
if (R.getResultKind() == clang::LookupResult::LookupResultKind::Found)
604+
if (const auto *VD = dyn_cast<clang::ValueDecl>(R.getFoundDecl()))
605+
return importDeclAlias(impl, DC, VD, name);
513606
}
514607

515608
// 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: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
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+
extern const unsigned int VA;
12+
extern const unsigned long long VW;
13+
14+
void FA(unsigned int);
15+
void FW(unsigned long long);
16+
17+
#define InvalidCall DoesNotExist
18+
19+
extern float UIA;
20+
extern double UIW;
21+
22+
#if defined(UNICODE)
23+
#define UI UIW
24+
#else
25+
#define UI UIA
26+
#endif

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: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
// RUN: %empty-directory(%t)
2+
// RUN: %target-typcheck-verify-swift -I %S/Inputs/custom-modules %s
3+
// 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
4+
// RUN: %target-typecheck-verify-swift -I %S/Inputs/custom-modules %s -Xcc -DUNICODE
5+
// 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
6+
7+
// expected-no-diagnostics
8+
9+
import Aliases
10+
11+
func f() {
12+
F(V)
13+
}
14+
15+
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 hidden swiftcc void @"$s5Alias1fyyF"(){{.*}}{
23+
// CHECK-ANSI-IR: entry:
24+
// CHECK-ANSI-IR: %0 = load i32, ptr @VA, align 8
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 dso_local void @FA(i32 noundef)
30+
// CHECK-ANSI-IR-NOT: declare dso_local void @FW(i64 noundef)
31+
32+
// CHECK-ANSI-IR: define hidden 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 hidden swiftcc void @"$s5Alias1fyyF"(){{.*}}{
42+
// CHECK-UNICODE-IR: entry:
43+
// CHECK-UNICODE-IR: %0 = load i64, ptr @VW, align 8
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 hidden 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: }

0 commit comments

Comments
 (0)