本文整理汇总了C#中ILCompiler.Compiler.CppCodeGen.CppGenerationBuffer类的典型用法代码示例。如果您正苦于以下问题:C# CppGenerationBuffer类的具体用法?C# CppGenerationBuffer怎么用?C# CppGenerationBuffer使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。
CppGenerationBuffer类属于ILCompiler.Compiler.CppCodeGen命名空间,在下文中一共展示了CppGenerationBuffer类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的C#代码示例。
示例1: CompileMethod
public void CompileMethod(CppMethodCodeNode methodCodeNodeNeedingCode)
{
MethodDesc method = methodCodeNodeNeedingCode.Method;
_compilation.Log.WriteLine("Compiling " + method.ToString());
if (method.HasCustomAttribute("System.Runtime", "RuntimeImportAttribute"))
{
CompileExternMethod(methodCodeNodeNeedingCode, ((EcmaMethod)method).GetRuntimeImportName());
return;
}
if (method.IsRawPInvoke())
{
CompileExternMethod(methodCodeNodeNeedingCode, method.GetPInvokeMethodMetadata().Name ?? method.Name);
return;
}
var methodIL = _compilation.GetMethodIL(method);
if (methodIL == null)
return;
try
{
var ilImporter = new ILImporter(_compilation, this, method, methodIL);
CompilerTypeSystemContext typeSystemContext = _compilation.TypeSystemContext;
MethodDebugInformation debugInfo = _compilation.GetDebugInfo(methodIL);
if (!_compilation.Options.NoLineNumbers)
{
IEnumerable<ILSequencePoint> sequencePoints = debugInfo.GetSequencePoints();
if (sequencePoints != null)
ilImporter.SetSequencePoints(sequencePoints);
}
IEnumerable<ILLocalVariable> localVariables = debugInfo.GetLocalVariables();
if (localVariables != null)
ilImporter.SetLocalVariables(localVariables);
IEnumerable<string> parameters = GetParameterNamesForMethod(method);
if (parameters != null)
ilImporter.SetParameterNames(parameters);
ilImporter.Compile(methodCodeNodeNeedingCode);
}
catch (Exception e)
{
_compilation.Log.WriteLine(e.Message + " (" + method + ")");
var builder = new CppGenerationBuffer();
builder.AppendLine();
builder.Append(GetCppMethodDeclaration(method, true));
builder.AppendLine();
builder.Append("{");
builder.Indent();
builder.AppendLine();
builder.Append("throw 0xC000C000;");
builder.Exdent();
builder.AppendLine();
builder.Append("}");
methodCodeNodeNeedingCode.SetCode(builder.ToString(), Array.Empty<Object>());
}
}
示例2: GetCodeForReloc
private String GetCodeForReloc(Relocation reloc, DependencyNode node, NodeFactory factory)
{
CppGenerationBuffer relocCode = new CppGenerationBuffer();
if (reloc.Target is CppMethodCodeNode)
{
var method = reloc.Target as CppMethodCodeNode;
relocCode.Append("(void*)&");
relocCode.Append(GetCppMethodDeclarationName(method.Method.OwningType, GetCppMethodName(method.Method)));
}
else if (reloc.Target is EETypeNode && node is EETypeNode)
{
relocCode.Append(GetCppMethodDeclarationName((reloc.Target as EETypeNode).Type, "__getMethodTable"));
relocCode.Append("()");
}
// Node is either an non-emitted type or a generic composition - both are ignored for CPP codegen
else if ((reloc.Target is TypeManagerIndirectionNode || reloc.Target is InterfaceDispatchMapNode || reloc.Target is EETypeOptionalFieldsNode || reloc.Target is GenericCompositionNode) && !(reloc.Target as ObjectNode).ShouldSkipEmittingObjectNode(factory))
{
string mangledTargetName = reloc.Target.GetMangledName();
bool shouldReplaceNamespaceQualifier = reloc.Target is GenericCompositionNode || reloc.Target is EETypeOptionalFieldsNode;
relocCode.Append(shouldReplaceNamespaceQualifier ? mangledTargetName.Replace("::", "_") : mangledTargetName);
relocCode.Append("()");
}
else if (reloc.Target is ObjectAndOffsetSymbolNode &&
(reloc.Target as ObjectAndOffsetSymbolNode).Target is ArrayOfEmbeddedPointersNode<InterfaceDispatchMapNode>)
{
relocCode.Append("dispatchMapModule");
}
else
{
relocCode.Append("NULL");
}
return relocCode.ToString();
}
示例3: AppendFormattedByteArray
private static void AppendFormattedByteArray(CppGenerationBuffer sb, byte[] array, int startIndex, int endIndex)
{
sb.Append("{");
sb.Append("0x");
sb.Append(BitConverter.ToString(array, startIndex, endIndex - startIndex).Replace("-", ",0x"));
sb.Append("}");
}
示例4: GetCodeForDelegate
private String GetCodeForDelegate(TypeDesc delegateType)
{
var sb = new CppGenerationBuffer();
MethodDesc method = delegateType.GetKnownMethod("Invoke", null);
AppendSlotTypeDef(sb, method);
sb.AppendLine();
sb.Append("static __slot__");
sb.Append(GetCppMethodName(method));
sb.Append(" __invoke__");
sb.Append(GetCppMethodName(method));
sb.Append("(void * pThis)");
sb.AppendLine();
sb.Append("{");
sb.Indent();
sb.AppendLine();
sb.Append("return (__slot__");
sb.Append(GetCppMethodName(method));
sb.Append(")(((");
sb.Append(GetCppSignatureTypeName(_compilation.TypeSystemContext.GetWellKnownType(WellKnownType.MulticastDelegate)));
sb.Append(")pThis)->m_functionPointer);");
sb.Exdent();
sb.AppendLine();
sb.Append("};");
return sb.ToString();
}
示例5: GetCodeForObjectNode
private String GetCodeForObjectNode(ObjectNode node, NodeFactory factory)
{
// virtual slots
var nodeData = node.GetData(factory, false);
CppGenerationBuffer nodeCode = new CppGenerationBuffer();
/* Create list of byte data. Used to divide contents between reloc and byte data
* First val - isReloc
* Second val - size of byte data if first value of tuple is false
*/
List<NodeDataSection> nodeDataSections = new List<NodeDataSection>();
byte[] actualData = new byte[nodeData.Data.Length];
Relocation[] relocs = nodeData.Relocs;
int nextRelocOffset = -1;
int nextRelocIndex = -1;
int lastByteIndex = 0;
if (relocs.Length > 0)
{
nextRelocOffset = relocs[0].Offset;
nextRelocIndex = 0;
}
int i = 0;
int offset = 0;
CppGenerationBuffer nodeDataDecl = new CppGenerationBuffer();
if (node is ISymbolNode)
{
offset = (node as ISymbolNode).Offset;
i = offset;
lastByteIndex = offset;
}
while (i < nodeData.Data.Length)
{
if (i == nextRelocOffset)
{
Relocation reloc = relocs[nextRelocIndex];
int size = _compilation.TypeSystemContext.Target.PointerSize;
// Make sure we've gotten the correct size for the reloc
System.Diagnostics.Debug.Assert(reloc.RelocType == (size == 8 ? RelocType.IMAGE_REL_BASED_DIR64 : RelocType.IMAGE_REL_BASED_HIGHLOW));
// Update nextRelocIndex/Offset
if (++nextRelocIndex < relocs.Length)
{
nextRelocOffset = relocs[nextRelocIndex].Offset;
}
nodeDataSections.Add(new NodeDataSection(NodeDataSectionType.Relocation, size));
i += size;
lastByteIndex = i;
}
else
{
i++;
if (i + 1 == nextRelocOffset || i + 1 == nodeData.Data.Length)
{
nodeDataSections.Add(new NodeDataSection(NodeDataSectionType.ByteData, (i + 1) - lastByteIndex));
}
}
}
string pointerType = node is EETypeNode ? "MethodTable * " : "void* ";
nodeCode.Append(pointerType);
if (node is EETypeNode)
{
nodeCode.Append(GetCppMethodDeclarationName((node as EETypeNode).Type, "__getMethodTable"));
}
else
{
string mangledName = ((ISymbolNode)node).GetMangledName();
// Rename generic composition and optional fields nodes to avoid name clash with types
bool shouldReplaceNamespaceQualifier = node is GenericCompositionNode || node is EETypeOptionalFieldsNode;
nodeCode.Append(shouldReplaceNamespaceQualifier ? mangledName.Replace("::", "_") : mangledName);
}
nodeCode.Append("()");
nodeCode.AppendLine();
nodeCode.Append("{");
nodeCode.Indent();
nodeCode.AppendLine();
nodeCode.Append("static struct {");
nodeCode.AppendLine();
nodeCode.Append(GetCodeForNodeStruct(nodeDataSections, node));
nodeCode.AppendLine();
nodeCode.Append("} mt = {");
nodeCode.Append(GetCodeForNodeData(nodeDataSections, relocs, nodeData.Data, node, offset, factory));
nodeCode.Append("};");
nodeCode.AppendLine();
nodeCode.Append("return ( ");
nodeCode.Append(pointerType);
nodeCode.Append(")&mt;");
nodeCode.Exdent();
nodeCode.AppendLine();
nodeCode.Append("}");
//.........这里部分代码省略.........
示例6: CompileMethod
public void CompileMethod(CppMethodCodeNode methodCodeNodeNeedingCode)
{
MethodDesc method = methodCodeNodeNeedingCode.Method;
_compilation.Logger.Writer.WriteLine("Compiling " + method.ToString());
if (method.HasCustomAttribute("System.Runtime", "RuntimeImportAttribute"))
{
CompileExternMethod(methodCodeNodeNeedingCode, ((EcmaMethod)method).GetRuntimeImportName());
return;
}
if (method.IsRawPInvoke())
{
CompileExternMethod(methodCodeNodeNeedingCode, method.GetPInvokeMethodMetadata().Name ?? method.Name);
return;
}
var methodIL = _compilation.GetMethodIL(method);
if (methodIL == null)
return;
// TODO: Remove this code once CppCodegen is able to generate code for the reflection startup path.
// The startup path runs before any user code is executed.
// For now we replace the startup path with a simple "ret". Reflection won't work, but
// programs not using reflection will.
if (method.Name == ".cctor")
{
MetadataType owningType = method.OwningType as MetadataType;
if (owningType != null &&
owningType.Name == "ReflectionExecution" && owningType.Namespace == "Internal.Reflection.Execution")
{
methodIL = new Internal.IL.Stubs.ILStubMethodIL(method, new byte[] { (byte)ILOpcode.ret }, Array.Empty<LocalVariableDefinition>(), null);
}
}
try
{
// TODO: hacky special-case
if (method.Name == "_ecvt_s")
throw new NotImplementedException();
var ilImporter = new ILImporter(_compilation, this, method, methodIL);
CompilerTypeSystemContext typeSystemContext = _compilation.TypeSystemContext;
MethodDebugInformation debugInfo = _compilation.GetDebugInfo(methodIL);
if (!_compilation.Options.HasOption(CppCodegenConfigProvider.NoLineNumbersString))
{
IEnumerable<ILSequencePoint> sequencePoints = debugInfo.GetSequencePoints();
if (sequencePoints != null)
ilImporter.SetSequencePoints(sequencePoints);
}
IEnumerable<ILLocalVariable> localVariables = debugInfo.GetLocalVariables();
if (localVariables != null)
ilImporter.SetLocalVariables(localVariables);
IEnumerable<string> parameters = GetParameterNamesForMethod(method);
if (parameters != null)
ilImporter.SetParameterNames(parameters);
ilImporter.Compile(methodCodeNodeNeedingCode);
}
catch (Exception e)
{
_compilation.Logger.Writer.WriteLine(e.Message + " (" + method + ")");
var sb = new CppGenerationBuffer();
sb.AppendLine();
AppendCppMethodDeclaration(sb, method, true);
sb.AppendLine();
sb.Append("{");
sb.Indent();
sb.AppendLine();
sb.Append("throw 0xC000C000;");
sb.Exdent();
sb.AppendLine();
sb.Append("}");
methodCodeNodeNeedingCode.SetCode(sb.ToString(), Array.Empty<Object>());
}
}
示例7: AppendSlotTypeDef
private void AppendSlotTypeDef(CppGenerationBuffer sb, MethodDesc method)
{
MethodSignature methodSignature = method.Signature;
TypeDesc thisArgument = null;
if (!methodSignature.IsStatic)
thisArgument = method.OwningType;
AppendSignatureTypeDef(sb, "__slot__" + GetCppMethodName(method), methodSignature, thisArgument);
}
示例8: ImportCall
//.........这里部分代码省略.........
if (retType.IsPointer)
{
Append("(intptr_t)");
}
}
}
else
{
needNewLine = true;
}
AddTypeReference(method.OwningType, true);
if (opcode == ILOpcode.newobj)
{
if (!retType.IsValueType)
{
// We do not reset needNewLine since we still need for the next statement.
if (needNewLine)
AppendLine();
Append("__allocate_object(");
Append(_writer.GetCppTypeName(retType));
Append("::__getMethodTable())");
AppendSemicolon();
needNewLine = true;
if (delegateInfo != null && delegateInfo.Thunk != null)
{
MethodDesc thunkMethod = delegateInfo.Thunk.Method;
AddMethodReference(thunkMethod);
// Update stack with new name.
((ExpressionEntry)_stack[_stack.Top - 2]).Name = temp;
var sb = new CppGenerationBuffer();
AppendLine();
sb.Append("(intptr_t)&");
sb.Append(_writer.GetCppTypeName(thunkMethod.OwningType));
sb.Append("::");
sb.Append(_writer.GetCppMethodName(thunkMethod));
PushExpression(StackValueKind.NativeInt, sb.ToString());
}
}
}
if (needNewLine)
AppendLine();
if (callViaSlot || delegateInvoke)
{
ExpressionEntry v = (ExpressionEntry)_stack[_stack.Top - (methodSignature.Length + 1)];
Append("(*");
Append(_writer.GetCppTypeName(method.OwningType));
Append("::");
Append(delegateInvoke ? "__invoke__" : "__getslot__");
Append(_writer.GetCppMethodName(method));
Append("(");
Append(v);
Append("))");
if (delegateInvoke)
{
v.Name =
"((" + _writer.GetCppSignatureTypeName(GetWellKnownType(WellKnownType.MulticastDelegate)) + ")" +
v.Name + ")->m_firstParameter";
}
示例9: ImportLoadString
private void ImportLoadString(int token)
{
string str = (string)_methodIL.GetObject(token);
PushTemp(StackValueKind.ObjRef, GetWellKnownType(WellKnownType.String));
var escaped = new CppGenerationBuffer();
foreach (char c in str)
{
switch (c)
{
case '\\':
escaped.Append("\\\\");
break;
case '\r':
escaped.Append("\\r");
break;
case '\n':
escaped.Append("\\n");
break;
case '\t':
escaped.Append("\\t");
break;
default:
// TODO: handle all characters < 32
escaped.Append(c);
break;
}
}
Append("__load_string_literal(\"");
Append(escaped.ToString());
Append("\")");
AppendSemicolon();
}
示例10: AppendVirtualSlots
private void AppendVirtualSlots(CppGenerationBuffer sb, TypeDesc implType, TypeDesc declType)
{
var baseType = declType.BaseType;
if (baseType != null)
AppendVirtualSlots(sb, implType, baseType);
IReadOnlyList<MethodDesc> virtualSlots = _compilation.NodeFactory.VTable(declType).Slots;
for (int i = 0; i < virtualSlots.Count; i++)
{
MethodDesc declMethod = virtualSlots[i];
MethodDesc implMethod = implType.GetClosestMetadataType().FindVirtualFunctionTargetMethodOnObjectType(declMethod);
sb.AppendLine();
if (implMethod.IsAbstract)
{
sb.Append("NULL,");
}
else
{
sb.Append("(void*)&");
sb.Append(GetCppMethodDeclarationName(implMethod.OwningType, GetCppMethodName(implMethod)));
sb.Append(",");
}
}
}
示例11: GetCodeForType
private String GetCodeForType(TypeDesc type)
{
var sb = new CppGenerationBuffer();
int totalSlots = 0;
TypeDesc t = type;
while (t != null)
{
IReadOnlyList<MethodDesc> virtualSlots = _compilation.NodeFactory.VTable(t).Slots;
totalSlots += virtualSlots.Count;
t = t.BaseType;
}
UInt16 flags = 0;
try
{
flags = EETypeBuilderHelpers.ComputeFlags(type);
}
catch
{
// TODO: Handling of missing dependencies
flags = 0;
}
sb.Append("MethodTable * ");
sb.Append(GetCppMethodDeclarationName(type, "__getMethodTable"));
sb.Append("()");
sb.AppendLine();
sb.Append("{");
sb.Indent();
sb.AppendLine();
sb.Append("static struct {");
sb.Indent();
// sb.Append(GCDesc);
sb.AppendLine();
sb.Append("RawEEType EEType;");
if (totalSlots != 0)
{
sb.AppendLine();
sb.Append("void * slots[");
sb.Append(totalSlots);
sb.Append("];");
}
sb.Exdent();
sb.AppendLine();
sb.Append("} mt = {");
sb.Indent();
// gcdesc
if (type.IsString)
{
// String has non-standard layout
sb.AppendLine();
sb.Append("{");
sb.Indent();
sb.AppendLine();
sb.Append("sizeof(uint16_t),");
sb.AppendLine();
sb.Append("0x"); // EEType::_usComponentSize
sb.Append(flags.ToStringInvariant("x4")); // EEType::_usFlags
sb.Append(",");
sb.AppendLine();
sb.Append("2 * sizeof(void*) + sizeof(int32_t) + 2,"); // EEType::_uBaseSize
}
else
if (type.IsSzArray)
{
sb.AppendLine();
sb.Append("{");
sb.Indent();
sb.AppendLine();
sb.Append("sizeof(");
sb.Append(GetCppSignatureTypeName(((ArrayType)type).ElementType)); // EEType::_usComponentSize
sb.Append("),");
sb.AppendLine();
sb.Append("0x");
sb.Append(flags.ToStringInvariant("x4")); // EEType::_usFlags
sb.Append(",");
sb.AppendLine();
sb.Append("3 * sizeof(void*),"); // EEType::_uBaseSize
}
else
if (type.IsArray)
{
sb.AppendLine();
sb.Append("{");
sb.Indent();
sb.AppendLine();
sb.Append("sizeof(");
sb.Append(GetCppSignatureTypeName(((ArrayType)type).ElementType)); // EEType::_usComponentSize
sb.Append("),");
sb.AppendLine();
sb.Append("0x");
sb.Append(flags.ToStringInvariant("x4")); // EEType::_usFlags
sb.Append(",");
sb.AppendLine();
sb.Append("3 * sizeof(void*) + "); // EEType::_uBaseSize
sb.Append(((ArrayType)type).Rank.ToStringInvariant());
sb.Append("* sizeof(int32_t) * 2,");
//.........这里部分代码省略.........
示例12: OutputMethod
private void OutputMethod(CppGenerationBuffer sb, MethodDesc m)
{
sb.AppendLine();
sb.Append(GetCppMethodDeclaration(m, false));
}
示例13: OutputType
private void OutputType(CppGenerationBuffer sb, TypeDesc t, bool full)
{
_emittedTypes.Add(t);
if (full)
{
if (!t.IsValueType)
{
var baseType = t.BaseType;
if (baseType != null)
{
if (!_emittedTypes.Contains(baseType))
{
OutputType(sb, baseType, full);
}
}
}
foreach (var field in t.GetFields())
{
var fieldType = GetFieldTypeOrPlaceholder(field);
if (fieldType.IsValueType && !fieldType.IsPrimitive && !field.IsStatic)
{
if (!_emittedTypes.Contains(fieldType))
{
OutputType(sb, fieldType, full);
}
}
}
}
string mangledName = GetCppTypeName(t);
int nesting = 0;
int current = 0;
// Create Namespaces. If a mangledName starts with just :: we will simply ignore it.
sb.AppendLine();
for (;;)
{
int sep = mangledName.IndexOf("::", current);
if (sep < 0)
break;
if (sep != 0)
{
// Case of a name not starting with ::
sb.Append("namespace " + mangledName.Substring(current, sep - current) + " { ");
nesting++;
}
current = sep + 2;
}
if (full)
{
sb.Append("class " + mangledName.Substring(current));
if (!t.IsValueType)
{
if (t.BaseType != null)
{
sb.Append(" : public " + GetCppTypeName(t.BaseType));
}
}
sb.Append(" {");
sb.AppendLine();
sb.Append("public:");
sb.Indent();
// TODO: Enable once the dependencies are tracked for arrays
// if (((DependencyNode)_compilation.NodeFactory.ConstructedTypeSymbol(t)).Marked)
if (!t.IsPointer && !t.IsByRef)
{
sb.AppendLine();
sb.Append("static MethodTable * __getMethodTable();");
}
IReadOnlyList<MethodDesc> virtualSlots = _compilation.NodeFactory.VTable(t).Slots;
int baseSlots = 0;
var baseType = t.BaseType;
while (baseType != null)
{
IReadOnlyList<MethodDesc> baseVirtualSlots = _compilation.NodeFactory.VTable(baseType).Slots;
if (baseVirtualSlots != null)
baseSlots += baseVirtualSlots.Count;
baseType = baseType.BaseType;
}
for (int slot = 0; slot < virtualSlots.Count; slot++)
{
MethodDesc virtualMethod = virtualSlots[slot];
sb.AppendLine();
sb.Append(GetCodeForVirtualMethod(virtualMethod, baseSlots + slot));
}
if (t.IsDelegate)
{
sb.AppendLine();
sb.Append(GetCodeForDelegate(t));
}
//.........这里部分代码省略.........
示例14: OutputTypes
private void OutputTypes(bool full)
{
var sb = new CppGenerationBuffer();
if (full)
{
_statics = new CppGenerationBuffer();
_statics.Indent();
_gcStatics = new CppGenerationBuffer();
_gcStatics.Indent();
_threadStatics = new CppGenerationBuffer();
_threadStatics.Indent();
_gcThreadStatics = new CppGenerationBuffer();
_gcThreadStatics.Indent();
}
_emittedTypes = new HashSet<TypeDesc>();
foreach (var t in _cppSignatureNames.Keys)
{
if (t.IsByRef || t.IsPointer)
continue;
// Base class types and valuetype instantance field types may be emitted out-of-order to make them
// appear before they are used.
if (_emittedTypes.Contains(t))
continue;
OutputType(sb, t, full);
}
_emittedTypes = null;
if (full)
{
sb.AppendLine();
sb.Append("struct {");
// No need to indent or add a new line as _statics is already properly indented
sb.Append(_statics.ToString());
sb.AppendLine();
sb.Append("} __statics;");
// TODO: Register GC statics with GC
sb.AppendLine();
sb.Append("struct {");
// No need to indent or add a new line as _gcStatics is already properly indented
sb.Append(_gcStatics.ToString());
sb.AppendLine();
sb.Append("} __gcStatics;");
sb.AppendLine();
_statics = null;
_gcStatics = null;
_threadStatics = null;
_gcThreadStatics = null;
}
Out.Write(sb.ToString());
sb.Clear();
}
示例15: AppendCppMethodCallParamList
public void AppendCppMethodCallParamList(CppGenerationBuffer sb, MethodDesc method)
{
var methodSignature = method.Signature;
bool hasThis = !methodSignature.IsStatic;
int argCount = methodSignature.Length;
if (hasThis)
argCount++;
List<string> parameterNames = null;
IEnumerable<string> parameters = GetParameterNamesForMethod(method);
if (parameters != null)
{
parameterNames = new List<string>(parameters);
if (parameterNames.Count != 0)
{
System.Diagnostics.Debug.Assert(parameterNames.Count == argCount);
}
else
{
parameterNames = null;
}
}
for (int i = 0; i < argCount; i++)
{
if (parameterNames != null)
{
sb.Append(SanitizeCppVarName(parameterNames[i]));
}
else
{
sb.Append("_a");
sb.Append(i.ToStringInvariant());
}
if (i != argCount - 1)
sb.Append(", ");
}
}