<div dir="ltr"><div>Justin, Thanks for the review and comments!</div>I'll fix the suggested formatting in the coming patch.<div>Some replies are inlined.<br><div class="gmail_extra"><br><div class="gmail_quote">On Tue, Dec 1, 2015 at 2:38 PM, Justin Bogner <span dir="ltr"><<a href="mailto:mail@justinbogner.com" target="_blank">mail@justinbogner.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex"><span class="">Rong Xu <<a href="mailto:xur@google.com">xur@google.com</a>> writes:<br>
> xur updated this revision to Diff 41428.<br>
> xur marked 2 inline comments as done.<br>
> xur added a comment.<br>
><br>
> Integrated Sean's most recently review comments.<br>
<br>
</span>This is looking pretty reasonable. Some style nitpicks and minor<br>
comments below.<br>
<div><div class="h5"><br>
><br>
> <a href="http://reviews.llvm.org/D12781" rel="noreferrer" target="_blank">http://reviews.llvm.org/D12781</a><br>
><br>
> Files:<br>
>   include/llvm/IR/DiagnosticInfo.h<br>
>   include/llvm/InitializePasses.h<br>
>   include/llvm/LinkAllPasses.h<br>
>   include/llvm/Transforms/Instrumentation.h<br>
>   lib/IR/DiagnosticInfo.cpp<br>
>   lib/Transforms/Instrumentation/CFGMST.h<br>
>   lib/Transforms/Instrumentation/CMakeLists.txt<br>
>   lib/Transforms/Instrumentation/Instrumentation.cpp<br>
>   lib/Transforms/Instrumentation/LLVMBuild.txt<br>
>   lib/Transforms/Instrumentation/PGOInstrumentation.cpp<br>
>   test/Transforms/PGOProfile/Inputs/branch1.proftext<br>
>   test/Transforms/PGOProfile/Inputs/branch2.proftext<br>
>   test/Transforms/PGOProfile/Inputs/criticaledge.proftext<br>
>   test/Transforms/PGOProfile/Inputs/landingpad.proftext<br>
>   test/Transforms/PGOProfile/Inputs/loop1.proftext<br>
>   test/Transforms/PGOProfile/Inputs/loop2.proftext<br>
>   test/Transforms/PGOProfile/Inputs/single_bb.proftext<br>
>   test/Transforms/PGOProfile/Inputs/switch.proftext<br>
>   test/Transforms/PGOProfile/branch1.ll<br>
>   test/Transforms/PGOProfile/branch2.ll<br>
>   test/Transforms/PGOProfile/checksum_mismatch.ll<br>
>   test/Transforms/PGOProfile/criticaledge.ll<br>
>   test/Transforms/PGOProfile/landingpad.ll<br>
>   test/Transforms/PGOProfile/loop1.ll<br>
>   test/Transforms/PGOProfile/loop2.ll<br>
>   test/Transforms/PGOProfile/noprofile_use.ll<br>
>   test/Transforms/PGOProfile/single_bb.ll<br>
>   test/Transforms/PGOProfile/switch.ll<br>
><br>
</div></div>> Index: test/Transforms/PGOProfile/switch.ll<br>
> ===================================================================<br>
> --- /dev/null<br>
> +++ test/Transforms/PGOProfile/switch.ll<br>
> @@ -0,0 +1,48 @@<br>
> +; RUN: opt < %s -pgo-instr-gen -S | FileCheck %s --check-prefix=GEN<br>
> +; RUN: llvm-profdata merge %S/Inputs/switch.proftext -o %T/switch.profdata<br>
> +; RUN: opt < %s -pgo-instr-use -pgo-test-profile-file=%T/switch.profdata -S | FileCheck %s --check-prefix=USE<br>
> +target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"<br>
<span class="">> +target triple = "x86_64-unknown-linux-gnu"<br>
> +<br>
</span>> +; GEN: @__llvm_profile_name_test_switch = private constant [11 x i8] c"test_switch"<br>
> +<br>
> +define void @test_switch(i32 %i) {<br>
> +entry:<br>
> +; GEN: entry:<br>
> +; GEN-NOT: call void @llvm.instrprof.increment<br>
> +  switch i32 %i, label %sw.default [<br>
<span class="">> +    i32 1, label %<a href="http://sw.bb" rel="noreferrer" target="_blank">sw.bb</a><br>
> +    i32 2, label %sw.bb1<br>
</span>> +    i32 3, label %sw.bb2<br>
> +  ]<br>
> +; USE: ]<br>
> +; USE-SAME: !prof ![[BW_SWITCH:[0-9]+]]<br>
> +<br>
> +<a href="http://sw.bb" rel="noreferrer" target="_blank">sw.bb</a>:<br>
> +; GEN: <a href="http://sw.bb" rel="noreferrer" target="_blank">sw.bb</a>:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([11 x i8], [11 x i8]* @__llvm_profile_name_test_switch, i32 0, i32 0), i64 46200943743, i32 4, i32 2)<br>
> +  br label %sw.epilog<br>
> +<br>
> +sw.bb1:<br>
> +; GEN: sw.bb1:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([11 x i8], [11 x i8]* @__llvm_profile_name_test_switch, i32 0, i32 0), i64 46200943743, i32 4, i32 0)<br>
> +  br label %sw.epilog<br>
> +<br>
> +sw.bb2:<br>
> +; GEN: sw.bb2:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([11 x i8], [11 x i8]* @__llvm_profile_name_test_switch, i32 0, i32 0), i64 46200943743, i32 4, i32 1)<br>
> +  br label %sw.epilog<br>
> +<br>
> +sw.default:<br>
> +; GEN: sw.default:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([11 x i8], [11 x i8]* @__llvm_profile_name_test_switch, i32 0, i32 0), i64 46200943743, i32 4, i32 3)<br>
> +  br label %sw.epilog<br>
> +<br>
> +sw.epilog:<br>
> +; GEN: sw.epilog:<br>
> +; GEN-NOT: call void @llvm.instrprof.increment<br>
> +  ret void<br>
> +; GEN: ret void<br>
> +}<br>
> +<br>
> +; USE: ![[BW_SWITCH]] = !{!"branch_weights", i32 3, i32 2, i32 0, i32 5}<br>
> Index: test/Transforms/PGOProfile/single_bb.ll<br>
> ===================================================================<br>
> --- /dev/null<br>
> +++ test/Transforms/PGOProfile/single_bb.ll<br>
> @@ -0,0 +1,12 @@<br>
> +; RUN: opt < %s -pgo-instr-gen -S | FileCheck %s --check-prefix=GEN<br>
> +target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"<br>
<span class="">> +target triple = "x86_64-unknown-linux-gnu"<br>
> +<br>
</span>> +; GEN: @__llvm_profile_name_single_bb = private constant [9 x i8] c"single_bb"<br>
> +<br>
> +define i32 @single_bb() {<br>
> +entry:<br>
> +; GEN: entry:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([9 x i8], [9 x i8]* @__llvm_profile_name_single_bb, i32 0, i32 0), i64 12884901887, i32 1, i32 0)<br>
> +  ret i32 0<br>
> +}<br>
> Index: test/Transforms/PGOProfile/noprofile_use.ll<br>
> ===================================================================<br>
> --- /dev/null<br>
> +++ test/Transforms/PGOProfile/noprofile_use.ll<br>
> @@ -0,0 +1,9 @@<br>
> +; RUN: not opt < %s -pgo-instr-use -pgo-test-profile-file=%T/notexisting.profdata -S  2>&1<br>
<br>
Could you FileCheck for the error message here please? It makes the<br>
purpose of the test a bit clearer.<br>
<br></blockquote><div><br></div><div>I used to have a grep command. But I got an error from *-win7 buildbot. They have a different system error message. I'll do some experiments to see what is the proper message to grep.</div><div> </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
> +<br>
> +target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"<br>
<span class="">> +target triple = "x86_64-unknown-linux-gnu"<br>
> +<br>
</span>> +define i32 @foo() {<br>
> +entry:<br>
> +  ret i32 0<br>
> +}<br>
> Index: test/Transforms/PGOProfile/loop2.ll<br>
> ===================================================================<br>
> --- /dev/null<br>
> +++ test/Transforms/PGOProfile/loop2.ll<br>
> @@ -0,0 +1,97 @@<br>
> +; RUN: opt < %s -pgo-instr-gen -S | FileCheck %s --check-prefix=GEN<br>
> +; RUN: llvm-profdata merge %S/Inputs/loop2.proftext -o %T/loop2.profdata<br>
> +; RUN: opt < %s -pgo-instr-use -pgo-test-profile-file=%T/loop2.profdata -S | FileCheck %s --check-prefix=USE<br>
> +target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"<br>
<span class="">> +target triple = "x86_64-unknown-linux-gnu"<br>
> +<br>
</span>> +; GEN: @__llvm_profile_name_test_nested_for = private constant [15 x i8] c"test_nested_for"<br>
<span class="">> +<br>
> +define i32 @test_nested_for(i32 %r, i32 %s, i32 %t) {<br>
> +entry:<br>
</span>> +; GEN: entry:<br>
> +  br label %for.cond<br>
> +<br>
> +for.cond:<br>
> +; GEN: for.cond:<br>
> +; GEN-NOT: call void @llvm.instrprof.increment<br>
> +  %i.0 = phi i32 [ 0, %entry ], [ %inc12, %for.inc11 ]<br>
> +  %nested_for_sum.0 = phi i32 [ 1, %entry ], [ %nested_for_sum.1, %for.inc11 ]<br>
> +  %cmp = icmp slt i32 %i.0, %r<br>
> +  br i1 %cmp, label %for.body, label %for.end13<br>
> +; USE: br i1 %cmp, label %for.body, label %for.end13<br>
> +; USE-SAME: !prof ![[BW_FOR_COND:[0-9]+]]<br>
> +<br>
> +for.body:<br>
> +; GEN: for.body:<br>
> +; GEN-NOT: call void @llvm.instrprof.increment<br>
> +  br label %for.cond1<br>
> +<br>
> +for.cond1:<br>
> +; GEN: for.cond1:<br>
> +; GEN-NOT: call void @llvm.instrprof.increment<br>
> +  %j.0 = phi i32 [ 0, %for.body ], [ %inc9, %for.inc8 ]<br>
> +  %nested_for_sum.1 = phi i32 [ %nested_for_sum.0, %for.body ], [ %nested_for_sum.2, %for.inc8 ]<br>
> +  %cmp2 = icmp slt i32 %j.0, %s<br>
> +  br i1 %cmp2, label %for.body3, label %for.end10<br>
> +; USE: br i1 %cmp2, label %for.body3, label %for.end10<br>
> +; USE-SAME: !prof ![[BW_FOR_COND1:[0-9]+]]<br>
> +<br>
> +for.body3:<br>
> +; GEN: for.body3:<br>
> +; GEN-NOT: call void @llvm.instrprof.increment<br>
> +  br label %for.cond4<br>
> +<br>
> +for.cond4:<br>
> +; GEN: for.cond4:<br>
> +; GEN-NOT: call void @llvm.instrprof.increment<br>
> +  %k.0 = phi i32 [ 0, %for.body3 ], [ %inc7, %for.inc ]<br>
> +  %nested_for_sum.2 = phi i32 [ %nested_for_sum.1, %for.body3 ], [ %inc, %for.inc ]<br>
> +  %cmp5 = icmp slt i32 %k.0, %t<br>
> +  br i1 %cmp5, label %for.body6, label %for.end<br>
> +; USE: br i1 %cmp5, label %for.body6, label %for.end<br>
> +; USE-SAME: !prof ![[BW_FOR_COND4:[0-9]+]]<br>
> +<br>
> +for.body6:<br>
> +; GEN: for.body6:<br>
> +; GEN-NOT: call void @llvm.instrprof.increment<br>
> +  %inc = add nsw i32 %nested_for_sum.2, 1<br>
> +  br label %for.inc<br>
> +<br>
> +for.inc:<br>
> +; GEN: for.inc:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([15 x i8], [15 x i8]* @__llvm_profile_name_test_nested_for, i32 0, i32 0), i64 74483645111, i32 4, i32 0)<br>
> +  %inc7 = add nsw i32 %k.0, 1<br>
> +  br label %for.cond4<br>
> +<br>
> +for.end:<br>
> +; GEN: for.end:<br>
> +; GEN-NOT: call void @llvm.instrprof.increment<br>
> +  br label %for.inc8<br>
> +<br>
> +for.inc8:<br>
> +; GEN: for.inc8:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([15 x i8], [15 x i8]* @__llvm_profile_name_test_nested_for, i32 0, i32 0), i64 74483645111, i32 4, i32 1)<br>
> +  %inc9 = add nsw i32 %j.0, 1<br>
> +  br label %for.cond1<br>
> +<br>
> +for.end10:<br>
> +; GEN: for.end10:<br>
> +; GEN-NOT: call void @llvm.instrprof.increment<br>
> +  br label %for.inc11<br>
> +<br>
> +for.inc11:<br>
> +; GEN: for.inc11:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([15 x i8], [15 x i8]* @__llvm_profile_name_test_nested_for, i32 0, i32 0), i64 74483645111, i32 4, i32 2)<br>
> +  %inc12 = add nsw i32 %i.0, 1<br>
> +  br label %for.cond<br>
> +<br>
> +for.end13:<br>
> +; GEN: for.end13:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([15 x i8], [15 x i8]* @__llvm_profile_name_test_nested_for, i32 0, i32 0), i64 74483645111, i32 4, i32 3)<br>
> +  ret i32 %nested_for_sum.0<br>
> +}<br>
> +<br>
> +; USE: ![[BW_FOR_COND]] = !{!"branch_weights", i32 10, i32 6}<br>
> +; USE: ![[BW_FOR_COND1]] = !{!"branch_weights", i32 33, i32 10}<br>
> +; USE: ![[BW_FOR_COND4]] = !{!"branch_weights", i32 186, i32 33}<br>
> +<br>
> Index: test/Transforms/PGOProfile/loop1.ll<br>
> ===================================================================<br>
> --- /dev/null<br>
> +++ test/Transforms/PGOProfile/loop1.ll<br>
> @@ -0,0 +1,43 @@<br>
> +; RUN: opt < %s -pgo-instr-gen -S | FileCheck %s --check-prefix=GEN<br>
> +; RUN: llvm-profdata merge %S/Inputs/loop1.proftext -o %T/loop1.profdata<br>
> +; RUN: opt < %s -pgo-instr-use -pgo-test-profile-file=%T/loop1.profdata -S | FileCheck %s --check-prefix=USE<br>
> +target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"<br>
<span class="">> +target triple = "x86_64-unknown-linux-gnu"<br>
> +<br>
</span>> +; GEN: @__llvm_profile_name_test_simple_for = private constant [15 x i8] c"test_simple_for"<br>
> +<br>
> +define i32 @test_simple_for(i32 %n) {<br>
> +entry:<br>
> +; GEN: entry:<br>
> +; GEN-NOT: call void @llvm.instrprof.increment<br>
> +  br label %for.cond<br>
> +<br>
> +for.cond:<br>
> +; GEN: for.cond:<br>
> +; GEN-NOT: call void @llvm.instrprof.increment<br>
> +  %i = phi i32 [ 0, %entry ], [ %inc1, %for.inc ]<br>
> +  %sum = phi i32 [ 1, %entry ], [ %inc, %for.inc ]<br>
> +  %cmp = icmp slt i32 %i, %n<br>
> +  br i1 %cmp, label %for.body, label %for.end<br>
> +; USE: br i1 %cmp, label %for.body, label %for.end<br>
> +; USE-SAME: !prof ![[BW_FOR_COND:[0-9]+]]<br>
> +<br>
> +for.body:<br>
> +; GEN: for.body:<br>
> +; GEN-NOT: call void @llvm.instrprof.increment<br>
> +  %inc = add nsw i32 %sum, 1<br>
> +  br label %for.inc<br>
> +<br>
> +for.inc:<br>
> +; GEN: for.inc:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([15 x i8], [15 x i8]* @__llvm_profile_name_test_simple_for, i32 0, i32 0), i64 34137660316, i32 2, i32 0)<br>
> +  %inc1 = add nsw i32 %i, 1<br>
> +  br label %for.cond<br>
> +<br>
> +for.end:<br>
> +; GEN: for.end:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([15 x i8], [15 x i8]* @__llvm_profile_name_test_simple_for, i32 0, i32 0), i64 34137660316, i32 2, i32 1)<br>
> +  ret i32 %sum<br>
> +}<br>
> +<br>
> +; USE: ![[BW_FOR_COND]] = !{!"branch_weights", i32 96, i32 4}<br>
> Index: test/Transforms/PGOProfile/landingpad.ll<br>
> ===================================================================<br>
> --- /dev/null<br>
> +++ test/Transforms/PGOProfile/landingpad.ll<br>
> @@ -0,0 +1,124 @@<br>
> +; RUN: opt < %s -pgo-instr-gen -S | FileCheck %s --check-prefix=GEN<br>
> +; RUN: llvm-profdata merge %S/Inputs/landingpad.proftext -o %T/landingpad.profdata<br>
> +; RUN: opt < %s -pgo-instr-use -pgo-test-profile-file=%T/landingpad.profdata -S | FileCheck %s --check-prefix=USE<br>
> +target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"<br>
<span class="">> +target triple = "x86_64-unknown-linux-gnu"<br>
> +<br>
</span>> +@val = global i32 0, align 4<br>
> +@_ZTIi = external constant i8*<br>
> +; GEN: @__llvm_profile_name_bar = private constant [3 x i8] c"bar"<br>
> +; GEN: @__llvm_profile_name_foo = private constant [3 x i8] c"foo"<br>
> +<br>
> +define i32 @bar(i32 %i) {<br>
> +entry:<br>
> +; GEN: entry:<br>
> +; GEN-NOT: call void @llvm.instrprof.increment<br>
> +  %rem = srem i32 %i, 3<br>
> +  %tobool = icmp ne i32 %rem, 0<br>
> +  br i1 %tobool, label %if.then, label %if.end<br>
> +; USE: br i1 %tobool, label %if.then, label %if.end<br>
> +; USE-SAME: !prof ![[BW_BAR_ENTRY:[0-9]+]]<br>
> +<br>
> +if.then:<br>
> +; GEN: if.then:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([3 x i8], [3 x i8]* @__llvm_profile_name_bar, i32 0, i32 0), i64 24868915205, i32 2, i32 1)<br>
> +  %exception = call i8* @__cxa_allocate_exception(i64 4)<br>
> +  %tmp = bitcast i8* %exception to i32*<br>
> +  store i32 %i, i32* %tmp, align 16<br>
> +  call void @__cxa_throw(i8* %exception, i8* bitcast (i8** @_ZTIi to i8*), i8* null)<br>
> +  unreachable<br>
> +<br>
> +if.end:<br>
> +; GEN: if.end:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([3 x i8], [3 x i8]* @__llvm_profile_name_bar, i32 0, i32 0), i64 24868915205, i32 2, i32 0)<br>
> +  ret i32 0<br>
> +}<br>
> +<br>
> +declare i8* @__cxa_allocate_exception(i64)<br>
> +<br>
> +declare void @__cxa_throw(i8*, i8*, i8*)<br>
> +<br>
> +define i32 @foo(i32 %i) personality i8* bitcast (i32 (...)* @__gxx_personality_v0 to i8*) {<br>
> +entry:<br>
> +; GEN: entry:<br>
> +; GEN-NOT: call void @llvm.instrprof.increment<br>
> +  %rem = srem i32 %i, 2<br>
> +  %tobool = icmp ne i32 %rem, 0<br>
> +  br i1 %tobool, label %if.then, label %if.end<br>
> +; USE: br i1 %tobool, label %if.then, label %if.end<br>
> +; USE-SAME: !prof ![[BW_FOO_ENTRY:[0-9]+]]<br>
> +<br>
> +if.then:<br>
> +; GEN: if.then:<br>
> +; GEN-NOT: call void @llvm.instrprof.increment<br>
> +  %mul = mul nsw i32 %i, 7<br>
> +  %call = invoke i32 @bar(i32 %mul)<br>
> +          to label %invoke.cont unwind label %lpad<br>
> +<br>
> +invoke.cont:<br>
> +; GEN: invoke.cont:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([3 x i8], [3 x i8]* @__llvm_profile_name_foo, i32 0, i32 0), i64 59130013419, i32 4, i32 1)<br>
> +  br label %if.end<br>
> +<br>
> +lpad:<br>
> +; GEN: lpad:<br>
> +; GEN-NOT: call void @llvm.instrprof.increment<br>
> +  %tmp = landingpad { i8*, i32 }<br>
> +          catch i8* bitcast (i8** @_ZTIi to i8*)<br>
> +  %tmp1 = extractvalue { i8*, i32 } %tmp, 0<br>
> +  %tmp2 = extractvalue { i8*, i32 } %tmp, 1<br>
> +  br label %catch.dispatch<br>
> +<br>
> +catch.dispatch:<br>
> +; GEN: catch.dispatch:<br>
> +; GEN-NOT: call void @llvm.instrprof.increment<br>
> +  %tmp3 = call i32 @llvm.eh.typeid.for(i8* bitcast (i8** @_ZTIi to i8*))<br>
> +  %matches = icmp eq i32 %tmp2, %tmp3<br>
> +  br i1 %matches, label %catch, label %eh.resume<br>
> +; USE: br i1 %matches, label %catch, label %eh.resume<br>
> +; USE-SAME: !prof ![[BW_CATCH_DISPATCH:[0-9]+]]<br>
> +<br>
> +catch:<br>
> +; GEN: catch:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([3 x i8], [3 x i8]* @__llvm_profile_name_foo, i32 0, i32 0), i64 59130013419, i32 4, i32 2)<br>
> +  %tmp4 = call i8* @__cxa_begin_catch(i8* %tmp1)<br>
> +  %tmp5 = bitcast i8* %tmp4 to i32*<br>
> +  %tmp6 = load i32, i32* %tmp5, align 4<br>
> +  %tmp7 = load i32, i32* @val, align 4<br>
> +  %sub = sub nsw i32 %tmp7, %tmp6<br>
> +  store i32 %sub, i32* @val, align 4<br>
> +  call void @__cxa_end_catch()<br>
> +  br label %try.cont<br>
> +<br>
> +try.cont:<br>
> +; GEN: try.cont:<br>
> +; GEN-NOT: call void @llvm.instrprof.increment<br>
> +  ret i32 -1<br>
> +<br>
> +if.end:<br>
> +; GEN: if.end:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([3 x i8], [3 x i8]* @__llvm_profile_name_foo, i32 0, i32 0), i64 59130013419, i32 4, i32 0)<br>
> +  %tmp8 = load i32, i32* @val, align 4<br>
> +  %add = add nsw i32 %tmp8, %i<br>
> +  store i32 %add, i32* @val, align 4<br>
> +  br label %try.cont<br>
> +<br>
> +eh.resume:<br>
> +; GEN: eh.resume:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([3 x i8], [3 x i8]* @__llvm_profile_name_foo, i32 0, i32 0), i64 59130013419, i32 4, i32 3)<br>
> +  %lpad.val = insertvalue { i8*, i32 } undef, i8* %tmp1, 0<br>
> +  %lpad.val3 = insertvalue { i8*, i32 } %lpad.val, i32 %tmp2, 1<br>
> +  resume { i8*, i32 } %lpad.val3<br>
> +}<br>
> +<br>
> +declare i32 @__gxx_personality_v0(...)<br>
> +<br>
> +declare i32 @llvm.eh.typeid.for(i8*)<br>
> +<br>
> +declare i8* @__cxa_begin_catch(i8*)<br>
> +<br>
> +declare void @__cxa_end_catch()<br>
> +<br>
> +; USE: ![[BW_BAR_ENTRY]] = !{!"branch_weights", i32 2, i32 1}<br>
> +; USE: ![[BW_FOO_ENTRY]] = !{!"branch_weights", i32 3, i32 2}<br>
> +; USE: ![[BW_CATCH_DISPATCH]] = !{!"branch_weights", i32 2, i32 0}<br>
> Index: test/Transforms/PGOProfile/criticaledge.ll<br>
> ===================================================================<br>
> --- /dev/null<br>
> +++ test/Transforms/PGOProfile/criticaledge.ll<br>
> @@ -0,0 +1,109 @@<br>
> +; RUN: opt < %s -pgo-instr-gen -S | FileCheck %s --check-prefix=GEN<br>
> +; RUN: llvm-profdata merge %S/Inputs/criticaledge.proftext -o %T/criticaledge.profdata<br>
> +; RUN: opt < %s -pgo-instr-use -pgo-test-profile-file=%T/criticaledge.profdata -S | FileCheck %s --check-prefix=USE<br>
> +target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"<br>
<span class="">> +target triple = "x86_64-unknown-linux-gnu"<br>
> +<br>
</span>> +; GEN: @__llvm_profile_name_test_criticalEdge = private constant [17 x i8] c"test_criticalEdge"<br>
> +; GEN: @"__llvm_profile_name_<stdin>:bar" = private constant [11 x i8] c"<stdin>:bar"<br>
> +<br>
> +define i32 @test_criticalEdge(i32 %i, i32 %j) {<br>
> +entry:<br>
> +; CHECK: entry:<br>
> +; GEN-NOT: call void @llvm.instrprof.increment<br>
> +  switch i32 %i, label %sw.default [<br>
<span class="">> +    i32 1, label %<a href="http://sw.bb" rel="noreferrer" target="_blank">sw.bb</a><br>
> +    i32 2, label %sw.bb1<br>
</span>> +    i32 3, label %sw.bb2<br>
> +    i32 4, label %sw.bb2<br>
> +; CHECK:    i32 3, label %entry.sw.bb2_crit_edge<br>
> +; CHECK:    i32 4, label %entry.sw.bb2_crit_edge1<br>
> +    i32 5, label %sw.bb2<br>
> +  ]<br>
> +; USE: ]<br>
> +; USE-SAME: !prof ![[BW_SWITCH:[0-9]+]]<br>
> +<br>
> +; CHECK: entry.sw.bb2_crit_edge1:<br>
> +; GEN:   call void @llvm.instrprof.increment(i8* getelementptr inbounds ([17 x i8], [17 x i8]* @__llvm_profile_name_test_criticalEdge, i32 0, i32 0), i64 82323253069, i32 8, i32 1)<br>
> +; CHECK:   br label %sw.bb2<br>
> +<br>
> +; CHECK: entry.sw.bb2_crit_edge:<br>
> +; GEN:   call void @llvm.instrprof.increment(i8* getelementptr inbounds ([17 x i8], [17 x i8]* @__llvm_profile_name_test_criticalEdge, i32 0, i32 0), i64 82323253069, i32 8, i32 0)<br>
> +; CHECK:   br label %sw.bb2<br>
> +<br>
> +<a href="http://sw.bb" rel="noreferrer" target="_blank">sw.bb</a>:<br>
> +; GEN: <a href="http://sw.bb" rel="noreferrer" target="_blank">sw.bb</a>:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([17 x i8], [17 x i8]* @__llvm_profile_name_test_criticalEdge, i32 0, i32 0), i64 82323253069, i32 8, i32 5)<br>
> +  %call = call i32 @bar(i32 2)<br>
> +  br label %sw.epilog<br>
> +<br>
> +sw.bb1:<br>
> +; GEN: sw.bb1:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([17 x i8], [17 x i8]* @__llvm_profile_name_test_criticalEdge, i32 0, i32 0), i64 82323253069, i32 8, i32 4)<br>
> +  %call2 = call i32 @bar(i32 1024)<br>
> +  br label %sw.epilog<br>
> +<br>
> +sw.bb2:<br>
> +; GEN: sw.bb2:<br>
> +; GEN-NOT: call void @llvm.instrprof.increment<br>
> +  %cmp = icmp eq i32 %j, 2<br>
> +  br i1 %cmp, label %if.then, label %if.end<br>
> +; USE: br i1 %cmp, label %if.then, label %if.end<br>
> +; USE-SAME: !prof ![[BW_SW_BB2:[0-9]+]]<br>
> +<br>
> +if.then:<br>
> +; GEN: if.then:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([17 x i8], [17 x i8]* @__llvm_profile_name_test_criticalEdge, i32 0, i32 0), i64 82323253069, i32 8, i32 2)<br>
> +  %call4 = call i32 @bar(i32 4)<br>
> +  br label %return<br>
> +<br>
> +if.end:<br>
> +; GEN: if.end:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([17 x i8], [17 x i8]* @__llvm_profile_name_test_criticalEdge, i32 0, i32 0), i64 82323253069, i32 8, i32 3)<br>
> +  %call5 = call i32 @bar(i32 8)<br>
> +  br label %sw.epilog<br>
> +<br>
> +sw.default:<br>
> +; GEN: sw.default:<br>
> +; GEN-NOT: call void @llvm.instrprof.increment<br>
> +  %call6 = call i32 @bar(i32 32)<br>
> +  %cmp7 = icmp sgt i32 %j, 10<br>
<span class="">> +  br i1 %cmp7, label %if.then8, label %if.end9<br>
</span>> +; USE: br i1 %cmp7, label %if.then8, label %if.end9<br>
> +; USE-SAME: !prof ![[BW_SW_DEFAULT:[0-9]+]]<br>
> +<br>
> +if.then8:<br>
> +; GEN: if.then8:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([17 x i8], [17 x i8]* @__llvm_profile_name_test_criticalEdge, i32 0, i32 0), i64 82323253069, i32 8, i32 7)<br>
> +  %add = add nsw i32 %call6, 10<br>
> +  br label %if.end9<br>
> +<br>
> +if.end9:<br>
> +; GEN: if.end9:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([17 x i8], [17 x i8]* @__llvm_profile_name_test_criticalEdge, i32 0, i32 0), i64 82323253069, i32 8, i32 6)<br>
> +  %res.0 = phi i32 [ %add, %if.then8 ], [ %call6, %sw.default ]<br>
> +  br label %sw.epilog<br>
> +<br>
> +sw.epilog:<br>
> +; GEN: sw.epilog:<br>
> +; GEN-NOT: call void @llvm.instrprof.increment<br>
> +  %res.1 = phi i32 [ %res.0, %if.end9 ], [ %call5, %if.end ], [ %call2, %sw.bb1 ], [ %call, %<a href="http://sw.bb" rel="noreferrer" target="_blank">sw.bb</a> ]<br>
> +  br label %return<br>
> +<br>
> +return:<br>
> +; GEN: return:<br>
> +; GEN-NOT: call void @llvm.instrprof.increment<br>
> +  %retval = phi i32 [ %res.1, %sw.epilog ], [ %call4, %if.then ]<br>
> +  ret i32 %retval<br>
> +}<br>
> +<br>
> +define internal i32 @bar(i32 %i) {<br>
> +entry:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([11 x i8], [11 x i8]* @"__llvm_profile_name_<stdin>:bar", i32 0, i32 0), i64 12884901887, i32 1, i32 0)<br>
> +  ret i32 %i<br>
> +}<br>
> +<br>
> +; USE: ![[BW_SWITCH]] = !{!"branch_weights", i32 2, i32 1, i32 0, i32 2, i32 1, i32 1}<br>
> +; USE: ![[BW_SW_BB2]] = !{!"branch_weights", i32 2, i32 2}<br>
> +; USE: ![[BW_SW_DEFAULT]] = !{!"branch_weights", i32 1, i32 1}<br>
> +<br>
> Index: test/Transforms/PGOProfile/checksum_mismatch.ll<br>
> ===================================================================<br>
> --- /dev/null<br>
> +++ test/Transforms/PGOProfile/checksum_mismatch.ll<br>
> @@ -0,0 +1,18 @@<br>
> +; RUN: llvm-profdata merge %S/Inputs/single_bb.proftext -o %T/single_bb.profdata<br>
> +; RUN: opt < %s -pgo-instr-use -pgo-test-profile-file=%T/single_bb.profdata -S 2>&1 | FileCheck %s<br>
<span class="">> +<br>
> +; CHECK: Function control flow change detected (hash mismatch) single_bb<br>
> +; CHECK: No profile data available for function uncalled<br>
</span>> +<br>
> +target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"<br>
<span class="">> +target triple = "x86_64-unknown-linux-gnu"<br>
> +<br>
</span>> +define i32 @single_bb() {<br>
> +entry:<br>
> +  ret i32 0<br>
> +}<br>
> +<br>
> +define i32 @uncalled(i32 %i, i32 %j) {<br>
> +  %mul = mul nsw i32 %i, %j<br>
> +  ret i32 %mul<br>
> +}<br>
> Index: test/Transforms/PGOProfile/branch2.ll<br>
> ===================================================================<br>
> --- /dev/null<br>
> +++ test/Transforms/PGOProfile/branch2.ll<br>
> @@ -0,0 +1,38 @@<br>
> +; RUN: opt < %s -pgo-instr-gen -S | FileCheck %s --check-prefix=GEN<br>
> +; RUN: llvm-profdata merge %S/Inputs/branch2.proftext -o %T/branch2.profdata<br>
> +; RUN: opt < %s -pgo-instr-use -pgo-test-profile-file=%T/branch2.profdata -S | FileCheck %s --check-prefix=USE<br>
> +target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"<br>
<span class="">> +target triple = "x86_64-unknown-linux-gnu"<br>
> +<br>
</span>> +; GEN: @__llvm_profile_name_test_br_2 = private constant [9 x i8] c"test_br_2"<br>
> +<br>
> +define i32 @test_br_2(i32 %i) {<br>
> +entry:<br>
> +; GEN: entry:<br>
> +; GEN-NOT: llvm.instrprof.increment<br>
> +  %cmp = icmp sgt i32 %i, 0<br>
<span class="">> +  br i1 %cmp, label %if.then, label %if.else<br>
</span>> +; USE: br i1 %cmp, label %if.then, label %if.else<br>
> +; USE-SAME: !prof ![[BW_ENTRY:[0-9]+]]<br>
> +<br>
> +if.then:<br>
> +; GEN: if.then:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([9 x i8], [9 x i8]* @__llvm_profile_name_test_br_2, i32 0, i32 0), i64 29667547796, i32 2, i32 0)<br>
<span class="">> +  %add = add nsw i32 %i, 2<br>
</span>> +  br label %if.end<br>
> +<br>
> +if.else:<br>
> +; GEN: if.else:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([9 x i8], [9 x i8]* @__llvm_profile_name_test_br_2, i32 0, i32 0), i64 29667547796, i32 2, i32 1)<br>
> +  %sub = sub nsw i32 %i, 2<br>
> +  br label %if.end<br>
> +<br>
> +if.end:<br>
> +; GEN: if.end:<br>
> +; GEN-NOT: llvm.instrprof.increment<br>
> +  %retv = phi i32 [ %add, %if.then ], [ %sub, %if.else ]<br>
> +  ret i32 %retv<br>
> +; GEN: ret<br>
> +}<br>
> +<br>
> +; USE: ![[BW_ENTRY]] = !{!"branch_weights", i32 1, i32 1}<br>
> Index: test/Transforms/PGOProfile/branch1.ll<br>
> ===================================================================<br>
> --- /dev/null<br>
> +++ test/Transforms/PGOProfile/branch1.ll<br>
> @@ -0,0 +1,31 @@<br>
> +; RUN: opt < %s -pgo-instr-gen -S | FileCheck %s --check-prefix=GEN<br>
> +; RUN: llvm-profdata merge %S/Inputs/branch1.proftext -o %T/branch1.profdata<br>
> +; RUN: opt < %s -pgo-instr-use -pgo-test-profile-file=%T/branch1.profdata -S | FileCheck %s --check-prefix=USE<br>
> +target datalayout = "e-m:e-i64:64-f80:128-n8:16:32:64-S128"<br>
<span class="">> +target triple = "x86_64-unknown-linux-gnu"<br>
> +<br>
</span>> +; GEN: @__llvm_profile_name_test_br_1 = private constant [9 x i8] c"test_br_1"<br>
> +<br>
> +define i32 @test_br_1(i32 %i) {<br>
> +entry:<br>
> +; GEN: entry:<br>
> +; GEN-NOT: llvm.instrprof.increment<br>
> +  %cmp = icmp sgt i32 %i, 0<br>
> +  br i1 %cmp, label %if.then, label %if.end<br>
> +; USE: br i1 %cmp, label %if.then, label %if.end<br>
> +; USE-SAME: !prof ![[BW_ENTRY:[0-9]+]]<br>
> +<br>
> +if.then:<br>
> +; GEN: if.then:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([9 x i8], [9 x i8]* @__llvm_profile_name_test_br_1, i32 0, i32 0), i64 25571299074, i32 2, i32 1)<br>
<span class="">> +  %add = add nsw i32 %i, 2<br>
</span>> +  br label %if.end<br>
> +<br>
> +if.end:<br>
> +; GEN: if.end:<br>
> +; GEN: call void @llvm.instrprof.increment(i8* getelementptr inbounds ([9 x i8], [9 x i8]* @__llvm_profile_name_test_br_1, i32 0, i32 0), i64 25571299074, i32 2, i32 0)<br>
> +  %retv = phi i32 [ %add, %if.then ], [ %i, %entry ]<br>
> +  ret i32 %retv<br>
> +}<br>
<span class="">> +<br>
> +; USE: ![[BW_ENTRY]] = !{!"branch_weights", i32 2, i32 1}<br>
</span>> Index: test/Transforms/PGOProfile/Inputs/switch.proftext<br>
> ===================================================================<br>
> --- /dev/null<br>
> +++ test/Transforms/PGOProfile/Inputs/switch.proftext<br>
> @@ -0,0 +1,8 @@<br>
> +test_switch<br>
> <a href="tel:%2B46200943743" value="+46200943743">+46200943743</a><br>
> +4<br>
> +0<br>
> +5<br>
> +2<br>
> +3<br>
> +<br>
> Index: test/Transforms/PGOProfile/Inputs/single_bb.proftext<br>
> ===================================================================<br>
> --- /dev/null<br>
> +++ test/Transforms/PGOProfile/Inputs/single_bb.proftext<br>
> @@ -0,0 +1,5 @@<br>
> +single_bb<br>
> +12884999999<br>
> +1<br>
> +1<br>
> +<br>
> Index: test/Transforms/PGOProfile/Inputs/loop2.proftext<br>
> ===================================================================<br>
> --- /dev/null<br>
> +++ test/Transforms/PGOProfile/Inputs/loop2.proftext<br>
> @@ -0,0 +1,8 @@<br>
> +test_nested_for<br>
> +74483645111<br>
> +4<br>
> +186<br>
> +33<br>
> +10<br>
> +6<br>
> +<br>
> Index: test/Transforms/PGOProfile/Inputs/loop1.proftext<br>
> ===================================================================<br>
> --- /dev/null<br>
> +++ test/Transforms/PGOProfile/Inputs/loop1.proftext<br>
> @@ -0,0 +1,6 @@<br>
> +test_simple_for<br>
> +34137660316<br>
> +2<br>
> +96<br>
> +4<br>
> +<br>
> Index: test/Transforms/PGOProfile/Inputs/landingpad.proftext<br>
> ===================================================================<br>
> --- /dev/null<br>
> +++ test/Transforms/PGOProfile/Inputs/landingpad.proftext<br>
> @@ -0,0 +1,14 @@<br>
> +foo<br>
> +59130013419<br>
> +4<br>
> +3<br>
> +1<br>
> +2<br>
> +0<br>
> +<br>
> +bar<br>
> +24868915205<br>
> +2<br>
> +1<br>
> +2<br>
> +<br>
> Index: test/Transforms/PGOProfile/Inputs/criticaledge.proftext<br>
> ===================================================================<br>
> --- /dev/null<br>
> +++ test/Transforms/PGOProfile/Inputs/criticaledge.proftext<br>
> @@ -0,0 +1,17 @@<br>
> +test_criticalEdge<br>
> +82323253069<br>
> +8<br>
> +2<br>
> +1<br>
> +2<br>
> +2<br>
> +0<br>
> +1<br>
> +2<br>
> +1<br>
> +<br>
> +<stdin>:bar<br>
> +12884901887<br>
> +1<br>
> +7<br>
> +<br>
> Index: test/Transforms/PGOProfile/Inputs/branch2.proftext<br>
> ===================================================================<br>
> --- /dev/null<br>
> +++ test/Transforms/PGOProfile/Inputs/branch2.proftext<br>
> @@ -0,0 +1,6 @@<br>
> +test_br_2<br>
> +29667547796<br>
> +2<br>
> +1<br>
> +1<br>
> +<br>
> Index: test/Transforms/PGOProfile/Inputs/branch1.proftext<br>
> ===================================================================<br>
> --- /dev/null<br>
> +++ test/Transforms/PGOProfile/Inputs/branch1.proftext<br>
> @@ -0,0 +1,6 @@<br>
> +test_br_1<br>
> +25571299074<br>
> +2<br>
> +3<br>
> +2<br>
> +<br>
> Index: lib/Transforms/Instrumentation/PGOInstrumentation.cpp<br>
> ===================================================================<br>
> --- /dev/null<br>
> +++ lib/Transforms/Instrumentation/PGOInstrumentation.cpp<br>
> @@ -0,0 +1,721 @@<br>
> +//===-- PGOInstru.cpp - PGO Instrumentation -------------------------------===//<br>
<br>
This should match the filename (PGOInstrumentation.cpp). I might even go<br>
so far as to say "MST-based PGO instrumentation" or something like that<br>
in the top comment, just to differentiate it from the frontend<br>
instrumentation.<br></blockquote><div><br></div><div>OK. will do</div><div> </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<br>
> +//<br>
> +//                      The LLVM Compiler Infrastructure<br>
> +//<br>
> +// This file is distributed under the University of Illinois Open Source<br>
> +// License. See LICENSE.TXT for details.<br>
> +//<br>
> +//===----------------------------------------------------------------------===//<br>
> +//<br>
<span class="">> +// This file implements PGO instrumentation using a minimum spanning tree based<br>
</span>> +// on the following paper:<br>
<span class="">> +//   [1] Donald E. Knuth, Francis R. Stevenson. Optimal measurement of points<br>
</span>> +//   for program frequency counts. BIT Numerical Mathematics 1973, Volume 13,<br>
> +//   Issue 3, pp 313-322<br>
> +// The idea of the algorithm based on the fact that for each node (except for<br>
> +// the entry and exit), the sum of incoming edge counts equals the sum of<br>
> +// outgoing edge counts. The count of edge on spanning tree can be derived from<br>
> +// those edges not on the spanning tree. Knuth proves this method instruments<br>
> +// the minimum number of edges.<br>
> +//<br>
> +// The minimal spanning tree here is actually a maximum weight tree -- on-tree<br>
> +// edges have higher frequencies (more likely to execute). The idea is to<br>
> +// instrument those less frequently executed edges to reduce the runtime<br>
> +// overhead of instrumented binaries.<br>
> +//<br>
> +// This file contains two passes:<br>
> +// (1) Pass PGOInstrumentationGen which instruments the IR to generate edge<br>
> +// count profile, and<br>
> +// (2) Pass PGOInstrumentationUse which reads the edge count profile and<br>
> +// annotates the branch weights.<br>
> +// To get the precise counter information, These two passes need to invoke at<br>
> +// the same compilation point (so they see the same IR). For pass<br>
> +// PGOInstrumentationGen, the real work is done in instrumentOneFunc(). For<br>
> +// pass PGOInstrumentationUse, the real work in done in class PGOUseFunc and<br>
> +// the profile is opened in module level and passed to each PGOUseFunc instance.<br>
> +// The shared code for PGOInstrumentationGen and PGOInstrumentationUse is put<br>
> +// in class FuncPGOInstrumentation.<br>
> +//<br>
> +// Class PGOEdge represents a CFG edge and some auxiliary information. Class<br>
> +// BBInfo contains auxiliary information for each BB. These two classes are used<br>
> +// in pass PGOInstrumentationGen. Class PGOUseEdge and UseBBInfo are the derived<br>
> +// class of PGOEdge and BBInfo, respectively. They contains extra data structure<br>
> +// used in populating profile counters.<br>
> +// The MST implementation is in Class CFGMST (CFGMST.h).<br>
> +//<br>
> +//===----------------------------------------------------------------------===//<br>
> +<br>
> +#include "llvm/Transforms/Instrumentation.h"<br>
> +#include "CFGMST.h"<br>
> +#include "llvm/ADT/DenseMap.h"<br>
> +#include "llvm/ADT/STLExtras.h"<br>
> +#include "llvm/ADT/Statistic.h"<br>
> +#include "llvm/Analysis/BlockFrequencyInfo.h"<br>
> +#include "llvm/Analysis/BranchProbabilityInfo.h"<br>
> +#include "llvm/Analysis/CFG.h"<br>
> +#include "llvm/IR/DiagnosticInfo.h"<br>
> +#include "llvm/IR/IRBuilder.h"<br>
> +#include "llvm/IR/InstIterator.h"<br>
> +#include "llvm/IR/Instructions.h"<br>
> +#include "llvm/IR/IntrinsicInst.h"<br>
> +#include "llvm/IR/MDBuilder.h"<br>
> +#include "llvm/IR/Module.h"<br>
> +#include "llvm/Pass.h"<br>
> +#include "llvm/ProfileData/InstrProfReader.h"<br>
> +#include "llvm/Support/BranchProbability.h"<br>
> +#include "llvm/Support/Debug.h"<br>
> +#include "llvm/Support/JamCRC.h"<br>
> +#include "llvm/Transforms/Utils/BasicBlockUtils.h"<br>
> +#include <string><br>
> +#include <utility><br>
> +#include <vector><br>
> +<br>
> +using namespace llvm;<br>
> +<br>
> +#define DEBUG_TYPE "pgo-instr"<br>
<br>
It's probably more discoverable to use "pgo-instrumentation" to match<br>
the filename.<br>
<br>
> +<br>
> +STATISTIC(NumOfPGOInstrument, "Number of edges instrumented.");<br>
> +STATISTIC(NumOfPGOEdge, "Number of edges.");<br>
> +STATISTIC(NumOfPGOBB, "Number of basic-blocks.");<br>
> +STATISTIC(NumOfPGOSplit, "Number of critical edge splits.");<br>
> +STATISTIC(NumOfPGOFunc, "Number of functions having valid profile counts.");<br>
> +STATISTIC(NumOfPGOMismatch, "Number of functions having mismatch profile.");<br>
> +STATISTIC(NumOfPGOMissing, "Number of functions without profile.");<br>
> +<br>
> +// Command line option to specify the file to read profile from. This is<br>
> +// mainly used for testing.<br>
<span class="">> +static cl::opt<std::string><br>
</span>> +    PGOProfileFile("pgo-test-profile-file", cl::init(""), cl::Hidden,<br>
<span class="">> +                   cl::value_desc("filename"),<br>
</span>> +                   cl::desc("Specify the path of profile data file. This is"<br>
> +                            "mainly for test purpose."));<br>
> +<br>
> +namespace {<br>
> +class PGOInstrumentationGen : public ModulePass {<br>
> +public:<br>
> +  static char ID;<br>
> +<br>
> +  PGOInstrumentationGen() : ModulePass(ID) {<br>
> +    initializePGOInstrumentationGenPass(*PassRegistry::getPassRegistry());<br>
> +  }<br>
> +<br>
> +  const char *getPassName() const override {<br>
> +    return "PGOInstrumentationGenPass";<br>
> +  }<br>
> +<br>
> +private:<br>
> +  bool runOnModule(Module &M) override;<br>
> +<br>
> +  void getAnalysisUsage(AnalysisUsage &AU) const override {<br>
> +    AU.addRequired<BlockFrequencyInfoWrapperPass>();<br>
> +    AU.addRequired<BranchProbabilityInfoWrapperPass>();<br>
> +  }<br>
> +};<br>
> +<br>
> +class PGOInstrumentationUse : public ModulePass {<br>
> +public:<br>
> +  static char ID;<br>
> +<br>
> +  // Provide the profile filename as the parameter.<br>
> +  PGOInstrumentationUse(StringRef Filename = StringRef(""))<br>
<br>
StringRef seems like a poor argument type here, since it isn't clear<br>
that the string needs to outlive the class.<br></blockquote><div><br></div><div>I'll switch to a string.</div><div> </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<br>
> +      : ModulePass(ID), ProfileFileName(Filename) {<br>
> +    if (!PGOProfileFile.empty())<br>
> +      ProfileFileName = StringRef(PGOProfileFile);<br>
> +    initializePGOInstrumentationUsePass(*PassRegistry::getPassRegistry());<br>
> +  }<br>
> +<br>
> +  const char *getPassName() const override {<br>
> +    return "PGOInstrumentationUsePass";<br>
> +  }<br>
> +<br>
> +private:<br>
> +  StringRef ProfileFileName;<br>
> +  std::unique_ptr<IndexedInstrProfReader> PGOReader;<br>
> +  bool runOnModule(Module &M) override;<br>
> +<br>
> +  void getAnalysisUsage(AnalysisUsage &AU) const override {<br>
> +    AU.addRequired<BlockFrequencyInfoWrapperPass>();<br>
> +    AU.addRequired<BranchProbabilityInfoWrapperPass>();<br>
> +  }<br>
> +};<br>
> +} // end anonymous namespace<br>
> +<br>
> +char PGOInstrumentationGen::ID = 0;<br>
> +INITIALIZE_PASS_BEGIN(PGOInstrumentationGen, "pgo-instr-gen",<br>
> +                      "PGO instrumentation.", false, false)<br>
> +INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)<br>
> +INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)<br>
> +INITIALIZE_PASS_END(PGOInstrumentationGen, "pgo-instr-gen",<br>
> +                    "PGO instrumentation.", false, false)<br>
> +<br>
> +ModulePass *llvm::createPGOInstrumentationGenPass() {<br>
> +  return new PGOInstrumentationGen();<br>
> +}<br>
> +<br>
> +char PGOInstrumentationUse::ID = 0;<br>
> +INITIALIZE_PASS_BEGIN(PGOInstrumentationUse, "pgo-instr-use",<br>
> +                      "Read PGO instrumentation profile.", false, false)<br>
> +INITIALIZE_PASS_DEPENDENCY(BlockFrequencyInfoWrapperPass)<br>
> +INITIALIZE_PASS_DEPENDENCY(BranchProbabilityInfoWrapperPass)<br>
> +INITIALIZE_PASS_END(PGOInstrumentationUse, "pgo-instr-use",<br>
> +                    "Read PGO instrumentation profile.", false, false)<br>
> +<br>
> +ModulePass *llvm::createPGOInstrumentationUsePass(StringRef Filename) {<br>
> +  return new PGOInstrumentationUse(Filename);<br>
> +}<br>
> +<br>
> +namespace {<br>
> +/// \brief An MST based instrumentation for PGO<br>
> +///<br>
> +/// Implements a Minimum Spanning Tree (MST) based instrumentation for PGO<br>
> +/// in the function level.<br>
> +//<br>
> +// This class implements the CFG edges. Note the CFG can be a multi-graph.<br>
<br>
This seems to switch from a doc-comment to a regular comment halfway<br>
through.<br>
<br>
> +struct PGOEdge {<br>
> +  const BasicBlock *SrcBB;<br>
> +  const BasicBlock *DestBB;<br>
> +  uint64_t Weight;<br>
> +  bool InMST;<br>
> +  bool Removed;<br>
> +  bool IsCritical;<br>
> +  PGOEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)<br>
> +      : SrcBB(Src), DestBB(Dest), Weight(W), InMST(false), Removed(false),<br>
> +        IsCritical(false) {}<br>
> +  // Return the information string of an edge.<br>
> +  const std::string infoString() const {<br>
> +    std::string Str = (Removed ? "-" : " ");<br>
> +    Str += (InMST ? " " : "*");<br>
> +    Str += (IsCritical ? "c" : " ");<br>
> +    Str += "  W=" + std::to_string(Weight);<br>
<br>
ISTR that std::to_string isn't available in all of the standard<br>
libraries we support, so this might fail on some of the bots as is.<br></blockquote><div><br></div><div>Thanks for points this ok. Maybe I should use sprintf.</div><div> </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<br>
> +    return Str;<br>
> +  }<br>
> +};<br>
> +<br>
> +// This class stores the auxiliary information for each BB.<br>
> +struct BBInfo {<br>
> +  BBInfo *Group;<br>
> +  uint32_t Index;<br>
> +  uint32_t Rank;<br>
> +<br>
> +  BBInfo(unsigned IX) : Group(this), Index(IX), Rank(0) {}<br>
> +<br>
> +  // Return the information string of this object.<br>
> +  const std::string infoString() const {<br>
> +    return "Index=" + std::to_string(Index);<br>
> +  }<br>
> +};<br>
> +<br>
> +// This class implements the CFG edges. Note the CFG can be a multi-graph.<br>
> +template <class Edge, class BBInfo> class FuncPGOInstrumentation {<br>
> +private:<br>
> +  Function &F;<br>
> +  void computeCFGHash();<br>
> +<br>
> +public:<br>
> +  std::string FuncName;<br>
> +  GlobalVariable *FuncNameVar;<br>
> +  // CFG hash value for this function.<br>
> +  uint64_t FunctionHash;<br>
> +<br>
> +  // The Minimum Spanning Tree of function CFG.<br>
> +  CFGMST<Edge, BBInfo> MST;<br>
> +<br>
> +  // Give an edge, find the BB that will be instrumented.<br>
> +  // Return nullptr if there is no BB to be instrumented.<br>
> +  BasicBlock *getInstrBB(Edge *E);<br>
> +<br>
> +  // Return the auxiliary BB information.<br>
> +  BBInfo &getBBInfo(const BasicBlock *BB) const { return MST.getBBInfo(BB); }<br>
> +<br>
> +  // Dump edges and BB information.<br>
> +  void dumpInfo(std::string Str = "") const {<br>
> +    std::string Message = "Dump Function " + FuncName + " Hash: " +<br>
> +                          std::to_string(FunctionHash) + "\t" + Str;<br>
> +    MST.dumpEdges(dbgs(), Message);<br>
<br>
Would it make more sense for dumpEdges to take a Twine?<br>
<br>
> +  }<br>
> +<br>
> +  FuncPGOInstrumentation(Function &Func, bool CreateGlobalVar = false,<br>
> +                         BranchProbabilityInfo *BPI_ = nullptr,<br>
> +                         BlockFrequencyInfo *BFI_ = nullptr)<br>
> +      : F(Func), FunctionHash(0), MST(F, BPI_, BFI_) {<br>
<br>
No need for underscores in BPI_ and BFI_ - the shadowing is unambiguous.<br>
<br>
> +    FuncName = getPGOFuncName(F);<br>
> +    computeCFGHash();<br>
> +    DEBUG(dumpInfo("after CFGMST"));<br>
> +<br>
> +    NumOfPGOBB += MST.BBInfos.size();<br>
> +    for (auto &Ei : MST.AllEdges) {<br>
<br>
Why "Ei"? "E" for edge would be more typical.<br>
<br>
> +      if (Ei->Removed)<br>
> +        continue;<br>
> +      NumOfPGOEdge++;<br>
> +      if (!Ei->InMST)<br>
> +        NumOfPGOInstrument++;<br>
> +    }<br>
> +<br>
> +    if (CreateGlobalVar)<br>
> +      FuncNameVar = createPGOFuncNameVar(F, FuncName);<br>
> +  };<br>
> +};<br>
> +<br>
> +// Compute Hash value for the CFG: the lower 32 bits are CRC32 of the index<br>
> +// value of each BB in the CFG. The higher 32 bits record the number of edges.<br>
> +template <class Edge, class BBInfo><br>
> +void FuncPGOInstrumentation<Edge, BBInfo>::computeCFGHash() {<br>
> +  std::vector<char> Indexes;<br>
> +  JamCRC JC;<br>
> +  for (auto &BB : F) {<br>
> +    const TerminatorInst *TI = BB.getTerminator();<br>
> +    for (unsigned s = 0, e = TI->getNumSuccessors(); s != e; ++s) {<br>
> +      BasicBlock *Succ = TI->getSuccessor(s);<br>
> +      uint32_t Index = getBBInfo(Succ).Index;<br>
> +      for (int i = 0; i < 4; i++)<br>
> +        Indexes.push_back((char)(Index >> (i * 8)));<br>
> +    }<br>
> +  }<br>
> +  JC.update(Indexes);<br>
> +  FunctionHash = (uint64_t)MST.AllEdges.size() << 32 | JC.getCRC();<br>
> +}<br>
> +<br>
> +template <class Edge, class BBInfo><br>
> +BasicBlock *FuncPGOInstrumentation<Edge, BBInfo>::getInstrBB(Edge *E) {<br>
> +  if (E->InMST || E->Removed)<br>
> +    return nullptr;<br>
<span class="">> +<br>
> +  BasicBlock *SrcBB = const_cast<BasicBlock *>(E->SrcBB);<br>
> +  BasicBlock *DestBB = const_cast<BasicBlock *>(E->DestBB);<br>
</span>> +  // For a fake edge, instrument the real BB.<br>
> +  if (SrcBB == nullptr)<br>
> +    return DestBB;<br>
> +  if (DestBB == nullptr)<br>
> +    return SrcBB;<br>
> +<br>
> +  // Instrument the SrcBB if it has a single successor,<br>
> +  // otherwise, the DestBB if this is not a critical edge.<br>
> +  TerminatorInst *TI = SrcBB->getTerminator();<br>
> +  if (TI->getNumSuccessors() <= 1)<br>
> +    return SrcBB;<br>
> +  if (!E->IsCritical)<br>
> +    return DestBB;<br>
> +<br>
> +  // For a critical edge, we have to split. Instrument the newly<br>
> +  // created BB.<br>
> +  NumOfPGOSplit++;<br>
> +  DEBUG(dbgs() << "Split critical edge: " << getBBInfo(SrcBB).Index << " --> "<br>
> +               << getBBInfo(DestBB).Index << "\n");<br>
> +  unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);<br>
> +  BasicBlock *InstrBB = SplitCriticalEdge(TI, SuccNum);<br>
> +  assert(InstrBB && "Critical edge is not split");<br>
> +<br>
> +  E->Removed = true;<br>
> +  return InstrBB;<br>
> +}<br>
> +<br>
> +// Visit all edge and instrument the edges not in MST.<br>
> +// Critical edges will be split.<br>
> +static void instrumentOneFunc(Function &F, Module *M,<br>
> +                              BranchProbabilityInfo *BPI,<br>
> +                              BlockFrequencyInfo *BFI) {<br>
> +  unsigned NumCounters = 0;<br>
> +  FuncPGOInstrumentation<PGOEdge, BBInfo> FuncInfo(F, true, BPI, BFI);<br>
> +  for (auto &Ei : FuncInfo.MST.AllEdges) {<br>
> +    if (!Ei->InMST && !Ei->Removed)<br>
> +      NumCounters++;<br>
> +  }<br>
> +<br>
> +  uint32_t j = 0;<br>
<br>
The style says this should be a capital J (also, why not I?).<br>
<br>
> +  for (auto &Ei : FuncInfo.MST.AllEdges) {<br>
> +    BasicBlock *InstrBB = FuncInfo.getInstrBB(Ei.get());<br>
> +    if (!InstrBB)<br>
> +      continue;<br>
> +<br>
> +    IRBuilder<> Builder(InstrBB, InstrBB->getFirstInsertionPt());<br>
> +    assert(Builder.GetInsertPoint() != InstrBB->end() &&<br>
> +           "Cannot get the Instrumentation point");<br>
> +    auto *I8PtrTy = Type::getInt8PtrTy(M->getContext());<br>
<br>
Not worth using auto here, `Type` is the same number of characters.<br>
<br>
> +    Builder.CreateCall(<br>
> +        Intrinsic::getDeclaration(M, Intrinsic::instrprof_increment),<br>
> +        {llvm::ConstantExpr::getBitCast(FuncInfo.FuncNameVar, I8PtrTy),<br>
> +         Builder.getInt64(FuncInfo.FunctionHash), Builder.getInt32(NumCounters),<br>
> +         Builder.getInt32(j++)});<br>
> +  }<br>
> +}<br>
> +<br>
> +struct PGOUseEdge : public PGOEdge {<br>
> +  bool CountValid;<br>
> +  uint64_t CountValue;<br>
> +  PGOUseEdge(const BasicBlock *Src, const BasicBlock *Dest, unsigned W = 1)<br>
> +      : PGOEdge(Src, Dest, W), CountValid(false), CountValue(0) {}<br>
> +<br>
> +  // Set edge count value<br>
> +  void setEdgeCount(uint64_t Value) {<br>
> +    CountValue = Value;<br>
> +    CountValid = true;<br>
> +  }<br>
> +<br>
> +  // Return the information string for this object.<br>
> +  const std::string infoString() const {<br>
> +    if (!CountValid)<br>
> +      return PGOEdge::infoString();<br>
> +    return PGOEdge::infoString() + "  Count=" + std::to_string(CountValue);<br>
> +  }<br>
> +};<br>
> +<br>
> +typedef SmallVector<PGOUseEdge *, 2> DirectEdges;<br>
> +<br>
> +// This class stores the auxiliary information for each BB.<br>
> +struct UseBBInfo : public BBInfo {<br>
> +  uint64_t CountValue;<br>
> +  bool CountValid;<br>
> +  int32_t UnknownCountInEdge;<br>
> +  int32_t UnknownCountOutEdge;<br>
> +  DirectEdges InEdges;<br>
> +  DirectEdges OutEdges;<br>
> +  UseBBInfo(unsigned IX)<br>
> +      : BBInfo(IX), CountValue(0), CountValid(false), UnknownCountInEdge(0),<br>
> +        UnknownCountOutEdge(0) {}<br>
> +  UseBBInfo(unsigned IX, uint64_t C)<br>
> +      : BBInfo(IX), CountValue(C), CountValid(true), UnknownCountInEdge(0),<br>
> +        UnknownCountOutEdge(0) {}<br>
> +<br>
> +  // Set the profile count value for this BB.<br>
> +  void setBBInfoCount(uint64_t Value) {<br>
> +    CountValue = Value;<br>
> +    CountValid = true;<br>
> +  }<br>
> +<br>
> +  // Return the information string of this object.<br>
> +  const std::string infoString() const {<br>
> +    if (!CountValid)<br>
> +      return BBInfo::infoString();<br>
> +    return BBInfo::infoString() + "  Count=" + std::to_string(CountValue);<br>
> +  }<br>
> +};<br>
> +<br>
> +// Sum up the count values for all the edges.<br>
> +static uint64_t sumEdgeCount(const ArrayRef<PGOUseEdge *> Edges) {<br>
> +  uint64_t Total = 0;<br>
> +  for (auto &Ei : Edges) {<br>
> +    if (Ei->Removed)<br>
> +      continue;<br>
> +    Total += Ei->CountValue;<br>
> +  }<br>
> +  return Total;<br>
> +}<br>
> +<br>
> +class PGOUseFunc {<br>
> +private:<br>
> +  Function &F;<br>
> +  Module *M;<br>
> +  // This member stores the shared information with class PGOGenFunc.<br>
> +  FuncPGOInstrumentation<PGOUseEdge, UseBBInfo> FuncInfo;<br>
> +<br>
> +  // Return the auxiliary BB information.<br>
> +  UseBBInfo &getBBInfo(const BasicBlock *BB) const {<br>
> +    return FuncInfo.getBBInfo(BB);<br>
> +  }<br>
> +<br>
> +  // The maximum count value in the profile. This is only used in PGO use<br>
> +  // compilation.<br>
> +  uint64_t ProgramMaxCount;<br>
> +<br>
> +  // Find the Instrumented BB and set the value.<br>
> +  void setInstrumentedCounts(const std::vector<uint64_t> &CountFromProfile);<br>
> +<br>
> +  // Set the edge counter value for the unknown edge -- there should be only<br>
> +  // one unknown edge.<br>
> +  void setEdgeCount(DirectEdges &Edges, uint64_t Value);<br>
> +<br>
> +  // Return FuncName string;<br>
> +  const std::string getFuncName() const { return FuncInfo.FuncName; }<br>
> +<br>
> +  // Set the hot/cold inline hints based on the count values.<br>
> +  void applyFunctionAttributes(uint64_t EntryCount, uint64_t MaxCount) {<br>
> +    if (ProgramMaxCount == 0)<br>
> +      return;<br>
> +    // Threshold of the hot functions.<br>
> +    const BranchProbability HotFunctionThreshold(1, 100);<br>
> +    // Threshold of the cold functions.<br>
> +    const BranchProbability ColdFunctionThreshold(2, 10000);<br>
> +    if (EntryCount >= HotFunctionThreshold.scale(ProgramMaxCount))<br>
> +      F.addFnAttr(llvm::Attribute::InlineHint);<br>
> +    else if (MaxCount <= ColdFunctionThreshold.scale(ProgramMaxCount))<br>
> +      F.addFnAttr(llvm::Attribute::Cold);<br>
<br>
This is more or less a workaround for limitations of the inliner and<br>
should eventually be removed in favour of making the inliner smarter,<br>
correct?<br></blockquote><div><br></div><div>This is to mimic what the Clang PGO is doing. Once inliner uses the profile information. all these should be gone. </div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<br>
> +  }<br>
> +<br>
> +public:<br>
> +  PGOUseFunc(Function &Func, Module *Modu,<br>
> +             BranchProbabilityInfo *BPI_ = nullptr,<br>
> +             BlockFrequencyInfo *BFI_ = nullptr)<br>
> +      : F(Func), M(Modu), FuncInfo(Func, false, BPI_, BFI_) {}<br>
> +<br>
> +  // Read counts for the instrumented BB from profile.<br>
> +  bool readCounters(IndexedInstrProfReader *PGOReader);<br>
> +<br>
> +  // Populate the counts for all BBs.<br>
> +  void populateCounters();<br>
> +<br>
> +  // Set the branch weights based on the count values.<br>
> +  void setBranchWeights();<br>
> +};<br>
> +<br>
> +// Visit all the edges and assign the count value for the instrumented<br>
> +// edges and the BB.<br>
> +void PGOUseFunc::setInstrumentedCounts(<br>
> +    const std::vector<uint64_t> &CountFromProfile) {<br>
> +<br>
> +  // Use a worklist as we will update the vector during the iteration.<br>
> +  std::vector<PGOUseEdge *> WorkList;<br>
> +  for (auto &Ei : FuncInfo.MST.AllEdges)<br>
> +    WorkList.push_back(Ei.get());<br>
> +<br>
> +  uint32_t j = 0;<br>
> +  for (auto &Ei : WorkList) {<br>
<br>
Same as before: j->J, Ei->E.<br>
<br>
> +    BasicBlock *InstrBB = FuncInfo.getInstrBB(Ei);<br>
> +    if (!InstrBB)<br>
> +      continue;<br>
> +    uint64_t CountValue = CountFromProfile[j++];<br>
> +    if (!Ei->Removed) {<br>
> +      getBBInfo(InstrBB).setBBInfoCount(CountValue);<br>
> +      Ei->setEdgeCount(CountValue);<br>
> +      continue;<br>
> +    }<br>
> +<br>
> +    // Need to add two new edges.<br>
> +    BasicBlock *SrcBB = const_cast<BasicBlock *>(Ei->SrcBB);<br>
> +    BasicBlock *DestBB = const_cast<BasicBlock *>(Ei->DestBB);<br>
> +    // Add new edge of SrcBB->InstrBB.<br>
> +    PGOUseEdge &NewEdge = FuncInfo.MST.addEdge(SrcBB, InstrBB, 0);<br>
> +    NewEdge.setEdgeCount(CountValue);<br>
> +    // Add new edge of InstrBB->DestBB.<br>
> +    PGOUseEdge &NewEdge1 = FuncInfo.MST.addEdge(InstrBB, DestBB, 0);<br>
<br>
Why not just reuse the NewEdge variable here?<br></blockquote><div><br></div><div>addEdge() returns a reference.  If I use the same variable name, it overwrites the previous edge rather adding a new edge.<br></div><div><br></div><blockquote class="gmail_quote" style="margin:0 0 0 .8ex;border-left:1px #ccc solid;padding-left:1ex">
<br>
> +    NewEdge1.setEdgeCount(CountValue);<br>
> +    NewEdge1.InMST = true;<br>
> +    getBBInfo(InstrBB).setBBInfoCount(CountValue);<br>
> +  }<br>
> +}<br>
> +<br>
> +// Set the count value for the unknown edge. There should be one and only one<br>
<span class="">> +// unknown edge in Edges vector.<br>
</span>> +void PGOUseFunc::setEdgeCount(DirectEdges &Edges, uint64_t Value) {<br>
> +  for (auto &Ei : Edges) {<br>
> +    if (Ei->CountValid)<br>
> +      continue;<br>
> +    Ei->setEdgeCount(Value);<br>
> +<br>
> +    getBBInfo(Ei->SrcBB).UnknownCountOutEdge--;<br>
> +    getBBInfo(Ei->DestBB).UnknownCountInEdge--;<br>
> +    return;<br>
> +  }<br>
> +  llvm_unreachable("Cannot find the unknown count edge");<br>
> +}<br>
> +<br>
> +// Read the profile from ProfileFileName and assign the value to the<br>
> +// instrumented BB and the edges. This function also updates ProgramMaxCount.<br>
> +// Return true if the profile are successfully read, and false on errors.<br>
> +bool PGOUseFunc::readCounters(IndexedInstrProfReader *PGOReader) {<br>
> +  auto &Ctx = M->getContext();<br>
> +  ErrorOr<InstrProfRecord> Result =<br>
> +      PGOReader->getInstrProfRecord(FuncInfo.FuncName, FuncInfo.FunctionHash);<br>
> +  if (std::error_code EC = Result.getError()) {<br>
> +    if (EC == instrprof_error::unknown_function)<br>
> +      NumOfPGOMissing++;<br>
> +    else if (EC == instrprof_error::hash_mismatch ||<br>
> +             EC == llvm::instrprof_error::malformed)<br>
> +      NumOfPGOMismatch++;<br>
> +<br>
> +    std::string Msg = EC.message() + std::string(" ") + F.getName().str();<br>
> +    Ctx.diagnose(<br>
> +        DiagnosticInfoPGOProfile(M->getName().data(), Msg, DS_Warning));<br>
> +    return false;<br>
> +  }<br>
> +  std::vector<uint64_t> &CountFromProfile = Result.get().Counts;<br>
> +<br>
> +  NumOfPGOFunc++;<br>
> +  DEBUG(dbgs() << CountFromProfile.size() << " counts\n");<br>
> +  uint64_t ValueSum = 0;<br>
> +  for (unsigned i = 0, e = CountFromProfile.size(); i < e; i++) {<br>
> +    DEBUG(dbgs() << "  " << i << ": " << CountFromProfile[i] << "\n");<br>
> +    ValueSum += CountFromProfile[i];<br>
> +  }<br>
> +<br>
> +  DEBUG(dbgs() << "SUM =  " << ValueSum << "\n");<br>
> +<br>
> +  getBBInfo(nullptr).UnknownCountOutEdge = 2;<br>
> +  getBBInfo(nullptr).UnknownCountInEdge = 2;<br>
> +<br>
> +  setInstrumentedCounts(CountFromProfile);<br>
> +  ProgramMaxCount = PGOReader->getMaximumFunctionCount();<br>
> +  return true;<br>
> +}<br>
> +<br>
> +// Populate the counters from instrumented BBs to all BBs.<br>
> +// In the end of this operation, all BBs should have a valid count value.<br>
> +void PGOUseFunc::populateCounters() {<br>
> +  // First set up Count variable for all BBs.<br>
> +  for (auto &Ei : FuncInfo.MST.AllEdges) {<br>
> +    if (Ei->Removed)<br>
> +      continue;<br>
> +<br>
> +    const BasicBlock *SrcBB = Ei->SrcBB;<br>
> +    const BasicBlock *DestBB = Ei->DestBB;<br>
> +    UseBBInfo &SrcInfo = getBBInfo(SrcBB);<br>
> +    UseBBInfo &DestInfo = getBBInfo(DestBB);<br>
> +    SrcInfo.OutEdges.push_back(Ei.get());<br>
> +    DestInfo.InEdges.push_back(Ei.get());<br>
> +    SrcInfo.UnknownCountOutEdge++;<br>
> +    DestInfo.UnknownCountInEdge++;<br>
> +<br>
> +    if (!Ei->CountValid)<br>
> +      continue;<br>
> +    DestInfo.UnknownCountInEdge--;<br>
> +    SrcInfo.UnknownCountOutEdge--;<br>
> +  }<br>
> +<br>
> +  bool Changes = true;<br>
> +  unsigned NumPasses = 0;<br>
> +  while (Changes) {<br>
> +    NumPasses++;<br>
> +    Changes = false;<br>
> +<br>
> +    // For efficient traversal, it's better to start from the end as most<br>
> +    // of the instrumented edges are at the end.<br>
> +    for (auto &BB : reverse(F)) {<br>
> +      UseBBInfo &Count = getBBInfo(&BB);<br>
> +      if (!Count.CountValid) {<br>
> +        if (Count.UnknownCountOutEdge == 0) {<br>
> +          Count.CountValue = sumEdgeCount(Count.OutEdges);<br>
> +          Count.CountValid = true;<br>
> +          Changes = true;<br>
> +        } else if (Count.UnknownCountInEdge == 0) {<br>
> +          Count.CountValue = sumEdgeCount(Count.InEdges);<br>
> +          Count.CountValid = true;<br>
> +          Changes = true;<br>
> +        }<br>
> +      }<br>
> +      if (Count.CountValid) {<br>
> +        if (Count.UnknownCountOutEdge == 1) {<br>
> +          uint64_t Total = Count.CountValue - sumEdgeCount(Count.OutEdges);<br>
> +          setEdgeCount(Count.OutEdges, Total);<br>
> +          Changes = true;<br>
> +        }<br>
> +        if (Count.UnknownCountInEdge == 1) {<br>
> +          uint64_t Total = Count.CountValue - sumEdgeCount(Count.InEdges);<br>
> +          setEdgeCount(Count.InEdges, Total);<br>
> +          Changes = true;<br>
> +        }<br>
> +      }<br>
> +    }<br>
> +  }<br>
> +<br>
> +  DEBUG(dbgs() << "Populate counts in " << NumPasses << " passes.\n");<br>
> +  // Assert every BB has a valid counter.<br>
> +  uint64_t FuncEntryCount = getBBInfo(&*F.begin()).CountValue;<br>
> +  uint64_t FuncMaxCount = FuncEntryCount;<br>
> +  for (auto &BB : F) {<br>
> +    assert(getBBInfo(&BB).CountValid && "BB count is not valid");<br>
> +    uint64_t Count = getBBInfo(&BB).CountValue;<br>
> +    if (Count > FuncMaxCount)<br>
> +      FuncMaxCount = Count;<br>
> +  }<br>
> +  applyFunctionAttributes(FuncEntryCount, FuncMaxCount);<br>
> +<br>
> +  DEBUG(FuncInfo.dumpInfo("after reading profile."));<br>
> +}<br>
> +<br>
> +// Assign the scaled count values to the BB with multiple out edges.<br>
> +void PGOUseFunc::setBranchWeights() {<br>
> +  // Generate MD_prof metadata for every branch instruction.<br>
> +  DEBUG(dbgs() << "\nSetting branch weights.\n");<br>
> +  MDBuilder MDB(M->getContext());<br>
> +  for (auto &BB : F) {<br>
> +    TerminatorInst *TI = BB.getTerminator();<br>
> +    if (TI->getNumSuccessors() < 2)<br>
> +      continue;<br>
> +    if (!isa<BranchInst>(TI) && !isa<SwitchInst>(TI))<br>
> +      continue;<br>
> +    if (getBBInfo(&BB).CountValue == 0)<br>
> +      continue;<br>
> +<br>
> +    // We have a non-zero Branch BB.<br>
> +    const UseBBInfo &BBCountInfo = getBBInfo(&BB);<br>
> +    unsigned Size = BBCountInfo.OutEdges.size();<br>
> +    SmallVector<unsigned, 2> EdgeCounts(Size, 0);<br>
> +    uint64_t MaxCount = 0;<br>
> +    for (unsigned s = 0; s < Size; s++) {<br>
> +      const PGOUseEdge *E = BBCountInfo.OutEdges[s];<br>
> +      const BasicBlock *SrcBB = E->SrcBB;<br>
> +      const BasicBlock *DestBB = E->DestBB;<br>
> +      if (DestBB == 0)<br>
> +        continue;<br>
> +      unsigned SuccNum = GetSuccessorNumber(SrcBB, DestBB);<br>
> +      uint64_t EdgeCount = E->CountValue;<br>
> +      if (EdgeCount > MaxCount)<br>
> +        MaxCount = EdgeCount;<br>
> +      EdgeCounts[SuccNum] = EdgeCount;<br>
> +    }<br>
> +    assert(MaxCount > 0 && "Bad max count");<br>
> +    uint64_t Scale = calculateCountScale(MaxCount);<br>
> +    SmallVector<unsigned, 4> Weights;<br>
> +    for (const auto &ECI : EdgeCounts)<br>
> +      Weights.push_back(scaleBranchCount(ECI, Scale));<br>
> +<br>
> +    TI->setMetadata(llvm::LLVMContext::MD_prof,<br>
> +                    MDB.createBranchWeights(Weights));<br>
> +    DEBUG(dbgs() << "Weight is: "; for (const auto &W<br>
> +                                        : Weights) dbgs()<br>
> +                                   << W << " ";<br>
> +          dbgs() << "\n";);<br>
<br>
This is formatted really strangely. It's possible that clang-format<br>
doesn't know how to deal with this code-in-DEBUG() stuff and you just<br>
need to format this manually (or file a bug on clang-format ;)<br>
<br>
> +  }<br>
> +}<br>
> +} // end anonymous namespace<br>
> +<br>
> +bool PGOInstrumentationGen::runOnModule(Module &M) {<br>
> +  for (auto &F : M) {<br>
> +    if (F.isDeclaration())<br>
> +      continue;<br>
> +    BranchProbabilityInfo *BPI =<br>
> +        &(getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI());<br>
> +    BlockFrequencyInfo *BFI =<br>
> +        &(getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI());<br>
> +    instrumentOneFunc(F, &M, BPI, BFI);<br>
> +  }<br>
> +  return true;<br>
> +}<br>
> +<br>
> +static void setPGOCountOnFunc(PGOUseFunc &Func,<br>
> +                              IndexedInstrProfReader *PGOReader) {<br>
> +  if (Func.readCounters(PGOReader)) {<br>
> +    Func.populateCounters();<br>
> +    Func.setBranchWeights();<br>
> +  }<br>
> +}<br>
> +<br>
> +bool PGOInstrumentationUse::runOnModule(Module &M) {<br>
> +  DEBUG(dbgs() << "Read in profile counters: ");<br>
> +  auto &Ctx = M.getContext();<br>
> +  // Read the counter array from file.<br>
> +  auto ReaderOrErr = IndexedInstrProfReader::create(ProfileFileName);<br>
> +  if (std::error_code EC = ReaderOrErr.getError()) {<br>
> +    Ctx.diagnose(<br>
> +        DiagnosticInfoPGOProfile(ProfileFileName.data(), EC.message()));<br>
> +    return false;<br>
> +  }<br>
> +<br>
> +  PGOReader = std::move(ReaderOrErr.get());<br>
> +  if (!PGOReader) {<br>
> +    Ctx.diagnose(DiagnosticInfoPGOProfile(ProfileFileName.data(),<br>
> +                                          "Cannot get PGOReader"));<br>
> +    return false;<br>
> +  }<br>
> +<br>
> +  for (auto &F : M) {<br>
> +    if (F.isDeclaration())<br>
> +      continue;<br>
> +    BranchProbabilityInfo *BPI =<br>
> +        &(getAnalysis<BranchProbabilityInfoWrapperPass>(F).getBPI());<br>
> +    BlockFrequencyInfo *BFI =<br>
> +        &(getAnalysis<BlockFrequencyInfoWrapperPass>(F).getBFI());<br>
> +    PGOUseFunc Func(F, &M, BPI, BFI);<br>
> +    setPGOCountOnFunc(Func, PGOReader.get());<br>
> +  }<br>
> +  return true;<br>
> +}<br>
> Index: lib/Transforms/Instrumentation/LLVMBuild.txt<br>
> ===================================================================<br>
> --- lib/Transforms/Instrumentation/LLVMBuild.txt<br>
> +++ lib/Transforms/Instrumentation/LLVMBuild.txt<br>
> @@ -19,4 +19,4 @@<br>
>  type = Library<br>
>  name = Instrumentation<br>
>  parent = Transforms<br>
> -required_libraries = Analysis Core MC Support TransformUtils<br>
> +required_libraries = Analysis Core MC Support TransformUtils ProfileData<br>
> Index: lib/Transforms/Instrumentation/Instrumentation.cpp<br>
> ===================================================================<br>
> --- lib/Transforms/Instrumentation/Instrumentation.cpp<br>
> +++ lib/Transforms/Instrumentation/Instrumentation.cpp<br>
> @@ -60,6 +60,8 @@<br>
>    initializeAddressSanitizerModulePass(Registry);<br>
>    initializeBoundsCheckingPass(Registry);<br>
>    initializeGCOVProfilerPass(Registry);<br>
> +  initializePGOInstrumentationGenPass(Registry);<br>
> +  initializePGOInstrumentationUsePass(Registry);<br>
>    initializeInstrProfilingPass(Registry);<br>
>    initializeMemorySanitizerPass(Registry);<br>
>    initializeThreadSanitizerPass(Registry);<br>
> Index: lib/Transforms/Instrumentation/CMakeLists.txt<br>
> ===================================================================<br>
> --- lib/Transforms/Instrumentation/CMakeLists.txt<br>
> +++ lib/Transforms/Instrumentation/CMakeLists.txt<br>
> @@ -6,6 +6,7 @@<br>
>    MemorySanitizer.cpp<br>
>    Instrumentation.cpp<br>
>    InstrProfiling.cpp<br>
> +  PGOInstrumentation.cpp<br>
>    SafeStack.cpp<br>
>    SanitizerCoverage.cpp<br>
>    ThreadSanitizer.cpp<br>
> Index: lib/Transforms/Instrumentation/CFGMST.h<br>
> ===================================================================<br>
> --- /dev/null<br>
> +++ lib/Transforms/Instrumentation/CFGMST.h<br>
> @@ -0,0 +1,211 @@<br>
> +//===-- CFGMST.h - Minimum Spanning Tree for CFG -------*- C++ -*-===//<br>
> +//<br>
> +//                      The LLVM Compiler Infrastructure<br>
> +//<br>
> +// This file is distributed under the University of Illinois Open Source<br>
> +// License. See LICENSE.TXT for details.<br>
> +//<br>
> +//===----------------------------------------------------------------------===//<br>
> +//<br>
> +// This file implements Union-find algorithm to compute Minimum Spanning Tree<br>
> +// for a given CFG.<br>
> +//<br>
> +//===----------------------------------------------------------------------===//<br>
> +<br>
> +#include "llvm/ADT/DenseMap.h"<br>
> +#include "llvm/ADT/STLExtras.h"<br>
> +#include "llvm/Analysis/BlockFrequencyInfo.h"<br>
> +#include "llvm/Analysis/BranchProbabilityInfo.h"<br>
> +#include "llvm/Analysis/CFG.h"<br>
> +#include "llvm/Support/BranchProbability.h"<br>
> +#include "llvm/Support/Debug.h"<br>
> +#include "llvm/Support/raw_ostream.h"<br>
> +#include "llvm/Transforms/Utils/BasicBlockUtils.h"<br>
> +#include <string><br>
> +#include <utility><br>
> +#include <vector><br>
> +<br>
> +namespace llvm {<br>
> +<br>
> +#define DEBUG_TYPE "cfgmst"<br>
> +<br>
> +template <class Edge, class BBInfo> class CFGMST {<br>
> +public:<br>
> +  Function &F;<br>
> +<br>
> +  // Store all the edges in CFG. It may contain some stale edges<br>
> +  // when Removed is set.<br>
<br>
Might as well use doc comments here.<br>
<br>
> +  std::vector<std::unique_ptr<Edge>> AllEdges;<br>
> +<br>
> +  // This map records the auxiliary information for each BB.<br>
> +  DenseMap<const BasicBlock *, std::unique_ptr<BBInfo>> BBInfos;<br>
> +<br>
> +  // Find the root group of the G and compress the path from G to the root.<br>
> +  BBInfo *findAndCompressGroup(BBInfo *G) {<br>
> +    if (G->Group != G)<br>
> +      G->Group = findAndCompressGroup(static_cast<BBInfo *>(G->Group));<br>
> +    return static_cast<BBInfo *>(G->Group);<br>
> +  }<br>
> +<br>
> +  // Union BB1 and BB2 into the same group and return true.<br>
> +  // Returns false if BB1 and BB2 are already in the same group.<br>
> +  bool unionGroups(const BasicBlock *BB1, const BasicBlock *BB2) {<br>
> +    BBInfo *BB1G = findAndCompressGroup(&getBBInfo(BB1));<br>
> +    BBInfo *BB2G = findAndCompressGroup(&getBBInfo(BB2));<br>
> +<br>
> +    if (BB1G == BB2G)<br>
> +      return false;<br>
> +<br>
> +    // Make the smaller rank tree a direct child or the root of high rank tree.<br>
> +    if (BB1G->Rank < BB2G->Rank)<br>
> +      BB1G->Group = BB2G;<br>
> +    else {<br>
> +      BB2G->Group = BB1G;<br>
> +      // If the ranks are the same, increment root of one tree by one.<br>
> +      if (BB1G->Rank == BB2G->Rank)<br>
> +        BB1G->Rank++;<br>
> +    }<br>
> +    return true;<br>
> +  }<br>
> +<br>
> +  // Give BB, return the auxiliary information.<br>
> +  BBInfo &getBBInfo(const BasicBlock *BB) const {<br>
> +    auto It = BBInfos.find(BB);<br>
> +    assert(It->second.get() != nullptr);<br>
> +    return *It->second.get();<br>
> +  }<br>
> +<br>
> +  // Traverse the CFG using a stack. Find all the edges and assign the weight.<br>
> +  // Edges with large weight will be put into MST first so they are less likely<br>
> +  // to be instrumented.<br>
> +  void buildEdges() {<br>
> +    DEBUG(dbgs() << "Build Edge on " << F.getName() << "\n");<br>
> +<br>
> +    const BasicBlock *BB = &(F.getEntryBlock());<br>
> +    // Add a fake edge to the entry.<br>
> +    addEdge(nullptr, BB, BFI->getEntryFreq());<br>
> +<br>
> +    // Special handling for single BB functions.<br>
> +    if (succ_empty(BB)) {<br>
> +      addEdge(BB, nullptr, BFI->getEntryFreq());<br>
> +      return;<br>
> +    }<br>
> +<br>
> +    static const uint32_t CriticalEdgeMultiplier = 1000;<br>
> +<br>
> +    for (Function::iterator BB = F.begin(), E = F.end(); BB != E; ++BB) {<br>
> +      TerminatorInst *TI = BB->getTerminator();<br>
> +      uint64_t BBWeight = BFI->getBlockFreq(&*BB).getFrequency();<br>
> +      uint64_t Weight;<br>
> +      if (int successors = TI->getNumSuccessors()) {<br>
> +        for (int i = 0; i != successors; ++i) {<br>
> +          BasicBlock *TargetBB = TI->getSuccessor(i);<br>
> +          bool Critical = isCriticalEdge(TI, i);<br>
> +          uint64_t scaleFactor = BBWeight;<br>
> +          if (Critical) {<br>
> +            if (scaleFactor < UINT64_MAX / CriticalEdgeMultiplier)<br>
> +              scaleFactor *= CriticalEdgeMultiplier;<br>
> +            else<br>
> +              scaleFactor = UINT64_MAX;<br>
> +          }<br>
> +          Weight = BPI->getEdgeProbability(&*BB, TargetBB).scale(scaleFactor);<br>
> +          addEdge(&*BB, TargetBB, Weight).IsCritical = Critical;<br>
> +          DEBUG(dbgs() << "  Edge: from " << BB->getName() << " to "<br>
> +                       << TargetBB->getName() << "  w=" << Weight << "\n");<br>
> +        }<br>
> +      } else {<br>
> +        addEdge(&*BB, nullptr, BBWeight);<br>
> +        DEBUG(dbgs() << "  Edge: from " << BB->getName() << " to exit"<br>
> +                     << " w = " << BBWeight << "\n");<br>
> +      }<br>
> +    }<br>
> +  }<br>
> +<br>
> +  // Sort CFG edges based on its weight.<br>
> +  void sortEdgesByWeight() {<br>
> +    std::stable_sort(<br>
> +        AllEdges.begin(), AllEdges.end(),<br>
> +        [](const std::unique_ptr<Edge> &Edge1, const std::unique_ptr<Edge> &Edge2) {<br>
> +          return Edge1->Weight > Edge2->Weight;<br>
> +        });<br>
> +  }<br>
> +<br>
> +  // Traverse all the edges and compute the Minimum Weight Spanning Tree<br>
> +  // using union-find algorithm.<br>
> +  void computeMinimumSpanningTree() {<br>
> +    // First, put all the critical edge with landing-pad as the Dest to MST.<br>
> +    // This works around the insufficient support of critical edges split<br>
> +    // when destination BB is a landing pad.<br>
> +    for (auto &Ei : AllEdges) {<br>
> +      if (Ei->Removed)<br>
> +        continue;<br>
> +      if (Ei->IsCritical) {<br>
> +        if (Ei->DestBB && Ei->DestBB->isLandingPad()) {<br>
> +          if (unionGroups(Ei->SrcBB, Ei->DestBB))<br>
> +            Ei->InMST = true;<br>
> +        }<br>
> +      }<br>
> +    }<br>
> +<br>
> +    for (auto &Ei : AllEdges) {<br>
> +      if (Ei->Removed)<br>
> +        continue;<br>
> +      if (unionGroups(Ei->SrcBB, Ei->DestBB))<br>
> +        Ei->InMST = true;<br>
> +    }<br>
> +  }<br>
> +<br>
> +  // Dump the Debug information about the instrumentation.<br>
> +  void dumpEdges(raw_ostream &OS, const StringRef Message = StringRef()) const {<br>
> +    if (!Message.empty())<br>
> +      OS << Message << "\n";<br>
> +    OS << "  Number of Basic Blocks: " << BBInfos.size() << "\n";<br>
> +    for (auto &BI : BBInfos) {<br>
> +      const BasicBlock *BB = BI.first;<br>
> +      OS << "  BB: " << (BB == nullptr ? "FakeNode" : BB->getName()) << "  "<br>
> +         << BI.second->infoString() << "\n";<br>
> +    }<br>
> +<br>
> +    OS << "  Number of Edges: " << AllEdges.size()<br>
> +       << " (*: Instrument, C: CriticalEdge, -: Removed)\n";<br>
> +    uint32_t Count = 0;<br>
> +    for (auto &EI : AllEdges) {<br>
> +      OS << "  Edge " << Count++ << ": " << getBBInfo(EI->SrcBB).Index << "-->"<br>
> +         << getBBInfo(EI->DestBB).Index << EI->infoString() << "\n";<br>
> +    };<br>
> +  }<br>
> +<br>
> +  // Add an edge to AllEdges with weight W.<br>
> +  Edge &addEdge(const BasicBlock *Src, const BasicBlock *Dest, uint64_t W) {<br>
> +    uint32_t Index = BBInfos.size();<br>
> +    auto Iter = BBInfos.end();<br>
> +    bool Inserted;<br>
> +    std::tie(Iter, Inserted) = BBInfos.insert(std::make_pair(Src, nullptr));<br>
> +    if (Inserted) {<br>
> +      // Newly inserted, update the real info.<br>
> +      Iter->second = std::move(llvm::make_unique<BBInfo>(Index));<br>
> +      Index++;<br>
> +    }<br>
> +    std::tie(Iter, Inserted) = BBInfos.insert(std::make_pair(Dest, nullptr));<br>
> +    if (Inserted)<br>
> +      // Newly inserted, update the real info.<br>
> +      Iter->second = std::move(llvm::make_unique<BBInfo>(Index));<br>
> +    AllEdges.emplace_back(new Edge(Src, Dest, W));<br>
> +    return *AllEdges.back();<br>
> +  }<br>
> +<br>
> +  BranchProbabilityInfo *BPI;<br>
> +  BlockFrequencyInfo *BFI;<br>
> +<br>
> +public:<br>
> +  CFGMST(Function &Func, BranchProbabilityInfo *BPI_ = nullptr,<br>
> +         BlockFrequencyInfo *BFI_ = nullptr)<br>
> +      : F(Func), BPI(BPI_), BFI(BFI_) {<br>
> +    buildEdges();<br>
> +    sortEdgesByWeight();<br>
> +    computeMinimumSpanningTree();<br>
> +  }<br>
> +};<br>
> +<br>
> +#undef DEBUG_TYPE // "cfgmst"<br>
> +} // end namespace llvm<br>
> Index: lib/IR/DiagnosticInfo.cpp<br>
> ===================================================================<br>
> --- lib/IR/DiagnosticInfo.cpp<br>
> +++ lib/IR/DiagnosticInfo.cpp<br>
> @@ -132,6 +132,12 @@<br>
>    DP << getMsg();<br>
>  }<br>
><br>
> +void DiagnosticInfoPGOProfile::print(DiagnosticPrinter &DP) const {<br>
> +  if (getFileName())<br>
> +    DP << getFileName() << ": ";<br>
> +  DP << getMsg();<br>
> +}<br>
> +<br>
>  bool DiagnosticInfoOptimizationBase::isLocationAvailable() const {<br>
>    return getDebugLoc();<br>
>  }<br>
> Index: include/llvm/Transforms/Instrumentation.h<br>
> ===================================================================<br>
> --- include/llvm/Transforms/Instrumentation.h<br>
> +++ include/llvm/Transforms/Instrumentation.h<br>
> @@ -79,6 +79,11 @@<br>
>  ModulePass *createGCOVProfilerPass(const GCOVOptions &Options =<br>
>                                     GCOVOptions::getDefault());<br>
><br>
> +// PGO Instrumention<br>
> +ModulePass *createPGOInstrumentationGenPass();<br>
> +ModulePass *<br>
> +createPGOInstrumentationUsePass(StringRef Filename = StringRef(""));<br>
> +<br>
>  /// Options for the frontend instrumentation based profiling pass.<br>
>  struct InstrProfOptions {<br>
>    InstrProfOptions() : NoRedZone(false) {}<br>
> @@ -149,6 +154,24 @@<br>
>  /// protect against stack-based overflow vulnerabilities.<br>
>  FunctionPass *createSafeStackPass(const TargetMachine *TM = nullptr);<br>
><br>
> +/// \brief Calculate what to divide by to scale counts.<br>
> +///<br>
> +/// Given the maximum count, calculate a divisor that will scale all the<br>
> +/// weights to strictly less than UINT32_MAX.<br>
> +static inline uint64_t calculateCountScale(uint64_t MaxCount) {<br>
> +  return MaxCount < UINT32_MAX ? 1 : MaxCount / UINT32_MAX + 1;<br>
> +}<br>
> +<br>
> +/// \brief Scale an individual branch count.<br>
> +///<br>
> +/// Scale a 64-bit weight down to 32-bits using \c Scale.<br>
> +///<br>
> +static inline uint32_t scaleBranchCount(uint64_t Count, uint64_t Scale) {<br>
> +  uint64_t Scaled = Count / Scale;<br>
> +  assert(Scaled <= UINT32_MAX && "overflow 32-bits");<br>
> +  return Scaled;<br>
> +}<br>
> +<br>
>  } // End llvm namespace<br>
><br>
>  #endif<br>
> Index: include/llvm/LinkAllPasses.h<br>
> ===================================================================<br>
> --- include/llvm/LinkAllPasses.h<br>
> +++ include/llvm/LinkAllPasses.h<br>
> @@ -85,6 +85,8 @@<br>
>        (void) llvm::createDomOnlyViewerPass();<br>
>        (void) llvm::createDomViewerPass();<br>
>        (void) llvm::createGCOVProfilerPass();<br>
> +      (void) llvm::createPGOInstrumentationGenPass();<br>
> +      (void) llvm::createPGOInstrumentationUsePass();<br>
>        (void) llvm::createInstrProfilingPass();<br>
>        (void) llvm::createFunctionInliningPass();<br>
>        (void) llvm::createAlwaysInlinerPass();<br>
> Index: include/llvm/InitializePasses.h<br>
> ===================================================================<br>
> --- include/llvm/InitializePasses.h<br>
> +++ include/llvm/InitializePasses.h<br>
> @@ -117,6 +117,8 @@<br>
>  void initializeExpandPostRAPass(PassRegistry&);<br>
>  void initializeAAResultsWrapperPassPass(PassRegistry &);<br>
>  void initializeGCOVProfilerPass(PassRegistry&);<br>
> +void initializePGOInstrumentationGenPass(PassRegistry&);<br>
> +void initializePGOInstrumentationUsePass(PassRegistry&);<br>
>  void initializeInstrProfilingPass(PassRegistry&);<br>
>  void initializeAddressSanitizerPass(PassRegistry&);<br>
>  void initializeAddressSanitizerModulePass(PassRegistry&);<br>
> Index: include/llvm/IR/DiagnosticInfo.h<br>
> ===================================================================<br>
> --- include/llvm/IR/DiagnosticInfo.h<br>
> +++ include/llvm/IR/DiagnosticInfo.h<br>
> @@ -60,6 +60,7 @@<br>
>    DK_OptimizationRemarkAnalysisAliasing,<br>
>    DK_OptimizationFailure,<br>
>    DK_MIRParser,<br>
> +  DK_PGOProfile,<br>
>    DK_FirstPluginKind<br>
>  };<br>
><br>
> @@ -250,6 +251,31 @@<br>
>    const Twine &Msg;<br>
>  };<br>
><br>
> +/// Diagnostic information for the PGO profiler.<br>
> +class DiagnosticInfoPGOProfile : public DiagnosticInfo {<br>
> +public:<br>
> +  DiagnosticInfoPGOProfile(const char *FileName, const Twine &Msg,<br>
> +                           DiagnosticSeverity Severity = DS_Error)<br>
> +      : DiagnosticInfo(DK_PGOProfile, Severity), FileName(FileName), Msg(Msg) {}<br>
> +<br>
> +  /// \see DiagnosticInfo::print.<br>
> +  void print(DiagnosticPrinter &DP) const override;<br>
> +<br>
> +  static bool classof(const DiagnosticInfo *DI) {<br>
> +    return DI->getKind() == DK_PGOProfile;<br>
> +  }<br>
> +<br>
> +  const char *getFileName() const { return FileName; }<br>
> +  const Twine &getMsg() const { return Msg; }<br>
> +<br>
> +private:<br>
> +  /// Name of the input file associated with this diagnostic.<br>
> +  const char *FileName;<br>
> +<br>
> +  /// Message to report.<br>
> +  const Twine &Msg;<br>
> +};<br>
> +<br>
>  /// Common features for diagnostics dealing with optimization remarks.<br>
>  class DiagnosticInfoOptimizationBase : public DiagnosticInfo {<br>
>  public:<br>
</blockquote></div><br></div></div></div>