diff --git a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/INodeWithCodeInfo.cs b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/INodeWithCodeInfo.cs index 9f6d2174906..62e8c282fc3 100644 --- a/src/coreclr/tools/Common/Compiler/DependencyAnalysis/INodeWithCodeInfo.cs +++ b/src/coreclr/tools/Common/Compiler/DependencyAnalysis/INodeWithCodeInfo.cs @@ -47,29 +47,4 @@ namespace ILCompiler.DependencyAnalysis HandlerLength = handlerLength; } } - - public interface INodeWithCodeInfo - { - FrameInfo[] FrameInfos - { - get; - } - - byte[] GCInfo - { - get; - } - - DebugEHClauseInfo[] DebugEHClauseInfos - { - get; - } - - ObjectNode.ObjectData EHInfo - { - get; - } - - ISymbolNode GetAssociatedDataNode(NodeFactory factory); - } } diff --git a/src/coreclr/tools/Common/Compiler/DisplayNameHelpers.cs b/src/coreclr/tools/Common/Compiler/DisplayNameHelpers.cs new file mode 100644 index 00000000000..674d54a95e0 --- /dev/null +++ b/src/coreclr/tools/Common/Compiler/DisplayNameHelpers.cs @@ -0,0 +1,206 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System.Text; + +using Internal.TypeSystem; + +using Debug = System.Diagnostics.Debug; + +namespace ILCompiler +{ + internal static class DisplayNameHelpers + { + public static string GetDisplayName(this MethodDesc method) + { + var sb = new StringBuilder(); + + sb.Append(method.OwningType.GetDisplayName()); + sb.Append('.'); + + if (method.IsConstructor) + { + sb.Append(method.OwningType.GetDisplayNameWithoutNamespace()); + } + else + { + sb.Append(method.Name); + } + + if (method.HasInstantiation) + { + sb.Append('<'); + for (int i = 0; i < method.Instantiation.Length - 1; i++) + sb.Append(method.Instantiation[i].GetDisplayNameWithoutNamespace()).Append(','); + + sb.Append(method.Instantiation[method.Instantiation.Length - 1].GetDisplayNameWithoutNamespace()); + sb.Append('>'); + } + + // Append parameters + sb.Append('('); + if (method.Signature.Length > 0) + { + for (int i = 0; i < method.Signature.Length - 1; i++) + sb.Append(method.Signature[i].GetDisplayNameWithoutNamespace()).Append(','); + + sb.Append(method.Signature[method.Signature.Length - 1].GetDisplayNameWithoutNamespace()); + } + + sb.Append(')'); + + return sb.ToString(); + } + + public static string GetDisplayName(this FieldDesc field) + { + return new StringBuilder(field.OwningType.GetDisplayName()) + .Append('.') + .Append(field.Name).ToString(); + } + +#if !READYTORUN + public static string GetDisplayName(this PropertyPseudoDesc property) + { + return new StringBuilder(property.OwningType.GetDisplayName()) + .Append('.') + .Append(property.Name).ToString(); + } +#endif + + public static string GetDisplayName(this TypeDesc type) + { + return Formatter.Instance.FormatName(type, FormatOptions.NamespaceQualify); + } + + public static string GetDisplayNameWithoutNamespace(this TypeDesc type) + { + return Formatter.Instance.FormatName(type, FormatOptions.None); + } + + private class Formatter : TypeNameFormatter + { + public readonly static Formatter Instance = new Formatter(); + + public override Unit AppendName(StringBuilder sb, ArrayType type, FormatOptions options) + { + AppendName(sb, type.ElementType, options); + sb.Append('['); + if (type.Rank > 1) + sb.Append(new string(',', type.Rank - 1)); + sb.Append(']'); + return default; + } + + public override Unit AppendName(StringBuilder sb, ByRefType type, FormatOptions options) + { + AppendName(sb, type.ParameterType, options); + sb.Append('&'); + return default; + } + + public override Unit AppendName(StringBuilder sb, PointerType type, FormatOptions options) + { + AppendName(sb, type.ParameterType, options); + sb.Append('*'); + return default; + } + + public override Unit AppendName(StringBuilder sb, FunctionPointerType type, FormatOptions options) + { + MethodSignature signature = type.Signature; + + sb.Append("delegate*<"); + for (int i = 0; i < signature.Length; i++) + { + AppendName(sb, signature[i], options); + sb.Append(','); + } + AppendName(sb, signature.ReturnType, options); + sb.Append('>'); + + return default; + } + + public override Unit AppendName(StringBuilder sb, GenericParameterDesc type, FormatOptions options) + { + sb.Append(type.Name); + return default; + } + + public override Unit AppendName(StringBuilder sb, SignatureMethodVariable type, FormatOptions options) + { + sb.Append("!!" + type.Index); + return default; + } + + public override Unit AppendName(StringBuilder sb, SignatureTypeVariable type, FormatOptions options) + { + sb.Append("!" + type.Index); + return default; + } + + protected override Unit AppendNameForInstantiatedType(StringBuilder sb, DefType type, FormatOptions options) + { + AppendName(sb, type.GetTypeDefinition(), options); + + FormatOptions parameterOptions = options & ~FormatOptions.NamespaceQualify; + + sb.Append('<'); + + for (int i = 0; i < type.Instantiation.Length; i++) + { + if (i != 0) + sb.Append(','); + + AppendName(sb, type.Instantiation[i], parameterOptions); + } + + sb.Append('>'); + + return default; + } + + protected override Unit AppendNameForNamespaceType(StringBuilder sb, DefType type, FormatOptions options) + { + NamespaceQualify(sb, type, options); + sb.Append(type.Name); + return default; + } + + protected override Unit AppendNameForNestedType(StringBuilder sb, DefType nestedType, DefType containingType, FormatOptions options) + { + if ((options & FormatOptions.NamespaceQualify) != 0) + { + AppendName(sb, containingType, options); + sb.Append('.'); + } + + sb.Append(nestedType.Name); + + return default; + } + + private void NamespaceQualify(StringBuilder sb, DefType type, FormatOptions options) + { + if ((options & FormatOptions.NamespaceQualify) != 0) + { + string ns = type.Namespace; + if (!string.IsNullOrEmpty(ns)) + { + sb.Append(ns); + sb.Append('.'); + } + } + } + + public struct Unit { } + } + + private enum FormatOptions + { + None = 0, + NamespaceQualify = 1, + } + } +} diff --git a/src/coreclr/tools/Common/Compiler/Logger.cs b/src/coreclr/tools/Common/Compiler/Logger.cs index af2d728577c..55f87b204db 100644 --- a/src/coreclr/tools/Common/Compiler/Logger.cs +++ b/src/coreclr/tools/Common/Compiler/Logger.cs @@ -1,24 +1,130 @@ // Licensed to the .NET Foundation under one or more agreements. // The .NET Foundation licenses this file to you under the MIT license. +using System; +using System.Collections.Generic; +using System.Reflection.Metadata; using System.IO; +using Internal.TypeSystem; +using Internal.TypeSystem.Ecma; + +using ILCompiler.Logging; + +using ILSequencePoint = Internal.IL.ILSequencePoint; +using MethodIL = Internal.IL.MethodIL; + namespace ILCompiler { - // Poor man's logger. We can do better than this. - public class Logger { + private readonly HashSet _suppressedWarnings; + public static Logger Null = new Logger(TextWriter.Null, false); public TextWriter Writer { get; } public bool IsVerbose { get; } - public Logger(TextWriter writer, bool isVerbose) + public Logger(TextWriter writer, bool isVerbose, IEnumerable suppressedWarnings) { Writer = TextWriter.Synchronized(writer); IsVerbose = isVerbose; + _suppressedWarnings = new HashSet(suppressedWarnings); + } + + public Logger(TextWriter writer, bool isVerbose) + : this(writer, isVerbose, Array.Empty()) + { + } + + public void LogWarning(string text, int code, MessageOrigin origin, string subcategory = MessageSubCategory.None) + { + MessageContainer? warning = MessageContainer.CreateWarningMessage(this, text, code, origin, subcategory); + if (warning.HasValue) + Writer.WriteLine(warning.Value.ToMSBuildString()); + } + + public void LogWarning(string text, int code, TypeSystemEntity origin, string subcategory = MessageSubCategory.None) + { + MessageOrigin messageOrigin = new MessageOrigin(origin); + MessageContainer? warning = MessageContainer.CreateWarningMessage(this, text, code, messageOrigin, subcategory); + if (warning.HasValue) + Writer.WriteLine(warning.Value.ToMSBuildString()); + } + + public void LogWarning(string text, int code, MethodIL origin, int ilOffset, string subcategory = MessageSubCategory.None) + { + string document = null; + int? lineNumber = null; + + IEnumerable sequencePoints = origin.GetDebugInfo()?.GetSequencePoints(); + if (sequencePoints != null) + { + foreach (var sequencePoint in sequencePoints) + { + if (sequencePoint.Offset <= ilOffset) + { + document = sequencePoint.Document; + lineNumber = sequencePoint.LineNumber; + } + } + } + + MessageOrigin messageOrigin = new MessageOrigin(origin.OwningMethod, document, lineNumber, null); + LogWarning(text, code, messageOrigin, subcategory); + } + + internal bool IsWarningSuppressed(int code, MessageOrigin origin) + { + if (_suppressedWarnings.Contains(code)) + return true; + + IEnumerable> suppressions = null; + + // TODO: Suppressions with different scopes + + + if (origin.MemberDefinition is MethodDesc method) + { + var ecmaMethod = method.GetTypicalMethodDefinition() as EcmaMethod; + suppressions = ecmaMethod?.GetDecodedCustomAttributes("System.Diagnostics.CodeAnalysis", "UnconditionalSuppressMessageAttribute"); + } + + if (suppressions != null) + { + foreach (CustomAttributeValue suppression in suppressions) + { + if (suppression.FixedArguments.Length != 2 + || suppression.FixedArguments[1].Value is not string warningId + || warningId.Length < 6 + || !warningId.StartsWith("IL") + || (warningId.Length > 6 && warningId[6] != ':') + || !int.TryParse(warningId.Substring(2, 4), out int suppressedCode)) + { + continue; + } + + if (code == suppressedCode) + { + return true; + } + } + } + + return false; + } + + internal bool IsWarningAsError(int code) + { + // TODO: warnaserror + return false; } } + + public static class MessageSubCategory + { + public const string None = ""; + public const string TrimAnalysis = "Trim analysis"; + } } diff --git a/src/coreclr/tools/Common/Compiler/Logging/MessageContainer.cs b/src/coreclr/tools/Common/Compiler/Logging/MessageContainer.cs new file mode 100644 index 00000000000..7f1da04ba32 --- /dev/null +++ b/src/coreclr/tools/Common/Compiler/Logging/MessageContainer.cs @@ -0,0 +1,206 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Text; +using Internal.TypeSystem; + +namespace ILCompiler.Logging +{ + public enum MessageCategory + { + Error = 0, + Warning, + Info, + Diagnostic, + + WarningAsError = 0xFF + } + + public readonly struct MessageContainer +#if false + : IComparable, IEquatable +#endif + { + /// + /// Optional data with a filename, line and column that triggered the + /// linker to output an error (or warning) message. + /// + public MessageOrigin? Origin { get; } + + public MessageCategory Category { get; } + + /// + /// Further categorize the message. + /// + public string SubCategory { get; } + + /// + /// Code identifier for errors and warnings reported by the IL linker. + /// + public int? Code { get; } + + /// + /// User friendly text describing the error or warning. + /// + public string Text { get; } + + /// + /// Create an error message. + /// + /// Humanly readable message describing the error + /// Unique error ID. Please see https://github.com/mono/linker/blob/master/doc/error-codes.md + /// for the list of errors and possibly add a new one + /// Optionally, further categorize this error + /// Filename, line, and column where the error was found + /// New MessageContainer of 'Error' category + internal static MessageContainer CreateErrorMessage(string text, int code, string subcategory = MessageSubCategory.None, MessageOrigin? origin = null) + { + if (!(code >= 1000 && code <= 2000)) + throw new ArgumentOutOfRangeException(nameof(code), $"The provided code '{code}' does not fall into the error category, which is in the range of 1000 to 2000 (inclusive)."); + + return new MessageContainer(MessageCategory.Error, text, code, subcategory, origin); + } + + /// + /// Create a warning message. + /// + /// Context with the relevant warning suppression info. + /// Humanly readable message describing the warning + /// Unique warning ID. Please see https://github.com/mono/linker/blob/master/doc/error-codes.md + /// for the list of warnings and possibly add a new one + /// /// Filename or member where the warning is coming from + /// Optionally, further categorize this warning + /// Optional warning version number. Versioned warnings can be controlled with the + /// warning wave option --warn VERSION. Unversioned warnings are unaffected by this option. + /// New MessageContainer of 'Warning' category + internal static MessageContainer? CreateWarningMessage(Logger context, string text, int code, MessageOrigin origin, string subcategory = MessageSubCategory.None) + { + if (!(code > 2000 && code <= 6000)) + throw new ArgumentOutOfRangeException(nameof(code), $"The provided code '{code}' does not fall into the warning category, which is in the range of 2001 to 6000 (inclusive)."); + + return CreateWarningMessageContainer(context, text, code, origin, subcategory); + } + + private static MessageContainer? CreateWarningMessageContainer(Logger context, string text, int code, MessageOrigin origin, string subcategory = MessageSubCategory.None) + { + if (context.IsWarningSuppressed(code, origin)) + return null; + + if (context.IsWarningAsError(code)) + return new MessageContainer(MessageCategory.WarningAsError, text, code, subcategory, origin); + + return new MessageContainer(MessageCategory.Warning, text, code, subcategory, origin); + } + + /// + /// Create a info message. + /// + /// Humanly readable message + /// New MessageContainer of 'Info' category + public static MessageContainer CreateInfoMessage(string text) + { + return new MessageContainer(MessageCategory.Info, text, null); + } + + /// + /// Create a diagnostics message. + /// + /// Humanly readable message + /// New MessageContainer of 'Diagnostic' category + public static MessageContainer CreateDiagnosticMessage(string text) + { + return new MessageContainer(MessageCategory.Diagnostic, text, null); + } + + private MessageContainer(MessageCategory category, string text, int? code, string subcategory = MessageSubCategory.None, MessageOrigin? origin = null) + { + Code = code; + Category = category; + Origin = origin; + SubCategory = subcategory; + Text = text; + } + + public override string ToString() => ToMSBuildString(); + + public string ToMSBuildString() + { + const string originApp = "ILC"; + string origin = Origin?.ToString() ?? originApp; + + StringBuilder sb = new StringBuilder(); + sb.Append(origin).Append(":"); + + if (!string.IsNullOrEmpty(SubCategory)) + sb.Append(" ").Append(SubCategory); + + string cat; + switch (Category) + { + case MessageCategory.Error: + case MessageCategory.WarningAsError: + cat = "error"; + break; + case MessageCategory.Warning: + cat = "warning"; + break; + default: + cat = ""; + break; + } + + if (!string.IsNullOrEmpty(cat)) + { + sb.Append(" ") + .Append(cat) + .Append(" IL") + .Append(Code.Value.ToString("D4")) + .Append(": "); + } + else + { + sb.Append(" "); + } + + if (Origin?.MemberDefinition != null) + { + if (Origin?.MemberDefinition is MethodDesc method) + sb.Append(method.GetDisplayName()); + else + sb.Append(Origin?.MemberDefinition.ToString()); + + sb.Append(": "); + } + + // Expected output $"{FileName(SourceLine, SourceColumn)}: {SubCategory}{Category} IL{Code}: ({MemberDisplayName}: ){Text}"); + sb.Append(Text); + return sb.ToString(); + } + +#if false + public bool Equals(MessageContainer other) => + (Category, Text, Code, SubCategory, Origin) == (other.Category, other.Text, other.Code, other.SubCategory, other.Origin); + + public override bool Equals(object obj) => obj is MessageContainer messageContainer && Equals(messageContainer); + public override int GetHashCode() => (Category, Text, Code, SubCategory, Origin).GetHashCode(); + + public int CompareTo(MessageContainer other) + { + if (Origin != null && other.Origin != null) + { + return Origin.Value.CompareTo(other.Origin.Value); + } + else if (Origin == null && other.Origin == null) + { + return (Code < other.Code) ? -1 : 1; + } + + return (Origin == null) ? 1 : -1; + } + + public static bool operator ==(MessageContainer lhs, MessageContainer rhs) => lhs.Equals(rhs); + public static bool operator !=(MessageContainer lhs, MessageContainer rhs) => !lhs.Equals(rhs); +#endif + } +} diff --git a/src/coreclr/tools/Common/Compiler/Logging/MessageOrigin.cs b/src/coreclr/tools/Common/Compiler/Logging/MessageOrigin.cs new file mode 100644 index 00000000000..5e162e711d5 --- /dev/null +++ b/src/coreclr/tools/Common/Compiler/Logging/MessageOrigin.cs @@ -0,0 +1,90 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. + +using System; +using System.Text; + +using Internal.TypeSystem; + +namespace ILCompiler.Logging +{ + public struct MessageOrigin +#if false + : IComparable, IEquatable +#endif + { + public string FileName { get; } + public TypeSystemEntity MemberDefinition { get; } + + public int? SourceLine { get; } + public int? SourceColumn { get; } + + public MessageOrigin(string fileName, int sourceLine = 0, int sourceColumn = 0) + { + FileName = fileName; + SourceLine = sourceLine; + SourceColumn = sourceColumn; + MemberDefinition = null; + } + + public MessageOrigin(TypeSystemEntity memberDefinition, string fileName = null, int? sourceLine = 0, int? sourceColumn = 0) + { + FileName = fileName; + MemberDefinition = memberDefinition; + SourceLine = sourceLine; + SourceColumn = sourceColumn; + } + + public override string ToString() + { + if (FileName == null) + return null; + + StringBuilder sb = new StringBuilder(FileName); + if (SourceLine.HasValue) + { + sb.Append("(").Append(SourceLine); + if (SourceColumn.HasValue) + sb.Append(",").Append(SourceColumn); + + sb.Append(")"); + } + + return sb.ToString(); + } + +#if false + public bool Equals(MessageOrigin other) => + (FileName, MemberDefinition, SourceLine, SourceColumn) == (other.FileName, other.MemberDefinition, other.SourceLine, other.SourceColumn); + + public override bool Equals(object obj) => obj is MessageOrigin messageOrigin && Equals(messageOrigin); + public override int GetHashCode() => (FileName, MemberDefinition, SourceLine, SourceColumn).GetHashCode(); + public static bool operator ==(MessageOrigin lhs, MessageOrigin rhs) => lhs.Equals(rhs); + public static bool operator !=(MessageOrigin lhs, MessageOrigin rhs) => !lhs.Equals(rhs); + + public int CompareTo(MessageOrigin other) + { + if (MemberDefinition != null && other.MemberDefinition != null) + { + return (MemberDefinition.DeclaringType?.Module?.Assembly?.Name?.Name, MemberDefinition.DeclaringType?.Name, MemberDefinition?.Name).CompareTo + ((other.MemberDefinition.DeclaringType?.Module?.Assembly?.Name?.Name, other.MemberDefinition.DeclaringType?.Name, other.MemberDefinition?.Name)); + } + else if (MemberDefinition == null && other.MemberDefinition == null) + { + if (FileName != null && other.FileName != null) + { + return string.Compare(FileName, other.FileName); + } + else if (FileName == null && other.FileName == null) + { + return (SourceLine, SourceColumn).CompareTo((other.SourceLine, other.SourceColumn)); + } + + return (FileName == null) ? 1 : -1; + } + + return (MemberDefinition == null) ? 1 : -1; + } +#endif + } +} diff --git a/src/coreclr/tools/Common/Compiler/Logging/ReferenceSource/MessageContainer.cs b/src/coreclr/tools/Common/Compiler/Logging/ReferenceSource/MessageContainer.cs new file mode 100644 index 00000000000..7a6fa377d16 --- /dev/null +++ b/src/coreclr/tools/Common/Compiler/Logging/ReferenceSource/MessageContainer.cs @@ -0,0 +1,241 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Diagnostics; +using System.Reflection; +using System.Text; +using Mono.Cecil; + +namespace Mono.Linker +{ + public readonly struct MessageContainer : IComparable, IEquatable + { + public static readonly MessageContainer Empty; + + /// + /// Optional data with a filename, line and column that triggered the + /// linker to output an error (or warning) message. + /// + public MessageOrigin? Origin { get; } + + public MessageCategory Category { get; } + + /// + /// Further categorize the message. + /// + public string SubCategory { get; } + + /// + /// Code identifier for errors and warnings reported by the IL linker. + /// + public int? Code { get; } + + /// + /// User friendly text describing the error or warning. + /// + public string Text { get; } + + /// + /// Create an error message. + /// + /// Humanly readable message describing the error + /// Unique error ID. Please see https://github.com/mono/linker/blob/master/doc/error-codes.md + /// for the list of errors and possibly add a new one + /// Optionally, further categorize this error + /// Filename, line, and column where the error was found + /// New MessageContainer of 'Error' category + internal static MessageContainer CreateErrorMessage (string text, int code, string subcategory = MessageSubCategory.None, MessageOrigin? origin = null) + { + if (!(code >= 1000 && code <= 2000)) + throw new ArgumentOutOfRangeException (nameof (code), $"The provided code '{code}' does not fall into the error category, which is in the range of 1000 to 2000 (inclusive)."); + + return new MessageContainer (MessageCategory.Error, text, code, subcategory, origin); + } + + /// + /// Create a custom error message. + /// + /// Humanly readable message describing the error + /// A custom error ID. This code should be greater than or equal to 6001 + /// to avoid any collisions with existing and future linker errors + /// Optionally, further categorize this error + /// Filename or member where the error is coming from + /// Custom MessageContainer of 'Error' category + public static MessageContainer CreateCustomErrorMessage (string text, int code, string subcategory = MessageSubCategory.None, MessageOrigin? origin = null) + { +#if DEBUG + Debug.Assert (Assembly.GetCallingAssembly () != typeof (MessageContainer).Assembly, + "'CreateCustomErrorMessage' is intended to be used by external assemblies only. Use 'CreateErrorMessage' instead."); +#endif + if (code <= 6000) + throw new ArgumentOutOfRangeException (nameof (code), $"The provided code '{code}' does not fall into the permitted range for external errors. To avoid possible collisions " + + "with existing and future {Constants.ILLink} errors, external messages should use codes starting from 6001."); + + return new MessageContainer (MessageCategory.Error, text, code, subcategory, origin); + } + + /// + /// Create a warning message. + /// + /// Context with the relevant warning suppression info. + /// Humanly readable message describing the warning + /// Unique warning ID. Please see https://github.com/mono/linker/blob/master/doc/error-codes.md + /// for the list of warnings and possibly add a new one + /// /// Filename or member where the warning is coming from + /// Optionally, further categorize this warning + /// Optional warning version number. Versioned warnings can be controlled with the + /// warning wave option --warn VERSION. Unversioned warnings are unaffected by this option. + /// New MessageContainer of 'Warning' category + internal static MessageContainer CreateWarningMessage (LinkContext context, string text, int code, MessageOrigin origin, WarnVersion version, string subcategory = MessageSubCategory.None) + { + if (!(code > 2000 && code <= 6000)) + throw new ArgumentOutOfRangeException (nameof (code), $"The provided code '{code}' does not fall into the warning category, which is in the range of 2001 to 6000 (inclusive)."); + + return CreateWarningMessageContainer (context, text, code, origin, version, subcategory); + } + + /// + /// Create a custom warning message. + /// + /// Context with the relevant warning suppression info. + /// Humanly readable message describing the warning + /// A custom warning ID. This code should be greater than or equal to 6001 + /// to avoid any collisions with existing and future linker warnings + /// Filename or member where the warning is coming from + /// Optional warning version number. Versioned warnings can be controlled with the + /// warning wave option --warn VERSION. Unversioned warnings are unaffected by this option + /// + /// Custom MessageContainer of 'Warning' category + public static MessageContainer CreateCustomWarningMessage (LinkContext context, string text, int code, MessageOrigin origin, WarnVersion version, string subcategory = MessageSubCategory.None) + { +#if DEBUG + Debug.Assert (Assembly.GetCallingAssembly () != typeof (MessageContainer).Assembly, + "'CreateCustomWarningMessage' is intended to be used by external assemblies only. Use 'CreateWarningMessage' instead."); +#endif + if (code <= 6000) + throw new ArgumentOutOfRangeException (nameof (code), $"The provided code '{code}' does not fall into the permitted range for external warnings. To avoid possible collisions " + + $"with existing and future {Constants.ILLink} warnings, external messages should use codes starting from 6001."); + + return CreateWarningMessageContainer (context, text, code, origin, version, subcategory); + } + + private static MessageContainer CreateWarningMessageContainer (LinkContext context, string text, int code, MessageOrigin origin, WarnVersion version, string subcategory = MessageSubCategory.None) + { + if (!(version >= WarnVersion.ILLink0 && version <= WarnVersion.Latest)) + throw new ArgumentException ($"The provided warning version '{version}' is invalid."); + + if (context.IsWarningSuppressed (code, origin)) + return Empty; + + if (version > context.WarnVersion) + return Empty; + + if (context.IsWarningAsError (code)) + return new MessageContainer (MessageCategory.WarningAsError, text, code, subcategory, origin); + + return new MessageContainer (MessageCategory.Warning, text, code, subcategory, origin); + } + + /// + /// Create a info message. + /// + /// Humanly readable message + /// New MessageContainer of 'Info' category + public static MessageContainer CreateInfoMessage (string text) + { + return new MessageContainer (MessageCategory.Info, text, null); + } + + /// + /// Create a diagnostics message. + /// + /// Humanly readable message + /// New MessageContainer of 'Diagnostic' category + public static MessageContainer CreateDiagnosticMessage (string text) + { + return new MessageContainer (MessageCategory.Diagnostic, text, null); + } + + private MessageContainer (MessageCategory category, string text, int? code, string subcategory = MessageSubCategory.None, MessageOrigin? origin = null) + { + Code = code; + Category = category; + Origin = origin; + SubCategory = subcategory; + Text = text; + } + + public override string ToString () => ToMSBuildString (); + + public string ToMSBuildString () + { + const string originApp = Constants.ILLink; + string origin = Origin?.ToString () ?? originApp; + + StringBuilder sb = new StringBuilder (); + sb.Append (origin).Append (":"); + + if (!string.IsNullOrEmpty (SubCategory)) + sb.Append (" ").Append (SubCategory); + + string cat; + switch (Category) { + case MessageCategory.Error: + case MessageCategory.WarningAsError: + cat = "error"; + break; + case MessageCategory.Warning: + cat = "warning"; + break; + default: + cat = ""; + break; + } + + if (!string.IsNullOrEmpty (cat)) { + sb.Append (" ") + .Append (cat) + .Append (" IL") + .Append (Code.Value.ToString ("D4")) + .Append (": "); + } else { + sb.Append (" "); + } + + if (Origin?.MemberDefinition != null) { + if (Origin?.MemberDefinition is MethodDefinition method) + sb.Append (method.GetDisplayName ()); + else + sb.Append (Origin?.MemberDefinition.FullName); + + sb.Append (": "); + } + + // Expected output $"{FileName(SourceLine, SourceColumn)}: {SubCategory}{Category} IL{Code}: ({MemberDisplayName}: ){Text}"); + sb.Append (Text); + return sb.ToString (); + } + + public bool Equals (MessageContainer other) => + (Category, Text, Code, SubCategory, Origin) == (other.Category, other.Text, other.Code, other.SubCategory, other.Origin); + + public override bool Equals (object obj) => obj is MessageContainer messageContainer && Equals (messageContainer); + public override int GetHashCode () => (Category, Text, Code, SubCategory, Origin).GetHashCode (); + + public int CompareTo (MessageContainer other) + { + if (Origin != null && other.Origin != null) { + return Origin.Value.CompareTo (other.Origin.Value); + } else if (Origin == null && other.Origin == null) { + return (Code < other.Code) ? -1 : 1; + } + + return (Origin == null) ? 1 : -1; + } + + public static bool operator == (MessageContainer lhs, MessageContainer rhs) => lhs.Equals (rhs); + public static bool operator != (MessageContainer lhs, MessageContainer rhs) => !lhs.Equals (rhs); + } +} diff --git a/src/coreclr/tools/Common/Compiler/Logging/ReferenceSource/MessageOrigin.cs b/src/coreclr/tools/Common/Compiler/Logging/ReferenceSource/MessageOrigin.cs new file mode 100644 index 00000000000..62725b69044 --- /dev/null +++ b/src/coreclr/tools/Common/Compiler/Logging/ReferenceSource/MessageOrigin.cs @@ -0,0 +1,98 @@ +// Licensed to the .NET Foundation under one or more agreements. +// The .NET Foundation licenses this file to you under the MIT license. +// See the LICENSE file in the project root for more information. + +using System; +using System.Linq; +using System.Text; +using Mono.Cecil; +using Mono.Cecil.Cil; + +namespace Mono.Linker +{ + public readonly struct MessageOrigin : IComparable, IEquatable + { +#nullable enable + public string? FileName { get; } + public IMemberDefinition? MemberDefinition { get; } +#nullable disable + public int SourceLine { get; } + public int SourceColumn { get; } + public int? ILOffset { get; } + + public MessageOrigin (string fileName, int sourceLine = 0, int sourceColumn = 0) + { + FileName = fileName; + SourceLine = sourceLine; + SourceColumn = sourceColumn; + MemberDefinition = null; + ILOffset = null; + } + + public MessageOrigin (IMemberDefinition memberDefinition, int? ilOffset = null) + { + FileName = null; + MemberDefinition = memberDefinition; + SourceLine = 0; + SourceColumn = 0; + ILOffset = ilOffset; + } + + public override string ToString () + { + int sourceLine = SourceLine, sourceColumn = SourceColumn; + string fileName = FileName; + if (MemberDefinition is MethodDefinition method && + method.DebugInformation.HasSequencePoints) { + var offset = ILOffset ?? 0; + SequencePoint correspondingSequencePoint = method.DebugInformation.SequencePoints + .Where (s => s.Offset <= offset)?.Last (); + if (correspondingSequencePoint != null) { + fileName = correspondingSequencePoint.Document.Url; + sourceLine = correspondingSequencePoint.StartLine; + sourceColumn = correspondingSequencePoint.StartColumn; + } + } + + if (fileName == null) + return null; + + StringBuilder sb = new StringBuilder (fileName); + if (sourceLine != 0) { + sb.Append ("(").Append (sourceLine); + if (sourceColumn != 0) + sb.Append (",").Append (sourceColumn); + + sb.Append (")"); + } + + return sb.ToString (); + } + + public bool Equals (MessageOrigin other) => + (FileName, MemberDefinition, SourceLine, SourceColumn) == (other.FileName, other.MemberDefinition, other.SourceLine, other.SourceColumn); + + public override bool Equals (object obj) => obj is MessageOrigin messageOrigin && Equals (messageOrigin); + public override int GetHashCode () => (FileName, MemberDefinition, SourceLine, SourceColumn).GetHashCode (); + public static bool operator == (MessageOrigin lhs, MessageOrigin rhs) => lhs.Equals (rhs); + public static bool operator != (MessageOrigin lhs, MessageOrigin rhs) => !lhs.Equals (rhs); + + public int CompareTo (MessageOrigin other) + { + if (MemberDefinition != null && other.MemberDefinition != null) { + return (MemberDefinition.DeclaringType?.Module?.Assembly?.Name?.Name, MemberDefinition.DeclaringType?.Name, MemberDefinition?.Name).CompareTo + ((other.MemberDefinition.DeclaringType?.Module?.Assembly?.Name?.Name, other.MemberDefinition.DeclaringType?.Name, other.MemberDefinition?.Name)); + } else if (MemberDefinition == null && other.MemberDefinition == null) { + if (FileName != null && other.FileName != null) { + return string.Compare (FileName, other.FileName); + } else if (FileName == null && other.FileName == null) { + return (SourceLine, SourceColumn).CompareTo ((other.SourceLine, other.SourceColumn)); + } + + return (FileName == null) ? 1 : -1; + } + + return (MemberDefinition == null) ? 1 : -1; + } + } +} diff --git a/src/coreclr/tools/Common/Compiler/Logging/ReferenceSource/README.md b/src/coreclr/tools/Common/Compiler/Logging/ReferenceSource/README.md new file mode 100644 index 00000000000..90170112b5d --- /dev/null +++ b/src/coreclr/tools/Common/Compiler/Logging/ReferenceSource/README.md @@ -0,0 +1 @@ +Sources from the mono/linker repo at commit 8ee2557ccbaf9e4cf243f15b8cb95da4eddb18aa. \ No newline at end of file diff --git a/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs b/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs index ff0cc91645d..e87fc0fef55 100644 --- a/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs +++ b/src/coreclr/tools/Common/JitInterface/CorInfoImpl.cs @@ -297,7 +297,12 @@ namespace Internal.JitInterface var node = _compilation.SymbolNodeFactory.PerMethodInstructionSetSupportFixup(actualSupport); _methodCodeNode.Fixups.Add(node); } +#else + MethodIL methodIL = (MethodIL)HandleToObject((IntPtr)_methodScope); + CodeBasedDependencyAlgorithm.AddDependenciesDueToMethodCodePresence(ref _additionalDependencies, _compilation.NodeFactory, MethodBeingCompiled, methodIL); + _methodCodeNode.InitializeNonRelocationDependencies(_additionalDependencies); #endif + PublishProfileData(); } @@ -388,6 +393,8 @@ namespace Internal.JitInterface _parameterIndexToNameMap = null; _localSlotToInfoMap = null; + + _additionalDependencies = null; #endif _debugLocInfos = null; _debugVarInfos = null; @@ -1315,6 +1322,8 @@ namespace Internal.JitInterface { _compilation.NodeFactory.Resolver.AddModuleTokenForMethod(method, HandleToModuleToken(ref pResolvedToken)); } +#else + _compilation.NodeFactory.MetadataManager.GetDependenciesDueToAccess(ref _additionalDependencies, _compilation.NodeFactory, methodIL, method); #endif } else @@ -1341,6 +1350,8 @@ namespace Internal.JitInterface { _compilation.NodeFactory.Resolver.AddModuleTokenForField(field, HandleToModuleToken(ref pResolvedToken)); } +#else + _compilation.NodeFactory.MetadataManager.GetDependenciesDueToAccess(ref _additionalDependencies, _compilation.NodeFactory, methodIL, field); #endif } else diff --git a/src/coreclr/tools/Common/JitInterface/JitConfigProvider.cs b/src/coreclr/tools/Common/JitInterface/JitConfigProvider.cs index 94352584177..b1b56fb67de 100644 --- a/src/coreclr/tools/Common/JitInterface/JitConfigProvider.cs +++ b/src/coreclr/tools/Common/JitInterface/JitConfigProvider.cs @@ -41,10 +41,10 @@ namespace Internal.JitInterface if (Interlocked.CompareExchange(ref s_instance, config, null) != null) throw new InvalidOperationException(); -#if READYTORUN NativeLibrary.SetDllImportResolver(typeof(CorInfoImpl).Assembly, (libName, assembly, searchPath) => { IntPtr libHandle = IntPtr.Zero; +#if READYTORUN if (libName == CorInfoImpl.JitLibrary) { if (!string.IsNullOrEmpty(jitPath)) @@ -56,15 +56,15 @@ namespace Internal.JitInterface libHandle = NativeLibrary.Load("clrjit_" + GetTargetSpec(target), assembly, searchPath); } } +#else + Debug.Assert(jitPath == null); +#endif if (libName == CorInfoImpl.JitSupportLibrary) { libHandle = NativeLibrary.Load("jitinterface_" + RuntimeInformation.ProcessArchitecture.ToString().ToLowerInvariant(), assembly, searchPath); } return libHandle; }); -#else - Debug.Assert(jitPath == null); -#endif CorInfoImpl.Startup(); } diff --git a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/ILCompiler.ReadyToRun.csproj b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/ILCompiler.ReadyToRun.csproj index fd51184b370..9b4dba1e724 100644 --- a/src/coreclr/tools/aot/ILCompiler.ReadyToRun/ILCompiler.ReadyToRun.csproj +++ b/src/coreclr/tools/aot/ILCompiler.ReadyToRun/ILCompiler.ReadyToRun.csproj @@ -83,6 +83,7 @@ + @@ -91,6 +92,8 @@ + +