6de9c8e3402d91764520c720abeee21048b99b7b
[platform/upstream/coreclr.git] / src / inc / corcompile.h
1 // Licensed to the .NET Foundation under one or more agreements.
2 // The .NET Foundation licenses this file to you under the MIT license.
3 // See the LICENSE file in the project root for more information.
4
5 /*****************************************************************************\
6 *                                                                             *
7 * CorCompile.h -    EE / Compiler interface                                   *
8 *                                                                             *
9 *               Version 1.0                                                   *
10 *******************************************************************************
11 *                                                                             *
12 *                                                                     *
13 *                                                                             *
14 \*****************************************************************************/
15 // See code:CorProfileData for information on Hot Cold splitting using profile data.
16
17
18 #ifndef _COR_COMPILE_H_
19 #define _COR_COMPILE_H_
20
21 #ifndef FEATURE_PREJIT
22 #error FEATURE_PREJIT is required for this file
23 #endif // FEATURE_PREJIT
24
25 #if !defined(_TARGET_X86_) || defined(FEATURE_PAL)
26 #ifndef WIN64EXCEPTIONS
27 #define WIN64EXCEPTIONS
28 #endif
29 #endif  // !_TARGET_X86_ || FEATURE_PAL
30
31 #include <cor.h>
32 #include <corhdr.h>
33 #include <corinfo.h>
34 #include <corjit.h>
35 #include <sstring.h>
36 #include <shash.h>
37 #include <daccess.h>
38 #include <corbbtprof.h>
39 #include <clrtypes.h>
40 #include <fixuppointer.h>
41
42 typedef DPTR(struct CORCOMPILE_CODE_MANAGER_ENTRY)
43     PTR_CORCOMPILE_CODE_MANAGER_ENTRY;
44 typedef DPTR(struct CORCOMPILE_EE_INFO_TABLE)
45     PTR_CORCOMPILE_EE_INFO_TABLE;
46 typedef DPTR(struct CORCOMPILE_HEADER)
47     PTR_CORCOMPILE_HEADER;
48 typedef DPTR(struct CORCOMPILE_IMPORT_TABLE_ENTRY)
49     PTR_CORCOMPILE_IMPORT_TABLE_ENTRY;
50 typedef DPTR(struct CORCOMPILE_COLD_METHOD_ENTRY)
51     PTR_CORCOMPILE_COLD_METHOD_ENTRY;
52 typedef DPTR(struct CORCOMPILE_EXCEPTION_LOOKUP_TABLE)
53     PTR_CORCOMPILE_EXCEPTION_LOOKUP_TABLE;
54 typedef DPTR(struct CORCOMPILE_EXCEPTION_LOOKUP_TABLE_ENTRY)
55    PTR_CORCOMPILE_EXCEPTION_LOOKUP_TABLE_ENTRY;
56 typedef DPTR(struct CORCOMPILE_EXCEPTION_CLAUSE)
57    PTR_CORCOMPILE_EXCEPTION_CLAUSE;
58 typedef DPTR(struct CORCOMPILE_VIRTUAL_IMPORT_THUNK)
59     PTR_CORCOMPILE_VIRTUAL_IMPORT_THUNK;
60 typedef DPTR(struct CORCOMPILE_EXTERNAL_METHOD_THUNK)
61     PTR_CORCOMPILE_EXTERNAL_METHOD_THUNK;
62 typedef DPTR(struct CORCOMPILE_EXTERNAL_METHOD_DATA_ENTRY)
63     PTR_CORCOMPILE_EXTERNAL_METHOD_DATA_ENTRY;
64 typedef DPTR(struct CORCOMPILE_VIRTUAL_SECTION_INFO)
65     PTR_CORCOMPILE_VIRTUAL_SECTION_INFO;
66 typedef DPTR(struct CORCOMPILE_IMPORT_SECTION)
67     PTR_CORCOMPILE_IMPORT_SECTION;
68
69 #ifdef _TARGET_X86_
70
71 typedef DPTR(RUNTIME_FUNCTION) PTR_RUNTIME_FUNCTION;
72
73
74 // Chained unwind info. Used for cold methods.
75 #define RUNTIME_FUNCTION_INDIRECT 0x80000000
76
77 #endif // _TARGET_X86_
78
79 // The stride is choosen as maximum value that still gives good page locality of RUNTIME_FUNCTION table touches (only one page of 
80 // RUNTIME_FUNCTION table is going to be touched during most IP2MD lookups).
81 //
82 // Smaller stride values also improve speed of IP2MD lookups, but this improvement is not significant (5% when going 
83 // from 8192 to 1024), so the working set / page locality was used as the metric to choose the optimum value.
84 //
85 #define RUNTIME_FUNCTION_LOOKUP_STRIDE  8192
86
87
88 typedef DPTR(struct CORCOMPILE_METHOD_PROFILE_LIST)
89     PTR_CORCOMPILE_METHOD_PROFILE_LIST;
90 typedef DPTR(struct CORCOMPILE_RUNTIME_DLL_INFO)
91     PTR_CORCOMPILE_RUNTIME_DLL_INFO;
92 typedef DPTR(struct CORCOMPILE_VERSION_INFO)  PTR_CORCOMPILE_VERSION_INFO;
93 typedef DPTR(struct COR_ILMETHOD) PTR_COR_ILMETHOD;
94
95 // This can be used to specify a dll that should be used as the compiler during ngen.
96 // If this is not specified, the default compiler dll will be used.
97 // If this is specified, it needs to be specified for all the assemblies that are ngenned.
98 #define NGEN_COMPILER_OVERRIDE_KEY W("NGen_JitName")
99
100 //
101 // CORCOMPILE_IMPORT_SECTION describes image range with references to other assemblies or runtime data structures
102 //
103 // There is number of different types of these ranges: eagerly initialized at image load vs. lazily initialized at method entry 
104 // vs. lazily initialized on first use; hot vs. cold, handles vs. code pointers, etc.
105 //
106 struct CORCOMPILE_IMPORT_SECTION
107 {
108     IMAGE_DATA_DIRECTORY    Section;            // Section containing values to be fixed up
109     USHORT                  Flags;              // One or more of CorCompileImportFlags
110     BYTE                    Type;               // One of CorCompileImportType
111     BYTE                    EntrySize;
112     DWORD                   Signatures;         // RVA of optional signature descriptors
113     DWORD                   AuxiliaryData;      // RVA of optional auxiliary data (typically GC info)
114 };
115
116 enum CorCompileImportType
117 {
118     CORCOMPILE_IMPORT_TYPE_UNKNOWN          = 0,
119     CORCOMPILE_IMPORT_TYPE_EXTERNAL_METHOD  = 1,
120     CORCOMPILE_IMPORT_TYPE_STUB_DISPATCH    = 2,
121     CORCOMPILE_IMPORT_TYPE_STRING_HANDLE    = 3,
122     CORCOMPILE_IMPORT_TYPE_TYPE_HANDLE      = 4,
123     CORCOMPILE_IMPORT_TYPE_METHOD_HANDLE    = 5,
124     CORCOMPILE_IMPORT_TYPE_VIRTUAL_METHOD   = 6,
125 };
126
127 enum CorCompileImportFlags
128 {
129     CORCOMPILE_IMPORT_FLAGS_EAGER           = 0x0001,   // Section at module load time.
130     CORCOMPILE_IMPORT_FLAGS_CODE            = 0x0002,   // Section contains code.
131     CORCOMPILE_IMPORT_FLAGS_PCODE           = 0x0004,   // Section contains pointers to code.
132 };
133
134 // ================================================================================
135 // Portable tagged union of a pointer field with a 30 bit scalar value
136 // ================================================================================
137
138 // The lowest bit of the tag will be set for tagged pointers. We also set the highest bit for convenience.
139 // It makes dereferences of tagged pointers to crash under normal circumstances.
140 // The highest bit of the tag will be set for tagged indexes (e.g. classid).
141
142 #define CORCOMPILE_TOKEN_TAG 0x80000001
143
144 // These two macros are mostly used just for debug-only checks to ensure that we have either tagged pointer (lowest bit is set)
145 // or tagged index (highest bit is set).
146 #define CORCOMPILE_IS_POINTER_TAGGED(token)     ((((SIZE_T)(token)) & 0x00000001) != 0)
147 #define CORCOMPILE_IS_INDEX_TAGGED(token)       ((((SIZE_T)(token)) & 0x80000000) != 0)
148
149 // The token (RVA of the fixup in most cases) is stored in the mid 30 bits of DWORD
150 #define CORCOMPILE_TAG_TOKEN(token)             ((SIZE_T)(((token)<<1)|CORCOMPILE_TOKEN_TAG))
151 #define CORCOMPILE_UNTAG_TOKEN(token)           ((((SIZE_T)(token))&~CORCOMPILE_TOKEN_TAG)>>1)
152
153 #ifdef _TARGET_ARM_
154 // Tagging of code pointers on ARM uses inverse logic because of the thumb bit.
155 #define CORCOMPILE_IS_PCODE_TAGGED(token)       ((((SIZE_T)(token)) & 0x00000001) == 0x00000000)
156 #define CORCOMPILE_TAG_PCODE(token)             ((SIZE_T)(((token)<<1)|0x80000000))
157 #else
158 #define CORCOMPILE_IS_PCODE_TAGGED(token)       CORCOMPILE_IS_POINTER_TAGGED(token)
159 #define CORCOMPILE_TAG_PCODE(token)             CORCOMPILE_TAG_TOKEN(token)
160 #endif
161
162 inline BOOL CORCOMPILE_IS_FIXUP_TAGGED(SIZE_T fixup, PTR_CORCOMPILE_IMPORT_SECTION pSection)
163 {
164 #ifdef _TARGET_ARM_
165     // Tagging of code pointers on ARM has to use inverse logic because of the thumb bit
166     if (pSection->Flags & CORCOMPILE_IMPORT_FLAGS_PCODE)
167     {
168         return CORCOMPILE_IS_PCODE_TAGGED(fixup);
169     }
170 #endif
171
172     return ((((SIZE_T)(fixup)) & CORCOMPILE_TOKEN_TAG) == CORCOMPILE_TOKEN_TAG);
173 }
174
175 enum CorCompileBuild
176 {
177     CORCOMPILE_BUILD_CHECKED,
178     CORCOMPILE_BUILD_FREE
179 };
180
181 enum CorCompileCodegen
182 {
183     CORCOMPILE_CODEGEN_DEBUGGING            = 0x0001,   // suports debugging (unoptimized code with symbol info)
184
185     CORCOMPILE_CODEGEN_PROFILING            = 0x0004,   // supports profiling
186     CORCOMPILE_CODEGEN_PROF_INSTRUMENTING   = 0x0008,   // code is instrumented to collect profile count info
187
188 };
189
190
191 // Used for INativeImageInstallInfo::GetConfigMask()
192 // A bind will ask for the particular bits it needs set; if all bits are set, it is a match.  Additional
193 // bits are ignored.
194
195 enum CorCompileConfigFlags
196 {
197     CORCOMPILE_CONFIG_DEBUG_NONE         = 0x01, // Assembly has Optimized code
198     CORCOMPILE_CONFIG_DEBUG              = 0x02, // Assembly has non-Optimized debuggable code
199     CORCOMPILE_CONFIG_DEBUG_DEFAULT      = 0x08, // Additional flag set if this particular setting is the
200                                                  // one indicated by the assembly debug custom attribute.
201
202     CORCOMPILE_CONFIG_PROFILING_NONE            = 0x100, // Assembly code has profiling hooks
203     CORCOMPILE_CONFIG_PROFILING                 = 0x200, // Assembly code has profiling hooks
204
205     CORCOMPILE_CONFIG_INSTRUMENTATION_NONE      = 0x1000, // Assembly code has no instrumentation
206     CORCOMPILE_CONFIG_INSTRUMENTATION           = 0x2000, // Assembly code has basic block instrumentation
207 };
208
209 // Values for Flags field of CORCOMPILE_HEADER.
210 enum CorCompileHeaderFlags
211 {
212     CORCOMPILE_HEADER_HAS_SECURITY_DIRECTORY    = 0x00000001,   // Original image had a security directory
213                                                                 // Note it is useless to cache the actual directory contents
214                                                                 // since it must be verified as part of the original image
215     CORCOMPILE_HEADER_IS_IBC_OPTIMIZED          = 0x00000002,
216
217     CORCOMPILE_HEADER_IS_READY_TO_RUN           = 0x00000004,
218 };
219
220 // 
221 // !!! INCREMENT THE MAJOR VERSION ANY TIME THERE IS CHANGE IN CORCOMPILE_HEADER STRUCTURE !!!
222 //
223 #define CORCOMPILE_SIGNATURE     0x0045474E     // 'NGEN'
224 #define CORCOMPILE_MAJOR_VERSION 0x0001
225 #define CORCOMPILE_MINOR_VERSION 0x0000
226
227 // This structure is pointed to by the code:IMAGE_COR20_HEADER (see file:corcompile.h#ManagedHeader)
228 // See the file:../../doc/BookOfTheRuntime/NGEN/NGENDesign.doc for more
229 struct CORCOMPILE_HEADER
230 {
231     // For backward compatibility reasons, VersionInfo field must be at offset 40, ManifestMetaData
232     // must be at 88, PEKind must be at 112/116 bytes, Machine must be at 120/124 bytes, and
233     // size of CORCOMPILE_HEADER must be 164/168 bytes.  Be careful when you modify this struct.
234     // See code:PEDecoder::GetMetaDataHelper.
235     DWORD                   Signature;
236     USHORT                  MajorVersion;
237     USHORT                  MinorVersion;
238
239     IMAGE_DATA_DIRECTORY    HelperTable;    // Table of function pointers to JIT helpers indexed by helper number
240     IMAGE_DATA_DIRECTORY    ImportSections; // points to array of code:CORCOMPILE_IMPORT_SECTION
241     IMAGE_DATA_DIRECTORY    ImportTable;    // points to table CORCOMPILE_IMPORT_TABLE_ENTRY
242     IMAGE_DATA_DIRECTORY    StubsData;      // contains the value to register with the stub manager for the delegate stubs & AMD64 tail call stubs
243     IMAGE_DATA_DIRECTORY    VersionInfo;    // points to a code:CORCOMPILE_VERSION_INFO
244     IMAGE_DATA_DIRECTORY    Dependencies;   // points to an array of code:CORCOMPILE_DEPENDENCY
245     IMAGE_DATA_DIRECTORY    DebugMap;       // points to an array of code:CORCOMPILE_DEBUG_RID_ENTRY hashed by method RID
246     IMAGE_DATA_DIRECTORY    ModuleImage;    // points to the freeze dried  Module structure
247     IMAGE_DATA_DIRECTORY    CodeManagerTable;  // points to a code:CORCOMPILE_CODE_MANAGER_ENTRY
248     IMAGE_DATA_DIRECTORY    ProfileDataList;// points to the list of code:CORCOMPILE_METHOD_PROFILE_LIST
249     IMAGE_DATA_DIRECTORY    ManifestMetaData; // points to the native manifest metadata
250     IMAGE_DATA_DIRECTORY    VirtualSectionsTable;// List of CORCOMPILE_VIRTUAL_SECTION_INFO. Contains a list of Section
251                                                 // ranges for debugging purposes. There is one entry in this table per
252                                                 // ZapVirtualSection in the NGEN image.  This data is used to fire ETW
253                                                 // events that describe the various VirtualSection in the NGEN image. These
254                                                 // events are used for diagnostics and performance purposes. Some of the
255                                                 // questions these events help answer are like : how effective is IBC
256                                                 // training data. They can also be used to have better nidump support for
257                                                 // decoding virtual section information ( start - end ranges for each
258                                                 // virtual section )
259
260     TADDR                   ImageBase;      // Actual image base address (ASLR fakes the image base in PE header while applying relocations in kernel)
261     DWORD                   Flags;          // Flags, see CorCompileHeaderFlags above
262
263     DWORD                   PEKind;         // CorPEKind of the original IL image
264
265     ULONG                   COR20Flags;     // Cached value of code:IMAGE_COR20_HEADER.Flags from original IL image
266     WORD                    Machine;        // Cached value of _IMAGE_FILE_HEADER.Machine from original IL image
267     WORD                    Characteristics;// Cached value of _IMAGE_FILE_HEADER.Characteristics from original IL image
268
269     IMAGE_DATA_DIRECTORY    EEInfoTable;    // points to a code:CORCOMPILE_EE_INFO_TABLE
270
271     // For backward compatibility (see above)
272     IMAGE_DATA_DIRECTORY    Dummy1;
273     IMAGE_DATA_DIRECTORY    Dummy2;
274     IMAGE_DATA_DIRECTORY    Dummy3;
275     IMAGE_DATA_DIRECTORY    Dummy4;
276 };
277
278 // CORCOMPILE_VIRTUAL_SECTION_INFO describes virtual section ranges. This data is used by nidump 
279 // and to fire ETW that are used for diagnostics and performance purposes. Some of the questions 
280 // these events help answer are like : how effective is IBC training data.
281 struct CORCOMPILE_VIRTUAL_SECTION_INFO
282 {
283     ULONG   VirtualAddress;
284     ULONG   Size;
285     DWORD   SectionType;
286 };
287
288 #define CORCOMPILE_SECTION_TYPES()                            \
289     CORCOMPILE_SECTION_TYPE(Module)                           \
290     CORCOMPILE_SECTION_TYPE(EETable)                          \
291     CORCOMPILE_SECTION_TYPE(WriteData)                        \
292     CORCOMPILE_SECTION_TYPE(WriteableData)                    \
293     CORCOMPILE_SECTION_TYPE(Data)                             \
294     CORCOMPILE_SECTION_TYPE(RVAStatics)                       \
295     CORCOMPILE_SECTION_TYPE(EEData)                           \
296     CORCOMPILE_SECTION_TYPE(DelayLoadInfoTableEager)          \
297     CORCOMPILE_SECTION_TYPE(DelayLoadInfoTable)               \
298     CORCOMPILE_SECTION_TYPE(EEReadonlyData)                   \
299     CORCOMPILE_SECTION_TYPE(ReadonlyData)                     \
300     CORCOMPILE_SECTION_TYPE(Class)                            \
301     CORCOMPILE_SECTION_TYPE(CrossDomainInfo)                  \
302     CORCOMPILE_SECTION_TYPE(MethodDesc)                       \
303     CORCOMPILE_SECTION_TYPE(MethodDescWriteable)              \
304     CORCOMPILE_SECTION_TYPE(Exception)                        \
305     CORCOMPILE_SECTION_TYPE(Instrument)                       \
306     CORCOMPILE_SECTION_TYPE(VirtualImportThunk)               \
307     CORCOMPILE_SECTION_TYPE(ExternalMethodThunk)              \
308     CORCOMPILE_SECTION_TYPE(HelperTable)                      \
309     CORCOMPILE_SECTION_TYPE(MethodPrecodeWriteable)           \
310     CORCOMPILE_SECTION_TYPE(MethodPrecodeWrite)               \
311     CORCOMPILE_SECTION_TYPE(MethodPrecode)                    \
312     CORCOMPILE_SECTION_TYPE(Win32Resources)                   \
313     CORCOMPILE_SECTION_TYPE(Header)                           \
314     CORCOMPILE_SECTION_TYPE(Metadata)                         \
315     CORCOMPILE_SECTION_TYPE(DelayLoadInfo)                    \
316     CORCOMPILE_SECTION_TYPE(ImportTable)                      \
317     CORCOMPILE_SECTION_TYPE(Code)                             \
318     CORCOMPILE_SECTION_TYPE(CodeHeader)                       \
319     CORCOMPILE_SECTION_TYPE(CodeManager)                      \
320     CORCOMPILE_SECTION_TYPE(UnwindData)                       \
321     CORCOMPILE_SECTION_TYPE(RuntimeFunction)                  \
322     CORCOMPILE_SECTION_TYPE(Stubs)                            \
323     CORCOMPILE_SECTION_TYPE(StubDispatchData)                 \
324     CORCOMPILE_SECTION_TYPE(ExternalMethodData)               \
325     CORCOMPILE_SECTION_TYPE(DelayLoadInfoDelayList)           \
326     CORCOMPILE_SECTION_TYPE(ReadonlyShared)                   \
327     CORCOMPILE_SECTION_TYPE(Readonly)                         \
328     CORCOMPILE_SECTION_TYPE(IL)                               \
329     CORCOMPILE_SECTION_TYPE(GCInfo)                           \
330     CORCOMPILE_SECTION_TYPE(ILMetadata)                       \
331     CORCOMPILE_SECTION_TYPE(Resources)                        \
332     CORCOMPILE_SECTION_TYPE(CompressedMaps)                   \
333     CORCOMPILE_SECTION_TYPE(Debug)                            \
334     CORCOMPILE_SECTION_TYPE(BaseRelocs)                       \
335
336 // Hot: Items are frequently accessed ( Indicated by either IBC data, or
337 //      statically known )
338
339 // Warm : Items are less frequently accessed, or frequently accessed 
340 //        but were not touched during IBC profiling.
341
342 // Cold : Least frequently accessed /shouldn't not be accessed
343 //        when running a scenario that was used during IBC
344 //        training ( training scenario )
345
346 // HotColdSorted : Sections marked with this category means they contain both
347 //                 Hot items and Cold items. The hot items are placed before 
348 //                 the cold items (Sorted)
349
350 #define CORCOMPILE_SECTION_RANGE_TYPES()                     \
351     CORCOMPILE_SECTION_RANGE_TYPE(Hot, 0x00010000)           \
352     CORCOMPILE_SECTION_RANGE_TYPE(Warm, 0x00020000)          \
353     CORCOMPILE_SECTION_RANGE_TYPE(Cold, 0x00040000)          \
354     CORCOMPILE_SECTION_RANGE_TYPE(HotColdSorted, 0x00080000) \
355
356
357 // IBCUnProfiled: Items in this VirtualSection are statically determined to be cold.
358 //                 (IBC Profiling wouldn't have helped put these item in a hot section).
359 //                 Items that currently doesn't have IBC probs, or are always put in a specific section 
360 //                 regardless of IBC data should fall in this category.
361
362 // IBCProfiled: IBC profiling placed items in this section, or
363 //              items are NOT placed into a hot section they didn't have IBC profiling data
364 //              ( IBC profiling would have helped put these items in a hot section ) 
365
366 #define CORCOMPILE_SECTION_IBCTYPES()                       \
367     CORCOMPILE_SECTION_IBCTYPE(IBCUnProfiled, 0x01000000)  \
368     CORCOMPILE_SECTION_IBCTYPE(IBCProfiled, 0x02000000)     \
369
370
371 // Support for VirtualSection Metadata/Categories
372 // Please update the VirtualSetionType ETW map in ClrEtwAll.man if you changed this enum.
373 // ZapVirtualSectionType is used to describe metadata about VirtualSections.
374 // The metadata consists of 3 sub-metadata parts.
375 // ---------------------------------------------------
376 // 1 byte       1 byte      2 bytes                 --
377 // <IBCType> <RangeType> <VirtualSectionType>       --
378 // ---------------------------------------------------
379 // 
380 // 
381 // VirtualSections are a CLR concept to aggregate data
382 // items that share common properties together (Hot/Cold/Warm, Writeable/
383 // Readonly ...etc.). VirtualSections are tagged with some categories when they
384 // are created (code:NewVirtualSection)
385 // The VirtualSection categorize are described more in VirtualSectionType enum.
386 // The categories describe 2 important aspects for each VirtualSection
387 // 
388 // ***********************************************
389 // IBCProfiled v.s NonIBCProfiled Categories.
390 // **********************************************
391 // 
392 // IBCProfiled: Distinguish between sections that IBC profiling data has been used 
393 //               to decide the layout of the data items in this section. 
394 // NonIBCProfiled: We don't have IBC data for all our datastructures.
395 //                  The access pattern/frequency for some data structures
396 //                  are statically determined. Sections that contain these data items 
397 //                  are marked as NonIBCProfiled. 
398 //
399 //***************************************************
400 // Access Frequency categories 
401 // **************************************************
402 // Hot: Data is frequently accessed
403 // Warm: Less frequently accessed than Hot
404 // Cold: Should be rarely accessed.
405 // 
406 // The combination of these 2 sub-categories gives us the following valid categories 
407 // 1-IBCProfiled | Hot: Hot based on IBC profiling data.
408 // 2-IBCProfiled | Cold: IBC profiling could have helped make this section hot.
409 // 3-NonIBCProfiled | Hot: Statically determined hot.
410 // 4-NonIBCProfiled | Warm: Staticaly determined warm.
411 // 5-NonIBCProfiled | Cold: Statically determined cold.
412 // 
413 // We should try to place data items into the correct section based on 
414 // the above categorization, this could mean that we might split 
415 // a virtual section into 2 sections if it contains multiple heterogeneous items.
416
417 enum ZapVirtualSectionType
418 {
419     // <IBCType>
420     IBCTypeReservedFlag = 0xFF000000,
421 #define CORCOMPILE_SECTION_IBCTYPE(ibcType, flag) ibcType##Section = flag,
422     CORCOMPILE_SECTION_IBCTYPES()
423 #undef CORCOMPILE_SECTION_IBCTYPE
424     
425     // <RangeType>
426     RangeTypeReservedFlag = 0x00FF0000,
427 #define CORCOMPILE_SECTION_RANGE_TYPE(rangeType, flag) rangeType##Range = flag,
428     CORCOMPILE_SECTION_RANGE_TYPES()
429 #undef CORCOMPILE_SECTION_RANGE_TYPE
430
431     // <VirtualSectionType>
432     VirtualSectionTypeReservedFlag = 0x0000FFFF,
433     VirtualSectionTypeStartSection = 0x0, // reserved so the first section start at 0x1
434 #define CORCOMPILE_SECTION_TYPE(virtualSectionType) virtualSectionType##Section,
435     CORCOMPILE_SECTION_TYPES()
436 #undef CORCOMPILE_SECTION_TYPE
437
438     CORCOMPILE_SECTION_TYPE_COUNT
439 };
440
441 class VirtualSectionData
442 {
443
444 public :
445     static UINT8 IBCType(DWORD sectionType) { return (UINT8) ((sectionType & IBCTypeReservedFlag) >> 24); }
446     static UINT8 RangeType(DWORD sectionType) { return (UINT8) ((sectionType & RangeTypeReservedFlag) >> 16); }
447     static UINT16 VirtualSectionType(DWORD sectionType) { return (UINT16) ((sectionType & VirtualSectionTypeReservedFlag)); }
448     static BOOL IsIBCProfiledColdSection(DWORD sectionType) 
449     {
450         return ((sectionType & ColdRange) == ColdRange) && ((sectionType & IBCProfiledSection) == IBCProfiledSection); 
451     }
452 };
453
454 struct CORCOMPILE_IMPORT_TABLE_ENTRY
455 {
456     USHORT                  wAssemblyRid;
457     USHORT                  wModuleRid;
458 };
459
460 struct CORCOMPILE_EE_INFO_TABLE
461 {
462     TADDR                      inlinedCallFrameVptr;
463     PTR_LONG                   addrOfCaptureThreadGlobal;
464     PTR_DWORD                  addrOfJMCFlag;
465     SIZE_T                     gsCookie;
466     CORINFO_Object **          emptyString;
467
468     DWORD                      threadTlsIndex;
469
470     DWORD                      rvaStaticTlsIndex;
471 };
472
473 /*********************************************************************************/
474
475 // This is the offset to the compressed blob of debug information
476
477 typedef ULONG CORCOMPILE_DEBUG_ENTRY;
478
479 // A single generic method may be get compiled into multiple copies of code for
480 // different instantiations, and can have multiple entries for the same RID.
481
482 struct CORCOMPILE_DEBUG_LABELLED_ENTRY
483 {
484     DWORD                       nativeCodeRVA;   // the ngen code RVA distinguishes this entry from others with the same RID.
485     CORCOMPILE_DEBUG_ENTRY      debugInfoOffset; // offset to the debug information for this native code
486 };
487
488 // Debug information is accessed using a table of RVAs indexed by the RID token for
489 // the method.
490
491 typedef CORCOMPILE_DEBUG_ENTRY CORCOMPILE_DEBUG_RID_ENTRY;
492
493 // If this bit is not set, the CORCOMPILE_DEBUG_RID_ENTRY RVA points to a compressed
494 // debug information blob.
495 // If this bit is set, the RVA points to CORCOMPILE_DEBUG_LABELLED_ENTRY.
496 // If this bit is set in CORCOMPILE_DEBUG_LABELLED_ENTRY, there is another entry following it.
497
498 const CORCOMPILE_DEBUG_RID_ENTRY CORCOMPILE_DEBUG_MULTIPLE_ENTRIES = 0x80000000;
499
500 inline bool IsMultipleLabelledEntries(CORCOMPILE_DEBUG_RID_ENTRY rva)
501 {
502     SUPPORTS_DAC;
503
504     return (rva & CORCOMPILE_DEBUG_MULTIPLE_ENTRIES) != 0;
505 }
506
507 inline unsigned GetDebugRidEntryHash(mdToken token)
508 {
509     SUPPORTS_DAC;
510
511     unsigned hashCode = token;
512
513     // mix it
514     hashCode -= hashCode >> 17;
515     hashCode -= hashCode >> 11;
516     hashCode -= hashCode >> 5;
517
518     return hashCode;
519 }
520
521 typedef DPTR(CORCOMPILE_DEBUG_ENTRY)   PTR_CORCOMPILE_DEBUG_ENTRY;
522 typedef DPTR(struct CORCOMPILE_DEBUG_LABELLED_ENTRY)   PTR_CORCOMPILE_DEBUG_LABELLED_ENTRY;
523 typedef DPTR(CORCOMPILE_DEBUG_RID_ENTRY)   PTR_CORCOMPILE_DEBUG_RID_ENTRY;
524
525 /*********************************************************************************/
526
527 struct CORCOMPILE_CODE_MANAGER_ENTRY
528 {
529     IMAGE_DATA_DIRECTORY    HotCode;
530     IMAGE_DATA_DIRECTORY    Code;
531     IMAGE_DATA_DIRECTORY    ColdCode;
532
533     IMAGE_DATA_DIRECTORY    ROData;
534
535     //Layout is
536     //HOT COMMON
537     //HOT IBC
538     //HOT GENERICS
539     //Hot due to procedure splitting
540     ULONG HotIBCMethodOffset;
541     ULONG HotGenericsMethodOffset;
542
543     //Layout is
544     //COLD IBC
545     //Cold due to procedure splitting.
546     ULONG ColdUntrainedMethodOffset;
547 };
548
549 #if defined(_TARGET_X86_) || defined(_TARGET_AMD64_)
550
551 #define _PRECODE_EXTERNAL_METHOD_THUNK      0x41
552 #define _PRECODE_VIRTUAL_IMPORT_THUNK       0x42
553
554     struct  CORCOMPILE_VIRTUAL_IMPORT_THUNK
555     {
556         BYTE                callJmp[5];     // Call/Jmp Pc-Rel32
557         BYTE                precodeType;    // 0x42 _PRECODE_VIRTUAL_IMPORT_THUNK
558         WORD                slotNum;
559     };
560
561     struct  CORCOMPILE_EXTERNAL_METHOD_THUNK
562     {
563         BYTE                callJmp[5];     // Call/Jmp Pc-Rel32
564         BYTE                precodeType;    // 0x41 _PRECODE_EXTERNAL_METHOD_THUNK
565         WORD                padding;
566     };
567
568 #elif defined(_TARGET_ARM_)
569
570     struct  CORCOMPILE_VIRTUAL_IMPORT_THUNK
571     {
572         // Array of words to do the following:
573         //
574         // mov r12, pc       ; Save the current address relative to which we will get slot ID and address to patch.
575         // ldr pc, [pc, #4]  ; Load the target address. Initially it will point to the helper stub that will patch it
576         //                   ; to point to the actual target on the first run.
577         WORD                m_rgCode[3];
578
579         // WORD to store the slot ID
580         WORD                slotNum;
581
582         // The target address - initially, this will point to VirtualMethodFixupStub.
583         // Post patchup by the stub, it will point to the actual method body.
584         PCODE               m_pTarget;
585     };
586
587     struct  CORCOMPILE_EXTERNAL_METHOD_THUNK
588     {
589         // Array of words to do the following:
590         //
591         // mov r12, pc       ; Save the current address relative to which we will get GCRef bitmap and address to patch.
592         // ldr pc, [pc, #4]  ; Load the target address. Initially it will point to the helper stub that will patch it
593         //                   ; to point to the actual target on the first run.
594         WORD                m_rgCode[3];
595
596         WORD                m_padding;
597
598         // The target address - initially, this will point to ExternalMethodFixupStub.
599         // Post patchup by the stub, it will point to the actual method body.
600         PCODE               m_pTarget;
601     };
602         
603 #elif defined(_TARGET_ARM64_)
604     struct  CORCOMPILE_VIRTUAL_IMPORT_THUNK
605     {
606         // Array of words to do the following:
607         //
608         // adr         x12, #0            ; Save the current address relative to which we will get slot ID and address to patch.
609         // ldr         x10, [x12, #16]    ; Load the target address. 
610         // br          x10                ; Jump to the target
611         DWORD                m_rgCode[3];
612
613         // WORD to store the slot ID
614         WORD                slotNum;
615
616         // The target address - initially, this will point to VirtualMethodFixupStub.
617         // Post patchup by the stub, it will point to the actual method body.
618         PCODE                m_pTarget;
619     };
620
621     struct  CORCOMPILE_EXTERNAL_METHOD_THUNK
622     {
623         // Array of words to do the following:
624         // adr         x12, #0            ; Save the current address relative to which we will get slot ID and address to patch.
625         // ldr         x10, [x12, #16]    ; Load the target address. 
626         // br          x10                ; Jump to the target
627         DWORD                m_rgCode[3];
628
629         DWORD                m_padding; //aligning stack to 16 bytes
630
631         // The target address - initially, this will point to ExternalMethodFixupStub.
632         // Post patchup by the stub, it will point to the actual method body.
633         PCODE                m_pTarget;
634     };
635
636 #endif
637
638 //
639 // GCRefMap blob starts with DWORDs lookup index of relative offsets into the blob. This lookup index is used to limit amount
640 // of linear scanning required to find entry in the GCRefMap. The size of this lookup index is 
641 // <totalNumberOfEntries in the GCRefMap> / GCREFMAP_LOOKUP_STRIDE.
642 //
643 #define GCREFMAP_LOOKUP_STRIDE 1024
644
645 enum CORCOMPILE_GCREFMAP_TOKENS
646 {
647     GCREFMAP_SKIP = 0,
648     GCREFMAP_REF = 1,
649     GCREFMAP_INTERIOR = 2,
650     GCREFMAP_METHOD_PARAM = 3,
651     GCREFMAP_TYPE_PARAM = 4,
652     GCREFMAP_VASIG_COOKIE = 5,
653 };
654
655 // Tags for fixup blobs
656 enum CORCOMPILE_FIXUP_BLOB_KIND
657 {
658     ENCODE_NONE                         = 0,
659     
660     ENCODE_MODULE_OVERRIDE              = 0x80,     /* When the high bit is set, override of the module immediately follows */
661
662     ENCODE_DICTIONARY_LOOKUP_THISOBJ    = 0x07,
663     ENCODE_DICTIONARY_LOOKUP_TYPE       = 0x08,
664     ENCODE_DICTIONARY_LOOKUP_METHOD     = 0x09,
665
666     ENCODE_TYPE_HANDLE                  = 0x10,     /* Type handle */
667     ENCODE_METHOD_HANDLE,                           /* Method handle */
668     ENCODE_FIELD_HANDLE,                            /* Field handle */
669
670     ENCODE_METHOD_ENTRY,                            /* For calling a method entry point */
671     ENCODE_METHOD_ENTRY_DEF_TOKEN,                  /* Smaller version of ENCODE_METHOD_ENTRY - method is def token */
672     ENCODE_METHOD_ENTRY_REF_TOKEN,                  /* Smaller version of ENCODE_METHOD_ENTRY - method is ref token */
673
674     ENCODE_VIRTUAL_ENTRY,                           /* For invoking a virtual method */
675     ENCODE_VIRTUAL_ENTRY_DEF_TOKEN,                 /* Smaller version of ENCODE_VIRTUAL_ENTRY - method is def token */
676     ENCODE_VIRTUAL_ENTRY_REF_TOKEN,                 /* Smaller version of ENCODE_VIRTUAL_ENTRY - method is ref token */
677     ENCODE_VIRTUAL_ENTRY_SLOT,                      /* Smaller version of ENCODE_VIRTUAL_ENTRY - type & slot */
678
679     ENCODE_READYTORUN_HELPER,                       /* ReadyToRun helper */
680     ENCODE_STRING_HANDLE,                           /* String token */
681
682     ENCODE_NEW_HELPER,                              /* Dynamically created new helpers */
683     ENCODE_NEW_ARRAY_HELPER,
684
685     ENCODE_ISINSTANCEOF_HELPER,                     /* Dynamically created casting helper */
686     ENCODE_CHKCAST_HELPER,
687
688     ENCODE_FIELD_ADDRESS,                           /* For accessing a cross-module static fields */
689     ENCODE_CCTOR_TRIGGER,                           /* Static constructor trigger */
690
691     ENCODE_STATIC_BASE_NONGC_HELPER,                /* Dynamically created static base helpers */
692     ENCODE_STATIC_BASE_GC_HELPER,
693     ENCODE_THREAD_STATIC_BASE_NONGC_HELPER,
694     ENCODE_THREAD_STATIC_BASE_GC_HELPER,
695
696     ENCODE_FIELD_BASE_OFFSET,                       /* Field base */
697     ENCODE_FIELD_OFFSET,
698
699     ENCODE_TYPE_DICTIONARY,
700     ENCODE_METHOD_DICTIONARY,
701
702     ENCODE_CHECK_TYPE_LAYOUT,
703     ENCODE_CHECK_FIELD_OFFSET,
704
705     ENCODE_DELEGATE_CTOR,
706
707     ENCODE_DECLARINGTYPE_HANDLE,
708
709     ENCODE_MODULE_HANDLE                = 0x50,     /* Module token */
710     ENCODE_STATIC_FIELD_ADDRESS,                    /* For accessing a static field */
711     ENCODE_MODULE_ID_FOR_STATICS,                   /* For accessing static fields */
712     ENCODE_MODULE_ID_FOR_GENERIC_STATICS,           /* For accessing static fields */
713     ENCODE_CLASS_ID_FOR_STATICS,                    /* For accessing static fields */
714     ENCODE_SYNC_LOCK,                               /* For synchronizing access to a type */
715     ENCODE_INDIRECT_PINVOKE_TARGET,                 /* For calling a pinvoke method ptr  */
716     ENCODE_PROFILING_HANDLE,                        /* For the method's profiling counter */
717     ENCODE_VARARGS_METHODDEF,                       /* For calling a varargs method */
718     ENCODE_VARARGS_METHODREF,
719     ENCODE_VARARGS_SIG,
720     ENCODE_ACTIVE_DEPENDENCY,                       /* Conditional active dependency */
721     ENCODE_METHOD_NATIVE_ENTRY,                     /* NativeCallable method token */
722 };
723
724 enum EncodeMethodSigFlags
725 {
726     ENCODE_METHOD_SIG_UnboxingStub              = 0x01,
727     ENCODE_METHOD_SIG_InstantiatingStub         = 0x02,
728     ENCODE_METHOD_SIG_MethodInstantiation       = 0x04,
729     ENCODE_METHOD_SIG_SlotInsteadOfToken        = 0x08,
730     ENCODE_METHOD_SIG_MemberRefToken            = 0x10,
731     ENCODE_METHOD_SIG_Constrained               = 0x20,
732     ENCODE_METHOD_SIG_OwnerType                 = 0x40,
733 };
734
735 enum EncodeFieldSigFlags
736 {
737     ENCODE_FIELD_SIG_IndexInsteadOfToken        = 0x08,
738     ENCODE_FIELD_SIG_MemberRefToken             = 0x10,
739     ENCODE_FIELD_SIG_OwnerType                  = 0x40,
740 };
741
742 class SBuffer;
743 class SigBuilder;
744 class PEDecoder;
745 class GCRefMapBuilder;
746
747 //REVIEW: include for ee exception info
748 #include "eexcp.h"
749
750 struct CORCOMPILE_EXCEPTION_LOOKUP_TABLE_ENTRY
751 {
752     DWORD MethodStartRVA;
753     DWORD ExceptionInfoRVA;
754 };
755
756 struct CORCOMPILE_EXCEPTION_LOOKUP_TABLE
757 {
758     // pointer to the first element of m_numLookupEntries elements 
759     CORCOMPILE_EXCEPTION_LOOKUP_TABLE_ENTRY m_Entries[1];
760
761     CORCOMPILE_EXCEPTION_LOOKUP_TABLE_ENTRY* ExceptionLookupEntry(unsigned i)
762     {
763         SUPPORTS_DAC_WRAPPER;
764         return &(PTR_CORCOMPILE_EXCEPTION_LOOKUP_TABLE_ENTRY(PTR_HOST_MEMBER_TADDR(CORCOMPILE_EXCEPTION_LOOKUP_TABLE,this,m_Entries))[i]);
765     }
766 };
767
768 struct CORCOMPILE_EXCEPTION_CLAUSE
769 {
770     CorExceptionFlag    Flags;
771     DWORD               TryStartPC;
772     DWORD               TryEndPC;
773     DWORD               HandlerStartPC;  
774     DWORD               HandlerEndPC;  
775     union {
776         mdToken         ClassToken;
777         DWORD           FilterOffset;
778     };  
779 };
780
781 //lower order bit (HAS_EXCEPTION_INFO_MASK) used to determine if the method has any exception handling
782 #define HAS_EXCEPTION_INFO_MASK 1
783
784 struct CORCOMPILE_COLD_METHOD_ENTRY
785 {
786 #ifdef WIN64EXCEPTIONS
787     DWORD       mainFunctionEntryRVA;
788 #endif
789     // TODO: hotCodeSize should be encoded in GC info
790     ULONG       hotCodeSize;
791 };
792
793 // MVID used by the metadata of all ngen images
794 // {70E9452F-5F0A-4f0e-8E02-203992F4221C}
795 EXTERN_GUID(NGEN_IMAGE_MVID, 0x70e9452f, 0x5f0a, 0x4f0e, 0x8e, 0x2, 0x20, 0x39, 0x92, 0xf4, 0x22, 0x1c);
796
797 typedef GUID CORCOMPILE_NGEN_SIGNATURE;
798
799 // To indicate that the dependency is not hardbound
800 // {DB15CD8C-1378-4963-9DF3-14D97E95D1A1}
801 EXTERN_GUID(INVALID_NGEN_SIGNATURE, 0xdb15cd8c, 0x1378, 0x4963, 0x9d, 0xf3, 0x14, 0xd9, 0x7e, 0x95, 0xd1, 0xa1);
802
803 struct CORCOMPILE_ASSEMBLY_SIGNATURE
804 {
805     // Metadata MVID.
806     GUID                    mvid;
807
808     // timestamp and IL image size for the source IL assembly.
809     // This is used for mini-dump to find matching metadata.
810     DWORD                   timeStamp;
811     DWORD                   ilImageSize;
812 };
813
814 typedef enum
815 {
816     CORECLR_INFO,
817     CROSSGEN_COMPILER_INFO,
818     NUM_RUNTIME_DLLS
819 } CorCompileRuntimeDlls;
820
821 extern LPCWSTR CorCompileGetRuntimeDllName(CorCompileRuntimeDlls id);
822
823 // Will always return a valid HMODULE for CLR_INFO, but will return NULL for NGEN_COMPILER_INFO
824 // if the DLL has not yet been loaded (it does not try to cause a load).
825 extern HMODULE CorCompileGetRuntimeDll(CorCompileRuntimeDlls id);
826
827 struct CORCOMPILE_RUNTIME_DLL_INFO
828 {
829     // This structure can only contain information not updated by authenticode signing. It is required
830     // for crossgen to work in buildlab. It particular, it cannot contain PE checksum because of it is
831     // update by authenticode signing.
832     DWORD                   timeStamp;
833     DWORD                   virtualSize;
834 };
835
836
837
838 struct CORCOMPILE_VERSION_INFO
839 {
840     // OS
841     WORD                    wOSPlatformID;
842     WORD                    wOSMajorVersion;
843
844     // For backward compatibility reasons, the following four fields must start at offset 4,
845     // be consequtive, and be 2 bytes each.  See code:PEDecoder::GetMetaDataHelper.
846     // EE Version
847     WORD                    wVersionMajor;
848     WORD                    wVersionMinor;
849     WORD                    wVersionBuildNumber;
850     WORD                    wVersionPrivateBuildNumber;
851
852     // Codegen flags
853     WORD                    wCodegenFlags;
854     WORD                    wConfigFlags;
855     WORD                    wBuild;
856
857     // Processor
858     WORD                    wMachine;
859     CORINFO_CPU             cpuInfo;
860
861     // Signature of source assembly
862     CORCOMPILE_ASSEMBLY_SIGNATURE   sourceAssembly;
863
864     // Signature which identifies this ngen image
865     CORCOMPILE_NGEN_SIGNATURE       signature;
866
867     // Timestamp info for runtime dlls
868     CORCOMPILE_RUNTIME_DLL_INFO     runtimeDllInfo[NUM_RUNTIME_DLLS];
869 };
870
871
872
873
874 struct CORCOMPILE_DEPENDENCY
875 {
876     // Pre-bind Ref
877     mdAssemblyRef                   dwAssemblyRef;
878
879     // Post-bind Def
880     mdAssemblyRef                   dwAssemblyDef;
881     CORCOMPILE_ASSEMBLY_SIGNATURE   signAssemblyDef;
882
883     CORCOMPILE_NGEN_SIGNATURE       signNativeImage;    // INVALID_NGEN_SIGNATURE if this a soft-bound dependency
884
885
886 };
887
888 /*********************************************************************************/
889 // Flags used to encode HelperTable
890 #if defined(_TARGET_ARM64_)
891 #define HELPER_TABLE_ENTRY_LEN      16
892 #else
893 #define HELPER_TABLE_ENTRY_LEN      8
894 #endif //defined(_TARGET_ARM64_)
895
896 #define HELPER_TABLE_ALIGN          8
897 #define CORCOMPILE_HELPER_PTR       0x80000000 // The entry is pointer to the helper (jump thunk otherwise)
898
899 // The layout of this struct is required to be
900 // a 'next' pointer followed by a CORBBTPROF_METHOD_HEADER
901 //
902 struct CORCOMPILE_METHOD_PROFILE_LIST
903 {
904     CORCOMPILE_METHOD_PROFILE_LIST *       next;
905 //  CORBBTPROF_METHOD_HEADER               info;
906
907     CORBBTPROF_METHOD_HEADER * GetInfo()
908     { return (CORBBTPROF_METHOD_HEADER *) (this+1); }
909 };
910
911 // see code:CorProfileData.GetHotTokens for how we determine what is in hot meta-data.
912 class CorProfileData
913 {
914 public:
915     CorProfileData(void *  rawProfileData);  // really of type ZapImage::ProfileDataSection*
916
917     struct CORBBTPROF_TOKEN_INFO *  GetTokenFlagsData(SectionFormat section)
918     {
919         if (this == NULL)
920             return NULL;
921         return this->profilingTokenFlagsData[section].data;
922     }
923
924     DWORD GetTokenFlagsCount(SectionFormat section)
925     {
926         if (this == NULL)
927             return 0;
928         return this->profilingTokenFlagsData[section].count;
929     }
930
931     CORBBTPROF_BLOB_ENTRY *  GetBlobStream()
932     {
933         if (this == NULL)
934             return NULL;
935         return this->blobStream;
936     }
937
938
939     // see code:MetaData::HotMetaDataHeader for details on reading hot meta-data
940     //
941     // for detail on where we use the API to store the hot meta data
942     //     * code:CMiniMdRW.SaveFullTablesToStream#WritingHotMetaData
943     //     * code:CMiniMdRW.SaveHotPoolsToStream
944     //     * code:CMiniMdRW.SaveHotPoolToStream#CallToGetHotTokens
945     //
946     ULONG GetHotTokens(int table, DWORD mask, DWORD hotValue, mdToken *tokenBuffer, ULONG maxCount)
947     {
948         ULONG count = 0;
949         SectionFormat format = (SectionFormat)(FirstTokenFlagSection + table);
950
951         CORBBTPROF_TOKEN_INFO *profilingData = profilingTokenFlagsData[format].data;
952         DWORD cProfilingData = profilingTokenFlagsData[format].count;
953
954         if (profilingData != NULL)
955         {
956             for (DWORD i = 0; i < cProfilingData; i++)
957             {
958                 if ((profilingData[i].flags & mask) == hotValue)
959                 {
960                     if (tokenBuffer != NULL && count < maxCount)
961                         tokenBuffer[count] = profilingData[i].token;
962                     count++;
963                 }
964             }
965         }
966         return count;
967     }
968
969     //
970     //  Token lookup methods
971     //
972     ULONG GetTypeProfilingFlagsOfToken(mdToken token)
973     {
974         _ASSERTE(TypeFromToken(token) == mdtTypeDef);
975         return  GetProfilingFlagsOfToken(token);
976     }
977
978     CORBBTPROF_BLOB_PARAM_SIG_ENTRY *GetBlobSigEntry(mdToken token)
979     {
980         _ASSERTE((TypeFromToken(token) == ibcTypeSpec) || (TypeFromToken(token) == ibcMethodSpec));
981
982         CORBBTPROF_BLOB_ENTRY *  pBlobEntry = GetBlobEntry(token);
983         if (pBlobEntry == NULL)
984             return NULL;
985
986         _ASSERTE(pBlobEntry->token == token);
987         _ASSERTE((pBlobEntry->type == ParamTypeSpec) || (pBlobEntry->type == ParamMethodSpec));
988
989         return (CORBBTPROF_BLOB_PARAM_SIG_ENTRY *) pBlobEntry;
990     }
991
992     CORBBTPROF_BLOB_NAMESPACE_DEF_ENTRY *GetBlobExternalNamespaceDef(mdToken token)
993     {
994         _ASSERTE(TypeFromToken(token) == ibcExternalNamespace);
995
996         CORBBTPROF_BLOB_ENTRY *  pBlobEntry = GetBlobEntry(token);
997         if (pBlobEntry == NULL)
998             return NULL;
999
1000         _ASSERTE(pBlobEntry->token == token);
1001         _ASSERTE(pBlobEntry->type == ExternalNamespaceDef);
1002
1003         return (CORBBTPROF_BLOB_NAMESPACE_DEF_ENTRY *) pBlobEntry;
1004     }
1005
1006     CORBBTPROF_BLOB_TYPE_DEF_ENTRY *GetBlobExternalTypeDef(mdToken token)
1007     {
1008         _ASSERTE(TypeFromToken(token) == ibcExternalType);
1009
1010         CORBBTPROF_BLOB_ENTRY *  pBlobEntry = GetBlobEntry(token);
1011         if (pBlobEntry == NULL)
1012             return NULL;
1013
1014         _ASSERTE(pBlobEntry->token == token);
1015         _ASSERTE(pBlobEntry->type == ExternalTypeDef);
1016
1017         return (CORBBTPROF_BLOB_TYPE_DEF_ENTRY *) pBlobEntry;
1018     }
1019
1020     CORBBTPROF_BLOB_SIGNATURE_DEF_ENTRY *GetBlobExternalSignatureDef(mdToken token)
1021     {
1022         _ASSERTE(TypeFromToken(token) == ibcExternalSignature);
1023
1024         CORBBTPROF_BLOB_ENTRY *  pBlobEntry = GetBlobEntry(token);
1025         if (pBlobEntry == NULL)
1026             return NULL;
1027
1028         _ASSERTE(pBlobEntry->token == token);
1029         _ASSERTE(pBlobEntry->type == ExternalSignatureDef);
1030
1031         return (CORBBTPROF_BLOB_SIGNATURE_DEF_ENTRY *) pBlobEntry;
1032     }
1033
1034     CORBBTPROF_BLOB_METHOD_DEF_ENTRY *GetBlobExternalMethodDef(mdToken token)
1035     {
1036         _ASSERTE(TypeFromToken(token) == ibcExternalMethod);
1037
1038         CORBBTPROF_BLOB_ENTRY *  pBlobEntry = GetBlobEntry(token);
1039         if (pBlobEntry == NULL)
1040             return NULL;
1041
1042         _ASSERTE(pBlobEntry->token == token);
1043         _ASSERTE(pBlobEntry->type == ExternalMethodDef);
1044
1045         return (CORBBTPROF_BLOB_METHOD_DEF_ENTRY *) pBlobEntry;
1046     }
1047
1048 private:
1049     ULONG GetProfilingFlagsOfToken(mdToken token)
1050     {
1051         SectionFormat section = (SectionFormat)((TypeFromToken(token) >> 24) + FirstTokenFlagSection);
1052
1053         CORBBTPROF_TOKEN_INFO *profilingData = this->profilingTokenFlagsData[section].data;
1054         DWORD cProfilingData = this->profilingTokenFlagsData[section].count;
1055
1056         if (profilingData != NULL)
1057         {
1058             for (DWORD i = 0; i < cProfilingData; i++)
1059             {
1060                 if (profilingData[i].token == token)
1061                     return profilingData[i].flags;
1062             }
1063         }
1064         return 0;
1065     }
1066
1067     CORBBTPROF_BLOB_ENTRY *GetBlobEntry(idTypeSpec token)
1068     {
1069         CORBBTPROF_BLOB_ENTRY *  pBlobEntry = this->GetBlobStream();
1070         if (pBlobEntry == NULL)
1071             return NULL;
1072
1073         while (pBlobEntry->TypeIsValid())
1074         {
1075             if (pBlobEntry->token == token)
1076             {
1077                 return pBlobEntry;
1078             }
1079             pBlobEntry = pBlobEntry->GetNextEntry();
1080         }
1081
1082         return NULL;
1083     }
1084
1085 private:
1086     struct
1087     {
1088         struct CORBBTPROF_TOKEN_INFO *data;
1089         DWORD   count;
1090     }
1091     profilingTokenFlagsData[SectionFormatCount];
1092
1093     CORBBTPROF_BLOB_ENTRY* blobStream;
1094 };
1095
1096 /*********************************************************************************/
1097 // IL region is used to group frequently used IL method bodies together
1098
1099 enum CorCompileILRegion
1100 {
1101     CORCOMPILE_ILREGION_INLINEABLE,     // Public inlineable methods
1102     CORCOMPILE_ILREGION_WARM,           // Other inlineable methods and methods that failed to NGen
1103     CORCOMPILE_ILREGION_GENERICS,       // Generic methods (may be needed to compile non-NGened instantiations)
1104     CORCOMPILE_ILREGION_COLD,           // Everything else (should be touched in rare scenarios like reflection or profiling only)
1105     CORCOMPILE_ILREGION_COUNT,
1106 };
1107
1108 /*********************************************************************************
1109  * ICorCompilePreloader is used to query preloaded EE data structures
1110  *********************************************************************************/
1111
1112 class ICorCompilePreloader
1113 {
1114  public:
1115     typedef void (__stdcall *CORCOMPILE_CompileStubCallback)(LPVOID pContext, CORINFO_METHOD_HANDLE hStub, CORJIT_FLAGS jitFlags);
1116
1117     //
1118     // Map methods are available after Serialize() is called
1119     // (which will cause it to allocate its data.) Note that returned
1120     // results are RVAs into the image.
1121     //
1122     // If compiling after serializing the preloaded image, these methods can
1123     // be used to avoid making entries in the various info tables.
1124     // Else, use ICorCompileInfo::CanEmbedXXX()
1125     //
1126
1127     virtual DWORD MapMethodEntryPoint(
1128             CORINFO_METHOD_HANDLE handle
1129             ) = 0;
1130
1131     virtual DWORD MapClassHandle(
1132             CORINFO_CLASS_HANDLE handle
1133             ) = 0;
1134
1135     virtual DWORD MapMethodHandle(
1136             CORINFO_METHOD_HANDLE handle
1137             ) = 0;
1138
1139     virtual DWORD MapFieldHandle(
1140             CORINFO_FIELD_HANDLE handle
1141             ) = 0;
1142
1143     virtual DWORD MapAddressOfPInvokeFixup(
1144             CORINFO_METHOD_HANDLE handle
1145             ) = 0;
1146
1147     virtual DWORD MapGenericHandle(
1148             CORINFO_GENERIC_HANDLE handle
1149             ) = 0;
1150
1151     virtual DWORD MapModuleIDHandle(
1152             CORINFO_MODULE_HANDLE handle
1153             )  = 0;
1154
1155     // Load a method for the specified method def
1156     // If the class or method is generic, instantiate all parameters with <object>
1157     virtual CORINFO_METHOD_HANDLE LookupMethodDef(mdMethodDef token) = 0;
1158
1159     // For the given ftnHnd fill in the methInfo structure and return true if successful.
1160     virtual bool GetMethodInfo(mdMethodDef token, CORINFO_METHOD_HANDLE ftnHnd, CORINFO_METHOD_INFO * methInfo) = 0;
1161
1162     // Returns region that the IL should be emitted in
1163     virtual CorCompileILRegion GetILRegion(mdMethodDef token) = 0;
1164
1165     // Find the (parameterized) method for the given blob from the profile data
1166     virtual CORINFO_METHOD_HANDLE FindMethodForProfileEntry(CORBBTPROF_BLOB_PARAM_SIG_ENTRY * profileBlobEntry) = 0;
1167
1168     virtual void ReportInlining(CORINFO_METHOD_HANDLE inliner, CORINFO_METHOD_HANDLE inlinee) = 0;
1169
1170     //
1171     // Call Link when you want all the fixups
1172     // to be applied.  You may call this e.g. after
1173     // compiling all the code for the module.
1174     // Return some stats about the types in the ngen image
1175     //
1176     virtual void Link() = 0;
1177
1178     virtual void FixupRVAs() = 0;
1179
1180     virtual void SetRVAsForFields(IMetaDataEmit * pEmit) = 0;
1181
1182     virtual void GetRVAFieldData(mdFieldDef fd, PVOID * ppData, DWORD * pcbSize, DWORD * pcbAlignment) = 0;
1183
1184     // The preloader also maintains a set of uncompiled generic
1185     // methods or methods in generic classes. A single method can be
1186     // registered or all the methods in a class can be registered.
1187     // The method is added to the set only if it should be compiled
1188     // into this ngen image
1189     //
1190     // The zapper registers methods and classes that are resolved by
1191     // findClass and findMethod during compilation
1192     virtual void AddMethodToTransitiveClosureOfInstantiations(CORINFO_METHOD_HANDLE handle) = 0;
1193     virtual void AddTypeToTransitiveClosureOfInstantiations(CORINFO_CLASS_HANDLE handle) = 0;
1194
1195     // Report reference to the given method from compiled code
1196     virtual void MethodReferencedByCompiledCode(CORINFO_METHOD_HANDLE handle) = 0;
1197
1198     virtual BOOL IsUncompiledMethod(CORINFO_METHOD_HANDLE handle) = 0;
1199
1200     // Return a method handle that was previously registered and
1201     // hasn't been compiled already, and remove it from the set
1202     // of uncompiled methods.
1203     // Return NULL if the set is empty
1204     virtual CORINFO_METHOD_HANDLE NextUncompiledMethod() = 0;
1205
1206     // Prepare a method and its statically determinable call graph if
1207     // a hint attribute has been applied. This is called to save
1208     // additional preparation information into the ngen image that
1209     // wouldn't normally be there (since we can't automatically
1210     // determine it's needed).
1211     virtual void PrePrepareMethodIfNecessary(CORINFO_METHOD_HANDLE hMethod) = 0;
1212
1213     // If a method requires stubs, this will call back passing method
1214     // handles for those stubs.
1215     virtual void GenerateMethodStubs(
1216             CORINFO_METHOD_HANDLE hMethod,
1217             bool                  fNgenProfileImage,
1218             CORCOMPILE_CompileStubCallback pfnCallback,
1219             LPVOID                pCallbackContext) = 0;
1220
1221     // Determines whether or not a method is a dynamic method.  This is used
1222     // to prevent operations that may require metadata knowledge at times other
1223     // than compile time.
1224     virtual bool IsDynamicMethod(CORINFO_METHOD_HANDLE hMethod) = 0;
1225
1226     // Set method profiling flags for layout of EE datastructures
1227     virtual void SetMethodProfilingFlags(CORINFO_METHOD_HANDLE hMethod, DWORD flags) = 0;
1228
1229     // Returns false if precompiled code must ensure that
1230     // the EE's DoPrestub function gets run before the
1231     // code for the method is used, i.e. if it returns false
1232     // then an indirect call must be made.
1233     //
1234     // Returning true does not guaratee that a direct call can be made:
1235     // there can be other reasons why the entry point cannot be embedded.
1236     //
1237     virtual bool CanSkipMethodPreparation (
1238             CORINFO_METHOD_HANDLE   callerHnd,      /* IN  */
1239             CORINFO_METHOD_HANDLE   calleeHnd,      /* IN  */
1240             CorInfoIndirectCallReason *pReason = NULL,
1241             CORINFO_ACCESS_FLAGS    accessFlags = CORINFO_ACCESS_ANY) = 0;
1242
1243     virtual BOOL CanEmbedModuleHandle(
1244             CORINFO_MODULE_HANDLE    moduleHandle) = 0;
1245
1246     // These check if we can hardbind to a handle.  They guarantee either that
1247     // the structure referred to by the handle is in a referenced zapped image
1248     // or will be saved into the module currently being zapped.  That is the
1249     // corresponding GetLoaderModuleForEmeddableXYZ call will return
1250     // either the module currently being zapped or a referenced zapped module.
1251     virtual BOOL CanEmbedClassID(CORINFO_CLASS_HANDLE    typeHandle) = 0;
1252     virtual BOOL CanEmbedModuleID(CORINFO_MODULE_HANDLE    moduleHandle) = 0;
1253     virtual BOOL CanEmbedClassHandle(CORINFO_CLASS_HANDLE    typeHandle) = 0;
1254     virtual BOOL CanEmbedMethodHandle(CORINFO_METHOD_HANDLE    methodHandle, CORINFO_METHOD_HANDLE contextHandle = NULL) = 0;
1255     virtual BOOL CanEmbedFieldHandle(CORINFO_FIELD_HANDLE    fieldHandle) = 0;
1256
1257     // Return true if we can both embed a direct hardbind to the handle _and_
1258     // no "restore" action is needed on the handle.  Equivalent to "CanEmbed + Prerestored".
1259     //
1260     // Typically a handle needs runtime restore it has embedded cross-module references
1261     // or other data that cannot be persisted directly.
1262     virtual BOOL CanPrerestoreEmbedClassHandle(
1263             CORINFO_CLASS_HANDLE classHnd) = 0;
1264
1265     // Return true if a method needs runtime restore
1266     // This is only the case if it is instantiated and any of its type arguments need restoring.
1267     virtual BOOL CanPrerestoreEmbedMethodHandle(
1268             CORINFO_METHOD_HANDLE methodHnd) = 0;
1269
1270     // Can a method entry point be embedded?
1271     virtual BOOL CanEmbedFunctionEntryPoint(
1272             CORINFO_METHOD_HANDLE   methodHandle,
1273             CORINFO_METHOD_HANDLE   contextHandle = NULL,
1274             CORINFO_ACCESS_FLAGS    accessFlags = CORINFO_ACCESS_ANY
1275             ) = 0;
1276
1277     // Prestub is not able to handle method restore in all cases for generics.
1278     // If it is the case the method has to be restored explicitly upfront.
1279     // See the comment inside the implemenation method for more details.
1280     virtual BOOL DoesMethodNeedRestoringBeforePrestubIsRun(
1281             CORINFO_METHOD_HANDLE   methodHandle
1282             ) = 0;
1283
1284     // Returns true if the given activation fixup is not necessary
1285     virtual BOOL CanSkipDependencyActivation(
1286             CORINFO_METHOD_HANDLE   context,
1287             CORINFO_MODULE_HANDLE   moduleFrom,
1288             CORINFO_MODULE_HANDLE   moduleTo) = 0;
1289
1290     virtual CORINFO_MODULE_HANDLE GetPreferredZapModuleForClassHandle(
1291             CORINFO_CLASS_HANDLE classHnd
1292             ) = 0;
1293
1294     virtual void NoteDeduplicatedCode(
1295             CORINFO_METHOD_HANDLE method, 
1296             CORINFO_METHOD_HANDLE duplicateMethod) = 0;
1297
1298 #ifdef FEATURE_READYTORUN_COMPILER
1299     // Returns a compressed encoding of the inline tracking map 
1300     // for this compilation
1301     virtual void GetSerializedInlineTrackingMap(
1302             IN OUT SBuffer    * pSerializedInlineTrackingMap
1303             ) = 0;
1304 #endif
1305
1306     //
1307     // Release frees the preloader
1308     //
1309
1310     virtual ULONG Release() = 0;
1311 };
1312
1313 //
1314 // The DataImage provides several "sections", which can be used
1315 // to sort data into different sets for locality control.  The Arrange
1316 // phase is responsible for placing items into sections.
1317 //
1318
1319 #define CORCOMPILE_SECTIONS() \
1320     CORCOMPILE_SECTION(MODULE) \
1321     CORCOMPILE_SECTION(WRITE) \
1322     CORCOMPILE_SECTION(METHOD_PRECODE_WRITE) \
1323     CORCOMPILE_SECTION(HOT_WRITEABLE) \
1324     CORCOMPILE_SECTION(WRITEABLE) \
1325     CORCOMPILE_SECTION(HOT) \
1326     CORCOMPILE_SECTION(METHOD_PRECODE_HOT) \
1327     CORCOMPILE_SECTION(RVA_STATICS_HOT) \
1328     CORCOMPILE_SECTION(RVA_STATICS_COLD) \
1329     CORCOMPILE_SECTION(WARM) \
1330     CORCOMPILE_SECTION(READONLY_SHARED_HOT) \
1331     CORCOMPILE_SECTION(READONLY_HOT) \
1332     CORCOMPILE_SECTION(READONLY_WARM) \
1333     CORCOMPILE_SECTION(READONLY_COLD) \
1334     CORCOMPILE_SECTION(READONLY_VCHUNKS_AND_DICTIONARY) \
1335     CORCOMPILE_SECTION(CLASS_COLD) \
1336     CORCOMPILE_SECTION(CROSS_DOMAIN_INFO) \
1337     CORCOMPILE_SECTION(METHOD_PRECODE_COLD) \
1338     CORCOMPILE_SECTION(METHOD_PRECODE_COLD_WRITEABLE) \
1339     CORCOMPILE_SECTION(METHOD_DESC_COLD) \
1340     CORCOMPILE_SECTION(METHOD_DESC_COLD_WRITEABLE) \
1341     CORCOMPILE_SECTION(MODULE_COLD) \
1342     CORCOMPILE_SECTION(DEBUG_COLD) \
1343     CORCOMPILE_SECTION(COMPRESSED_MAPS) \
1344
1345 enum CorCompileSection
1346 {
1347 #define CORCOMPILE_SECTION(section) CORCOMPILE_SECTION_##section,
1348     CORCOMPILE_SECTIONS()
1349 #undef CORCOMPILE_SECTION
1350
1351     CORCOMPILE_SECTION_COUNT
1352 };
1353
1354 enum VerboseLevel
1355 {
1356     CORCOMPILE_NO_LOG,
1357     CORCOMPILE_STATS,
1358     CORCOMPILE_VERBOSE
1359 };
1360
1361 class ZapImage;
1362
1363 // When NGEN install /Profile is run, the ZapProfilingHandleImport fixup table contains
1364 // these 5 values per MethodDesc
1365 enum
1366 {
1367     kZapProfilingHandleImportValueIndexFixup        = 0,
1368     kZapProfilingHandleImportValueIndexEnterAddr    = 1,
1369     kZapProfilingHandleImportValueIndexLeaveAddr    = 2,
1370     kZapProfilingHandleImportValueIndexTailcallAddr = 3,
1371     kZapProfilingHandleImportValueIndexClientData   = 4,
1372
1373     kZapProfilingHandleImportValueIndexCount
1374 };
1375
1376 class ICorCompileDataStore
1377 {
1378  public:
1379     // Returns ZapImage
1380     virtual ZapImage * GetZapImage() = 0;
1381
1382     // Report an error during preloading:
1383     // 'token' is the metadata token that triggered the error
1384     // hr is the HRESULT from the thrown Exception, or S_OK if we don't have an thrown exception
1385     // resID is the resourceID with additional information from the thrown Exception, or 0
1386     //
1387     virtual void Error(mdToken token, HRESULT hr, UINT _resID, LPCWSTR description) = 0;
1388 };
1389
1390
1391 class ICorCompilationDomain
1392 {
1393  public:
1394
1395     // Sets the application context for fusion
1396     // to use when binding, using a shell exe file path
1397     virtual HRESULT SetContextInfo(
1398             LPCWSTR                 path,
1399             BOOL                    isExe
1400             ) = 0;
1401
1402     // Retrieves the dependencies of the code which
1403     // has been compiled
1404     virtual HRESULT GetDependencies(
1405             CORCOMPILE_DEPENDENCY   **ppDependencies,
1406             DWORD                   *cDependencies
1407             ) = 0;
1408
1409
1410 #ifdef CROSSGEN_COMPILE
1411     virtual HRESULT SetPlatformWinmdPaths(
1412             LPCWSTR                 pwzPlatformWinmdPaths
1413             ) = 0;
1414 #endif
1415 };
1416
1417 /*********************************************************************************
1418  * ICorCompileInfo is the interface for a compiler
1419  *********************************************************************************/
1420 // Define function pointer ENCODEMODULE_CALLBACK
1421 typedef DWORD (*ENCODEMODULE_CALLBACK)(LPVOID pModuleContext, CORINFO_MODULE_HANDLE moduleHandle);
1422
1423 // Define function pointer DEFINETOKEN_CALLBACK
1424 typedef void (*DEFINETOKEN_CALLBACK)(LPVOID pModuleContext, CORINFO_MODULE_HANDLE moduleHandle, DWORD index, mdTypeRef* token);
1425
1426 typedef HRESULT (*CROSS_DOMAIN_CALLBACK)(LPVOID pArgs);
1427
1428 class ICorCompileInfo
1429 {
1430   public:
1431
1432
1433     //
1434     // Currently no other instance of the EE may be running inside
1435     // a process that is used as an NGEN compilation process.
1436     //
1437     // So, the host must call StartupAsCompilationProcess before compiling
1438     // any code, and Shutdown after finishing.
1439     //
1440     // The arguments control which native image of mscorlib to use.
1441     // This matters for hardbinding.
1442     //
1443
1444     virtual HRESULT Startup(
1445             BOOL fForceDebug,
1446             BOOL fForceProfiling,
1447             BOOL fForceInstrument) = 0;
1448
1449     // Creates a new compilation domain
1450     // The BOOL arguments control what kind of a native image is
1451     // to be generated. Other factors affect what kind of a native image
1452     // will actually be generated. GetAssemblyVersionInfo() ultimately reflects
1453     // the kind of native image that will be generated
1454     //
1455     // pEmitter - sets this as the emitter to use when generating tokens for
1456     // the dependency list.  If this is NULL, dependencies won't be computed.
1457
1458     virtual HRESULT CreateDomain(
1459             ICorCompilationDomain **ppDomain, // [OUT]
1460             IMetaDataAssemblyEmit   *pEmitter,
1461             BOOL fForceDebug,
1462             BOOL fForceProfiling,
1463             BOOL fForceInstrument
1464             ) = 0;
1465
1466     // calls pfnCallback in the specified domain
1467     virtual HRESULT MakeCrossDomainCallback(
1468             ICorCompilationDomain*  pDomain,
1469             CROSS_DOMAIN_CALLBACK   pfnCallback,
1470             LPVOID                  pArgs
1471             ) = 0;
1472
1473     // Destroys a compilation domain
1474     virtual HRESULT DestroyDomain(
1475             ICorCompilationDomain *pDomain
1476             ) = 0;
1477
1478     // Loads an assembly manifest module into the EE
1479     // and returns a handle to it.
1480     virtual HRESULT LoadAssemblyByPath(
1481             LPCWSTR                  wzPath,
1482             BOOL                     fExplicitBindToNativeImage,
1483             CORINFO_ASSEMBLY_HANDLE *pHandle
1484             ) = 0;
1485
1486
1487 #ifdef FEATURE_COMINTEROP
1488     // Loads a WinRT typeref into the EE and returns
1489     // a handle to it.  We have to load all typerefs
1490     // during dependency computation since assemblyrefs 
1491     // are meaningless to WinRT.
1492     virtual HRESULT LoadTypeRefWinRT(
1493             IMDInternalImport       *pAssemblyImport,
1494             mdTypeRef               ref,
1495             CORINFO_ASSEMBLY_HANDLE *pHandle
1496             ) = 0;
1497 #endif
1498
1499     virtual BOOL IsInCurrentVersionBubble(CORINFO_MODULE_HANDLE hModule) = 0;
1500
1501     // Loads a module from an assembly into the EE
1502     // and returns a handle to it.
1503     virtual HRESULT LoadAssemblyModule(
1504             CORINFO_ASSEMBLY_HANDLE assembly,
1505             mdFile                  file,
1506             CORINFO_MODULE_HANDLE   *pHandle
1507             ) = 0;
1508
1509
1510     // Checks to see if an up to date zap exists for the
1511     // assembly
1512     virtual BOOL CheckAssemblyZap(
1513         CORINFO_ASSEMBLY_HANDLE assembly,
1514       __out_ecount_opt(*cAssemblyManifestModulePath)
1515         LPWSTR                  assemblyManifestModulePath,
1516         LPDWORD                 cAssemblyManifestModulePath
1517         ) = 0;
1518
1519     // Sets up the compilation target in the EE
1520     virtual HRESULT SetCompilationTarget(
1521             CORINFO_ASSEMBLY_HANDLE     assembly,
1522             CORINFO_MODULE_HANDLE       module
1523             ) = 0;
1524
1525
1526     // Returns the dependency load setting for an assembly ref
1527     virtual HRESULT GetLoadHint(
1528             CORINFO_ASSEMBLY_HANDLE hAssembly,
1529             CORINFO_ASSEMBLY_HANDLE hAssemblyDependency,
1530             LoadHintEnum *loadHint,
1531             LoadHintEnum *defaultLoadHint = NULL
1532             ) = 0;
1533
1534     // Returns information on how the assembly has been loaded
1535     virtual HRESULT GetAssemblyVersionInfo(
1536             CORINFO_ASSEMBLY_HANDLE hAssembly,
1537             CORCOMPILE_VERSION_INFO *pInfo
1538             ) = 0;
1539
1540     // Returns the manifest metadata for an assembly
1541     // Use the internal IMDInternalImport for performance.
1542     // Creation of the public IMetaDataImport * triggers
1543     // conversion to R/W metadata that slows down all subsequent accesses.
1544     virtual IMDInternalImport * GetAssemblyMetaDataImport(
1545             CORINFO_ASSEMBLY_HANDLE assembly
1546             ) = 0;
1547
1548     // Returns an interface to query the metadata for a loaded module
1549     // Use the internal IMDInternalImport for performance.
1550     // Creation of the public IMetaDataAssemblyImport * triggers
1551     // conversion to R/W metadata that slows down all subsequent accesses.
1552     virtual IMDInternalImport * GetModuleMetaDataImport(
1553             CORINFO_MODULE_HANDLE   module
1554             ) = 0;
1555
1556     // Returns the module of the assembly which contains the manifest,
1557     // or NULL if the manifest is standalone.
1558     virtual CORINFO_MODULE_HANDLE GetAssemblyModule(
1559             CORINFO_ASSEMBLY_HANDLE assembly
1560             ) = 0;
1561
1562     // Returns the assembly of a loaded module
1563     virtual CORINFO_ASSEMBLY_HANDLE GetModuleAssembly(
1564             CORINFO_MODULE_HANDLE   module
1565             ) = 0;
1566
1567     // Returns the current PEDecoder of a loaded module.
1568     virtual PEDecoder * GetModuleDecoder(
1569             CORINFO_MODULE_HANDLE   module
1570             ) = 0;
1571
1572     // Gets the full file name, including path, of a loaded module
1573     virtual void GetModuleFileName(
1574         CORINFO_MODULE_HANDLE module,
1575         SString               &result
1576         ) = 0;
1577
1578     // Get a class def token
1579     virtual HRESULT GetTypeDef(
1580             CORINFO_CLASS_HANDLE    classHandle,
1581             mdTypeDef              *token
1582             ) = 0;
1583
1584     // Get a method def token
1585     virtual HRESULT GetMethodDef(
1586             CORINFO_METHOD_HANDLE   methodHandle,
1587             mdMethodDef            *token
1588             ) = 0;
1589
1590     // Get a field def token
1591     virtual HRESULT GetFieldDef(
1592             CORINFO_FIELD_HANDLE    fieldHandle,
1593             mdFieldDef             *token
1594             ) = 0;
1595
1596     // Get the loader module for mscorlib
1597     virtual CORINFO_MODULE_HANDLE GetLoaderModuleForMscorlib() = 0;
1598
1599     // Get the loader module for a type (where the type is regarded as
1600     // living for the purposes of loading, unloading, and ngen).
1601     //
1602     // classHandle must have passed CanEmbedClassHandle, since the zapper
1603     // should only care about the module where a type
1604     // prefers to be saved if it knows that that module is either
1605     // an zapped module or is the module currently being compiled.
1606     // See vm\ceeload.h for more information
1607     virtual CORINFO_MODULE_HANDLE GetLoaderModuleForEmbeddableType(
1608             CORINFO_CLASS_HANDLE   classHandle
1609             ) = 0;
1610
1611     // Get the loader module for a method (where the method is regarded as
1612     // living for the purposes of loading, unloading, and ngen)
1613     //
1614     // methodHandle must have passed CanEmbedMethodHandle, since the zapper
1615     // should only care about the module where a type
1616     // prefers to be saved if it knows that that module is either
1617     // an zapped module or is the module currently being compiled.
1618     // See vm\ceeload.h for more information
1619     virtual CORINFO_MODULE_HANDLE GetLoaderModuleForEmbeddableMethod(
1620             CORINFO_METHOD_HANDLE   methodHandle
1621             ) = 0;
1622
1623     // Get the loader module for a method (where the method is regarded as
1624     // living for the purposes of loading, unloading, and ngen)
1625     // See vm\ceeload.h for more information
1626     virtual CORINFO_MODULE_HANDLE GetLoaderModuleForEmbeddableField(
1627             CORINFO_FIELD_HANDLE   fieldHandle
1628             ) = 0;
1629
1630     // Set the list of assemblies we can hard bind to
1631     virtual void SetAssemblyHardBindList(
1632       __in_ecount(cHardBindList)
1633         LPWSTR * pHardBindList,
1634         DWORD    cHardBindList
1635         ) = 0;
1636
1637     // Encode a module for the imports table
1638     virtual void EncodeModuleAsIndexes(
1639             CORINFO_MODULE_HANDLE fromHandle,
1640             CORINFO_MODULE_HANDLE handle,
1641             DWORD *pAssemblyIndex,
1642             DWORD *pModuleIndex,
1643             IMetaDataAssemblyEmit *pAssemblyEmit) = 0;
1644
1645
1646     // Encode a class into the given SigBuilder.
1647     virtual void EncodeClass(
1648             CORINFO_MODULE_HANDLE referencingModule,
1649             CORINFO_CLASS_HANDLE classHandle,
1650             SigBuilder * pSigBuilder,
1651             LPVOID encodeContext,
1652             ENCODEMODULE_CALLBACK pfnEncodeModule) = 0;
1653
1654     // Encode a method into the given SigBuilder.
1655     virtual void EncodeMethod(
1656             CORINFO_MODULE_HANDLE referencingModule,
1657             CORINFO_METHOD_HANDLE handle,
1658             SigBuilder * pSigBuilder,
1659             LPVOID encodeContext,
1660             ENCODEMODULE_CALLBACK pfnEncodeModule,
1661             CORINFO_RESOLVED_TOKEN * pResolvedToken = NULL,
1662             CORINFO_RESOLVED_TOKEN * pConstrainedResolvedToken = NULL,
1663             BOOL fEncodeUsingResolvedTokenSpecStreams = FALSE) = 0;
1664
1665     // Returns non-null methoddef or memberref token if it is sufficient to encode the method (no generic instantiations, etc.)
1666     virtual mdToken TryEncodeMethodAsToken(
1667             CORINFO_METHOD_HANDLE handle, 
1668             CORINFO_RESOLVED_TOKEN * pResolvedToken,
1669             CORINFO_MODULE_HANDLE * referencingModule) = 0;
1670
1671     // Returns method slot (for encoding virtual stub dispatch)
1672     virtual DWORD TryEncodeMethodSlot(
1673             CORINFO_METHOD_HANDLE handle) = 0;
1674
1675     // Encode a field into the given SigBuilder.
1676     virtual void EncodeField(
1677             CORINFO_MODULE_HANDLE referencingModule,
1678             CORINFO_FIELD_HANDLE handle,
1679             SigBuilder * pSigBuilder,
1680             LPVOID encodeContext,
1681             ENCODEMODULE_CALLBACK pfnEncodeModule,
1682             CORINFO_RESOLVED_TOKEN * pResolvedToken = NULL,
1683             BOOL fEncodeUsingResolvedTokenSpecStreams = FALSE) = 0;
1684
1685
1686     // Encode generic dictionary signature
1687     virtual void EncodeGenericSignature(
1688             LPVOID signature,
1689             BOOL fMethod,
1690             SigBuilder * pSigBuilder,
1691             LPVOID encodeContext,
1692             ENCODEMODULE_CALLBACK pfnEncodeModule) = 0;
1693
1694
1695     virtual BOOL IsEmptyString(
1696             mdString token,
1697             CORINFO_MODULE_HANDLE module) = 0;
1698
1699
1700     // Preload a modules' EE data structures
1701     // directly into an executable image
1702
1703     virtual ICorCompilePreloader * PreloadModule(
1704             CORINFO_MODULE_HANDLE   moduleHandle,
1705             ICorCompileDataStore    *pData,
1706             CorProfileData          *profileData
1707             ) = 0;
1708
1709     // Gets the codebase URL for the assembly
1710     virtual void GetAssemblyCodeBase(
1711             CORINFO_ASSEMBLY_HANDLE hAssembly,
1712             SString                 &result) = 0;
1713
1714     // Returns the GC-information for a method. This is the simple representation
1715     // and can be used when a code that can trigger a GC does not have access
1716     // to the CORINFO_METHOD_HANDLE (which is normally used to access the GC information)
1717     //
1718     // Returns S_FALSE if there is no simple representation for the method's GC info
1719     //
1720     virtual void GetCallRefMap(
1721             CORINFO_METHOD_HANDLE hMethod,
1722             GCRefMapBuilder * pBuilder) = 0;
1723
1724     // Returns a compressed block of debug information
1725     //
1726     // Uncompressed debug maps are passed in.
1727     // Writes to outgoing SBuffer.
1728     // Throws on failure.
1729     virtual void CompressDebugInfo(
1730             IN ICorDebugInfo::OffsetMapping  * pOffsetMapping,
1731             IN ULONG            iOffsetMapping,
1732             IN ICorDebugInfo::NativeVarInfo  * pNativeVarInfo,
1733             IN ULONG            iNativeVarInfo,
1734             IN OUT SBuffer    * pDebugInfoBuffer
1735             ) = 0;
1736
1737
1738
1739     // Allows to set verbose level for log messages, enabled in retail build too for stats
1740     virtual HRESULT SetVerboseLevel(
1741             IN  VerboseLevel            level) = 0;
1742
1743     // Get the compilation flags that are shared between JIT and NGen
1744     virtual HRESULT GetBaseJitFlags(
1745             IN  CORINFO_METHOD_HANDLE   hMethod,
1746             OUT CORJIT_FLAGS           *pFlags) = 0;
1747
1748     // needed for stubs to obtain the number of bytes to copy into the native image
1749     // return the beginning of the stub and the size to copy (in bytes)
1750     virtual void* GetStubSize(void *pStubAddress, DWORD *pSizeToCopy) = 0;
1751
1752     // Takes a stub and blits it into the buffer, resetting the reference count
1753     // to 1 on the clone. The buffer has to be large enough to hold the stub object and the code
1754     virtual HRESULT GetStubClone(void *pStub, BYTE *pBuffer, DWORD dwBufferSize) = 0;
1755
1756     // true if the method has [NativeCallableAttribute]
1757     virtual BOOL IsNativeCallableMethod(CORINFO_METHOD_HANDLE handle) = 0;
1758
1759     virtual BOOL GetIsGeneratingNgenPDB() = 0;
1760     virtual void SetIsGeneratingNgenPDB(BOOL fGeneratingNgenPDB) = 0;
1761
1762 #ifdef FEATURE_READYTORUN_COMPILER
1763     virtual CORCOMPILE_FIXUP_BLOB_KIND GetFieldBaseOffset(
1764             CORINFO_CLASS_HANDLE classHnd, 
1765             DWORD * pBaseOffset
1766             ) = 0;
1767
1768     virtual BOOL NeedsTypeLayoutCheck(CORINFO_CLASS_HANDLE classHnd) = 0;
1769     virtual void EncodeTypeLayout(CORINFO_CLASS_HANDLE classHandle, SigBuilder * pSigBuilder) = 0;
1770
1771     virtual BOOL AreAllClassesFullyLoaded(CORINFO_MODULE_HANDLE moduleHandle) = 0;
1772
1773     virtual int GetVersionResilientTypeHashCode(CORINFO_MODULE_HANDLE moduleHandle, mdToken token) = 0;
1774
1775     virtual int GetVersionResilientMethodHashCode(CORINFO_METHOD_HANDLE methodHandle) = 0;
1776 #endif
1777
1778     virtual BOOL HasCustomAttribute(CORINFO_METHOD_HANDLE method, LPCSTR customAttributeName) = 0;
1779 };
1780
1781 /*****************************************************************************/
1782 // This function determines the compile flags to use for a generic intatiation
1783 // since only the open instantiation can be verified.
1784 // See the comment associated with CORJIT_FLAG_SKIP_VERIFICATION for details.
1785 //
1786 // On return:
1787 // if *raiseVerificationException=TRUE, the caller should raise a VerificationException.
1788 // if *unverifiableGenericCode=TRUE, the method is a generic instantiation with
1789 // unverifiable code
1790
1791 CORJIT_FLAGS GetCompileFlagsIfGenericInstantiation(
1792         CORINFO_METHOD_HANDLE method,
1793         CORJIT_FLAGS compileFlags,
1794         ICorJitInfo * pCorJitInfo,
1795         BOOL * raiseVerificationException,
1796         BOOL * unverifiableGenericCode);
1797
1798 // Returns the global instance of JIT->EE interface for NGen
1799
1800 extern "C" ICorDynamicInfo * __stdcall GetZapJitInfo();
1801
1802 // Returns the global instance of Zapper->EE interface
1803
1804 extern "C" ICorCompileInfo * __stdcall GetCompileInfo();
1805
1806 // Stress mode to leave some methods/types uncompiled in the ngen image.
1807 // Those methods will be JIT-compiled at runtime as needed.
1808
1809 extern "C" unsigned __stdcall PartialNGenStressPercentage();
1810
1811 // create a PDB dumping all functions in hAssembly into pdbPath
1812 extern "C" HRESULT __stdcall CreatePdb(CORINFO_ASSEMBLY_HANDLE hAssembly, BSTR pNativeImagePath, BSTR pPdbPath, BOOL pdbLines, BSTR pManagedPdbSearchPath, LPCWSTR pDiasymreaderPath);
1813
1814 extern bool g_fNGenMissingDependenciesOk;
1815
1816 extern bool g_fNGenWinMDResilient;
1817
1818 #ifdef FEATURE_READYTORUN_COMPILER
1819 extern bool g_fReadyToRunCompilation;
1820 #endif
1821
1822 inline bool IsReadyToRunCompilation()
1823 {
1824 #ifdef FEATURE_READYTORUN_COMPILER
1825     return g_fReadyToRunCompilation;
1826 #else
1827     return false;
1828 #endif
1829 }
1830
1831 #endif /* COR_COMPILE_H_ */