RISC-V: Move mode assertion out of conditional branch in emit_insn
[official-gcc.git] / gcc / d / dmd / dstruct.d
blobdf4d07a81d997f331df317f5b1bcc3665b9f603f
1 /**
2 * Struct and union declarations.
4 * Specification: $(LINK2 https://dlang.org/spec/struct.html, Structs, Unions)
6 * Copyright: Copyright (C) 1999-2024 by The D Language Foundation, All Rights Reserved
7 * Authors: $(LINK2 https://www.digitalmars.com, Walter Bright)
8 * License: $(LINK2 https://www.boost.org/LICENSE_1_0.txt, Boost License 1.0)
9 * Source: $(LINK2 https://github.com/dlang/dmd/blob/master/src/dmd/dstruct.d, _dstruct.d)
10 * Documentation: https://dlang.org/phobos/dmd_dstruct.html
11 * Coverage: https://codecov.io/gh/dlang/dmd/src/master/src/dmd/dstruct.d
14 module dmd.dstruct;
16 import core.stdc.stdio;
18 import dmd.aggregate;
19 import dmd.arraytypes;
20 import dmd.astenums;
21 import dmd.attrib;
22 import dmd.declaration;
23 import dmd.dmodule;
24 import dmd.dscope;
25 import dmd.dsymbol;
26 import dmd.dsymbolsem;
27 import dmd.dtemplate;
28 import dmd.errors;
29 import dmd.expression;
30 import dmd.func;
31 import dmd.globals;
32 import dmd.id;
33 import dmd.identifier;
34 import dmd.location;
35 import dmd.mtype;
36 import dmd.opover;
37 import dmd.target;
38 import dmd.tokens;
39 import dmd.typesem;
40 import dmd.typinf;
41 import dmd.visitor;
43 /***************************************
44 * Search sd for a member function of the form:
45 * `extern (D) string toString();`
46 * Params:
47 * sd = struct declaration to search
48 * Returns:
49 * FuncDeclaration of `toString()` if found, `null` if not
51 FuncDeclaration search_toString(StructDeclaration sd)
53 Dsymbol s = search_function(sd, Id.tostring);
54 FuncDeclaration fd = s ? s.isFuncDeclaration() : null;
55 if (fd)
57 __gshared TypeFunction tftostring;
58 if (!tftostring)
60 tftostring = new TypeFunction(ParameterList(), Type.tstring, LINK.d);
61 tftostring = tftostring.merge().toTypeFunction();
63 fd = fd.overloadExactMatch(tftostring);
65 return fd;
68 /***************************************
69 * Request additional semantic analysis for TypeInfo generation.
70 * Params:
71 * sc = context
72 * t = type that TypeInfo is being generated for
74 extern (D) void semanticTypeInfo(Scope* sc, Type t)
76 if (sc)
78 if (sc.intypeof)
79 return;
80 if (!sc.needsCodegen())
81 return;
84 if (!t)
85 return;
87 void visitVector(TypeVector t)
89 semanticTypeInfo(sc, t.basetype);
92 void visitAArray(TypeAArray t)
94 semanticTypeInfo(sc, t.index);
95 semanticTypeInfo(sc, t.next);
98 void visitStruct(TypeStruct t)
100 //printf("semanticTypeInfo.visit(TypeStruct = %s)\n", t.toChars());
101 StructDeclaration sd = t.sym;
103 /* Step 1: create TypeInfoDeclaration
105 if (!sc) // inline may request TypeInfo.
107 Scope scx;
108 scx.eSink = global.errorSink;
109 scx._module = sd.getModule();
110 getTypeInfoType(sd.loc, t, &scx);
111 sd.requestTypeInfo = true;
113 else if (!sc.minst)
115 // don't yet have to generate TypeInfo instance if
116 // the typeid(T) expression exists in speculative scope.
118 else
120 getTypeInfoType(sd.loc, t, sc);
121 sd.requestTypeInfo = true;
123 // https://issues.dlang.org/show_bug.cgi?id=15149
124 // if the typeid operand type comes from a
125 // result of auto function, it may be yet speculative.
126 // unSpeculative(sc, sd);
129 /* Step 2: If the TypeInfo generation requires sd.semantic3, run it later.
130 * This should be done even if typeid(T) exists in speculative scope.
131 * Because it may appear later in non-speculative scope.
133 if (!sd.members)
134 return; // opaque struct
135 if (!sd.xeq && !sd.xcmp && !sd.postblit && !sd.tidtor && !sd.xhash && !search_toString(sd))
136 return; // none of TypeInfo-specific members
138 // If the struct is in a non-root module, run semantic3 to get
139 // correct symbols for the member function.
140 if (sd.semanticRun >= PASS.semantic3)
142 // semantic3 is already done
144 else if (TemplateInstance ti = sd.isInstantiated())
146 if (ti.minst && !ti.minst.isRoot())
147 Module.addDeferredSemantic3(sd);
149 else
151 if (sd.inNonRoot())
153 //printf("deferred sem3 for TypeInfo - sd = %s, inNonRoot = %d\n", sd.toChars(), sd.inNonRoot());
154 Module.addDeferredSemantic3(sd);
159 void visitTuple(TypeTuple t)
161 if (t.arguments)
163 foreach (arg; *t.arguments)
165 semanticTypeInfo(sc, arg.type);
170 /* Note structural similarity of this Type walker to that in isSpeculativeType()
173 Type tb = t.toBasetype();
174 switch (tb.ty)
176 case Tvector: visitVector(tb.isTypeVector()); break;
177 case Taarray: visitAArray(tb.isTypeAArray()); break;
178 case Tstruct: visitStruct(tb.isTypeStruct()); break;
179 case Ttuple: visitTuple (tb.isTypeTuple()); break;
181 case Tclass:
182 case Tenum: break;
184 default: semanticTypeInfo(sc, tb.nextOf()); break;
188 enum StructFlags : int
190 none = 0x0,
191 hasPointers = 0x1, // NB: should use noPointers as in ClassFlags
194 /***********************************************************
195 * All `struct` declarations are an instance of this.
197 extern (C++) class StructDeclaration : AggregateDeclaration
199 FuncDeclarations postblits; // Array of postblit functions
200 FuncDeclaration postblit; // aggregate postblit
202 FuncDeclaration xeq; // TypeInfo_Struct.xopEquals
203 FuncDeclaration xcmp; // TypeInfo_Struct.xopCmp
204 FuncDeclaration xhash; // TypeInfo_Struct.xtoHash
205 extern (C++) __gshared FuncDeclaration xerreq; // object.xopEquals
206 extern (C++) __gshared FuncDeclaration xerrcmp; // object.xopCmp
208 // ABI-specific type(s) if the struct can be passed in registers
209 TypeTuple argTypes;
211 structalign_t alignment; // alignment applied outside of the struct
212 ThreeState ispod; // if struct is POD
214 // `bool` fields that are compacted into bit fields in a string mixin
215 private extern (D) static struct BitFields
217 bool zeroInit; // !=0 if initialize with 0 fill
218 bool hasIdentityAssign; // true if has identity opAssign
219 bool hasBlitAssign; // true if opAssign is a blit
220 bool hasIdentityEquals; // true if has identity opEquals
221 bool hasNoFields; // has no fields
222 bool hasCopyCtor; // copy constructor
223 bool hasPointerField; // members with indirections
224 bool hasVoidInitPointers; // void-initialized unsafe fields
225 bool hasSystemFields; // @system members
226 bool hasFieldWithInvariant; // invariants
227 bool computedTypeProperties;// the above 3 fields are computed
228 // Even if struct is defined as non-root symbol, some built-in operations
229 // (e.g. TypeidExp, NewExp, ArrayLiteralExp, etc) request its TypeInfo.
230 // For those, today TypeInfo_Struct is generated in COMDAT.
231 bool requestTypeInfo;
234 import dmd.common.bitfields : generateBitFields;
235 mixin(generateBitFields!(BitFields, ushort));
237 extern (D) this(const ref Loc loc, Identifier id, bool inObject)
239 super(loc, id);
240 zeroInit = false; // assume false until we do semantic processing
241 ispod = ThreeState.none;
242 // For forward references
243 type = new TypeStruct(this);
245 if (inObject)
247 if (id == Id.ModuleInfo && !Module.moduleinfo)
248 Module.moduleinfo = this;
252 static StructDeclaration create(const ref Loc loc, Identifier id, bool inObject)
254 return new StructDeclaration(loc, id, inObject);
257 override StructDeclaration syntaxCopy(Dsymbol s)
259 StructDeclaration sd =
260 s ? cast(StructDeclaration)s
261 : new StructDeclaration(loc, ident, false);
262 ScopeDsymbol.syntaxCopy(sd);
263 return sd;
266 override const(char)* kind() const
268 return "struct";
271 override final void finalizeSize()
273 //printf("StructDeclaration::finalizeSize() %s, sizeok = %d\n", toChars(), sizeok);
274 assert(sizeok != Sizeok.done);
276 if (sizeok == Sizeok.inProcess)
278 return;
280 sizeok = Sizeok.inProcess;
282 //printf("+StructDeclaration::finalizeSize() %s, fields.length = %d, sizeok = %d\n", toChars(), fields.length, sizeok);
284 fields.setDim(0); // workaround
286 // Set the offsets of the fields and determine the size of the struct
287 FieldState fieldState;
288 bool isunion = isUnionDeclaration() !is null;
289 for (size_t i = 0; i < members.length; i++)
291 Dsymbol s = (*members)[i];
292 s.setFieldOffset(this, &fieldState, isunion);
294 if (type.ty == Terror)
296 errors = true;
297 return;
300 if (structsize == 0)
302 hasNoFields = true;
303 alignsize = 1;
305 // A fine mess of what size a zero sized struct should be
306 final switch (classKind)
308 case ClassKind.d:
309 case ClassKind.cpp:
310 structsize = 1;
311 break;
313 case ClassKind.c:
314 case ClassKind.objc:
315 if (target.c.bitFieldStyle == TargetC.BitFieldStyle.MS)
317 /* Undocumented MS behavior for:
318 * struct S { int :0; };
320 structsize = 4;
322 else if (target.c.bitFieldStyle == TargetC.BitFieldStyle.DM)
324 structsize = 0;
325 alignsize = 0;
327 else
328 structsize = 0;
329 break;
333 // Round struct size up to next alignsize boundary.
334 // This will ensure that arrays of structs will get their internals
335 // aligned properly.
336 if (alignment.isDefault() || alignment.isPack())
337 structsize = (structsize + alignsize - 1) & ~(alignsize - 1);
338 else
339 structsize = (structsize + alignment.get() - 1) & ~(alignment.get() - 1);
341 sizeok = Sizeok.done;
343 //printf("-StructDeclaration::finalizeSize() %s, fields.length = %d, structsize = %d\n", toChars(), cast(int)fields.length, cast(int)structsize);
345 if (errors)
346 return;
348 // Calculate fields[i].overlapped
349 if (checkOverlappedFields())
351 errors = true;
352 return;
355 // Determine if struct is all zeros or not
356 zeroInit = true;
357 foreach (vd; fields)
359 if (vd._init)
361 if (vd._init.isVoidInitializer())
362 /* Treat as 0 for the purposes of putting the initializer
363 * in the BSS segment, or doing a mass set to 0
365 continue;
367 // Zero size fields are zero initialized
368 if (vd.type.size(vd.loc) == 0)
369 continue;
371 // Examine init to see if it is all 0s.
372 auto exp = vd.getConstInitializer();
373 if (!exp || !_isZeroInit(exp))
375 zeroInit = false;
376 break;
379 else if (!vd.type.isZeroInit(loc))
381 zeroInit = false;
382 break;
387 argTypes = target.toArgTypes(type);
390 /// Compute cached type properties for `TypeStruct`
391 extern(D) final void determineTypeProperties()
393 if (computedTypeProperties)
394 return;
395 foreach (vd; fields)
397 if (vd.storage_class & STC.ref_ || vd.hasPointers())
398 hasPointerField = true;
400 if (vd._init && vd._init.isVoidInitializer() && vd.type.hasPointers())
401 hasVoidInitPointers = true;
403 if (vd.storage_class & STC.system || vd.type.hasSystemFields())
404 hasSystemFields = true;
406 if (!vd._init && vd.type.hasVoidInitPointers())
407 hasVoidInitPointers = true;
409 if (vd.type.hasInvariant())
410 hasFieldWithInvariant = true;
412 computedTypeProperties = true;
415 /***************************************
416 * Determine if struct is POD (Plain Old Data).
418 * POD is defined as:
419 * $(OL
420 * $(LI not nested)
421 * $(LI no postblits, destructors, or assignment operators)
422 * $(LI no `ref` fields or fields that are themselves non-POD)
424 * The idea being these are compatible with C structs.
426 * Returns:
427 * true if struct is POD
429 final bool isPOD()
431 // If we've already determined whether this struct is POD.
432 if (ispod != ThreeState.none)
433 return (ispod == ThreeState.yes);
435 ispod = ThreeState.yes;
437 import dmd.clone;
438 bool hasCpCtorLocal;
439 needCopyCtor(this, hasCpCtorLocal);
441 if (enclosing || search(this, loc, Id.postblit) || search(this, loc, Id.dtor) || hasCpCtorLocal)
443 ispod = ThreeState.no;
444 return false;
447 // Recursively check all fields are POD.
448 for (size_t i = 0; i < fields.length; i++)
450 VarDeclaration v = fields[i];
451 if (v.storage_class & STC.ref_)
453 ispod = ThreeState.no;
454 return false;
457 Type tv = v.type.baseElemOf();
458 if (tv.ty == Tstruct)
460 TypeStruct ts = cast(TypeStruct)tv;
461 StructDeclaration sd = ts.sym;
462 if (!sd.isPOD())
464 ispod = ThreeState.no;
465 return false;
470 return (ispod == ThreeState.yes);
473 /***************************************
474 * Determine if struct has copy construction (copy constructor or postblit)
475 * Returns:
476 * true if struct has copy construction
478 final bool hasCopyConstruction()
480 return postblit || hasCopyCtor;
483 override final inout(StructDeclaration) isStructDeclaration() inout @nogc nothrow pure @safe
485 return this;
488 override void accept(Visitor v)
490 v.visit(this);
493 final uint numArgTypes() const
495 return argTypes && argTypes.arguments ? cast(uint) argTypes.arguments.length : 0;
498 final Type argType(uint index)
500 return index < numArgTypes() ? (*argTypes.arguments)[index].type : null;
504 /***************************************
505 * Verifies whether the struct declaration has a
506 * constructor that is not a copy constructor.
507 * Optionally, it can check whether the struct
508 * declaration has a regular constructor, that
509 * is not disabled.
511 * Params:
512 * checkDisabled = if the struct has a regular
513 non-disabled constructor
514 * Returns:
515 * true, if the struct has a regular (optionally,
516 * not disabled) constructor, false otherwise.
518 final bool hasRegularCtor(bool checkDisabled = false)
520 if (!ctor)
521 return false;
523 bool result;
524 overloadApply(ctor, (Dsymbol s)
526 if (auto td = s.isTemplateDeclaration())
528 if (checkDisabled && td.onemember)
530 if (auto ctorDecl = td.onemember.isCtorDeclaration())
532 if (ctorDecl.storage_class & STC.disable)
533 return 0;
536 result = true;
537 return 1;
539 if (auto ctorDecl = s.isCtorDeclaration())
541 if (!ctorDecl.isCpCtor && (!checkDisabled || !(ctorDecl.storage_class & STC.disable)))
543 result = true;
544 return 1;
547 return 0;
549 return result;
553 /**********************************
554 * Determine if exp is all binary zeros.
555 * Params:
556 * exp = expression to check
557 * Returns:
558 * true if it's all binary 0
560 bool _isZeroInit(Expression exp)
562 switch (exp.op)
564 case EXP.int64:
565 return exp.toInteger() == 0;
567 case EXP.null_:
568 return true;
570 case EXP.structLiteral:
572 auto sle = exp.isStructLiteralExp();
573 if (sle.sd.isNested())
574 return false;
575 const isCstruct = sle.sd.isCsymbol(); // C structs are default initialized to all zeros
576 foreach (i; 0 .. sle.sd.fields.length)
578 auto field = sle.sd.fields[i];
579 if (field.type.size(field.loc))
581 auto e = sle.elements && i < sle.elements.length ? (*sle.elements)[i] : null;
582 if (e ? !_isZeroInit(e)
583 : !isCstruct && !field.type.isZeroInit(field.loc))
584 return false;
587 return true;
590 case EXP.arrayLiteral:
592 auto ale = cast(ArrayLiteralExp)exp;
594 const dim = ale.elements ? ale.elements.length : 0;
596 if (ale.type.toBasetype().ty == Tarray) // if initializing a dynamic array
597 return dim == 0;
599 foreach (i; 0 .. dim)
601 if (!_isZeroInit(ale[i]))
602 return false;
605 /* Note that true is returned for all T[0]
607 return true;
610 case EXP.string_:
612 StringExp se = cast(StringExp)exp;
614 if (se.type.toBasetype().ty == Tarray) // if initializing a dynamic array
615 return se.len == 0;
617 foreach (i; 0 .. se.len)
619 if (se.getIndex(i) != 0)
620 return false;
622 return true;
625 case EXP.vector:
627 auto ve = cast(VectorExp) exp;
628 return _isZeroInit(ve.e1);
631 case EXP.float64:
632 case EXP.complex80:
634 import dmd.root.ctfloat : CTFloat;
635 return (exp.toReal() is CTFloat.zero) &&
636 (exp.toImaginary() is CTFloat.zero);
639 default:
640 return false;
644 /***********************************************************
645 * Unions are a variation on structs.
647 extern (C++) final class UnionDeclaration : StructDeclaration
649 extern (D) this(const ref Loc loc, Identifier id)
651 super(loc, id, false);
654 override UnionDeclaration syntaxCopy(Dsymbol s)
656 assert(!s);
657 auto ud = new UnionDeclaration(loc, ident);
658 StructDeclaration.syntaxCopy(ud);
659 return ud;
662 override const(char)* kind() const
664 return "union";
667 override inout(UnionDeclaration) isUnionDeclaration() inout
669 return this;
672 override void accept(Visitor v)
674 v.visit(this);