strlen.cは4バイトもしくは8バイト単位で文字列の長さを数える

標準ライブラリのstrlen(3)とか言っても、whileループより速いものって作れるんだろうかと思って、以下のファイルを眺めてみた。

glibc$ find ./ -iname strlen*
./sysdeps/sh/strlen.S
./sysdeps/i386/i486/strlen.S
./sysdeps/i386/i586/strlen.S
./sysdeps/i386/strlen.c
./sysdeps/ia64/strlen.S
./sysdeps/sparc/sparc32/sparcv9/strlen.S
./sysdeps/sparc/sparc32/strlen.S
./sysdeps/sparc/sparc64/strlen.S
./sysdeps/x86_64/strlen.S
./sysdeps/powerpc/powerpc32/strlen.S
./sysdeps/powerpc/powerpc64/strlen.S
./locale/strlen-hash.h
./string/strlen.c

386依存と思われる、「i386/strlen.c」は、

asm("cld\n"                   /* Search forward.  */
    /* Some old versions of gas need `repne' instead of `repnz'.  */
    "repnz\n"                 /* Look for a zero byte.  */
    "scasb" /* %0, %1, %3 */ :
    "=c" (cnt) : "D" (str), "0" (-1), "a" (0));

とか、インラインアセンブラ。うーん、これはそのうち調べるとして、アーキテクチャ非依存と思われる「string/strlen.c」のほうを見てみた。

すると、32ビットアーキテクチャなら4バイト単位、64ビットアーキテクチャなら8バイト単位で0ターミネーションをスキャンしていることが分かった。そして、そのスキャン方法がビット演算を使ったトリッキーなものらしいことが分かった。

/* Copyright (C) 1991,1993,1997,2000,2003,2009 Free Software Foundation, Inc.
   This file is part of the GNU C Library.
   Written by Torbjorn Granlund (tege@sics.se),
   with help from Dan Sahlin (dan@sics.se);
   commentary by Jim Blandy (jimb@ai.mit.edu).

   The GNU C Library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2.1 of the License, or (at your option) any later version.

   The GNU C Library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with the GNU C Library; if not, write to the Free
   Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
   02111-1307 USA.  */

#include <string.h>
#include <stdlib.h>

#undef strlen

/* Return the length of the null-terminated string STR.  Scan for
   the null terminator quickly by testing four bytes at a time.  */
size_t
strlen (str)
     const char *str;
{
  const char *char_ptr;
  const unsigned long int *longword_ptr;
  unsigned long int longword, himagic, lomagic;

  /* Handle the first few characters by reading one character at a time.
     Do this until CHAR_PTR is aligned on a longword boundary.  */
  for (char_ptr = str; ((unsigned long int) char_ptr
			& (sizeof (longword) - 1)) != 0;
       ++char_ptr)
    if (*char_ptr == '\0')
      return char_ptr - str;

  /* All these elucidatory comments refer to 4-byte longwords,
     but the theory applies equally well to 8-byte longwords.  */

  longword_ptr = (unsigned long int *) char_ptr;

  /* Bits 31, 24, 16, and 8 of this number are zero.  Call these bits
     the "holes."  Note that there is a hole just to the left of
     each byte, with an extra at the end:

     bits:  01111110 11111110 11111110 11111111
     bytes: AAAAAAAA BBBBBBBB CCCCCCCC DDDDDDDD

     The 1-bits make sure that carries propagate to the next 0-bit.
     The 0-bits provide holes for carries to fall into.  */
  himagic = 0x80808080L;
  lomagic = 0x01010101L;
  if (sizeof (longword) > 4)
    {
      /* 64-bit version of the magic.  */
      /* Do the shift in two steps to avoid a warning if long has 32 bits.  */
      himagic = ((himagic << 16) << 16) | himagic;
      lomagic = ((lomagic << 16) << 16) | lomagic;
    }
  if (sizeof (longword) > 8)
    abort ();

  /* Instead of the traditional loop which tests each character,
     we will test a longword at a time.  The tricky part is testing
     if *any of the four* bytes in the longword in question are zero.  */
  for (;;)
    {
      longword = *longword_ptr++;

      if (((longword - lomagic) & ~longword & himagic) != 0)
	{
	  /* Which of the bytes was the zero?  If none of them were, it was
	     a misfire; continue the search.  */

	  const char *cp = (const char *) (longword_ptr - 1);

	  if (cp[0] == 0)
	    return cp - str;
	  if (cp[1] == 0)
	    return cp - str + 1;
	  if (cp[2] == 0)
	    return cp - str + 2;
	  if (cp[3] == 0)
	    return cp - str + 3;
	  if (sizeof (longword) > 4)
	    {
	      if (cp[4] == 0)
		return cp - str + 4;
	      if (cp[5] == 0)
		return cp - str + 5;
	      if (cp[6] == 0)
		return cp - str + 6;
	      if (cp[7] == 0)
		return cp - str + 7;
	    }
	}
    }
}
libc_hidden_builtin_def (strlen)

最初数バイトのアラインメントのバウンダリ判定とか64ビットのこととかを除くと、キモとなるのは、

  himagic = 0x80808080L;
  lomagic = 0x01010101L;

  for (;;)
    {
      longword = *longword_ptr++;
      if (((longword - lomagic) & ~longword & himagic) != 0)

じゃないかという気がする。基本的なアイデアは、ビット演算でバイト単位での桁溢れを検出するということのような気がするけど、どうしてこれでそんなことができるのかということと、本当にそれが高速なのかということが全然分からない。

それで、ちょっと適当に0と1を並べてみた。

himagic   10000000 10000000 10000000 10000000

lomagic   00000001 00000001 00000001 00000001

longword  11100010 00000000 00101001 11100100


          11100000 11111111 00101000 11100011 longword - lomagic  (1)

          00011101 11111111 11010110 00011011 ~longword           (2)

          10000000 10000000 10000000 10000000 himagic             (3)

          00000000 10000000 00000000 00000000 (1) & (2) & (3)

おお、確かlongwordのどこかのバイトが0のときだけ、((longword - lomagic) & ~longword & himagic)は0以外になる。なぜなら各バイトの最上位の桁が(1)と(2)の両方で「1」となるのは00000000のときだけ。だから(3)でマスクすれば、当然「00000000」のところだけが「10000000」となって残る。うーん。

しかし、これが最速だという議論の背景が分からない。もし、0xff0000000、0x00ff0000、0x0000ff00、0x000000ffと4パターンでマスクして0判定をやることになるんだとしたら、そもそも条件判定がほぼ4倍になるってことだろうか。