Misc changes from runtimelab:NativeAOT (#47323)

* Improved logger for the AOT compiler. The logic is mostly taken from IL Linker where prople spent a bunch of time on it.
* Bunch of other changes.
This commit is contained in:
Michal Strehovský authored and GitHub committed 2021-01-22 06:26:12 -08:00
1 parent dd468b7ff7
commit ea656385b0
11 files changed
+969 -32

No files matched your search

@@ -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);
}
}
@@ -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<Formatter.Unit, FormatOptions>
{
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,
}
}
}
+109 -3
View File
@@ -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<int> _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<int> suppressedWarnings)
{
Writer = TextWriter.Synchronized(writer);
IsVerbose = isVerbose;
_suppressedWarnings = new HashSet<int>(suppressedWarnings);
}
public Logger(TextWriter writer, bool isVerbose)
: this(writer, isVerbose, Array.Empty<int>())
{
}
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<ILSequencePoint> 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<CustomAttributeValue<TypeDesc>> 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<TypeDesc> 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";
}
}
@@ -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<MessageContainer>, IEquatable<MessageContainer>
#endif
{
/// <summary>
/// Optional data with a filename, line and column that triggered the
/// linker to output an error (or warning) message.
/// </summary>
public MessageOrigin? Origin { get; }
public MessageCategory Category { get; }
/// <summary>
/// Further categorize the message.
/// </summary>
public string SubCategory { get; }
/// <summary>
/// Code identifier for errors and warnings reported by the IL linker.
/// </summary>
public int? Code { get; }
/// <summary>
/// User friendly text describing the error or warning.
/// </summary>
public string Text { get; }
/// <summary>
/// Create an error message.
/// </summary>
/// <param name="text">Humanly readable message describing the error</param>
/// <param name="code">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</param>
/// <param name="subcategory">Optionally, further categorize this error</param>
/// <param name="origin">Filename, line, and column where the error was found</param>
/// <returns>New MessageContainer of 'Error' category</returns>
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);
}
/// <summary>
/// Create a warning message.
/// </summary>
/// <param name="context">Context with the relevant warning suppression info.</param>
/// <param name="text">Humanly readable message describing the warning</param>
/// <param name="code">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</param>
/// /// <param name="origin">Filename or member where the warning is coming from</param>
/// <param name="subcategory">Optionally, further categorize this warning</param>
/// <param name="version">Optional warning version number. Versioned warnings can be controlled with the
/// warning wave option --warn VERSION. Unversioned warnings are unaffected by this option. </param>
/// <returns>New MessageContainer of 'Warning' category</returns>
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);
}
/// <summary>
/// Create a info message.
/// </summary>
/// <param name="text">Humanly readable message</param>
/// <returns>New MessageContainer of 'Info' category</returns>
public static MessageContainer CreateInfoMessage(string text)
{
return new MessageContainer(MessageCategory.Info, text, null);
}
/// <summary>
/// Create a diagnostics message.
/// </summary>
/// <param name="text">Humanly readable message</param>
/// <returns>New MessageContainer of 'Diagnostic' category</returns>
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
}
}
@@ -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<MessageOrigin>, IEquatable<MessageOrigin>
#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
}
}
@@ -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<MessageContainer>, IEquatable<MessageContainer>
{
public static readonly MessageContainer Empty;
/// <summary>
/// Optional data with a filename, line and column that triggered the
/// linker to output an error (or warning) message.
/// </summary>
public MessageOrigin? Origin { get; }
public MessageCategory Category { get; }
/// <summary>
/// Further categorize the message.
/// </summary>
public string SubCategory { get; }
/// <summary>
/// Code identifier for errors and warnings reported by the IL linker.
/// </summary>
public int? Code { get; }
/// <summary>
/// User friendly text describing the error or warning.
/// </summary>
public string Text { get; }
/// <summary>
/// Create an error message.
/// </summary>
/// <param name="text">Humanly readable message describing the error</param>
/// <param name="code">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</param>
/// <param name="subcategory">Optionally, further categorize this error</param>
/// <param name="origin">Filename, line, and column where the error was found</param>
/// <returns>New MessageContainer of 'Error' category</returns>
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);
}
/// <summary>
/// Create a custom error message.
/// </summary>
/// <param name="text">Humanly readable message describing the error</param>
/// <param name="code">A custom error ID. This code should be greater than or equal to 6001
/// to avoid any collisions with existing and future linker errors</param>
/// <param name="subcategory">Optionally, further categorize this error</param>
/// <param name="origin">Filename or member where the error is coming from</param>
/// <returns>Custom MessageContainer of 'Error' category</returns>
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);
}
/// <summary>
/// Create a warning message.
/// </summary>
/// <param name="context">Context with the relevant warning suppression info.</param>
/// <param name="text">Humanly readable message describing the warning</param>
/// <param name="code">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</param>
/// /// <param name="origin">Filename or member where the warning is coming from</param>
/// <param name="subcategory">Optionally, further categorize this warning</param>
/// <param name="version">Optional warning version number. Versioned warnings can be controlled with the
/// warning wave option --warn VERSION. Unversioned warnings are unaffected by this option. </param>
/// <returns>New MessageContainer of 'Warning' category</returns>
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);
}
/// <summary>
/// Create a custom warning message.
/// </summary>
/// <param name="context">Context with the relevant warning suppression info.</param>
/// <param name="text">Humanly readable message describing the warning</param>
/// <param name="code">A custom warning ID. This code should be greater than or equal to 6001
/// to avoid any collisions with existing and future linker warnings</param>
/// <param name="origin">Filename or member where the warning is coming from</param>
/// <param name="version">Optional warning version number. Versioned warnings can be controlled with the
/// warning wave option --warn VERSION. Unversioned warnings are unaffected by this option</param>
/// <param name="subcategory"></param>
/// <returns>Custom MessageContainer of 'Warning' category</returns>
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);
}
/// <summary>
/// Create a info message.
/// </summary>
/// <param name="text">Humanly readable message</param>
/// <returns>New MessageContainer of 'Info' category</returns>
public static MessageContainer CreateInfoMessage (string text)
{
return new MessageContainer (MessageCategory.Info, text, null);
}
/// <summary>
/// Create a diagnostics message.
/// </summary>
/// <param name="text">Humanly readable message</param>
/// <returns>New MessageContainer of 'Diagnostic' category</returns>
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);
}
}
@@ -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<MessageOrigin>, IEquatable<MessageOrigin>
{
#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;
}
}
}
@@ -0,0 +1 @@
Sources from the mono/linker repo at commit 8ee2557ccbaf9e4cf243f15b8cb95da4eddb18aa.
@@ -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
@@ -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();
}
@@ -83,6 +83,7 @@
<Compile Include="..\..\Common\Compiler\DependencyAnalysis\Target_X86\X86Emitter.cs" Link="Compiler\DependencyAnalysis\Target_X86\X86Emitter.cs" />
<Compile Include="..\..\Common\Compiler\DependencyTrackingLevel.cs" Link="Compiler\DependencyTrackingLevel.cs" />
<Compile Include="..\..\Common\Compiler\DevirtualizationManager.cs" Link="Compiler\DevirtualizationManager.cs" />
<Compile Include="..\..\Common\Compiler\DisplayNameHelpers.cs" Link="Compiler\DisplayNameHelpers.cs" />
<Compile Include="..\..\Common\Compiler\HardwareIntrinsicHelpers.cs" Link="Compiler\HardwareIntrinsicHelpers.cs" />
<Compile Include="..\..\Common\Compiler\ICompilationRootProvider.cs" Link="Compiler\ICompilationRootProvider.cs" />
<Compile Include="..\..\Common\Compiler\InstructionSetSupport.cs" Link="Compiler\InstructionSetSupport.cs" />
@@ -91,6 +92,8 @@
<Compile Include="..\..\Common\Compiler\SingleMethodRootProvider.cs" Link="Compiler\SingleMethodRootProvider.cs" />
<Compile Include="..\..\Common\Compiler\TypeExtensions.cs" Link="Compiler\TypeExtensions.cs" />
<Compile Include="..\..\Common\Compiler\VectorFieldLayoutAlgorithm.cs" Link="Compiler\VectorFieldLayoutAlgorithm.cs" />
<Compile Include="..\..\Common\Compiler\Logging\MessageContainer.cs" Link="Compiler\Logging\MessageContainer.cs" />
<Compile Include="..\..\Common\Compiler\Logging\MessageOrigin.cs" Link="Compiler\Logging\MessageOrigin.cs" />
<Compile Include="..\..\Common\Compiler\Logger.cs" Link="Compiler\Logger.cs" />
<Compile Include="..\..\Common\JitInterface\CorInfoTypes.VarInfo.cs" Link="JitInterface\CorInfoTypes.VarInfo.cs" />
<Compile Include="..\..\Common\JitInterface\SystemVStructClassificator.cs" Link="JitInterface\SystemVStructClassificator.cs" />