@@ -409,6 +409,9 @@ BRANCH_TO_GUARD[4][2] = {
409409
410410#define TRACE_STACK_SIZE 5
411411
412+ #define CONFIDENCE_RANGE 1000
413+ #define CONFIDENCE_CUTOFF 333
414+
412415/* Returns 1 on success,
413416 * 0 if it failed to produce a worthwhile trace,
414417 * and -1 on an error.
@@ -431,6 +434,7 @@ translate_bytecode_to_trace(
431434 _Py_CODEUNIT * instr ;
432435 } trace_stack [TRACE_STACK_SIZE ];
433436 int trace_stack_depth = 0 ;
437+ int confidence = CONFIDENCE_RANGE ; // Adjusted by branch instructions
434438
435439#ifdef Py_DEBUG
436440 char * python_lltrace = Py_GETENV ("PYTHON_LLTRACE" );
@@ -513,7 +517,6 @@ translate_bytecode_to_trace(
513517 uint32_t oparg = instr -> op .arg ;
514518 uint32_t extras = 0 ;
515519
516-
517520 if (opcode == EXTENDED_ARG ) {
518521 instr ++ ;
519522 extras += 1 ;
@@ -543,11 +546,22 @@ translate_bytecode_to_trace(
543546 int counter = instr [1 ].cache ;
544547 int bitcount = _Py_popcount32 (counter );
545548 int jump_likely = bitcount > 8 ;
549+ if (jump_likely ) {
550+ confidence = confidence * bitcount / 16 ;
551+ }
552+ else {
553+ confidence = confidence * (16 - bitcount ) / 16 ;
554+ }
555+ if (confidence < CONFIDENCE_CUTOFF ) {
556+ DPRINTF (2 , "Confidence too low (%d)\n" , confidence );
557+ OPT_STAT_INC (low_confidence );
558+ goto done ;
559+ }
546560 uint32_t uopcode = BRANCH_TO_GUARD [opcode - POP_JUMP_IF_FALSE ][jump_likely ];
547561 _Py_CODEUNIT * next_instr = instr + 1 + _PyOpcode_Caches [_PyOpcode_Deopt [opcode ]];
548- DPRINTF (4 , "%s(%d): counter=%x, bitcount=%d, likely=%d, uopcode=%s\n" ,
562+ DPRINTF (2 , "%s(%d): counter=%x, bitcount=%d, likely=%d, confidence =%d, uopcode=%s\n" ,
549563 _PyUOpName (opcode ), oparg ,
550- counter , bitcount , jump_likely , _PyUOpName (uopcode ));
564+ counter , bitcount , jump_likely , confidence , _PyUOpName (uopcode ));
551565 ADD_TO_TRACE (uopcode , max_length , 0 , target );
552566 if (jump_likely ) {
553567 _Py_CODEUNIT * target_instr = next_instr + oparg ;
0 commit comments