pg.ddx.io  pgsql-bugs@postgresql.org mailing list archive  
help / color / mirror / Atom feed
BUG #15923: Prepared statements take way too much memory.
8+ messages / 6 participants
[nested] [flat]

* BUG #15923: Prepared statements take way too much memory.
@ 2019-07-24 21:39 PG Bug reporting form <noreply@postgresql.org>
  2019-07-24 22:23 ` Re: BUG #15923: Prepared statements take way too much memory. Tom Lane <tgl@sss.pgh.pa.us>
  2019-07-26 01:04 ` Re: BUG #15923: Prepared statements take way too much memory. Andres Freund <andres@anarazel.de>
  0 siblings, 2 replies; 8+ messages in thread

From: PG Bug reporting form @ 2019-07-24 21:39 UTC (permalink / raw)
  To: pgsql-bugs@lists.postgresql.org; +Cc: dmigowski@ikoffice.de

The following bug has been logged on the website:

Bug reference:      15923
Logged by:          Daniel Migowski
Email address:      dmigowski@ikoffice.de
PostgreSQL version: 11.2
Operating system:   Windows, Linux, doesn&#39;t matters
Description:        

Hello,

Prepared Statements take too much memory. This is a bug report I already
filled a few years as #14726
(https://www.postgresql.org/message-id/20170702090956.1469.41812%40wrigleys.postgresql.org)
 ago but now I have a proof and can provide a testcase for you to simply
verify my assumptions. 

I have a large query like https://explain.depesz.com/s/gN2, which results in
30MB query plans. 

To verify if that is true I wrote a small script that prepares this query (a
simple SELECT * FROM myNotSoSimpleFatView) 250 times:

DO $$ 
DECLARE i int4; 
BEGIN 
    FOR i IN 1..250 LOOP 
        RAISE NOTICE 'This is prepared statement %', i;
        EXECUTE 'PREPARE testxy_'||i||' AS SELECT *, ''test_'||i||''' FROM
vw_report_salesinvoice WHERE salesinvoice_id = $1;'; 
    END LOOP; 
END $$;

To reproduce just insert your favority view and primary key name after the
FROM and have a look at memory consumption for yourself.

31540 postgres  20   0 1414452 976,9m  26816 R  99,6 12,2   0:11.11 postgres
  after a few queries
31540 postgres  20   0 2480276 1,903g  26816 R  99,9 24,3   0:23.10 postgres
  after 66 queries
31540 postgres  20   0 3824908 3,097g  26816 R  99,9 39,6   0:38.07 postgres
 after 100 queries
31540 postgres  20   0 5727036 4,786g  26816 R  99,9 61,2   0:59.04 postgres
 after 160 queries
...
31540 postgres  20   0 8646140 7,351g  19712 S   0,0 94,0   1:31.81 postgres
after 250 queries     <-  WTF 7 point 5 whopping gigs of RAM just for a few
prepared statements? Thats about 45M for each query!! 

PostgreSQL crashes regulary at my customer servers, because I use automatic
prepared statements for queries that are done often. At least I thought that
would be a good idea. 

Please note that this bug also affects other (like
https://github.com/rails/rails/issues/14645, where they just stopped using
Prepared Statements alltogether as a solution to their crashes).Most users
that use an ORM enable prepared queries, not seeing that PostgreSQL just
isn't capable to handle them. 

I have the problem on 9.5, and testing this on 11.2 still shows the same
behaviour. Please, please, someone have a look at where all that memory goes
and I will immediately roll out a new version to all of my customers. I love
your database and the stability, but this is definitely a point where you
can drastically improve!

Best and kindest regards,
Daniel Migowski



^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* Re: BUG #15923: Prepared statements take way too much memory.
  2019-07-24 21:39 BUG #15923: Prepared statements take way too much memory. PG Bug reporting form <noreply@postgresql.org>
@ 2019-07-24 22:23 ` Tom Lane <tgl@sss.pgh.pa.us>
  2019-07-26 00:41   ` Re: BUG #15923: Prepared statements take way too much memory. Andres Freund <andres@anarazel.de>
  2019-07-26 02:16   ` Re: BUG #15923: Prepared statements take way too much memory. Andres Freund <andres@anarazel.de>
  1 sibling, 2 replies; 8+ messages in thread

From: Tom Lane @ 2019-07-24 22:23 UTC (permalink / raw)
  To: dmigowski@ikoffice.de; +Cc: pgsql-bugs@lists.postgresql.org

PG Bug reporting form <noreply@postgresql.org> writes:
> Prepared Statements take too much memory.

I'm not really sure what you expect us to do about this.  If you
PREPARE a bunch of statements and never DEALLOCATE them, then yes
they're going to consume memory; maybe a lot of memory if the
plans are complex.

The only thing we could do to reduce the memory consumption is to
throw away the plans, which kind of defeats the purpose of a
prepared statement, wouldn't you say?  And even holding onto enough
information to re-create the plan later would consume some amount
of memory, so you will still have a problem if you keep making
prepared statements and never release them.

			regards, tom lane





^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* Re: BUG #15923: Prepared statements take way too much memory.
  2019-07-24 21:39 BUG #15923: Prepared statements take way too much memory. PG Bug reporting form <noreply@postgresql.org>
  2019-07-24 22:23 ` Re: BUG #15923: Prepared statements take way too much memory. Tom Lane <tgl@sss.pgh.pa.us>
@ 2019-07-26 00:41   ` Andres Freund <andres@anarazel.de>
  1 sibling, 0 replies; 8+ messages in thread

From: Andres Freund @ 2019-07-26 00:41 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; John Naylor <jcnaylor@gmail.com>; +Cc: Daniel Migowski <dmigowski@ikoffice.de>; 'pgsql-bugs@lists.postgresql.org' <pgsql-bugs@lists.postgresql.org>

Hi,

On 2019-07-25 18:13:33 -0400, Tom Lane wrote:
> FWIW, I've thought for some time that we should invent a memory context
> allocator that's meant for data that doesn't get realloc'd (much) after
> first allocation, with lower overhead than aset.c has.

Same.

Although I've wondered whether we'd actually want to tie that to a
separate memory context, but instead add it as an option to set on a
context. It seems like that could potentially reduce overhead, by
avoiding the need to have multiple contexts around. E.g. something like
MemoryContextUseBulkAlloc().  For aset.c that could e.g. switch the
context's callbacks to ones where AllocSetAlloc() is much simpler (one
strategy for large allocations, for the rest don't manage a freelist,
and don't round up allocation sizes).  Not sure what's better.



FWIW, here's a few steps towards tracing aset.c events:

perf probe -x /home/andres/build/postgres/dev-assert/vpath/src/backend/postgres --add 'AllocSetAlloc context->name:string size:u64'
perf probe -x /home/andres/build/postgres/dev-assert/vpath/src/backend/postgres --add 'AllocSetFree:3 context->name:string chunk->size:u64'
perf probe -x /home/andres/build/postgres/dev-assert/vpath/src/backend/postgres --add 'AllocSetFree:18 context->name:string chunk->size:u64'
perf probe -x /home/andres/build/postgres/dev-assert/vpath/src/backend/postgres --add 'AllocSetRealloc:9 context->name:string oldsize=chunk->size:u64 size:u64'
perf probe -x /home/andres/build/postgres/dev-assert/vpath/src/backend/postgres --add 'AllocSetReset context->name:string'
perf probe -x /home/andres/build/postgres/dev-assert/vpath/src/backend/postgres --add 'AllocSetDelete context->name:string'
perf probe -x /home/andres/build/postgres/dev-assert/vpath/src/backend/postgres --add 'AllocSetContextCreateInternal name:string'
perf probe -x /home/andres/build/postgres/dev-assert/vpath/src/backend/postgres --add 'raw_parser'
perf probe -x /home/andres/build/postgres/dev-assert/vpath/src/backend/postgres --add 'raw_parser%return'
perf probe -x /home/andres/build/postgres/dev-assert/vpath/src/backend/postgres --add 'pg_analyze_and_rewrite'
perf probe -x /home/andres/build/postgres/dev-assert/vpath/src/backend/postgres --add 'pg_analyze_and_rewrite%return'
perf probe -x /home/andres/build/postgres/dev-assert/vpath/src/backend/postgres --add 'planner%return'
perf probe -x /home/andres/build/postgres/dev-assert/vpath/src/backend/postgres --add 'planner'

which then can be used with perf record to trace a backend's
allocations:

perf record $(for e in AllocSetContextCreateInternal AllocSetDelete AllocSetReset AllocSetAlloc AllocSetFree AllocSetRealloc AllocSetFree raw_parser raw_parser__return pg_analyze_and_rewrite  pg_analyze_and_rewrite__return planner planner__return ; do echo "-e probe_postgres:$e";done) -p 26963
<execute query>
ctrl-c

perf script

        postgres 26963 [000] 58737.065318:  probe_postgres:AllocSetContextCreateInternal: (55eba8540c23) name_string="TopTransactionContext"
        postgres 26963 [000] 58737.065331:                  probe_postgres:AllocSetAlloc: (55eba853f906) name="TopMemoryContext" size_u64=480
        postgres 26963 [000] 58737.065345:                     probe_postgres:raw_parser: (55eba819f68c)
        postgres 26963 [000] 58737.065355:                  probe_postgres:AllocSetAlloc: (55eba853f906) name="MessageContext" size_u64=160
        postgres 26963 [000] 58737.065362:                  probe_postgres:AllocSetAlloc: (55eba853f906) name="MessageContext" size_u64=944
        postgres 26963 [000] 58737.065367:                  probe_postgres:AllocSetAlloc: (55eba853f906) name="MessageContext" size_u64=64
...
        postgres 26963 [000] 58737.067714:                  probe_postgres:AllocSetAlloc: (55eba853f906) name="MessageContext" size_u64=32
        postgres 26963 [000] 58737.067721:             probe_postgres:raw_parser__return: (55eba819f68c <- 55eba83f2254)
        postgres 26963 [000] 58737.067734:                  probe_postgres:AllocSetAlloc: (55eba853f906) name="TopTransactionContext" size_u64=24
        postgres 26963 [000] 58737.067740:                  probe_postgres:AllocSetAlloc: (55eba853f906) name="TopTransactionContext" size_u64=104
        postgres 26963 [000] 58737.067746:         probe_postgres:pg_analyze_and_rewrite: (55eba83f232b)
        postgres 26963 [000] 58737.067753:                  probe_postgres:AllocSetAlloc: (55eba853f906) name="MessageContext" size_u64=208
        postgres 26963 [000] 58737.067759:                  probe_postgres:AllocSetAlloc: (55eba853f906) name="MessageContext" size_u64=216
...
        postgres 26963 [000] 58737.074248:                  probe_postgres:AllocSetAlloc: (55eba853f906) name="MessageContext" size_u64=32
        postgres 26963 [000] 58737.074260:                  probe_postgres:AllocSetAlloc: (55eba853f906) name="MessageContext" size_u64=32
        postgres 26963 [000] 58737.074266: probe_postgres:pg_analyze_and_rewrite__return: (55eba83f232b <- 55eba83f2ae9)
        postgres 26963 [000] 58737.074273:                        probe_postgres:planner: (55eba8326c51)
        postgres 26963 [000] 58737.074280:                  probe_postgres:AllocSetAlloc: (55eba853f906) name="MessageContext" size_u64=128
        postgres 26963 [000] 58737.074305:                  probe_postgres:AllocSetAlloc: (55eba853f906) name="MessageContext" size_u64=536
        postgres 26963 [000] 58737.074316:                  probe_postgres:AllocSetAlloc: (55eba853f906) name="MessageContext" size_u64=48
...
        postgres 26963 [000] 58737.076820:                  probe_postgres:AllocSetAlloc: (55eba853f906) name="MessageContext" size_u64=16
        postgres 26963 [000] 58737.076827:                probe_postgres:AllocSetRealloc: (55eba85403f6) name="MessageContext" oldsize=32 size_u64=24
        postgres 26963 [000] 58737.076843:  probe_postgres:AllocSetContextCreateInternal: (55eba8540c23) name_string="inline_function"
        postgres 26963 [000] 58737.076854:                  probe_postgres:AllocSetAlloc: (55eba853f906) name="inline_function" size_u64=179
        postgres 26963 [000] 58737.076861:                  probe_postgres:AllocSetAlloc: (55eba853f906) name="inline_function" size_u64=48
        postgres 26963 [000] 58737.076869:                  probe_postgres:AllocSetAlloc: (55eba853f906) name="inline_function" size_u64=40
        postgres 26963 [000] 58737.076876:                  probe_postgres:AllocSetAlloc: (55eba853f906) name="inline_function" size_u64=16
        postgres 26963 [000] 58737.076883:                  probe_postgres:AllocSetAlloc: (55eba853f906) name="inline_function" size_u64=8
        postgres 26963 [000] 58737.076891:                     probe_postgres:raw_parser: (55eba819f68c)
        postgres 26963 [000] 58737.076903:                  probe_postgres:AllocSetAlloc: (55eba853f906) name="inline_function" size_u64=160
        postgres 26963 [000] 58737.076910:                  probe_postgres:AllocSetAlloc: (55eba853f906) name="inline_function" size_u64=180
...
        postgres 26963 [000] 58737.091725:                  probe_postgres:AllocSetAlloc: (55eba853f906) name="MessageContext" size_u64=128
        postgres 26963 [000] 58737.091733:                probe_postgres:planner__return: (55eba8326c51 <- 55eba83f24ba)
        postgres 26963 [000] 58737.091740:                  probe_postgres:AllocSetAlloc: (55eba853f906) name="MessageContext" size_u64=32
        postgres 26963 [000] 58737.091749:                   probe_postgres:AllocSetFree: (55eba853f4fc) name="TopTransactionContext" size=128
...

the query here was just \dt+.


it's possible that you'd need to change the offsets slightly, depending
on compiler options. One can see tracable lines with:
perf probe -x /home/andres/build/postgres/dev-assert/vpath/src/backend/postgres --line AllocSetRealloc
and the available variables with:
erf probe -x /home/andres/build/postgres/dev-assert/vpath/src/backend/postgres --vars AllocSetRealloc:9


Shouldn't be hard to parse that into something giving actual stats for
each memory context, and each query phase.


> Such an allocator would be ideal for plancache.c, and perhaps other
> use-cases such as plpgsql function parsetrees.

Probably also for raw parsing. Bet we'd save more than we'd loose by not
freeing during it.


> IMV this would have these properties:
>
> * Doesn't support retail pfree; to recover space you must destroy the
> whole context.  We could just make pfree a no-op.  With the details
> sketched below, repalloc would have to throw an error (because it would
> not know the size of the old chunk), but I think that's OK for the
> intended purpose.

> * Minimum chunk header overhead, ie only the context pointer required by
> the mmgr.c infrastructure.  In particular, don't store the chunk size.

I'm not sure it's worth eliding the size. Will make it hard to adapt the
new type of context to new code - it's pretty hard to guarantee that
there's not one random utility function in some rarely executed path
that does need the size.


> (Possibly, instead of freelists, we'd trouble to track
> end-of-block space in more than one active block, so that we avoid
> wasting such space when a large allocation doesn't quite fit.)

Hm, doesn't aset.c already solve that by not putting the oversized block
at the head of the block list?



> A totally different idea is to make a variant version of copyObject
> that is intended to produce a compact form of a node tree, and does
> not create a separate palloc allocation for each node but just packs
> them as tightly as it can in larger palloc chunks.  This could outperform
> the no-pfree-context idea because it wouldn't need even context-pointer
> overhead for each node.

If done right, it'd probably also yield considerably higher spatial
locality in the memory layout.


> The stumbling block here is that nobody is gonna tolerate maintaining
> two versions of copyfuncs.c, so you'd have to find a way for a single
> set of copy functions to support this output format as well as the
> traditional one.  (Alternatively, maybe we could learn to autogenerate
> the copy functions from annotated struct definitions; people have
> muttered about that for years but not done anything.)

Yea, I think we'd have to autogenerate them to go for that.  I'm kinda
hoping that maybe John Naylor would take a look, after he made all our
lives quite a bit easier with the other catalog script work...

In the 'pipe dream' version of this, that script would be able to
generate code to adjust pointers after a memcpy... That'd make
copyObject() of such flattened trees much much cheaper.

Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* Re: BUG #15923: Prepared statements take way too much memory.
  2019-07-24 21:39 BUG #15923: Prepared statements take way too much memory. PG Bug reporting form <noreply@postgresql.org>
  2019-07-24 22:23 ` Re: BUG #15923: Prepared statements take way too much memory. Tom Lane <tgl@sss.pgh.pa.us>
@ 2019-07-26 02:16   ` Andres Freund <andres@anarazel.de>
  1 sibling, 0 replies; 8+ messages in thread

From: Andres Freund @ 2019-07-26 02:16 UTC (permalink / raw)
  To: Thomas Munro <thomas.munro@gmail.com>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Daniel Migowski <dmigowski@ikoffice.de>; pgsql-bugs@lists.postgresql.org <pgsql-bugs@lists.postgresql.org>

Hi,

On 2019-07-26 10:55:35 +1200, Thomas Munro wrote:
> IIUC the only advantage of a
> special compacting copyObject() would be that it could presumably get
> precisely the right sized single piece of memory, but is that worth
> the complexity of a two-phase design (IIUC you'd want recursive
> tell-me-how-much-memory-you'll-need, then allocate all at once)?  A
> chain of smaller chunks should be nearly as good (just a small amount
> of wasted space in the final chunk).

I was wondering if we somehow could have a 'header' for Node trees,
which'd keep track of their size when built incrementally. But it seems
like the amount of changes that'd require would be far too
extensive. We, I think, would have to pass down additional pointers in
too many places, not to even talk about the difficulty of tracking the
size precisely during incremental changes.

Although *if* we had it, we could probably avoid a lot of unnecessary
tree copying, by having copy-on-write + reference counting logic.


This kind of thing would be a lot of easier to solve with C++ than C (or
well, just any modern-ish language)... We could have "smart" references
to points in the query tree that keep track both of where they are, and
what the head of the whole tree is.  And the immutable flattened tree
they could just use offsets instead of pointers, and resolve those
offsets within the accessor.



> (Auto-generated read/write/copy/eq functions would be a good idea
> anyway.)

Indeed.


> >> References to data like table and datatype definitions that are copied
> >> into the plan but are also copied multiple times. Doesn't matter for
> >> ...
> > TBH that sounds like a dead end to me.  Detecting duplicate subtrees would
> > be astonishingly expensive, and I doubt that there will be enough of them
> > to really repay the effort in typical queries.
> 
> Yeah, deduplicating common subplans may be too tricky and expensive.

It'd sure be interesting to write a function that computes stats about
which types of nodes consume how much memory. Shouldn't be too hard.

I'm mildly suspecting that a surprisingly large overhead in complex
query trees comes from target lists that are the same in many parts of
the tree.


Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* Re: BUG #15923: Prepared statements take way too much memory.
  2019-07-24 21:39 BUG #15923: Prepared statements take way too much memory. PG Bug reporting form <noreply@postgresql.org>
@ 2019-07-26 01:04 ` Andres Freund <andres@anarazel.de>
  1 sibling, 0 replies; 8+ messages in thread

From: Andres Freund @ 2019-07-26 01:04 UTC (permalink / raw)
  To: PG Bug reporting form <noreply@postgresql.org>; +Cc: pgsql-bugs@lists.postgresql.org; dmigowski@ikoffice.de

Hi,

On 2019-07-24 21:39:35 +0000, PG Bug reporting form wrote:
> I have the problem on 9.5, and testing this on 11.2 still shows the same
> behaviour. Please, please, someone have a look at where all that memory goes
> and I will immediately roll out a new version to all of my customers. I love
> your database and the stability, but this is definitely a point where you
> can drastically improve!

If you had a reproducible testcase, you'd be more likely to get useful
input... While there's some bigger architectural reasons at play here
too, the overhead you show here seems a bit abnormal still.

IMO bug reports aren't a great avenue for random improvement requests.

Greetings,

Andres Freund





^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* RE: BUG #15923: Prepared statements take way too much memory.
@ 2019-07-28 11:14 Daniel Migowski <dmigowski@ikoffice.de>
  2019-07-29 06:11 ` Re: BUG #15923: Prepared statements take way too much memory. Thomas Munro <thomas.munro@gmail.com>
  0 siblings, 1 reply; 8+ messages in thread

From: Daniel Migowski @ 2019-07-28 11:14 UTC (permalink / raw)
  To: Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; Thomas Munro <thomas.munro@gmail.com>; +Cc: 'pgsql-bugs@lists.postgresql.org' <pgsql-bugs@lists.postgresql.org>

Hello,

Thanks for all your replies, I try to combine the answers for the last mails on the subject.

------ In reply to Tom Lane -------

Creating a new type of MemoryContext (FlatMemoryContext?) sounds like a good idea for me, because it sounds minimal invasive, I will try that. I believe that it doesn't need a maximum block size, does it? One could give a size for blocks that are requested by malloc, and every time someone pallocs a larger area this is directly malloced and returned. I saw that AllocSec used an initial size which is doubled every time the previous size isn't sufficient anymore. Should the new MemoryContext should behave identically? 

I wonder if this MemoryContext should make good use of a "finalize" function, which can be called after no work in the context is expected anymore, and which realloc's the allocated blocks to the really used size so the C-lib can reuse the unused memory. Maybe even AllocSec could profit from it as a first step. Checking the stats the used vs. malloced mem is at a low 60%.  

> This wouldn't take very much new code, and it would potentially offer up to perhaps 2X space savings compared to aset.c, thanks to cutting the per-chunk overhead.  Whether that's enough to float your boat with respect to cached plans isn't too clear, though.

No, boat will still sink, but it's a good start and servers are less likely to crash.

> A totally different idea is to make a variant version of copyObject that is intended to produce a compact form of a node tree, and does not create a separate palloc allocation for each node but just packs them as tightly as it can in larger palloc chunks. ..

On the copyObject code that should be autogenerated, I thought a lot about how this would be possible with macros, but couldn't think of anything, because one macro statement would have to produce source code in two distinct places (at least in two functions). Is there similar code somewhere else in the source tree ?

See below for more on that subject

> ...serialization of node tree...

I also don't like serialization very much, because I already rewrote the Standard Serialization Mechanism in Java very successfully, but now about the problems in case of graph type object dependencies (which don't seem to exist in NodeSets because then the objectCopy function would also have to cope with that and doesn't). But if everything else fails in the end it might by a good idea. However, I believe the size of the rewritten query plan is many times the original node tree and used often, so it might not be a good idea. 

------ In reply to Thomas Munro ------

Regarding your comments on the variant version of copyObject, I also believe that a FlatMemoryContext would result in nearly the same memory usage at a first glance, except for the Chunk headers Tom Lane also noticed. One should measure how much space could really be saved when we don't need the chunk headers. 

But I like the calculate-memory variant one would get when the copyObject code is generated. The two phase variant would not even be slower because the overhead of pallocing every chunk for every node MUST be higher than a simple calculation of the required space. This feels a bit like inlining the allocation logic into the copyObject code, and would be the best variant regarding speed AND size. 

------ In reply to Andres Freund ------

> Yea, I think we'd have to autogenerate them to go for that.  I'm kinda hoping that maybe John Naylor would take a look, after he made all our lives quite a bit easier with the other catalog script work... In the 'pipe dream' version of this, that script would be able to generate code to adjust pointers after a memcpy... That'd make copyObject() of such flattened trees much cheaper.

Thanks for the input, I will have a look at it. When copyObject on such trees is such a common operation, it might be feasible to store the length of such a readonly-tree somewhere within the tree itself, so one knows the exact length of a node including all its subnodes, which "should" always be in a contiguous range of memory anyway, and we would just have to apply an offset to all pointers within the copied area. 

Or, when we come back to the two-pass idea of preallocating a large chunk of memory for the nodes, one could use the same function to calculate the range on the fly. 

I see the problem here that the current implementation of copyObject (which is used in many placed in the code) would have to be aware that the source nodes are allocated in a flat MemoryContext for this to work through everywhere in the codebase. This could be achived if a chunk header for the nodes is not omitted (althought the chunk header would not be set by the MemoryContext but by the copyNode implementation for FlatMemoryContext itself. If the current memory isn't flat, normal pallocs have to be done.). Does code exist with the assumption that every node resides in its own allocated chunk?
 
> It'd sure be interesting to write a function that computes stats about which types of nodes consume how much memory. Shouldn't be too hard. I'm mildly suspecting that a surprisingly large overhead in complex query trees comes from target lists that are the same in many parts of the tree.

This would be the second part of the refactoring. I was wondering if one could reduce the data that is stored in the tree in the first place by using references to existing structures instead. 

------ Conclusion -------

* A FlatMemoryContext would reduce memory usage by 40%(?), and the current copyNode infrastructure could remain as is.
* Using a code generator for the nodes is commonly agreed to be a good idea (and the amount of node types in nodes.h make me believe that the amount of hand written code would drop significantly when using one). 
* An autogenerated copyObjectFlat would be able to determine the total size of a node and its descendants and could copy a tree with a single palloc, making FlatMemoryContext obsolete and even yielding a higher memory reduction. 
* IF we keep the ChunkHeader in FlatMemoryContext, then the "standard" copy node would be able to fallback to a very fast memcopy+pointeroffsetchange variant. The profit here might outweigh the few percent of memory we gain when we skip the header. But then we have no memory gains vs. using the FlatMemoryContext alone.

So:

* A FlatMemoryContext is a good idea and I will try to implement it. 
* Code generation could speed things up significantly and a variant would just contribute to memory if we skip chunk headers (if that is allowed at all).
* There is more work to do afterwards, because the trees are still too big.

------------------------------------------------

Some more questions: 
* Why are MemoryContextAllocZeroAligned and MemoryContextAllocZero the same function?
* I wonder if we just cannot drop the raw_parse_tree altogether for large statements when the query tree has been generated. I know you need it in case the definition of tables etc. change to recreate the query tree, but wouldn't it be possible the recreate the raw_parse_tree from the query_string in that very rare event also? The query_string is already the most compacted form of the raw_parse_tree, right?  
* Does code exist with the assumption that every node resides in its own allocated chunk? (asked already above)
* Where can I find the existing code generation script? Is it called during make or before checkin?

------------------------------------------------

Thanks for reading through this. I sadly cannot provide an example because this would mean to include my companies whole database schema and I just gave up after spending 30 minutes to clean it up enough, but the complexity of the view can still be viewed at https://explain.depesz.com/s/gN2 

Regards,
Daniel Migowski





^ permalink  raw  reply  [nested|flat] 8+ messages in thread

* Re: BUG #15923: Prepared statements take way too much memory.
  2019-07-28 11:14 RE: BUG #15923: Prepared statements take way too much memory. Daniel Migowski <dmigowski@ikoffice.de>
@ 2019-07-29 06:11 ` Thomas Munro <thomas.munro@gmail.com>
  2019-07-30 03:59   ` Re: BUG #15923: Prepared statements take way too much memory. Kyotaro Horiguchi <horikyota.ntt@gmail.com>
  0 siblings, 1 reply; 8+ messages in thread

From: Thomas Munro @ 2019-07-29 06:11 UTC (permalink / raw)
  To: Daniel Migowski <dmigowski@ikoffice.de>; +Cc: Tom Lane <tgl@sss.pgh.pa.us>; Andres Freund <andres@anarazel.de>; pgsql-bugs@lists.postgresql.org <pgsql-bugs@lists.postgresql.org>

On Sun, Jul 28, 2019 at 11:14 PM Daniel Migowski <dmigowski@ikoffice.de> wrote:
> * Why are MemoryContextAllocZeroAligned and MemoryContextAllocZero the same function?

It's not really relevant to the discussion about memory usage, but since
you asked about MemoryContextAllocZeroAligned:

I noticed that stuff a while back when another project I follow was
tweaking related stuff.  The idea behind those functions is that we
have our own specialised memset()-like macros.
MemoryContextAllocZeroAligned() uses MemSetLoop(), while
MemoryContextAllocZero() uses MemSetAligned().  Those date back nearly
two decades and were apparently based on experiments done at the time.
The comments talk about avoiding function call overhead and
specialising for constant lengths, so I suppose we assumed that
compilers at the time didn't automatically know how to inline plain
old memset() calls.

These days, you'd think you could add "assume aligned" attributes to
all memory-allocation-like functions and then change a few key things
to be static inline so that the constants can be seen in the right
places, and get all of the same benefits (and probably more) for free
from the compiler's alignment analysis and inlining powers.

As for what benefits might actually be available, for constants it's
clear but for alignment, I'm doubtful.  When Clang 8 on amd64 inlines
a memset() with a known aligned destination (for various alignment
sizes) and constant size, it generates a bunch of movups instructions,
or with -march set to a modern arch, maybe vmovups, and some
variations depending on size.  Note 'u' (unaligned) instructions, not
'a' (aligned): that is, it doesn't even care that I said it the
destination was aligned!  I found claims from a couple of Intel
sources that this sort of thing stopped making any difference to
performance in the Nehalem microarchitecture (2008).  It still matters
whether the data actually is aligned, but not whether you use the
instructions that tolerate misalignment, so there is apparently no
point in generating different code, and therefore, as far as memset()
goes, apparently no gain from annotating allocation functions as
returning aligned pointers.  As for other architectures or compilers,
I don't know.

For curiosity, here's an experimental patch that gets rid of the
MemSetXXX() stuff, adds some (useless?) annotations about alignment
and makes palloc0() and MemoryContextAllocZero() inline so that they
can benefit from inlining with a visible constant size in eg
newNode().  It didn't seem to do anything very interesting apart from
remove a few hundred lines of code, so I didn't get around to digging
further or sharing it earlier.  Or maybe I was just doing it wrong.
(In this patch it's using sizeof(long) which isn't enough to be
considered aligned for the wider move instructions, but I tried
various sizes when trying to trigger different codegen, without
success).


--
Thomas Munro
https://enterprisedb.com

Attachments:

0001-Use-compiler-alignment-hints-for-palloc-and-memset.patch (application/x-patch, 15.2K) download From 60b5c203ee2396cb72508cbf7d76d112f196df14 Mon Sep 17 00:00:00 2001 From: Thomas Munro <thomas.munro@gmail.com> Date: Thu, 4 Jul 2019 10:13:44 +1200 Subject: [PATCH] Use compiler alignment hints for palloc and memset. --- src/backend/postmaster/pgstat.c | 2 +- src/backend/storage/ipc/procsignal.c | 2 +- src/backend/utils/adt/numeric.c | 2 +- src/backend/utils/mmgr/aset.c | 4 +- src/backend/utils/mmgr/mcxt.c | 117 +-------------------------- src/common/fe_memutils.c | 6 -- src/include/c.h | 105 ++++-------------------- src/include/nodes/nodes.h | 4 +- src/include/utils/palloc.h | 44 +++++----- 9 files changed, 50 insertions(+), 236 deletions(-) diff --git a/src/backend/postmaster/pgstat.c b/src/backend/postmaster/pgstat.c index b4f2b28b51..09dd0912e3 100644 --- a/src/backend/postmaster/pgstat.c +++ b/src/backend/postmaster/pgstat.c @@ -3206,7 +3206,7 @@ pgstat_progress_start_command(ProgressCommandType cmdtype, Oid relid) PGSTAT_BEGIN_WRITE_ACTIVITY(beentry); beentry->st_progress_command = cmdtype; beentry->st_progress_command_target = relid; - MemSet(&beentry->st_progress_param, 0, sizeof(beentry->st_progress_param)); + MemSet((void *) &beentry->st_progress_param, 0, sizeof(beentry->st_progress_param)); PGSTAT_END_WRITE_ACTIVITY(beentry); } diff --git a/src/backend/storage/ipc/procsignal.c b/src/backend/storage/ipc/procsignal.c index 7605b2c367..ea9c23c0b3 100644 --- a/src/backend/storage/ipc/procsignal.c +++ b/src/backend/storage/ipc/procsignal.c @@ -116,7 +116,7 @@ ProcSignalInit(int pss_idx) MyProcPid, pss_idx); /* Clear out any leftover signal reasons */ - MemSet(slot->pss_signalFlags, 0, NUM_PROCSIGNALS * sizeof(sig_atomic_t)); + MemSet((void *) slot->pss_signalFlags, 0, NUM_PROCSIGNALS * sizeof(sig_atomic_t)); /* Mark slot with my PID */ slot->pss_pid = MyProcPid; diff --git a/src/backend/utils/adt/numeric.c b/src/backend/utils/adt/numeric.c index 201784bbf6..d324124d9a 100644 --- a/src/backend/utils/adt/numeric.c +++ b/src/backend/utils/adt/numeric.c @@ -451,7 +451,7 @@ static void dump_var(const char *str, NumericVar *var); pfree(buf); \ } while (0) -#define init_var(v) MemSetAligned(v, 0, sizeof(NumericVar)) +#define init_var(v) MemSet(v, 0, sizeof(NumericVar)) #define NUMERIC_DIGITS(num) (NUMERIC_HEADER_IS_SHORT(num) ? \ (num)->choice.n_short.n_data : (num)->choice.n_long.n_data) diff --git a/src/backend/utils/mmgr/aset.c b/src/backend/utils/mmgr/aset.c index 6e4a343439..d20dedb9e5 100644 --- a/src/backend/utils/mmgr/aset.c +++ b/src/backend/utils/mmgr/aset.c @@ -508,7 +508,7 @@ AllocSetContextCreateInternal(MemoryContext parent, set->keeper = block; /* Finish filling in aset-specific parts of the context header */ - MemSetAligned(set->freelist, 0, sizeof(set->freelist)); + MemSet(set->freelist, 0, sizeof(set->freelist)); set->initBlockSize = initBlockSize; set->maxBlockSize = maxBlockSize; @@ -575,7 +575,7 @@ AllocSetReset(MemoryContext context) #endif /* Clear chunk freelists */ - MemSetAligned(set->freelist, 0, sizeof(set->freelist)); + MemSet(set->freelist, 0, sizeof(set->freelist)); block = set->blocks; diff --git a/src/backend/utils/mmgr/mcxt.c b/src/backend/utils/mmgr/mcxt.c index b07be12236..1bac9f72a9 100644 --- a/src/backend/utils/mmgr/mcxt.c +++ b/src/backend/utils/mmgr/mcxt.c @@ -803,82 +803,6 @@ MemoryContextAlloc(MemoryContext context, Size size) return ret; } -/* - * MemoryContextAllocZero - * Like MemoryContextAlloc, but clears allocated memory - * - * We could just call MemoryContextAlloc then clear the memory, but this - * is a very common combination, so we provide the combined operation. - */ -void * -MemoryContextAllocZero(MemoryContext context, Size size) -{ - void *ret; - - AssertArg(MemoryContextIsValid(context)); - AssertNotInCriticalSection(context); - - if (!AllocSizeIsValid(size)) - elog(ERROR, "invalid memory alloc request size %zu", size); - - context->isReset = false; - - ret = context->methods->alloc(context, size); - if (unlikely(ret == NULL)) - { - MemoryContextStats(TopMemoryContext); - ereport(ERROR, - (errcode(ERRCODE_OUT_OF_MEMORY), - errmsg("out of memory"), - errdetail("Failed on request of size %zu in memory context \"%s\".", - size, context->name))); - } - - VALGRIND_MEMPOOL_ALLOC(context, ret, size); - - MemSetAligned(ret, 0, size); - - return ret; -} - -/* - * MemoryContextAllocZeroAligned - * MemoryContextAllocZero where length is suitable for MemSetLoop - * - * This might seem overly specialized, but it's not because newNode() - * is so often called with compile-time-constant sizes. - */ -void * -MemoryContextAllocZeroAligned(MemoryContext context, Size size) -{ - void *ret; - - AssertArg(MemoryContextIsValid(context)); - AssertNotInCriticalSection(context); - - if (!AllocSizeIsValid(size)) - elog(ERROR, "invalid memory alloc request size %zu", size); - - context->isReset = false; - - ret = context->methods->alloc(context, size); - if (unlikely(ret == NULL)) - { - MemoryContextStats(TopMemoryContext); - ereport(ERROR, - (errcode(ERRCODE_OUT_OF_MEMORY), - errmsg("out of memory"), - errdetail("Failed on request of size %zu in memory context \"%s\".", - size, context->name))); - } - - VALGRIND_MEMPOOL_ALLOC(context, ret, size); - - MemSetLoop(ret, 0, size); - - return ret; -} - /* * MemoryContextAllocExtended * Allocate space within the specified context using the given flags. @@ -897,7 +821,7 @@ MemoryContextAllocExtended(MemoryContext context, Size size, int flags) context->isReset = false; - ret = context->methods->alloc(context, size); + ret = pg_assume_aligned(context->methods->alloc(context, size), sizeof(long)); if (unlikely(ret == NULL)) { if ((flags & MCXT_ALLOC_NO_OOM) == 0) @@ -915,7 +839,7 @@ MemoryContextAllocExtended(MemoryContext context, Size size, int flags) VALGRIND_MEMPOOL_ALLOC(context, ret, size); if ((flags & MCXT_ALLOC_ZERO) != 0) - MemSetAligned(ret, 0, size); + memset(ret, 0, size); return ret; } @@ -951,39 +875,6 @@ palloc(Size size) return ret; } -void * -palloc0(Size size) -{ - /* duplicates MemoryContextAllocZero to avoid increased overhead */ - void *ret; - MemoryContext context = CurrentMemoryContext; - - AssertArg(MemoryContextIsValid(context)); - AssertNotInCriticalSection(context); - - if (!AllocSizeIsValid(size)) - elog(ERROR, "invalid memory alloc request size %zu", size); - - context->isReset = false; - - ret = context->methods->alloc(context, size); - if (unlikely(ret == NULL)) - { - MemoryContextStats(TopMemoryContext); - ereport(ERROR, - (errcode(ERRCODE_OUT_OF_MEMORY), - errmsg("out of memory"), - errdetail("Failed on request of size %zu in memory context \"%s\".", - size, context->name))); - } - - VALGRIND_MEMPOOL_ALLOC(context, ret, size); - - MemSetAligned(ret, 0, size); - - return ret; -} - void * palloc_extended(Size size, int flags) { @@ -1000,7 +891,7 @@ palloc_extended(Size size, int flags) context->isReset = false; - ret = context->methods->alloc(context, size); + ret = pg_assume_aligned(context->methods->alloc(context, size), sizeof(long)); if (unlikely(ret == NULL)) { if ((flags & MCXT_ALLOC_NO_OOM) == 0) @@ -1018,7 +909,7 @@ palloc_extended(Size size, int flags) VALGRIND_MEMPOOL_ALLOC(context, ret, size); if ((flags & MCXT_ALLOC_ZERO) != 0) - MemSetAligned(ret, 0, size); + MemSet(ret, 0, size); return ret; } diff --git a/src/common/fe_memutils.c b/src/common/fe_memutils.c index ce99b4f4da..5b3cf862d8 100644 --- a/src/common/fe_memutils.c +++ b/src/common/fe_memutils.c @@ -118,12 +118,6 @@ palloc(Size size) return pg_malloc_internal(size, 0); } -void * -palloc0(Size size) -{ - return pg_malloc_internal(size, MCXT_ALLOC_ZERO); -} - void * palloc_extended(Size size, int flags) { diff --git a/src/include/c.h b/src/include/c.h index 2a082afab1..d9cfb96b58 100644 --- a/src/include/c.h +++ b/src/include/c.h @@ -193,6 +193,18 @@ #define pg_unreachable() abort() #endif +/* + * Hint that a function always returns pointers to memory with given alignment, + * or that a given pointer has a given alignment. + */ +#if defined(__GNUC__) && (GCC_VERSION >= 40900 || defined(__clang__)) +#define pg_attribute_assume_aligned(x) __attribute__((assume_aligned(x))) +#define pg_assume_aligned(p, x) __builtin_assume_aligned((p), (x)) +#else +#define pg_attribute_assume_aligned(x) +#define pg_assume_aligned(p, x) (p) +#endif + /* * Hints to the compiler about the likelihood of a branch. Both likely() and * unlikely() return the boolean value of the contained expression. @@ -924,98 +936,11 @@ extern void ExceptionalCondition(const char *conditionName, } \ } while (0) - -/* Get a bit mask of the bits set in non-long aligned addresses */ -#define LONG_ALIGN_MASK (sizeof(long) - 1) - -/* - * MemSet - * Exactly the same as standard library function memset(), but considerably - * faster for zeroing small word-aligned structures (such as parsetree nodes). - * This has to be a macro because the main point is to avoid function-call - * overhead. However, we have also found that the loop is faster than - * native libc memset() on some platforms, even those with assembler - * memset() functions. More research needs to be done, perhaps with - * MEMSET_LOOP_LIMIT tests in configure. - */ -#define MemSet(start, val, len) \ - do \ - { \ - /* must be void* because we don't know if it is integer aligned yet */ \ - void *_vstart = (void *) (start); \ - int _val = (val); \ - Size _len = (len); \ -\ - if ((((uintptr_t) _vstart) & LONG_ALIGN_MASK) == 0 && \ - (_len & LONG_ALIGN_MASK) == 0 && \ - _val == 0 && \ - _len <= MEMSET_LOOP_LIMIT && \ - /* \ - * If MEMSET_LOOP_LIMIT == 0, optimizer should find \ - * the whole "if" false at compile time. \ - */ \ - MEMSET_LOOP_LIMIT != 0) \ - { \ - long *_start = (long *) _vstart; \ - long *_stop = (long *) ((char *) _start + _len); \ - while (_start < _stop) \ - *_start++ = 0; \ - } \ - else \ - memset(_vstart, _val, _len); \ - } while (0) - /* - * MemSetAligned is the same as MemSet except it omits the test to see if - * "start" is word-aligned. This is okay to use if the caller knows a-priori - * that the pointer is suitably aligned (typically, because he just got it - * from palloc(), which always delivers a max-aligned pointer). + * Previously we had our own implementation of memset, but now we rely on + * the compiler to inline when appropriate with alignment analysis. */ -#define MemSetAligned(start, val, len) \ - do \ - { \ - long *_start = (long *) (start); \ - int _val = (val); \ - Size _len = (len); \ -\ - if ((_len & LONG_ALIGN_MASK) == 0 && \ - _val == 0 && \ - _len <= MEMSET_LOOP_LIMIT && \ - MEMSET_LOOP_LIMIT != 0) \ - { \ - long *_stop = (long *) ((char *) _start + _len); \ - while (_start < _stop) \ - *_start++ = 0; \ - } \ - else \ - memset(_start, _val, _len); \ - } while (0) - - -/* - * MemSetTest/MemSetLoop are a variant version that allow all the tests in - * MemSet to be done at compile time in cases where "val" and "len" are - * constants *and* we know the "start" pointer must be word-aligned. - * If MemSetTest succeeds, then it is okay to use MemSetLoop, otherwise use - * MemSetAligned. Beware of multiple evaluations of the arguments when using - * this approach. - */ -#define MemSetTest(val, len) \ - ( ((len) & LONG_ALIGN_MASK) == 0 && \ - (len) <= MEMSET_LOOP_LIMIT && \ - MEMSET_LOOP_LIMIT != 0 && \ - (val) == 0 ) - -#define MemSetLoop(start, val, len) \ - do \ - { \ - long * _start = (long *) (start); \ - long * _stop = (long *) ((char *) _start + (Size) (len)); \ - \ - while (_start < _stop) \ - *_start++ = 0; \ - } while (0) - +#define MemSet(a, b, c) memset((a), (b), (c)) /* ---------------------------------------------------------------- * Section 8: random stuff diff --git a/src/include/nodes/nodes.h b/src/include/nodes/nodes.h index 4e2fb39105..3c2bb93fdd 100644 --- a/src/include/nodes/nodes.h +++ b/src/include/nodes/nodes.h @@ -545,7 +545,7 @@ typedef struct Node #define newNode(size, tag) \ ({ Node *_result; \ AssertMacro((size) >= sizeof(Node)); /* need the tag, at least */ \ - _result = (Node *) palloc0fast(size); \ + _result = (Node *) palloc0(size); \ _result->type = (tag); \ _result; \ }) @@ -562,7 +562,7 @@ extern PGDLLIMPORT Node *newNodeMacroHolder; #define newNode(size, tag) \ ( \ AssertMacro((size) >= sizeof(Node)), /* need the tag, at least */ \ - newNodeMacroHolder = (Node *) palloc0fast(size), \ + newNodeMacroHolder = (Node *) palloc0(size), \ newNodeMacroHolder->type = (tag), \ newNodeMacroHolder \ ) diff --git a/src/include/utils/palloc.h b/src/include/utils/palloc.h index a5f435ee06..784dba271c 100644 --- a/src/include/utils/palloc.h +++ b/src/include/utils/palloc.h @@ -68,34 +68,38 @@ extern PGDLLIMPORT MemoryContext CurrentMemoryContext; /* * Fundamental memory-allocation operations (more are in utils/memutils.h) */ -extern void *MemoryContextAlloc(MemoryContext context, Size size); -extern void *MemoryContextAllocZero(MemoryContext context, Size size); -extern void *MemoryContextAllocZeroAligned(MemoryContext context, Size size); +extern void *MemoryContextAlloc(MemoryContext context, Size size) pg_attribute_assume_aligned(sizeof(long)); extern void *MemoryContextAllocExtended(MemoryContext context, - Size size, int flags); + Size size, int flags) pg_attribute_assume_aligned(sizeof(long)); -extern void *palloc(Size size); -extern void *palloc0(Size size); -extern void *palloc_extended(Size size, int flags); -extern void *repalloc(void *pointer, Size size); +extern void *palloc(Size size) pg_attribute_assume_aligned(sizeof(long)); +extern void *palloc_extended(Size size, int flags) pg_attribute_assume_aligned(sizeof(long)); +extern void *repalloc(void *pointer, Size size) pg_attribute_assume_aligned(sizeof(long)); extern void pfree(void *pointer); /* - * The result of palloc() is always word-aligned, so we can skip testing - * alignment of the pointer when deciding which MemSet variant to use. - * Note that this variant does not offer any advantage, and should not be - * used, unless its "sz" argument is a compile-time constant; therefore, the - * issue that it evaluates the argument multiple times isn't a problem in - * practice. + * Inline zeroed-memory functions to give the compiler a chance to inline the + * memset(). */ -#define palloc0fast(sz) \ - ( MemSetTest(0, sz) ? \ - MemoryContextAllocZeroAligned(CurrentMemoryContext, sz) : \ - MemoryContextAllocZero(CurrentMemoryContext, sz) ) +static inline void * +palloc0(Size size) +{ + void *memory = palloc(size); + memset(memory, 0, size); + return memory; +} + +static inline void * +MemoryContextAllocZero(MemoryContext context, Size size) +{ + void *memory = MemoryContextAlloc(context, size); + memset(memory, 0, size); + return memory; +} /* Higher-limit allocators. */ -extern void *MemoryContextAllocHuge(MemoryContext context, Size size); -extern void *repalloc_huge(void *pointer, Size size); +extern void *MemoryContextAllocHuge(MemoryContext context, Size size) pg_attribute_assume_aligned(sizeof(long)); +extern void *repalloc_huge(void *pointer, Size size) pg_attribute_assume_aligned(sizeof(long)); /* * Although this header file is nominally backend-only, certain frontend -- 2.22.0
^ permalink raw reply [nested|flat] 8+ messages in thread

* Re: BUG #15923: Prepared statements take way too much memory.
  2019-07-28 11:14 RE: BUG #15923: Prepared statements take way too much memory. Daniel Migowski <dmigowski@ikoffice.de>
  2019-07-29 06:11 ` Re: BUG #15923: Prepared statements take way too much memory. Thomas Munro <thomas.munro@gmail.com>
@ 2019-07-30 03:59   ` Kyotaro Horiguchi <horikyota.ntt@gmail.com>
  0 siblings, 0 replies; 8+ messages in thread

From: Kyotaro Horiguchi @ 2019-07-30 03:59 UTC (permalink / raw)
  To: thomas.munro@gmail.com; +Cc: dmigowski@ikoffice.de; tgl@sss.pgh.pa.us; andres@anarazel.de; pgsql-bugs@lists.postgresql.org

At Mon, 29 Jul 2019 18:11:04 +1200, Thomas Munro <thomas.munro@gmail.com> wrote in <CA+hUKGLfa6ANa0vs7Lf0op0XBH05HE8SyX8NFhDyT7k2CHYLXw@mail.gmail.com>
> On Sun, Jul 28, 2019 at 11:14 PM Daniel Migowski <dmigowski@ikoffice.de> wrote:
> > * Why are MemoryContextAllocZeroAligned and MemoryContextAllocZero the same function?
> 
> It's not really relevant to the discussion about memory usage, but since
> you asked about MemoryContextAllocZeroAligned:
> 
> I noticed that stuff a while back when another project I follow was
> tweaking related stuff.  The idea behind those functions is that we
> have our own specialised memset()-like macros.
> MemoryContextAllocZeroAligned() uses MemSetLoop(), while
> MemoryContextAllocZero() uses MemSetAligned().  Those date back nearly
> two decades and were apparently based on experiments done at the time.
> The comments talk about avoiding function call overhead and
> specialising for constant lengths, so I suppose we assumed that
> compilers at the time didn't automatically know how to inline plain
> old memset() calls.
> 
> These days, you'd think you could add "assume aligned" attributes to
> all memory-allocation-like functions and then change a few key things
> to be static inline so that the constants can be seen in the right
> places, and get all of the same benefits (and probably more) for free
> from the compiler's alignment analysis and inlining powers.
> 
> As for what benefits might actually be available, for constants it's
> clear but for alignment, I'm doubtful.  When Clang 8 on amd64 inlines
> a memset() with a known aligned destination (for various alignment
> sizes) and constant size, it generates a bunch of movups instructions,
> or with -march set to a modern arch, maybe vmovups, and some
> variations depending on size.  Note 'u' (unaligned) instructions, not
> 'a' (aligned): that is, it doesn't even care that I said it the
> destination was aligned!  I found claims from a couple of Intel
> sources that this sort of thing stopped making any difference to
> performance in the Nehalem microarchitecture (2008).  It still matters
> whether the data actually is aligned, but not whether you use the
> instructions that tolerate misalignment, so there is apparently no
> point in generating different code, and therefore, as far as memset()
> goes, apparently no gain from annotating allocation functions as
> returning aligned pointers.  As for other architectures or compilers,
> I don't know.
> 
> For curiosity, here's an experimental patch that gets rid of the
> MemSetXXX() stuff, adds some (useless?) annotations about alignment
> and makes palloc0() and MemoryContextAllocZero() inline so that they
> can benefit from inlining with a visible constant size in eg
> newNode().  It didn't seem to do anything very interesting apart from
> remove a few hundred lines of code, so I didn't get around to digging
> further or sharing it earlier.  Or maybe I was just doing it wrong.
> (In this patch it's using sizeof(long) which isn't enough to be
> considered aligned for the wider move instructions, but I tried
> various sizes when trying to trigger different codegen, without
> success).

FWIW, I saw gcc/x64 -O2 emit "rep stosq" for memset() having
constant length and "not-aligned" pointer are passed. Of course
aligned(8) didn't make difference at all.  Emitted a seris of
movex for smaller chunks.  And always emitted "call memset" for
non-constant length.

That makes me think that the "aligned" attribute works some
different way. Anyway I haven't find any further explantion about
the hint than "compiler considers alignment on the
varialbe/type/function"...

regards.

-- 
Kyotaro Horiguchi
NTT Open Source Software Center





^ permalink  raw  reply  [nested|flat] 8+ messages in thread


end of thread, other threads:[~2019-07-30 03:59 UTC | newest]

Thread overview: 8+ messages (download: mbox mbox.gz follow: Atom feed)
-- links below jump to the message on this page --
2019-07-24 21:39 BUG #15923: Prepared statements take way too much memory. PG Bug reporting form <noreply@postgresql.org>
2019-07-24 22:23 ` Tom Lane <tgl@sss.pgh.pa.us>
2019-07-26 00:41   ` Andres Freund <andres@anarazel.de>
2019-07-26 02:16   ` Andres Freund <andres@anarazel.de>
2019-07-26 01:04 ` Andres Freund <andres@anarazel.de>
2019-07-28 11:14 RE: BUG #15923: Prepared statements take way too much memory. Daniel Migowski <dmigowski@ikoffice.de>
2019-07-29 06:11 ` Thomas Munro <thomas.munro@gmail.com>
2019-07-30 03:59   ` Kyotaro Horiguchi <horikyota.ntt@gmail.com>

This inbox is served by DDX for PostgreSQL; see mirroring instructions
for how to clone and mirror all data and code used for this inbox