Skip to content

Add Builtin.print_disabled() #39698

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

Closed
wants to merge 1 commit into from
Closed
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
3 changes: 3 additions & 0 deletions include/swift/AST/Builtins.def
Original file line number Diff line number Diff line change
Expand Up @@ -642,6 +642,9 @@ BUILTIN_MISC_OPERATION(StaticReport, "staticReport", "", Special)
/// Returns the selected assertion configuration.
BUILTIN_MISC_OPERATION(AssertConf, "assert_configuration", "n", Special)

/// PrintDisabled has type () -> Bool
BUILTIN_MISC_OPERATION(PrintDisabled, "print_disabled", "n", Special)

/// StringObjectOr has type (T,T) -> T.
/// Sets bits in a string object. The first operand is bit-cast string literal
/// pointer to an integer. The second operand is the bit mask to be or'd into
Expand Down
9 changes: 9 additions & 0 deletions include/swift/AST/SILOptions.h
Original file line number Diff line number Diff line change
Expand Up @@ -127,6 +127,15 @@ class SILOptions {
/// The assert configuration controls how assertions behave.
unsigned AssertConfig = Debug;

enum PrintConfiguration: unsigned {
// Used by stdlib code to tell whether client is built with -disable-print
Normal = 0,
Disabled = 1,
};

/// The print configuration how printing from stdlib should behave.
unsigned PrintConfig = Normal;

/// Should we print out instruction counts if -print-stats is passed in?
bool PrintInstCounts = false;

Expand Down
4 changes: 4 additions & 0 deletions include/swift/Option/FrontendOptions.td
Original file line number Diff line number Diff line change
Expand Up @@ -446,6 +446,10 @@ def enable_experimental_static_assert :
Flag<["-"], "enable-experimental-static-assert">,
HelpText<"Enable experimental #assert">;

def experimental_disable_print : Flag<["-"], "experimental-disable-print">,
Flags<[FrontendOption, HelpHidden]>,
HelpText<"Turn print() calls into no-ops.">;

def enable_experimental_named_opaque_types :
Flag<["-"], "enable-experimental-named-opaque-types">,
HelpText<"Enable experimental support for named opaque result types">;
Expand Down
5 changes: 5 additions & 0 deletions include/swift/SILOptimizer/Utils/ConstantFolding.h
Original file line number Diff line number Diff line change
Expand Up @@ -64,6 +64,9 @@ class ConstantFolder {
/// The assert configuration of SILOptions.
unsigned AssertConfiguration;

/// The print configuration of SILOptions.
unsigned PrintConfiguration;

/// Print diagnostics as part of mandatory constant propagation.
bool EnableDiagnostics;

Expand All @@ -79,11 +82,13 @@ class ConstantFolder {
/// \param Callback Called for each constant folded instruction.
ConstantFolder(SILOptFunctionBuilder &FuncBuilder,
unsigned AssertConfiguration,
unsigned PrintConfiguration,
bool EnableDiagnostics = false,
std::function<void (SILInstruction *)> Callback =
[](SILInstruction *){}) :
FuncBuilder(FuncBuilder),
AssertConfiguration(AssertConfiguration),
PrintConfiguration(PrintConfiguration),
EnableDiagnostics(EnableDiagnostics),
Callback(Callback) { }

Expand Down
9 changes: 9 additions & 0 deletions lib/AST/Builtins.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1682,6 +1682,12 @@ static ValueDecl *getAssertConfOperation(ASTContext &C, Identifier Id) {
return getBuiltinFunction(Id, {}, Int32Ty);
}

static ValueDecl *getPrintDisabledOperation(ASTContext &C, Identifier Id) {
// () -> Int1
auto Int1Ty = BuiltinIntegerType::get(1, C);
return getBuiltinFunction(Id, {}, Int1Ty);
}

static ValueDecl *getFixLifetimeOperation(ASTContext &C, Identifier Id) {
// <T> T -> ()
BuiltinFunctionBuilder builder(C);
Expand Down Expand Up @@ -2675,6 +2681,9 @@ ValueDecl *swift::getBuiltinValueDecl(ASTContext &Context, Identifier Id) {

case BuiltinValueKind::AssertConf:
return getAssertConfOperation(Context, Id);

case BuiltinValueKind::PrintDisabled:
return getPrintDisabledOperation(Context, Id);

case BuiltinValueKind::FixLifetime:
return getFixLifetimeOperation(Context, Id);
Expand Down
7 changes: 7 additions & 0 deletions lib/Frontend/CompilerInvocation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1397,6 +1397,13 @@ static bool ParseSILArgs(SILOptions &Opts, ArgList &Args,
(IRGenOpts.shouldOptimize() ? SILOptions::Release : SILOptions::Debug);
}

Opts.PrintConfig = Args.hasArg(OPT_experimental_disable_print)
? SILOptions::Disabled
: SILOptions::Normal;
if (FEOpts.ParseStdlib) {
Opts.PrintConfig = SILOptions::DisableReplacement;
}

// -Ounchecked might also set removal of runtime asserts (cond_fail).
Opts.RemoveRuntimeAsserts |= Args.hasArg(OPT_RemoveRuntimeAsserts);

Expand Down
4 changes: 4 additions & 0 deletions lib/IRGen/GenBuiltin.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1087,6 +1087,10 @@ if (Builtin.ID == BuiltinValueKind::id) { \
out.add(DebugAssert);
return;
}

if (Builtin.ID == BuiltinValueKind::PrintDisabled) {
llvm_unreachable("PrintDisabled not constant folded");
}

if (Builtin.ID == BuiltinValueKind::DestroyArray) {
// The input type is (T.Type, Builtin.RawPointer, Builtin.Word).
Expand Down
1 change: 1 addition & 0 deletions lib/SIL/IR/OperandOwnership.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -641,6 +641,7 @@ BUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, AllocRaw)
BUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, And)
BUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, GenericAnd)
BUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, AssertConf)
BUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, PrintDisabled)
BUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, AssignCopyArrayNoAlias)
BUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, AssignCopyArrayFrontToBack)
BUILTIN_OPERAND_OWNERSHIP(InstantaneousUse, AssignCopyArrayBackToFront)
Expand Down
1 change: 1 addition & 0 deletions lib/SIL/IR/ValueOwnership.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -486,6 +486,7 @@ CONSTANT_OWNERSHIP_BUILTIN(None, IsSameMetatype)
CONSTANT_OWNERSHIP_BUILTIN(None, Alignof)
CONSTANT_OWNERSHIP_BUILTIN(None, AllocRaw)
CONSTANT_OWNERSHIP_BUILTIN(None, AssertConf)
CONSTANT_OWNERSHIP_BUILTIN(None, PrintDisabled)
CONSTANT_OWNERSHIP_BUILTIN(None, UToSCheckedTrunc)
CONSTANT_OWNERSHIP_BUILTIN(None, SToSCheckedTrunc)
CONSTANT_OWNERSHIP_BUILTIN(None, SToUCheckedTrunc)
Expand Down
3 changes: 2 additions & 1 deletion lib/SILOptimizer/IPO/GlobalOpt.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -409,7 +409,8 @@ replaceLoadsByKnownValue(SILFunction *InitF, SILGlobalVariable *SILG,
// constant, e.g.
// let a = 1
// let b = a + 1
ConstantFolder constFolder(FunctionBuilder, PM->getOptions().AssertConfig);
ConstantFolder constFolder(FunctionBuilder, PM->getOptions().AssertConfig,
PM->getOptions().PrintConfig);
for (SILInstruction *inst : insertedInsts) {
constFolder.addToWorklist(inst);
}
Expand Down
2 changes: 1 addition & 1 deletion lib/SILOptimizer/Mandatory/ConstantPropagation.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -35,7 +35,7 @@ class ConstantPropagation : public SILFunctionTransform {
void run() override {
SILOptFunctionBuilder FuncBuilder(*this);
ConstantFolder Folder(FuncBuilder, getOptions().AssertConfig,
EnableDiagnostics);
getOptions().PrintConfig, EnableDiagnostics);
Folder.initializeWorklist(*getFunction());
auto Invalidation = Folder.processWorkList();

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,7 @@ static bool isBarrier(SILInstruction *inst) {
case BuiltinValueKind::ShuffleVector:
case BuiltinValueKind::StaticReport:
case BuiltinValueKind::AssertConf:
case BuiltinValueKind::PrintDisabled:
case BuiltinValueKind::StringObjectOr:
case BuiltinValueKind::UToSCheckedTrunc:
case BuiltinValueKind::SToUCheckedTrunc:
Expand Down
1 change: 1 addition & 0 deletions lib/SILOptimizer/Transforms/SimplifyCFG.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -138,6 +138,7 @@ class SimplifyCFG {
bool EnableJumpThread)
: FuncBuilder(T), Fn(Fn), PM(T.getPassManager()),
ConstFolder(FuncBuilder, PM->getOptions().AssertConfig,
PM->getOptions().PrintConfig,
/* EnableDiagnostics */ false,
[&](SILInstruction *I) { constFoldingCallback(I); }),
ShouldVerify(Verify), EnableJumpThread(EnableJumpThread) {}
Expand Down
28 changes: 25 additions & 3 deletions lib/SILOptimizer/Utils/ConstantFolding.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -1152,6 +1152,15 @@ static SILValue constantFoldIsConcrete(BuiltinInst *BI) {
return inst;
}

static SILValue constantFoldPrintDisabled(BuiltinInst *BI, bool PrintDisabled) {
SILBuilderWithScope builder(BI);
auto *inst = builder.createIntegerLiteral(
BI->getLoc(), SILType::getBuiltinIntegerType(1, builder.getASTContext()),
PrintDisabled);
BI->replaceAllUsesWith(inst);
return inst;
}

static SILValue constantFoldBuiltin(BuiltinInst *BI,
Optional<bool> &ResultsInError) {
const IntrinsicInfo &Intrinsic = BI->getIntrinsicInfo();
Expand Down Expand Up @@ -1569,7 +1578,8 @@ void ConstantFolder::initializeWorklist(SILFunction &f) {
}

if (isApplyOfBuiltin(*inst, BuiltinValueKind::GlobalStringTablePointer) ||
isApplyOfBuiltin(*inst, BuiltinValueKind::IsConcrete)) {
isApplyOfBuiltin(*inst, BuiltinValueKind::IsConcrete) ||
isApplyOfBuiltin(*inst, BuiltinValueKind::PrintDisabled)) {
WorkList.insert(inst);
continue;
}
Expand Down Expand Up @@ -1779,7 +1789,7 @@ ConstantFolder::processWorkList() {
if (isApplyOfBuiltin(*I, BuiltinValueKind::GlobalStringTablePointer)) {
if (constantFoldGlobalStringTablePointerBuiltin(cast<BuiltinInst>(I),
EnableDiagnostics)) {
// Here, the bulitin instruction got folded, so clean it up.
// Here, the builtin instruction got folded, so clean it up.
eliminateDeadInstruction(I, callbacks);
}
continue;
Expand All @@ -1804,13 +1814,25 @@ ConstantFolder::processWorkList() {

if (isApplyOfBuiltin(*I, BuiltinValueKind::IsConcrete)) {
if (constantFoldIsConcrete(cast<BuiltinInst>(I))) {
// Here, the bulitin instruction got folded, so clean it up.
// Here, the builtin instruction got folded, so clean it up.
recursivelyDeleteTriviallyDeadInstructions(I, /*force*/ true,
callbacks);
}
continue;
}

if (PrintConfiguration != SILOptions::DisableReplacement) {
if (isApplyOfBuiltin(*I, BuiltinValueKind::PrintDisabled)) {
if (constantFoldPrintDisabled(cast<BuiltinInst>(I),
PrintConfiguration ==
SILOptions::Disabled)) {
// Here, the builtin instruction got folded, so clean it up.
eliminateDeadInstruction(I, callbacks);
}
continue;
}
}

if (auto *bi = dyn_cast<BuiltinInst>(I)) {
if (auto kind = bi->getBuiltinKind()) {
if (SILValue v = specializePolymorphicBuiltin(bi, kind.getValue())) {
Expand Down
13 changes: 13 additions & 0 deletions stdlib/public/core/Builtin.swift
Original file line number Diff line number Diff line change
Expand Up @@ -768,6 +768,19 @@ func _trueAfterDiagnostics() -> Builtin.Int1 {
return true._value
}

/// Whether client code is built with -print-disabled.
@_alwaysEmitIntoClient
private func _isPrintingDisabled() -> Bool {
return Bool(Builtin.print_disabled())
}

// For testing only.
@_alwaysEmitIntoClient
private func _customPrint(_ s: String) {
if _isPrintingDisabled() { return }
print(s)
}

/// Returns the dynamic type of a value.
///
/// You can use the `type(of:)` function to find the dynamic type of a value,
Expand Down
25 changes: 25 additions & 0 deletions test/stdlib/print-disabled.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
// RUN: %empty-directory(%t)
// RUN: %target-build-swift %s -Xfrontend -disable-access-control -o %t/Release -O
// RUN: %target-build-swift %s -Xfrontend -disable-access-control -o %t/ReleasePrintDisabled -O -disable-print
// RUN: %target-run %t/Release | %FileCheck %s
// RUN: %target-run %t/ReleasePrintDisabled | %FileCheck %s --check-prefix CHECK-PRINT-DISABLED

// REQUIRES: executable_test

#if canImport(Darwin)
import Darwin
#elseif canImport(Glibc)
import Glibc
#elseif os(Windows)
import CRT
import WinSDK
#endif

puts("Start\n")
_customPrint("Hello world!")

// CHECK: Start
// CHECK: Hello world!

// CHECK-PRINT-DISABLED: Start
// CHECK-PRINT-DISABLED-NOT: Hello world!