🚀 go-pugleaf

RetroBBS NetNews Server

Inspired by RockSolid Light RIP Retro Guy

Article View: comp.std.c
Article #4284

Re: Aliasing in C

#4284
From: Jerry Coffin
Date: Fri, 27 Oct 1995 17:31
62 lines
2338 bytes
sanjoy@leland.Stanford.EDU (sanjoy ghosh) wrote:

>struct try {
>        int     tr1;
>        int     tr2;
>        int     tr3;
>        int     tr4;
>};

>int try1 (struct try *array, int *index)
>{
>        int     i;

>        for (i = 0; i < 10; i++)
>        {
>                array[index[i]].tr3 = i;
>                array[index[i]].tr2 = i + 10;
>                array[index[i]].tr1 = i + 20;
>        }
>}


>Most compilers assume that index and array could be aliased and reload index[i]
>for each of the 3 indexes into array in the loop body.  So they load index[i]
>and compute the address of array[index[i]] 3 times.  Is this really necessary
>in ANSI C?  Can't we assume that index and array cannot overlap since they
>point to non-compatible objects, and if you write to one you can screw up the
>other?  Do any compilers assume that they are NOT aliased and optimize the
>indexing?

It looks to me like you should be able to assume they're not aliased.  A
quick test with MSC 9.1 shows that it loads the address of index[i] once
and reuses it for the rest of the loop:

; Line 12
	xor	edi, edi
$L158:
	lea	ebx, DWORD PTR [edx+edi*4]		; ebx = index +i
; Line 14
	mov	eax, DWORD PTR [ebx]		; eax = array + ebx
	shl	eax, 4
	mov	DWORD PTR [eax+ecx+8], edi		
; Line 15
	lea	eax, DWORD PTR [edi+10]
	mov	esi, DWORD PTR [ebx]		; esi = array + ebx
	inc	edi
	shl	esi, 4
	mov	DWORD PTR [esi+ecx+4], eax

I'm not at all sure that means a whole lot though - with the right
switches, MS openly documents the fact that their optimizer can and will
break code with aliasing.  Ultimately, trying to prove the validity of
an assumption about the standard by showing that somebody else made that
assumption proves virtually nothing about the standard itself.
    Later,
    Jerry.

/* I can barely express my own opinions; I certainly can't
 * express anybody else's.
 *
 * The universe is a figment of its own imagination.
 */
Technical Details
Message-ID: <46r0jn$r08@natasha.rmii.com>
Path: arc1-ca.pugleaf.net!news.rmii.com!usenet
References: <46msr4$ee9@elaine25.Stanford.EDU>

Show Full Headers
Complete Article Headers
Path: arc1-ca.pugleaf.net!news.rmii.com!usenet
From: jcoffin@rmii.com (Jerry Coffin)
Newsgroups: comp.std.c
Subject: Re: Aliasing in C
Date: Fri, 27 Oct 1995 17:31:22 GMT
Organization: TAEUS
Message-ID: <46r0jn$r08@natasha.rmii.com>
References: <46msr4$ee9@elaine25.Stanford.EDU>
NNTP-Posting-Host: slip8124.rmii.com
X-Newsreader: Forte Free Agent 1.0.82