Skip to content

FloatLiteralExpr now is lowered directly into SIL. #23010

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 1 commit into from
Mar 1, 2019
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
14 changes: 10 additions & 4 deletions include/swift/AST/Expr.h
Original file line number Diff line number Diff line change
Expand Up @@ -823,11 +823,11 @@ class NumberLiteralExpr : public LiteralExpr {
}
};


/// Integer literal with a '+' or '-' sign, like '+4' or '- 2'.
///
/// After semantic analysis assigns types, this is guaranteed to only have
/// a BuiltinIntegerType.
/// After semantic analysis assigns types, this is guaranteed to have
/// a BuiltinIntegerType or be a normal type and implicitly be
/// AnyBuiltinIntegerType.
class IntegerLiteralExpr : public NumberLiteralExpr {
public:
IntegerLiteralExpr(StringRef Val, SourceLoc DigitsLoc, bool Implicit = false)
Expand Down Expand Up @@ -855,9 +855,12 @@ class IntegerLiteralExpr : public NumberLiteralExpr {
};

/// FloatLiteralExpr - Floating point literal, like '4.0'. After semantic
/// analysis assigns types, this is guaranteed to only have a
/// analysis assigns types, BuiltinTy is guaranteed to only have a
/// BuiltinFloatingPointType.
class FloatLiteralExpr : public NumberLiteralExpr {
/// This is the type of the builtin literal.
Type BuiltinTy;

public:
FloatLiteralExpr(StringRef Val, SourceLoc Loc, bool Implicit = false)
: NumberLiteralExpr(ExprKind::FloatLiteral, Val, Loc, Implicit)
Expand All @@ -870,6 +873,9 @@ class FloatLiteralExpr : public NumberLiteralExpr {
static bool classof(const Expr *E) {
return E->getKind() == ExprKind::FloatLiteral;
}

Type getBuiltinType() const { return BuiltinTy; }
void setBuiltinType(Type ty) { BuiltinTy = ty; }
};

/// A Boolean literal ('true' or 'false')
Expand Down
10 changes: 10 additions & 0 deletions lib/AST/ASTDumper.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1831,6 +1831,16 @@ class PrintExpr : public ExprVisitor<PrintExpr> {
printCommon(E, "float_literal_expr");
PrintWithColorRAII(OS, LiteralValueColor)
<< " value=" << E->getDigitsText();
PrintWithColorRAII(OS, LiteralValueColor) << " builtin_initializer=";
E->getBuiltinInitializer().dump(
PrintWithColorRAII(OS, LiteralValueColor).getOS());
PrintWithColorRAII(OS, LiteralValueColor) << " initializer=";
E->getInitializer().dump(PrintWithColorRAII(OS, LiteralValueColor).getOS());
if (!E->getBuiltinType().isNull()) {
PrintWithColorRAII(OS, TypeColor) << " builtin_type='";
E->getBuiltinType().print(PrintWithColorRAII(OS, TypeColor).getOS());
PrintWithColorRAII(OS, TypeColor) << "'";
}
PrintWithColorRAII(OS, ParenthesisColor) << ')';
}

Expand Down
12 changes: 10 additions & 2 deletions lib/AST/Expr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -974,8 +974,16 @@ llvm::APFloat FloatLiteralExpr::getValue() const {
assert(!getType().isNull() && "Semantic analysis has not completed");
assert(!getType()->hasError() && "Should have a valid type");

return getFloatLiteralValue(isNegative(), getDigitsText(),
getType()->castTo<BuiltinFloatType>()->getAPFloatSemantics());
Type ty = getType();
if (!ty->is<BuiltinFloatType>()) {
assert(!getBuiltinType().isNull() && "Semantic analysis has not completed");
assert(!getBuiltinType()->hasError() && "Should have a valid type");
ty = getBuiltinType();
}

return getFloatLiteralValue(
isNegative(), getDigitsText(),
ty->castTo<BuiltinFloatType>()->getAPFloatSemantics());
}

StringLiteralExpr::StringLiteralExpr(StringRef Val, SourceRange Range,
Expand Down
13 changes: 12 additions & 1 deletion lib/SILGen/SILGenApply.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -5543,10 +5543,21 @@ RValue SILGenFunction::emitLiteral(LiteralExpr *literal, SGFContext C) {
integerLiteral,
SILType::getBuiltinIntegerLiteralType(getASTContext()),
integerLiteral->getRawValue()));
CanType ty = integerManaged.getType().getASTType()->getCanonicalType();
CanType ty = integerManaged.getType().getASTType();
builtinLiteralArgs = RValue(*this, {integerManaged}, ty);
builtinInit = integerLiteral->getBuiltinInitializer();
init = integerLiteral->getInitializer();
} else if (auto floatLiteral = dyn_cast<FloatLiteralExpr>(literal)) {
auto *litTy = floatLiteral->getBuiltinType()->castTo<BuiltinFloatType>();
ManagedValue floatManaged = ManagedValue::forUnmanaged(B.createFloatLiteral(
floatLiteral,
SILType::getBuiltinFloatType(litTy->getFPKind(), getASTContext()),
floatLiteral->getValue()));

CanType ty = floatManaged.getType().getASTType();
builtinLiteralArgs = RValue(*this, {floatManaged}, ty);
builtinInit = floatLiteral->getBuiltinInitializer();
init = floatLiteral->getInitializer();
} else {
ASTContext &ctx = getASTContext();
SourceLoc loc = literal->getStartLoc();
Expand Down
7 changes: 5 additions & 2 deletions lib/SILGen/SILGenExpr.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -959,8 +959,11 @@ RValue RValueEmitter::visitIntegerLiteralExpr(IntegerLiteralExpr *E,
}
RValue RValueEmitter::visitFloatLiteralExpr(FloatLiteralExpr *E,
SGFContext C) {
return RValue(SGF, E,
ManagedValue::forUnmanaged(SGF.B.createFloatLiteral(E)));
if (E->getType()->is<BuiltinFloatType>())
return RValue(SGF, E,
ManagedValue::forUnmanaged(SGF.B.createFloatLiteral(E)));

return SGF.emitLiteral(E, C);
}

RValue RValueEmitter::visitBooleanLiteralExpr(BooleanLiteralExpr *E,
Expand Down
3 changes: 3 additions & 0 deletions lib/SILOptimizer/Utils/ConstantFolding.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1122,6 +1122,9 @@ static SILValue foldFPTrunc(BuiltinInst *BI, const BuiltinInfo &Builtin,
tryExtractLiteralText(flitInst, fplitStr);

auto userType = CE ? CE->getType() : destType;
if (auto *FLE = Loc.getAsASTNode<FloatLiteralExpr>()) {
userType = FLE->getType();
}
auto diagId = overflow
? diag::warning_float_trunc_overflow
: (hexnInexact ? diag::warning_float_trunc_hex_inexact
Expand Down
228 changes: 5 additions & 223 deletions lib/Sema/CSApply.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1060,65 +1060,6 @@ namespace {
/// Describes either a type or the name of a type to be resolved.
using TypeOrName = llvm::PointerUnion<Identifier, Type>;

/// Convert the given literal expression via a protocol pair.
///
/// This routine handles the two-step literal conversion process used
/// by integer, float, character, extended grapheme cluster, and string
/// literals. The first step uses \c builtinProtocol while the second
/// step uses \c protocol.
///
/// \param literal The literal expression.
///
/// \param type The literal type. This type conforms to \c protocol,
/// and may also conform to \c builtinProtocol.
///
/// \param openedType The literal type as it was opened in the type system.
///
/// \param protocol The protocol that describes the literal requirement.
///
/// \param literalType Either the name of the associated type in
/// \c protocol that describes the argument type of the conversion function
/// (\c literalFuncName) or the argument type itself.
///
/// \param literalFuncName The name of the conversion function requirement
/// in \c protocol.
///
/// \param builtinProtocol The "builtin" form of the protocol, which
/// always takes builtin types and can only be properly implemented
/// by standard library types. If \c type does not conform to this
/// protocol, it's literal type will.
///
/// \param builtinLiteralType Either the name of the associated type in
/// \c builtinProtocol that describes the argument type of the builtin
/// conversion function (\c builtinLiteralFuncName) or the argument type
/// itself.
///
/// \param builtinLiteralFuncName The name of the conversion function
/// requirement in \c builtinProtocol.
///
/// \param isBuiltinArgType Function that determines whether the given
/// type is acceptable as the argument type for the builtin conversion.
///
/// \param brokenProtocolDiag The diagnostic to emit if the protocol
/// is broken.
///
/// \param brokenBuiltinProtocolDiag The diagnostic to emit if the builtin
/// protocol is broken.
///
/// \returns the converted literal expression.
Expr *convertLiteral(Expr *literal,
Type type,
Type openedType,
ProtocolDecl *protocol,
TypeOrName literalType,
DeclName literalFuncName,
ProtocolDecl *builtinProtocol,
TypeOrName builtinLiteralType,
DeclName builtinLiteralFuncName,
bool (*isBuiltinArgType)(Type),
Diag<> brokenProtocolDiag,
Diag<> brokenBuiltinProtocolDiag);

/// Convert the given literal expression via a protocol pair.
///
/// This routine handles the two-step literal conversion process used
Expand Down Expand Up @@ -1903,19 +1844,11 @@ namespace {
DeclName builtinInitName(tc.Context, DeclBaseName::createConstructor(),
{ tc.Context.Id_builtinFloatLiteral });

return convertLiteral(
expr,
type,
cs.getType(expr),
protocol,
tc.Context.Id_FloatLiteralType,
initName,
builtinProtocol,
maxType,
builtinInitName,
nullptr,
diag::float_literal_broken_proto,
diag::builtin_float_literal_broken_proto);
expr->setBuiltinType(maxType);
return convertLiteralInPlace(
expr, type, protocol, tc.Context.Id_FloatLiteralType, initName,
builtinProtocol, builtinInitName, diag::float_literal_broken_proto,
diag::builtin_float_literal_broken_proto);
}

Expr *visitBooleanLiteralExpr(BooleanLiteralExpr *expr) {
Expand Down Expand Up @@ -6865,157 +6798,6 @@ ExprRewriter::coerceObjectArgumentToType(Expr *expr,
/*isImplicit*/ true));
}

Expr *ExprRewriter::convertLiteral(Expr *literal,
Type type,
Type openedType,
ProtocolDecl *protocol,
TypeOrName literalType,
DeclName literalFuncName,
ProtocolDecl *builtinProtocol,
TypeOrName builtinLiteralType,
DeclName builtinLiteralFuncName,
bool (*isBuiltinArgType)(Type),
Diag<> brokenProtocolDiag,
Diag<> brokenBuiltinProtocolDiag) {
auto &tc = cs.getTypeChecker();

auto getType = [&](const Expr *E) -> Type {
return cs.getType(E);
};

auto setType = [&](Expr *E, Type Ty) {
cs.setType(E, Ty);
};

// If coercing a literal to an unresolved type, we don't try to look up the
// witness members, just do it.
if (type->is<UnresolvedType>()) {
// Instead of updating the literal expr in place, allocate a new node. This
// avoids issues where Builtin types end up on expr nodes and pollute
// diagnostics.
literal = cast<LiteralExpr>(literal)->shallowClone(tc.Context, setType,
getType);

// The literal expression has this type.
cs.setType(literal, type);
return literal;
}

// Check whether this literal type conforms to the builtin protocol.
Optional<ProtocolConformanceRef> builtinConformance;
if (builtinProtocol &&
(builtinConformance =
tc.conformsToProtocol(
type, builtinProtocol, cs.DC,
(ConformanceCheckFlags::InExpression)))) {

// Find the builtin argument type we'll use.
Type argType;
if (builtinLiteralType.is<Type>())
argType = builtinLiteralType.get<Type>();
else
argType = tc.getWitnessType(type, builtinProtocol,
*builtinConformance,
builtinLiteralType.get<Identifier>(),
brokenBuiltinProtocolDiag);

if (!argType)
return nullptr;

// Make sure it's of an appropriate builtin type.
if (isBuiltinArgType && !isBuiltinArgType(argType)) {
tc.diagnose(builtinProtocol->getLoc(), brokenBuiltinProtocolDiag);
return nullptr;
}

// Instead of updating the literal expr in place, allocate a new node. This
// avoids issues where Builtin types end up on expr nodes and pollute
// diagnostics.
literal = cast<LiteralExpr>(literal)->shallowClone(tc.Context, setType,
getType);

// The literal expression has this type.
cs.setType(literal, argType);

// Call the builtin conversion operation.
// FIXME: Bogus location info.
Expr *base =
TypeExpr::createImplicitHack(literal->getLoc(), type, tc.Context);

cs.cacheExprTypes(base);
cs.setExprTypes(base);
cs.setExprTypes(literal);
SmallVector<Expr *, 1> arguments = { literal };

Expr *result = tc.callWitness(base, dc,
builtinProtocol, *builtinConformance,
builtinLiteralFuncName,
arguments,
brokenBuiltinProtocolDiag);
if (result)
cs.cacheExprTypes(result);

return result;
}

// This literal type must conform to the (non-builtin) protocol.
assert(protocol && "requirements should have stopped recursion");
auto conformance = tc.conformsToProtocol(type, protocol, cs.DC,
ConformanceCheckFlags::InExpression);
assert(conformance && "must conform to literal protocol");

// Figure out the (non-builtin) argument type if there is one.
Type argType;
if (literalType.is<Identifier>() &&
literalType.get<Identifier>().empty()) {
// If there is no argument to the constructor function, then just pass in
// the empty tuple.
literal =
cs.cacheType(
TupleExpr::createEmpty(tc.Context, literal->getLoc(),
literal->getLoc(),
/*implicit*/!literal->getLoc().isValid()));
} else {
// Otherwise, figure out the type of the constructor function and coerce to
// it.
if (literalType.is<Type>())
argType = literalType.get<Type>();
else
argType = tc.getWitnessType(type, protocol, *conformance,
literalType.get<Identifier>(),
brokenProtocolDiag);
if (!argType)
return nullptr;

// Convert the literal to the non-builtin argument type via the
// builtin protocol, first.
// FIXME: Do we need an opened type here?
literal = convertLiteral(literal, argType, argType, nullptr, Identifier(),
Identifier(), builtinProtocol,
builtinLiteralType, builtinLiteralFuncName,
isBuiltinArgType, brokenProtocolDiag,
brokenBuiltinProtocolDiag);
if (!literal)
return nullptr;
}

// Convert the resulting expression to the final literal type.
// FIXME: Bogus location info.
Expr *base = TypeExpr::createImplicitHack(literal->getLoc(), type,
tc.Context);
cs.cacheExprTypes(base);
cs.setExprTypes(base);
cs.setExprTypes(literal);

literal = tc.callWitness(base, dc,
protocol, *conformance, literalFuncName,
literal, brokenProtocolDiag);
if (literal)
cs.cacheExprTypes(literal);

return literal;
}

Expr *ExprRewriter::convertLiteralInPlace(Expr *literal,
Type type,
ProtocolDecl *protocol,
Expand Down
2 changes: 1 addition & 1 deletion test/SILGen/default_arguments.swift
Original file line number Diff line number Diff line change
Expand Up @@ -26,8 +26,8 @@ func defarg1(i: Int = 17, d: Double, s: String = "Hello") { }

// CHECK-LABEL: sil hidden [ossa] @$s17default_arguments15testDefaultArg1yyF
func testDefaultArg1() {
// CHECK: [[FLOAT64:%[0-9]+]] = metatype $@thin Double.Type
// CHECK: [[FLOATLIT:%[0-9]+]] = float_literal $Builtin.FPIEEE{{64|80}}, {{0x4009000000000000|0x4000C800000000000000}}
// CHECK: [[FLOAT64:%[0-9]+]] = metatype $@thin Double.Type
// CHECK: [[LITFN:%[0-9]+]] = function_ref @$sSd20_builtinFloatLiteralSdBf{{[_0-9]*}}__tcfC
// CHECK: [[FLOATVAL:%[0-9]+]] = apply [[LITFN]]([[FLOATLIT]], [[FLOAT64]])
// CHECK: [[DEF0FN:%[0-9]+]] = function_ref @$s17default_arguments7defarg1{{.*}}A_
Expand Down
2 changes: 1 addition & 1 deletion test/SILGen/default_constructor.swift
Original file line number Diff line number Diff line change
Expand Up @@ -19,8 +19,8 @@ struct D {
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Int.Type
// CHECK: [[FN:%.*]] = function_ref @$sSi22_builtinIntegerLiteralSiBI_tcfC : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK-NEXT: [[LEFT:%.*]] = apply [[FN]]([[VALUE]], [[METATYPE]]) : $@convention(method) (Builtin.IntLiteral, @thin Int.Type) -> Int
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Double.Type
// CHECK-NEXT: [[VALUE:%.*]] = float_literal $Builtin.FPIEEE{{64|80}}, {{0x400C000000000000|0x4000E000000000000000}}
// CHECK-NEXT: [[METATYPE:%.*]] = metatype $@thin Double.Type
// CHECK: [[FN:%.*]] = function_ref @$sSd20_builtinFloatLiteralSdBf{{64|80}}__tcfC : $@convention(method) (Builtin.FPIEEE{{64|80}}, @thin Double.Type) -> Double
// CHECK-NEXT: [[RIGHT:%.*]] = apply [[FN]]([[VALUE]], [[METATYPE]]) : $@convention(method) (Builtin.FPIEEE{{64|80}}, @thin Double.Type) -> Double
// CHECK-NEXT: [[RESULT:%.*]] = tuple ([[LEFT]] : $Int, [[RIGHT]] : $Double)
Expand Down
Loading