Microsoft MVP성태의 닷넷 이야기
.NET Framework: 763. .NET Core 2.1 - Tiered Compilation 도입 [링크 복사], [링크+제목 복사]
조회: 11688
글쓴 사람
정성태 (techsharer at outlook.com)
홈페이지
첨부 파일
(연관된 글이 4개 있습니다.)

.NET Core 2.1 - Tiered Compilation 도입

아래의 글에 tiered compilation에 대한 소개가 있습니다.

Announcing .NET Core 2.1
; https://devblogs.microsoft.com/dotnet/announcing-net-core-2-1/

"Adaptive optimization"이라고도 알려진 이것의 개념은 간단합니다. 이 옵션이 켜져 있으면 해당 응용 프로그램은 JIT 컴파일 시에 최적화보다는 빠른 속도를 위주로 기계어 번역을 하게 됩니다. 이 단계를 "first tier"라고 합니다. 그러다, 자주 실행되는 메서드가 있으면 그에 대해 감지하고 다시 최적화된 코드로 JIT 컴파일을 하는 식인데 이를 "second tier"라고 합니다.

과거 자바 런타임이 했던 방식과 유사한 면이 있습니다. 자바의 경우 최초 실행 시에 JIT하지 않고 바이트 언어를 그냥 인터프리팅 식으로 그때그때 해석해서 실행하는데, 자주 실행되는 함수라고 판단이 되면 그제서야 JIT를 해 기계어로 번역하는 식입니다.

"tiered compilation" 적용 방법은 프로젝트 파일에 TieredCompilation 옵션을 true로 설정하거나,

<Project Sdk="Microsoft.NET.Sdk">

  <PropertyGroup>
    <OutputType>Exe</OutputType>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <Description>A simple .NET Core global tool called "dotnetsay".</Description>
    ...[생략]...
    <TieredCompilation>true</TieredCompilation>
  </PropertyGroup>

  <ItemGroup Condition="'$(ContinuousIntegrationBuild)'=='true'">
    <PackageReference Include="Microsoft.SourceLink.GitHub" Version="1.0.0-beta-62925-02" PrivateAssets="All"/>
  </ItemGroup>

</Project>

.NET Core 2.1 이상의 응용 프로그램을 실행 시 환경 변수에 COMPlus_TieredCompilation을 "1"로 설정하면 됩니다.

SET COMPlus_TieredCompilation="1"

(2023-11-20 업데이트: .NET Core 3.0+부터는 TieredCompilation 옵션의 기본값이 enabled로 바뀌었습니다.)




혹시 눈으로 직접 확인해 볼 수 있을까요? ^^

그래서 예제 코드를 하나 준비해봤습니다.

using System;
using System.Reflection;
using System.Threading;

namespace ConsoleApp1
{
    // 빌드: .NET Core x64 + Release
    class Program
    {
        static void Main(string[] args)
        {
            Thread t = new Thread(CheckMethodJitAddress);
            t.IsBackground = true;

            Program pg = new Program();

            {
                pg.ManyCalls();
                CheckMethodJitAddress(false);
            }

            Console.ReadLine(); // first-tier 확인을 위해!
            t.Start(true);

            Thread.Sleep(1000);

            while (true)
            {
                pg.ManyCalls(); // 아마 이 루프의 어디선가 second-tier로 진행할 듯!
                Thread.Sleep(1000);
            }
        }

        public long ManyCalls()
        {
            long sum = 0;

            for (int i = 0; i < (Environment.TickCount % 10_000); i ++)
            {
                sum += i;
            }

            return sum;
        }

        private static void CheckMethodJitAddress(object obj)
        {
            do
            {
                MethodInfo mi = typeof(Program).GetMethod("ManyCalls");
                RuntimeMethodHandle rmh = mi.MethodHandle;

                Console.WriteLine(rmh.GetFunctionPointer().ToString("x"));
                Thread.Sleep(1000);
            } while ((bool)obj == true);
        }
    }
}

위의 코드를 실행하면, ManyCalls라는 메서드를 1초에 한 번씩 계속 실행하는데 다른 스레드에서는 그것의 FunctionPointer를 구해,

상황별 GetFunctionPointer 반환값 정리
; https://www.sysnet.pe.kr/2/0/1027

출력합니다. JIT가 2번째가 되면 FunctionPointer의 주소가 바뀔 거라고 생각한 건데요, 의외로 계속 바뀌지 않고 그냥 고정된 값을 출력합니다. 음... ^^ 딴 방법을 이용해야 할 것 같습니다.

이를 위해 windbg를 이용해 봤는데요, sos 확장을 로드하고,

0:009> .loadby sos coreclr

ManyCalls의 JIT 이후의 기계어 코드 위치를 다음과 같이 확인할 수 있습니다.

0:009> !name2ee ConsoleApp1!ConsoleApp1.Program
Module:      00007ff7b2024578
Assembly:    ConsoleApp1.dll
Token:       0000000002000002
MethodTable: 00007ff7b2025560
EEClass:     00007ff7b21c1088
Name:        ConsoleApp1.Program

0:009> !dumpmt -md  00007ff7b2025560
EEClass:         00007ff7b21c1088
Module:          00007ff7b2024578
Name:            ConsoleApp1.Program
mdToken:         0000000002000002
File:            E:\ConsoleApp1\bin\Release\netcoreapp2.1\ConsoleApp1.dll
BaseSize:        0x18
ComponentSize:   0x0
Slots in VTable: 8
Number of IFaces in IFaceMap: 0
--------------------------------------
MethodDesc Table
           Entry       MethodDesc    JIT Name
00007ff807aa2020 00007ff807600988 PreJIT System.Object.ToString()
00007ff807aa2040 00007ff807600990 PreJIT System.Object.Equals(System.Object)
00007ff807aa2090 00007ff8076009b8 PreJIT System.Object.GetHashCode()
00007ff807aa20a0 00007ff8076009d8 PreJIT System.Object.Finalize()
00007ff7b21410b0 00007ff7b2025550    JIT ConsoleApp1.Program..ctor()
00007ff7b2141098 00007ff7b2025508    JIT ConsoleApp1.Program.Main(System.String[])
00007ff7b21410a0 00007ff7b2025520    JIT ConsoleApp1.Program.ManyCalls()
00007ff7b21410a8 00007ff7b2025538    JIT ConsoleApp1.Program.CheckMethodJitAddress(System.Object)

00007ff7b21410a0 값은 실제로 GetFunctionPointer가 반환한 값과 일치합니다. ManyCalls 메서드에 대해 좀 더 살펴보면,

0:009> !DumpMD /d 00007ff7b2025520
Method Name:          ConsoleApp1.Program.ManyCalls()
Class:                00007ff7b21c1088
MethodTable:          00007ff7b2025560
mdToken:              0000000006000002
Module:               00007ff7b2024578
IsJitted:             yes
Current CodeAddr:     00007ff7b2142010
Code Version History:
  CodeAddr:           00007ff7b2142010  (Tier 0)
  NativeCodeVersion:  0000000000000000

최초 한 번 실행된 상태이기 때문에 "Tier 0" 단계임을 알 수 있습니다. 그리고 응용 프로그램을 계속 실행해 ManyCalls를 어느 정도 실행한 시점에 다시 windbg로 멈추고 덤프를 해보면,

0:010> !DumpMD /d 00007ff7b2025520
Method Name:          ConsoleApp1.Program.ManyCalls()
Class:                00007ff7b21c1088
MethodTable:          00007ff7b2025560
mdToken:              0000000006000002
Module:               00007ff7b2024578
IsJitted:             yes
Current CodeAddr:     00007ff7b21439e0
Code Version History:
  CodeAddr:           00007ff7b21439e0  (Tier 1)
  NativeCodeVersion:  000001e92a9693c0
  CodeAddr:           00007ff7b2142010  (Tier 0)
  NativeCodeVersion:  0000000000000000

보는 바와 같이 JIT CodeAddr 위치가 바뀌었고 Tier 1이라고 보여줍니다. 즉, 실제로 JIT가 대상 메서드에 대해 2번 발생한 것입니다.




그런데 GetFunctionPointer 반환값은 무엇일까요? Tier 1 단계에서 해당 위치를 역어셈블 해보면,

0:010> u 00007ff7b21410a0
00007ff7`b21410a0 e93b290000      jmp     00007ff7`b21439e0
...[생략]...

보는 바와 같이 jmp 문의 위치가 바로 GetFunctionPointer의 값입니다. jmp 문의 기계어를 보면 e93b290000인데, 5바이트 중 첫 번째 e9이 jmp이고 이후의 4바이트가 점프할 상대 변위(offset) 값입니다.

jmp     == e9
offset  == 3b290000

실제로 GetFunctionPointer가 반환한 00007ff7b21410a0 주소와 "!dumpmd"로 확인한 "Current CodeAddr"의 00007ff7b21439e0 주소의 차이를 보면,

0:010> ? 00007ff7`b21439e0 - 00007ff7`b21410a0
Evaluate expression: 10560 = 00000000`00002940

0:010> ? 00007ff7`b21439e0 - 00007ff7`b21410a0 - 5
Evaluate expression: 10555 = 00000000`0000293b

0000293b 값이 나옵니다. little endian 저장임을 감안하면 e93b290000 기계어 코드와 정확히 일치합니다.




windbg를 통해 알게 된 지식으로 이제 C#에서의 확인 코드를 다음과 같이 작성할 수 있습니다.

private static void CheckMethodJitAddress(object obj)
{
    do
    {
        MethodInfo mi = typeof(Program).GetMethod("ManyCalls");
        RuntimeMethodHandle rmh = mi.MethodHandle;

        IntPtr ptr = rmh.GetFunctionPointer();

        byte jmpCode = Marshal.ReadByte(ptr);    // jmp 문
        int offset = Marshal.ReadInt32(ptr + 1); // offset 값

        Console.WriteLine(jmpCode.ToString("x") + ": " + offset.ToString("x8"));

        Thread.Sleep(1000);
    } while ((bool)obj == true);
}

이렇게 바꾸고 실행하면 다음과 같은 출력 결과를 볼 수 있습니다.

called: 1
e9: 0000108b
e8: 0000041b
called: 2
e8: 0000041b
e8: 0000041b
...[생략]...
called: 28
e8: 0000041b
called: 29
e8: 0000041b
called: 30
e9: 0000392b
called: 31

보면 다음과 같은 공통점이 나옵니다.

1번째 호출: e9 0000108b
2번째 ~ 29번째 호출: e8 0000041b
30번째 호출: e9 0000392b

실제로 저 단계별로 windbg에서 점프 위치에 대한 값을 확인해 보면,

[1번째 호출]
0:010> u 00007ff7`ad9710a0
00007ff7`ad9710a0 e98b100000      jmp     00007ff7`ad972130
...[생략]...


[2번째 ~ 29번째 호출]
0:010> u 00007ff7`ad9710a0
00007ff7`ad9710a0 e8fbd4ab5f      call    coreclr!PrecodeFixupThunk (00007ff8`0d42e5a0)
...[생략]...


[30번째 호출]
0:010> u 00007ff7`ad9710a0
00007ff7`ad9710a0 e96b340000      jmp     00007ff7`ad974510
...[생략]...

위의 결과를 바탕으로 대략 결론이 유추됩니다. 처음 메서드 호출 시 Tier-0 JIT를 빠르게 한 다음 그 이후의 호출에서는 최적화 JIT을 하기보다는 최적화를 할 조건을 갖출 때까지의 판단 코드가 있는 PrecodeFixupThunk를 경유해서 호출이 되다가 30번째 호출이 되었을 때 비로소 Tier-1 JIT를 하게 되는 것입니다.

(첨부 파일은 이 글의 예제 코드를 포함합니다.)




(2024-04-04: 업데이트)

pgo_tier_instrument_1.png




[이 글에 대해서 여러분들과 의견을 공유하고 싶습니다. 틀리거나 미흡한 부분 또는 의문 사항이 있으시면 언제든 댓글 남겨주십시오.]

[연관 글]






[최초 등록일: ]
[최종 수정일: 4/4/2024]

Creative Commons License
이 저작물은 크리에이티브 커먼즈 코리아 저작자표시-비영리-변경금지 2.0 대한민국 라이센스에 따라 이용하실 수 있습니다.
by SeongTae Jeong, mailto:techsharer at outlook.com

비밀번호

댓글 작성자
 




... 16  17  [18]  19  20  21  22  23  24  25  26  27  28  29  30  ...
NoWriterDateCnt.TitleFile(s)
13170정성태11/24/20224980Windows: 213. 윈도우 - 싱글 스레드는 컨텍스트 스위칭이 없을까요?
13169정성태11/23/20225603Windows: 212. 윈도우의 Protected Process (Light) 보안 [1]파일 다운로드2
13168정성태11/22/20224874제니퍼 .NET: 31. 제니퍼 닷넷 적용 사례 (9) - DB 서비스에 부하가 걸렸다?!
13167정성태11/21/20224908.NET Framework: 2070. .NET 7 - Console.ReadKey와 리눅스의 터미널 타입
13166정성태11/20/20224634개발 환경 구성: 651. Windows 사용자 경험으로 WSL 환경에 dotnet 런타임/SDK 설치 방법
13165정성태11/18/20224541개발 환경 구성: 650. Azure - "scm" 프로세스와 엮인 서비스 모음
13164정성태11/18/20225459개발 환경 구성: 649. Azure - 비주얼 스튜디오를 이용한 AppService 원격 디버그 방법
13163정성태11/17/20225381개발 환경 구성: 648. 비주얼 스튜디오에서 안드로이드 기기 인식하는 방법
13162정성태11/15/20226459.NET Framework: 2069. .NET 7 - AOT(ahead-of-time) 컴파일
13161정성태11/14/20225700.NET Framework: 2068. C# - PublishSingleFile로 배포한 이미지의 역어셈블 가능 여부 (난독화 필요성) [4]
13160정성태11/11/20225627.NET Framework: 2067. C# - PublishSingleFile 적용 시 native/managed 모듈 통합 옵션
13159정성태11/10/20228799.NET Framework: 2066. C# - PublishSingleFile과 관련된 옵션 [3]
13158정성태11/9/20225111오류 유형: 826. Workload definition 'wasm-tools' in manifest 'microsoft.net.workload.mono.toolchain' [...] conflicts with manifest 'microsoft.net.workload.mono.toolchain.net7'
13157정성태11/8/20225761.NET Framework: 2065. C# - Mutex의 비동기 버전파일 다운로드1
13156정성태11/7/20226668.NET Framework: 2064. C# - Mutex와 Semaphore/SemaphoreSlim 차이점파일 다운로드1
13155정성태11/4/20226187디버깅 기술: 183. TCP 동시 접속 (연결이 아닌) 시도를 1개로 제한한 서버
13154정성태11/3/20225654.NET Framework: 2063. .NET 5+부터 지원되는 GC.GetGCMemoryInfo파일 다운로드1
13153정성태11/2/20226928.NET Framework: 2062. C# - 코드로 재현하는 소켓 상태(SYN_SENT, SYN_RECV)
13152정성태11/1/20225558.NET Framework: 2061. ASP.NET Core - DI로 추가한 클래스의 초기화 방법 [1]
13151정성태10/31/20225675C/C++: 161. Windows 11 환경에서 raw socket 테스트하는 방법파일 다운로드1
13150정성태10/30/20225711C/C++: 160. Visual Studio 2022로 빌드한 C++ 프로그램을 위한 다른 PC에서 실행하는 방법
13149정성태10/27/20225639오류 유형: 825. C# - CLR ETW 이벤트 수신이 GCHeapStats_V1/V2에 대해 안 되는 문제파일 다운로드1
13148정성태10/26/20225632오류 유형: 824. msbuild 에러 - error NETSDK1005: Assets file '...\project.assets.json' doesn't have a target for 'net5.0'. Ensure that restore has run and that you have included 'net5.0' in the TargetFramew
13147정성태10/25/20224759오류 유형: 823. Visual Studio 2022 - Unable to attach to CoreCLR. The debugger's protocol is incompatible with the debuggee.
13146정성태10/24/20225586.NET Framework: 2060. C# - Java의 Xmx와 유사한 힙 메모리 최댓값 제어 옵션 HeapHardLimit
13145정성태10/21/20225846오류 유형: 822. db2 - Password validation for user db2inst1 failed with rc = -2146500508
... 16  17  [18]  19  20  21  22  23  24  25  26  27  28  29  30  ...