%%
%%Copyright1994-2019TheMathWorks,Inc.
%%
%%Abstract:
%%ThisTLClibraryfilecontainsthegeneralpurposeutilityfunctions
%%foraccessingdatatypeinformation.
%%
 
%if EXISTS("_DTYPELIB_") == 0
%assign _DTYPELIB_ = 1
 
%include "autosarsup.tlc"
%include "utillib.tlc"
%include "blkio_api.tlc"
 
%if EXISTS("DSP32")
  %assign SizeOfDouble = 4
%else
  %assign SizeOfDouble = 8
%endif
 
%assign int32MinValue = (-2147483647 - 1)
 
%<LibAddToCompiledModel("SizeOfDouble", SizeOfDouble)>
 
%%populatetheemptySymbolicWidthandSymbolicDimensionfields
%%usingthefcnsgeneratedinfileCGTypes_SymbolicWidth.tlc
%if ::CompiledModel.CGTypes.IncludeSymbolicWidth
  %%
  %include "CGTypes_SymbolicWidth.tlc"
%endif
%%donepopulatingtheSymbolicWidthandSymbolicDimension
 
%function SLibCoderTypesBaseName() void
  %return ::CompiledModel.CoderTypesInfo.BaseName
%endfunction
 
%function SLibCoderModelReferenceTypesBaseName() void
  %return ::CompiledModel.CoderTypesInfo.ModelReferenceTypesBaseName
%endfunction
 
%function SLibCoderBuiltinTypeidTypesBaseName() void
  %return ::CompiledModel.CoderTypesInfo.BuiltinTypeidTypesBaseName
%endfunction
 
%function SLibCoderMultiwordTypesBaseName() void
  %return ::CompiledModel.CoderTypesInfo.MultiwordTypesBaseName
%endfunction
 
%function SLibCoderZerocrossingTypesBaseName() void
  %return ::CompiledModel.CoderTypesInfo.ZerocrossingTypesBaseName
%endfunction
 
%function SLibCoderHalfTypeHdrBaseName() void
  %return ::CompiledModel.CoderTypesInfo.HalfTypeHdrBaseName
%endfunction
 
%function SLibCoderHalfTypeSrcBaseName() void
  %return ::CompiledModel.CoderTypesInfo.HalfTypeSrcBaseName
%endfunction
 
%function SLibCoderTypesFilename() void
  %return ::CompiledModel.CoderTypesInfo.FileName
%endfunction
 
%function SLibCoderModelReferenceTypesFilename() void
  %return ::CompiledModel.CoderTypesInfo.ModelReferenceTypesFileName
%endfunction
 
%function SLibCoderBuiltinTypeidTypesFilename() void
  %return ::CompiledModel.CoderTypesInfo.BuiltinTypeidTypesFileName
%endfunction
 
%function SLibCoderMultiwordTypesFilename() void
  %return ::CompiledModel.CoderTypesInfo.MultiwordTypesFileName
%endfunction
 
%function SLibCoderZerocrossingTypesFilename() void
  %return ::CompiledModel.CoderTypesInfo.ZerocrossingTypesFileName
%endfunction
 
%function SLibCoderHalfTypeHdrFilename() void
  %return ::CompiledModel.CoderTypesInfo.HalfTypeHdrFileName
%endfunction
 
%function SLibCoderHalfTypeSrcFilename() void
  %return ::CompiledModel.CoderTypesInfo.HalfTypeSrcFileName
%endfunction
 
%function SLibCoderTypesFilePath() void
  %return ::CompiledModel.CoderTypesInfo.FilePath
%endfunction
 
%function SLibCoderModelReferenceTypesFilePath() void
  %return ::CompiledModel.CoderTypesInfo.ModelReferenceTypesFilePath
%endfunction
 
%function SLibCoderBuiltinTypeidTypesFilePath() void
  %return ::CompiledModel.CoderTypesInfo.BuiltinTypeidTypesFilePath
%endfunction
 
%function SLibCoderMultiwordTypesFilePath() void
  %return ::CompiledModel.CoderTypesInfo.MultiwordTypesFilePath
%endfunction
 
%function SLibCoderZerocrossingTypesFilePath() void
  %return ::CompiledModel.CoderTypesInfo.ZerocrossingTypesFilePath
%endfunction
 
%function SLibCoderHalfTypeHdrFilePath() void
  %return ::CompiledModel.CoderTypesInfo.HalfTypeHdrFilePath
%endfunction
 
%function SLibCoderHalfTypeSrcFilePath() void
  %return ::CompiledModel.CoderTypesInfo.HalfTypeSrcFilePath
%endfunction
 
%function SLibPotentialCoderTypesBaseNames() void
  %return ::CompiledModel.CoderTypesInfo.PotentialBaseNames
%endfunction
 
%function FcnUsedCoderTypes(coderTypesFile) void
  %assign usedCoderTypesFiles = SLibUsedCoderTypesFilenames()
  %foreach fIdx = SIZE(usedCoderTypesFiles, 1)
    %assign usedCoderTypesFile = usedCoderTypesFiles[fIdx]
    %if usedCoderTypesFile == coderTypesFile
      %return TLC_TRUE
    %endif
  %endforeach
  %return TLC_FALSE
%endfunction
 
%function SLibUsedMultiwordTypes() void
  %return FcnUsedCoderTypes(SLibCoderMultiwordTypesFilename())
%endfunction
 
%function SLibUsedZerocrossingTypes() void
  %return FcnUsedCoderTypes(SLibCoderZerocrossingTypesFilename())
%endfunction
 
%function SLibUsedHalfPrecisionTypes() void
  %return FcnUsedCoderTypes(SLibCoderHalfTypeHdrFilename())
%endfunction
 
%function SLibUsedBuiltinTypeidTypes() void
  %return FcnUsedCoderTypes(SLibCoderBuiltinTypeidTypesFilename())
%endfunction
 
%function SLibUsedModelReferenceTypes() void
  %return FcnUsedCoderTypes(SLibCoderModelReferenceTypesFilename())
%endfunction
 
%function SLibUsedCoderTypesFileNames() void
  %return ::CompiledModel.CoderTypesInfo.UsedFilenames
%endfunction
 
%function SLibUsedCoderTypesFilenames() void
  %return ::CompiledModel.CoderTypesInfo.UsedFilenames
%endfunction
 
%function SLibUsedNumericCoderTypesFilenames() void
  %return ::CompiledModel.CoderTypesInfo.UsedNumericFilenames
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%
%function SLibIncludeUsedCoderTypesFilenames() void
  %assign coderTypesFiles = SLibUsedCoderTypesFilenames()
  %openfile buffer
  %foreach fIdx = SIZE(coderTypesFiles,1)
  #include "%"
  %endforeach
  %closefile buffer
  %return buffer
%endfunction
 
%function SLibIncludeUsedNumericCoderTypesFilenames() void
  %assign coderTypesFiles = SLibUsedNumericCoderTypesFilenames()
  %openfile buffer
  %foreach fIdx = SIZE(coderTypesFiles,1)
  #include "%"
  %endforeach
  %closefile buffer
  %return buffer
%endfunction
 
 
%%Function:FcnGenerateStructElementOffsetString=========================
%%Abstract:
%%Utilityfunctionforconstructingthestringcorrespondingtothe
%%element'soffset(struct/bus)
%%
%function FcnGenerateStructElementOffsetString(offsetList) void
  %% Initialize the output string
  %assign fullOffset = ""
 
  %% The first element in the list is a numeric value, the others are strings
  %% like "value*loopcounter"
  %assign sep = ""
  %foreach idxOffset = SIZE(offsetList,0)-1
    %assign fullOffset = fullOffset + sep + offsetList[idxOffset+1][0]
    %assign sep = " + "
  %endforeach
 
  %% Convert the first element to a string
  %assign optOffset = ISEQUAL(offsetList[0][0],0) ? "" : "%"
 
  %% Construct the full offset string (value1*loopcounter1 +...+ valueN*loopcounterN + constant)
  %if WHITE_SPACE(fullOffset)
      %assign fullOffset = WHITE_SPACE(optOffset) ? "" : "%<optOffset>"
  %else
      %assign fullOffset = WHITE_SPACE(optOffset) ? "%<fullOffset>" : "%<fullOffset> + %<optOffset>"
  %endif
 
  %return fullOffset
%endfunction
 
%%Function:SLibAssignSLStructToUserStructND=============================
%%Abstract:
%%MarshallaSimulink'sarrayofstructurestoanuser'sarrayofstructures.
%%
%function SLibAssignSLStructToUserStructND(dTypeId, width, dst, srcAddr, offsetList, level, isCplx) Output
  %assign dataTypeSize = LibGetDataTypeSLSizeFromId(dTypeId)
  %%
  %if isCplx
    %% Lists for holding real&imag offsets
    %assign reOffsetList = Matrix(1,1) [0]
    %assign imOffsetList = Matrix(1,1) [0]
  %endif
  %%
  %% Add a loop and correct offset for non-scalar struct
  %if ISEQUAL(width,1)==TLC_FALSE
    %assign loopCounter = "i%<level>"
    %assign dtName = isCplx ? LibGetDataTypeComplexNameFromId(dTypeId) : LibGetDataTypeNameFromId(dTypeId)
    %assign dst = "((" + dtName + "*)" + dst + ")[%<loopCounter>]"
    %if isCplx
      %% Real part read every 2*i
      %assign loopOffset = ISEQUAL(dataTypeSize,1) ? "2*%<loopCounter>" : "%<dataTypeSize>*(2*%<loopCounter>)"
      %assign reOffsetList = offsetList + ["%<loopOffset>"]
      %% Imag part read every 2*i+1
      %assign loopOffset = ISEQUAL(dataTypeSize,1) ? "2*%<loopCounter> + 1" : "%<dataTypeSize>*(2*%<loopCounter> + 1)"
      %assign imOffsetList = offsetList + ["%<loopOffset>"]
    %else
      %assign loopOffset = ISEQUAL(dataTypeSize,1) ? "%<loopCounter>" : "%<dataTypeSize>*%<loopCounter>"
      %assign offsetList = offsetList + ["%<loopOffset>"]
    %endif
    {
      int_T %<loopCounter>;
      for (%<loopCounter> = 0; %<loopCounter> < %<width>; %<loopCounter>++) {
    %assign level = level + 1
  %else
    %if isCplx
      %assign reOffsetList = offsetList
      %assign imOffsetList = offsetList + ["%<dataTypeSize>"]
    %endif
  %endif
  %%
  %foreach idxE = LibDataTypeNumElements(dTypeId)
    %assign eName = LibDataTypeElementName(dTypeId, idxE)
    %assign eDTypeId = LibGetDataTypeIdAliasedThruToFromId(LibDataTypeElementDataTypeId(dTypeId, idxE))
    %assign eWidth = LibDataTypeElementWidth(dTypeId, idxE)
    %assign eOffset = LibDataTypeElementOffset(dTypeId, idxE)
    %if !isCplx
      %% Update the offset list for reading this element
      %assign eOffsetList = offsetList
      %assign eOffsetList[0][0] = eOffsetList[0][0] + eOffset
    %else
      %% Update the offset list for reading the real part of this element
      %assign eReOffsetList = reOffsetList
      %assign eReOffsetList[0][0] = eReOffsetList[0][0] + eOffset
      %% Update the offset list for reading the imag part of this element
      %assign eImOffsetList = imOffsetList
      %assign eImOffsetList[0][0] = eImOffsetList[0][0] + eOffset
    %endif
    %%
    %% This element can be an array of complex structures only if it
    %% corresponds to a multi-word fixed-point array. Complex Simulink.Bus
    %% are not yet supported.
    %assign eIsCplx = LibDataTypeElementIsComplex(dTypeId, idxE)
 
    %% there is no nested complex data type.
    %assert !(isCplx && eIsCplx)
 
    %if !isCplx
      %assign eDst = dst+"."+eName
    %else
      %assign eDstReal = dst+"."+tRealPart+"."+eName
      %assign eDstImag = dst+"."+tImagPart+"."+eName
    %endif
    %%
    %if LibIsStructDataType(eDTypeId)
      %if !isCplx
        %% Recurse for marshalling sub-structure element
        %<SLibAssignSLStructToUserStructND(eDTypeId, eWidth, ...
          eDst, srcAddr, eOffsetList, level, eIsCplx)>/
      %else
        %% Recurse for marshalling sub-structure element for the real part
        %% of the root structure
        %<SLibAssignSLStructToUserStructND(eDTypeId, eWidth,...
           eDstReal, srcAddr, eReOffsetList, level, eIsCplx)>/
        %% Recurse for marshalling sub-structure element for the imag part
        %% of the root structure
        %<SLibAssignSLStructToUserStructND(eDTypeId, eWidth, ...
          eDstImag, srcAddr, eImOffsetList, level, eIsCplx)>/
      %endif
    %else
      %assign eDTypeSize = LibGetDataTypeSLSizeFromId(eDTypeId)
      %assign optAddr = ISEQUAL(eWidth,1) ? "&" : ""
      %if eIsCplx
        %assign eWidth = eWidth*2
      %endif
      %if !isCplx
        %% Generate the full string corresponding to the element's offset
        %% and add the string to the the Src address
        %assign eOffsetStr = FcnGenerateStructElementOffsetString(eOffsetList)
        %assign eSrc = WHITE_SPACE(eOffsetStr) ? srcAddr : srcAddr +" + %<eOffsetStr>"
      %else
        %% Generate the full string corresponding to the element's offset
        %% for the real part of the root structure and add the string to
        %% the real part of the root structure
        %assign eOffsetStr = FcnGenerateStructElementOffsetString(eReOffsetList)
        %assign eSrcReal = WHITE_SPACE(eOffsetStr) ? srcAddr : srcAddr +" + %<eOffsetStr>"
        %% Do the same as previously but for the imag part
        %assign eOffsetStr = FcnGenerateStructElementOffsetString(eImOffsetList)
        %assign eSrcImag = WHITE_SPACE(eOffsetStr) ? srcAddr : srcAddr +" + %<eOffsetStr>"
      %endif
      %if ISEQUAL(eWidth,1)
        %% Scalar structure element
        %if !isCplx
          %% Simple assignment
          %<eDst> = *((%<LibGetDataTypeNameFromId(eDTypeId)>*)(%<eSrc>));
        %else
          %% Real part assignment
          %<eDstReal> = *((%<LibGetDataTypeNameFromId(eDTypeId)>*)(%<eSrcReal>));
          %% Imag part assignment
          %<eDstImag> = *((%<LibGetDataTypeNameFromId(eDTypeId)>*)(%<eSrcImag>));
        %endif
      %else
        %% Wide structure element
        %if !isCplx
          (void) %<LibGenMemFcnCall("memcpy", "%<optAddr>%<eDst>", ...
            "%<eSrc>", "%")>;
        %else
          (void) %<LibGenMemFcnCall("memcpy", "%<optAddr>%<eDstReal>",...
             "%<eSrcReal>", "%")>;
          (void) %<LibGenMemFcnCall("memcpy", "%<optAddr>%<eDstImag>", ...
             "%<eSrcImag>", "%")>;
        %endif
      %endif
    %endif
  %endforeach
  %if ISEQUAL(width,1)==TLC_FALSE
    %% Close the block and foor-loop statements
      }
    }
  %endif
 
%endfunction
 
 
%%Function:SLibAssignUserStructToSLStructND=============================
%%Abstract:
%%Marshallanuser'sarrayofstructurestoaSimulink'sarrayofstructures.
%%
%function SLibAssignUserStructToSLStructND(dTypeId, width, dstAddr, src, offsetList, level, isCplx) Output
  %assign dataTypeSize = LibGetDataTypeSLSizeFromId(dTypeId)
  %%
  %if isCplx
    %% Lists for holding real&imag offsets
    %assign reOffsetList = Matrix(1,1) [0]
    %assign imOffsetList = Matrix(1,1) [0]
  %endif
  %%
  %% Add a loop and correct offset for non-scalar struct
  %if ISEQUAL(width,1)==TLC_FALSE
    %assign loopCounter = "i%<level>"
    %assign dtName = isCplx ? LibGetDataTypeComplexNameFromId(dTypeId) : LibGetDataTypeNameFromId(dTypeId)
    %assign src = "((" + dtName + "*)" + src + ")[%<loopCounter>]"
    %if isCplx
      %% Real part read every 2*i
      %assign loopOffset = ISEQUAL(dataTypeSize,1) ? "2*%<loopCounter>" : "%<dataTypeSize>*(2*%<loopCounter>)"
      %assign reOffsetList = offsetList + ["%<loopOffset>"]
      %% Imag part read every 2*i+1
      %assign loopOffset = ISEQUAL(dataTypeSize,1) ? "2*%<loopCounter> + 1" : "%<dataTypeSize>*(2*%<loopCounter> + 1)"
      %assign imOffsetList = offsetList + ["%<loopOffset>"]
    %else
      %assign loopOffset = ISEQUAL(dataTypeSize,1) ? "%<loopCounter>" : "%<dataTypeSize>*%<loopCounter>"
      %assign offsetList = offsetList + ["%<loopOffset>"]
    %endif
    {
      int_T %<loopCounter>;
      for (%<loopCounter> = 0; %<loopCounter> < %<width>; %<loopCounter>++) {
    %assign level = level + 1
  %else
    %if isCplx
      %assign reOffsetList = offsetList
      %assign imOffsetList = offsetList + ["%<dataTypeSize>"]
    %endif
  %endif
  %%
  %foreach idxE = LibDataTypeNumElements(dTypeId)
    %assign eName = LibDataTypeElementName(dTypeId, idxE)
    %assign eDTypeId = LibGetDataTypeIdAliasedThruToFromId(LibDataTypeElementDataTypeId(dTypeId, idxE))
    %assign eWidth = LibDataTypeElementWidth(dTypeId, idxE)
    %assign eOffset = LibDataTypeElementOffset(dTypeId, idxE)
    %if !isCplx
      %% Update the offset list for reading this element
      %assign eOffsetList = offsetList
      %assign eOffsetList[0][0] = eOffsetList[0][0] + eOffset
    %else
      %% Update the offset list for reading the real part of this element
      %assign eReOffsetList = reOffsetList
      %assign eReOffsetList[0][0] = eReOffsetList[0][0] + eOffset
      %% Update the offset list for reading the imag part of this element
      %assign eImOffsetList = imOffsetList
      %assign eImOffsetList[0][0] = eImOffsetList[0][0] + eOffset
    %endif
    %%
    %% This element can be an array of complex structures only if it
    %% corresponds to a multi-word fixed-point array.Complex Simulink.Bus
    %% are not yet supported.
    %assign eIsCplx = LibDataTypeElementIsComplex(dTypeId, idxE)
    %if !isCplx
      %assign eSrc = src+"."+eName
    %else
      %assign eSrcReal = src+"."+tRealPart+"."+eName
      %assign eSrcImag = src+"."+tImagPart+"."+eName
    %endif
    %%
    %if LibIsStructDataType(eDTypeId)
      %if !isCplx
        %% Recurse for marshalling sub-structure element
        %<SLibAssignUserStructToSLStructND(eDTypeId, eWidth, dstAddr, ...
          eSrc, eOffsetList, level, eIsCplx)>/
      %else
        %% Recurse for marshalling sub-structure element for the real part
        %% of the root structure
        %<SLibAssignUserStructToSLStructND(eDTypeId, eWidth, dstAddr, ...
          eSrcReal, eReOffsetList, level, eIsCplx)>/
        %% Recurse for marshalling sub-structure element for the imag part
        %% of the root structure
        %<SLibAssignUserStructToSLStructND(eDTypeId, eWidth, dstAddr, ...
          eSrcImag, eImOffsetList, level, eIsCplx)>/
      %endif
    %else
      %assign eDTypeSize = LibGetDataTypeSLSizeFromId(eDTypeId)
      %assign optAddr = ISEQUAL(eWidth,1) ? "&" : ""
      %if eIsCplx
        %assign eWidth = eWidth*2
      %endif
      %if !isCplx
        %% Generate the full string corresponding to the element's offset
        %% and add the string to the the Dst address
        %assign eOffsetStr = FcnGenerateStructElementOffsetString(eOffsetList)
        %assign eDst = WHITE_SPACE(eOffsetStr) ? dstAddr : dstAddr+ " + %<eOffsetStr>"
      %else
        %% Generate the full string corresponding to the element's offset
        %% for the real part of the root structure and add the string to
        %% the real part of the root structure
        %assign eOffsetStr = FcnGenerateStructElementOffsetString(eReOffsetList)
        %assign eDstReal = WHITE_SPACE(eOffsetStr) ? dstAddr : dstAddr +" + %<eOffsetStr>"
        %% Do the same as previously but for the imag part
        %assign eOffsetStr = FcnGenerateStructElementOffsetString(eImOffsetList)
        %assign eDstImag = WHITE_SPACE(eOffsetStr) ? dstAddr : dstAddr +" + %<eOffsetStr>"
      %endif
      %if ISEQUAL(eWidth,1)
        %% Scalar structure element
        %if !isCplx
          %% Simple assignment
          *((%<LibGetDataTypeNameFromId(eDTypeId)>*)(%<eDst>)) = %<eSrc>;
        %else
          %% Real part assignment
          *((%<LibGetDataTypeNameFromId(eDTypeId)>*)(%<eDstReal>)) = %<eSrcReal>;
          %% Imag part assignment
          *((%<LibGetDataTypeNameFromId(eDTypeId)>*)(%<eDstImag>)) = %<eSrcImag>;
        %endif
      %else
        %% Wide structure element
        %if !isCplx
          (void) %<LibGenMemFcnCall("memcpy", "%<eDst>", ...
            "%<optAddr>%<eSrc>", "%")>;
        %else
          (void) %<LibGenMemFcnCall("memcpy", "%<eDstReal>",...
             "%<optAddr>%<eSrcReal>", "%")>;
          (void) %<LibGenMemFcnCall("memcpy", "%<eDstImag>", ...
             "%<optAddr>%<eSrcImag>", "%")>;
        %endif
        %%
      %endif
    %endif
  %endforeach
  %if ISEQUAL(width,1)==TLC_FALSE
    %% Close the block and foor-loop statements
      }
    }
  %endif
%endfunction
 
 
%%Function:SLibAssignSLStructToUserStruct===============================
%%Abstract:
%%MarshallSimulink.Bus=>userstructurerepresentation
%%
%function SLibAssignSLStructToUserStruct(dTypeId, dst, srcAddr, startOffset) Output
  %% Redirect the call to the more generic function by setting the width=1, the level
  %% of recursion to 0 and the complexity=TLC_FALSE.
  %<SLibAssignSLStructToUserStructND(dTypeId, 1, dst, srcAddr, Matrix(1,1) [0], 0, TLC_FALSE)>/
%endfunction
 
 
%%Function:SLibAssignUserStructToSLStruct===============================
%%Abstract:
%%Marshalluserstructure=>Simulink.Busrepresentation
%%
%function SLibAssignUserStructToSLStruct(dTypeId, dstAddr, src, startOffset) Output
  %% Redirect the call to the more generic function by setting the width=1, the level
  %% of recursion to 0 and the complexity=TLC_FALSE
  %<SLibAssignUserStructToSLStructND(dTypeId, 1, dstAddr, src, Matrix(1,1) [0], 0, TLC_FALSE)>/
%endfunction
 
%%Function:SLibValueIsAllZeros============================================
%%Abstract:
%%Returntrueifwecantellagivenvalueofadatatypeisof
%%zero-representation,consideringfloatinitializationoptions.
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/tStringSupport.m
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/inlineVariants/tInlineVariants8.m
%%
%function SLibValueIsAllZeros(dTypeId, valueToSet, bSetFltsAndDblsToZero) void
  %%
  %if ISEQUAL(valueToSet,0)
    %return 1
  %endif
  %%
  %if TYPE(valueToSet) == "String"
    %%
    %% The string case could be many things such as a #define'd constant
    %% can't handle all possibilities. The key case and most common case
    %% is memset to 0, so handle that one case.
    %%
    %if valueToSet == "0"
      %return 1
    %endif
    %%
    %assign upperValueToSet = FEVAL("upper", valueToSet)
    %if upperValueToSet == "0U" || ...
        upperValueToSet == "0L" || ...
        upperValueToSet == "0UL" || ...
        upperValueToSet == "0LU" || ...
        upperValueToSet == "0.0" || ...
        upperValueToSet == "0.0F" || ...
        upperValueToSet == "FLOATTOHALF(0.0F)" %%half ground value
      %return 1
    %endif
    %%
    %% Handle boolean data type
    %%
    %if upperValueToSet == "FALSE"
      %assign dThruId = LibGetDataTypeIdAliasedThruToFromId(dTypeId)
      %if dThruId == tSS_BOOLEAN
        %return 1
      %endif
    %endif
    %%
    %% Handle struct data type
    %%
    %if LibIsStructDataType(dTypeId) || LibIsEnumDataType(dTypeId)
      %%
      %assign gndValue = SLibGetGroundValueFromId(dTypeId)
      %if ISEQUAL(valueToSet, gndValue) %% be conservative
        %return !(::CompiledModel.DataTypes.DataType[dTypeId].GroundHasNonZero || ...
          (bSetFltsAndDblsToZero && ...
          ::CompiledModel.DataTypes.DataType[dTypeId].GroundHasFloats))
      %endif
    %endif
    %%
  %endif
  %%
  %return 0
  %%
%endfunction
 
%%Function:SLibValueIsAllZeroBitsCrudeCheck===============================
%%Abstract:
%%Returntrueifwecantellagivenvalueofadatatypeisof
%%zero-representation.
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/tValueVariants.m
%%
%function SLibValueIsAllZeroBitsCrudeCheck(dTypeId, valueToSet) void
  %if LibDoesDataTypeNeedConstructor(dTypeId)
    %return TLC_FALSE
  %else
    %%Check if the valueToSet is a vector
    %if TYPE(valueToSet) == "Vector"
      %assign sze = SIZE(valueToSet)
      %assign retVal = TLC_TRUE
      %foreach idx = sze[1]
        %assign val = SLibValueIsAllZeros(dTypeId, valueToSet[idx], InitFltsAndDblsToZero)
        %if ISEQUAL(val,TLC_FALSE)
          %return TLC_FALSE
        %endif
      %endforeach
      %return retVal
    %else
      %return SLibValueIsAllZeros(dTypeId, valueToSet, InitFltsAndDblsToZero)
    %endif
  %endif
%endfunction
 
%%Function:SLibDataTypeRequiresZeroInit======================================
%%Abstract:
%%Thisfunctionreturnstrueifadata-elementofagivenrequiresalogical
%%zerointialization.
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/-tStringSupport.m
%%
%function SLibDataTypeRequiresZeroInit(dTypeId, bSetFltsAndDblsToZero) void
  %%
  %if LibDoesDataTypeNeedConstructor(dTypeId)
    %return TLC_FALSE
  %elseif LibIsStructDataType(dTypeId)
    %if ::CompiledModel.DataTypes.DataType[dTypeId].GroundHasNonZero
      %return TLC_FALSE
    %elseif bSetFltsAndDblsToZero && ::CompiledModel.DataTypes.DataType[dTypeId].GroundHasFloats
      %return TLC_FALSE
    %else
      %return TLC_TRUE
    %endif
  %else
    %assign gndValue = SLibGetGroundValueFromIdStrictOpt(dTypeId,0)
    %return SLibValueIsAllZeros(dTypeId, gndValue, bSetFltsAndDblsToZero)
  %endif
  %%
%endfunction
 
 
%%Function:SLibGroundIsZero=================================================
%%Note:
%%
%function SLibGroundIsZero(dTypeId) void
  %return SLibDataTypeRequiresZeroInit(dTypeId, InitFltsAndDblsToZero)
%endfunction
 
%%Function:SLibDefaultInitialValueIsAllZeroBits==============================
%%Note:
%%JustawrapperofSLibGroundIsZerofornow.Seecommentsin
%%SLibGetDefaultInitialValueFromIdalso.
%%
%%NotethatfuturechangetoSLibGetDefaultInitialValueFromIdmeans
%%changetothisfunctionneededaswell.
%%
%%
%function SLibDefaultInitialValueIsAllZeroBits(dTypeId) void
  %return SLibDataTypeRequiresZeroInit(dTypeId, InitFltsAndDblsToZero)
%endfunction
 
%%Function:SLibAllValuesMatch================================================
%%Abstract:
%%Returnstrueifallelementsofavaluesvectormatch.
%%TopTester:test/toolbox/simulink/blocks/buses/tbus.m
%%
%function SLibAllValuesMatch(aValueVector) void
  %if TYPE(aValueVector) == "Vector"
    %assign vectSize = SIZE(aValueVector)
    %assign retVal = TLC_TRUE
    %assign firstEl = aValueVector[0]
    %foreach idx = vectSize[1]
      %if !ISEQUAL(aValueVector[idx], firstEl)
        %return TLC_FALSE
      %endif
    %endforeach
  %endif
  %return TLC_TRUE
%endfunction
 
%%Function:LibCGTypeIsComplex================================================
%%Abstract:
%%Returnwhetherornotthisisacomplextype.Alsoreturnstrueforcomplex
%%matrices,aliasestocomplextypes,andpointerstocomplextypes
%%
%function LibCGTypeIsComplex(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.GetIsComplex", cgTypeIdx)
%endfunction
 
%%Function:SLibCGTypeIsComplexStrict==========================================
%%Abstract:
%%StrictversionofLibCGTypeIsComplex.Returnsfalseforcomplex
%%matrices,aliasestocomplextypes,andpointerstocomplextypes
%%
%function SLibCGTypeIsComplexStrict(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.Constructor", cgTypeIdx) == "complex"
%endfunction
 
%%Function:LibCGTypeIsPointer================================================
%%Abstract:
%%Returnwhetherornotthisisapointertype
%%
%function LibCGTypeIsPointer(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.Constructor", cgTypeIdx) == "pointer"
%endfunction
 
%%Function:LibCGTypeIsReference================================================
%%Abstract:
%%Returnwhetherornotthisisapointertype
%%
%function LibCGTypeIsReference(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.Constructor", cgTypeIdx) == "reference"
%endfunction
 
%%Function:LibCGTypeIsRenamed================================================
%%Abstract:
%%Returnwhetherornotthisisarenamedtype
%%
%function LibCGTypeIsRenamed(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.Constructor", cgTypeIdx) == "renamed"
%endfunction
 
%%Function:LibCGTypeIsVoid===================================================
%%Abstract:
%%Returnwhetherornotthisisavoidtype
%%
%function LibCGTypeIsVoid(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.Constructor", cgTypeIdx) == "void"
%endfunction
 
%%Function:LibCGTypeIsFixed==================================================
%%Abstract:
%%Returnwhetherornotthisisafixedpointtype
%%
%function LibCGTypeIsFixed(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.Constructor", cgTypeIdx) == "fixed"
%endfunction
 
%%Function:LibCGTypeIsChar===================================================
%%Abstract:
%%Returnwhetherornotthisisachartype
%%
%function LibCGTypeIsChar(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.Constructor", cgTypeIdx) == "char"
%endfunction
 
%%Function:LibCGTypeIsString=================================================
%%Abstract:
%%Returnwhetherornotthisisastringtype
%%
%function LibCGTypeIsString(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.Constructor", cgTypeIdx) == "string"
%endfunction
 
%%Function:LibCGTypeIsUnkonwn================================================
%%Abstract:
%%Returnwhetherornotthisisanunknowntype
%%
%function LibCGTypeIsUnknown(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.Constructor", cgTypeIdx) == "unknown"
%endfunction
 
 
%%Function:LibCGTypeIsEmxArray================================================
%%Abstract:
%%ReturnwhetherornotthisisanemxArraytype.
%%emxArraysaregeneratedfromdynamicmatrixtypeswhenthecodegenerator
%%doesnotknowthesizeofamatrixanddoesnotorcannotdeterminean
%%upperboundonitssize.
%%
%%Ingeneratedcode,thislookslike"structemxArray_name>_name>*"
%%
%function LibCGTypeIsEmxArray(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.GetIsEmxArray", cgTypeIdx)
%endfunction
%%Function:LibCGTypeIsConvertedToEmxArray==================================
%%Abstract:
%%IfacgTypeIdxcorrespondstoadynamicmatrixthathasbeenloweredtoan
%%emxArraystructpointer,thiswillreturntrue.
%%
%function LibCGTypeIsConvertedToEmxArray(cgTypeIdx) void
  %assign result = CGMODEL_ACCESS("CGType.GetConvertedToEmxArray", cgTypeIdx)
  %return result != -1
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibCGTypeIsStdContainer
%%Abstract:
%%IfacgTypeIdxcorrespondstoastaticmatrixthatistobeloweredtostdcontainer,
%%thiswillreturntrue.
%function LibCGTypeIsStdContainer(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.GetIsStdContainer", cgTypeIdx)
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibCGTypeContainsStdContainer
%%Abstract:
%%IfacgTypeIdxcorrespondstoatypethatisorcontainsstdcontainertype,
%%thiswillreturntrue.
%function LibCGTypeContainsStdContainer(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.GetContainsStdContainer", cgTypeIdx)
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibCGTypeIsStdContainerClass
%%Abstract:
%%IfacgTypeIdxcorrespondstoastdcontainerclasstype,
%%thiswillreturntrue.
%function LibCGTypeIsStdContainerClass(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.GetIsStdContainerClass", cgTypeIdx)
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibCGTypeStdContainerName
%%Abstract:
%%IfacgTypeIdxcorrespondestoastdcontainertype,returnstdcontainername.
%function LibCGTypeStdContainerName(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.GetStdContainerName", cgTypeIdx)
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibCGTypeStdContainerReferenceIndex
%%Abstract:
%%IfacgTypeIdxcorrespondestoastdcontainertype,returnthereferencedmatrixtypeindex.
%function LibCGTypeStdContainerReferenceIndex(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.GetStdContainerReferenceIndex", cgTypeIdx)
%endfunction
 
%%Function:LibCGTypeIsEnum================================================
%%Abstract:
%%Returnwhetherornotthisisanenumeratedtype.Returnstrueformatrices
%%ofenums,aliasestoenums,andpointerstoenums
%%
%function LibCGTypeIsEnum(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.GetIsEnum", cgTypeIdx)
%endfunction
 
%%Function:SLibCGTypeIsEnumStrict==============================================
%%Abstract:
%%StrictversionofLibCGTypeIsEnum.Returnsfalseformatrices
%%ofenums,aliasestoenums,andpointerstoenums
%%
%function SLibCGTypeIsEnumStrict(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.Constructor", cgTypeIdx) == "enum"
%endfunction
 
%%Function:LibCGTypeScalarBaseType===========================================
%%Abstract:
%%Returnsthescalar(orprimitive)basetypeofaCGtype.
%%
%function LibCGTypeScalarBaseType(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.GetScalarBaseType", cgTypeIdx)
%endfunction %% end of LibCGTypeScalarBaseType
 
%%Function:LibCGTypeFixedPointBaseType===========================================
%%Abstract:
%%Returnsthescalar(orprimitive)basetypeofaCGtype.Calls
%%LibCGTypeScalarBaseTypeinternally.Willnotreturncomplextypes.
%%
%function LibCGTypeFixedPointBaseType(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.GetFixedPointBaseType", cgTypeIdx)
%endfunction %% end of LibCGTypeFixedPointBaseType
 
%%Function:LibCGTypeTag===========================================
%%Abstract:
%%ReturnsthetagforaCGtype.
%%
%function LibCGTypeTag(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.Tag", cgTypeIdx)
%endfunction %% end of LibCGTypeTag
 
%%Function:LibCGTypeIsOpaqueStruct===========================================
%%Abstract:
%%ReturnswhetheraCGtypeisanopaquestruct
%%
%function LibCGTypeIsOpaqueStruct(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.IsOpaque", cgTypeIdx)
%endfunction %% end of LibCGTypeIsOpaqueStruct
 
%%Function:LibCGTypeBias===========================================
%%Abstract:
%%ReturnsthebiasofaCGType
%%
%function LibCGTypeBias(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.Bias", cgTypeIdx)
%endfunction
 
%%Function:LibCGTypeSlope===========================================
%%Abstract:
%%ReturnstheslopeofaCGType
%%
%function LibCGTypeSlope(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.Slope", cgTypeIdx)
%endfunction
 
%%Function:LibCGTypeNBits===========================================
%%Abstract:
%%ReturnstheNBitsofaCGType
%%
%function LibCGTypeNBits(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.NBits", cgTypeIdx)
%endfunction
 
%%Function:LibCGTypeIsSigned===========================================
%%Abstract:
%%ReturnswhetherafixedpointCGTypeissigned
%%
%function LibCGTypeIsSigned(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.IsSigned", cgTypeIdx)
%endfunction
 
%%Function:LibCGTypeExponent===========================================
%%Abstract:
%%ReturnswhethertheexponentofafixedpointCGType
%%
%function LibCGTypeExponent(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.Exponent", cgTypeIdx)
%endfunction
 
%%Function:LibCGTypeIsLoweredMultiword===========================================
%%Abstract:
%%ReturnswhetherastructCGTypealoweredmulti-wordtype
%%
%function LibCGTypeIsLoweredMultiword(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.IsLoweredMultiword", cgTypeIdx)
%endfunction
 
%%Function:LibCGTypeStructAlignment===========================================
%%Abstract:
%%ReturnsthealignmentofastructCGType
%%
%function LibCGTypeStructAlignment(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.StructAlignment", cgTypeIdx)
%endfunction
 
%%Function:LibCGTypeNumMembers===========================================
%%Abstract:
%%ReturnsthenumberofmembersofastructCGType
%%
%function LibCGTypeNumMembers(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.NumMembers", cgTypeIdx)
%endfunction
 
%%Function:LibCGTypeMemberName===========================================
%%Abstract:
%%ReturnsthenameofamemberofastructCGType
%%
%function LibCGTypeMemberName(cgTypeIdx, memberIdx) void
  %return CGMODEL_ACCESS("CGType.Member.Name", cgTypeIdx, memberIdx)
%endfunction
 
%%Function:LibCGTypeMemberCGTypeIdx===========================================
%%Abstract:
%%ReturnstheCGTypeindexofamemberofastructCGType
%%
%function LibCGTypeMemberCGTypeIdx(cgTypeIdx, memberIdx) void
  %return CGMODEL_ACCESS("CGType.Member.CGTypeIdx", cgTypeIdx, memberIdx)
%endfunction
 
%%Function:LibCGTypeMemberCGTypeIdx===========================================
%%Abstract:
%%ReturnsthealignmentofamemberofastructCGType
%%
%function LibCGTypeMemberAlignment(cgTypeIdx, memberIdx) void
  %return CGMODEL_ACCESS("CGType.Member.Alignment", cgTypeIdx, memberIdx)
%endfunction
 
%function LibGetRecordCGTypeIdx(record) void
  %if ISFIELD(record, "CGTypeIdx")
    %return record.CGTypeIdx
  %elseif ISFIELD(record, "VarGroupIdx")
    %assign varGroupIdx = record.VarGroupIdx
    %return SLibVarGroupElementType(varGroupIdx[0], varGroupIdx[1])
  %else
    %assign errMsg = "Should not get here"
    %<LibReportFatalError(errMsg)>
  %endif
%endfunction
 
%%Function:LibGetRecordIsMatrix==============================================
%%Abstract:
%%Returnstrueifagivendatarecordhasamatrixtype
%%
%function LibGetRecordIsMatrix(record) void
  %assign cgTypeIdx = SLibGetRecordContainerCGTypeIdx(record)
  %return LibCGTypeIsMatrix(cgTypeIdx) && "1" != LibCGTypeSymbolicWidth(cgTypeIdx)
%endfunction
 
%%Function:LibCGTypeIsMatrix=================================================
%%Abstract:
%%Returnswhetherornotthisisamatrixtypeoranaliasofamatrixtype.
%%
%function LibCGTypeIsMatrix(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.GetIsMatrix", cgTypeIdx)
%endfunction
 
%%Function:SLibCGTypeIsMatrixStrict===========================================
%%Abstract:
%%StrictversionofLibCGTypeIsMatrix.Returnsfalseforaliasestomatrixtypes.
%%
%function SLibCGTypeIsMatrixStrict(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.Constructor", cgTypeIdx) == "matrix"
%endfunction
 
%%Function:LibCGTypeIsStruct====================================================
%%Abstract:
%%Returntrueifthistypeisastructtype(oranaliasoforpointertoastructtype)
%%
%function LibCGTypeIsStruct(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.GetIsStruct", cgTypeIdx)
%endfunction
 
%%Function:LibCGTypeIsClass====================================================
%%Abstract:
%%Returntrueifthistypeisastructtype(oranaliasoforpointertoastructtype)
%%
%function LibCGTypeIsClass(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.GetIsClass", cgTypeIdx)
%endfunction
 
%%Function:SLibCGTypeIsStructStrict===========================================
%%Abstract:
%%StrictversionofLibCGTypeIsStruct.Willreturnfalseforpointerstoor
%%aliasesofstructtypes
%%
%function SLibCGTypeIsStructStrict(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.Constructor", cgTypeIdx) == "struct"
%endfunction
 
%%Function:LibCGTypeIsArrayOfStructs=========================================
%%Abstract:
%%Returntrueifwehaveanarrayofstructures
%%
%function LibCGTypeIsArrayOfStructs(cgTypeIdx) void
  %assign arrayOfStructs = TLC_FALSE
  %if LibCGTypeIsMatrix(cgTypeIdx)
    %assign arrayOfStructs = LibCGTypeIsStruct(LibCGTypeBaseIndex(cgTypeIdx))
  %endif
  %return arrayOfStructs
%endfunction
 
%%Function:LibCGTypeWidth====================================================
%%Abstract:
%%Returnwidthinelements
%%
%function LibCGTypeWidth(cgTypeIdx) void
  %if cgTypeIdx < ::CompiledModel.DataTypes.NumSLBuiltInDataTypes
    %return 1
  %else
    %return CGMODEL_ACCESS("CGType.Width", cgTypeIdx)
  %endif
%endfunction
 
%%Function:SLibEvalSymbolicWidth========================================
%%Abstract:
%%ReturnsthesymbolicwidthforagivenCGTypeindex.Itwillusethe
%%customstorageobjectidentifier,ifaUseParamIdentifierisfalse.
%%OtherwiseitwillusetheSimulinkparameteridentifier.
%%
%function SLibEvalSymbolicWidth(aCGTypeIdx, aUseParamIdentifier) void
  %assign prevVal = ::UseParamIdentifierForSymbolicDim
  %assign ::UseParamIdentifierForSymbolicDim = aUseParamIdentifier
  %assign fcnName = "SLibCGType" + "%<aCGTypeIdx>" + "SymbolicWidth"
  %assign symDims = %<fcnName>()
  %assign ::UseParamIdentifierForSymbolicDim = prevVal
  %return symDims
%endfunction
 
%%Function:LibCGTypeSymbolicWidth============================================
%%Abstract:
%%ReturnthesymbolicwidthofaCGType
%%TopTester:test/toolbox/simulink/variants/tCSCDefine.m
%%
%function LibCGTypeSymbolicWidth(cgTypeIdx) void
  %assign cgType = ::CompiledModel.CGTypes.CGType[cgTypeIdx]
  %if ISFIELD(cgType, "SymbolicWidth")
    %if ISEMPTY(cgType.SymbolicWidth)
      %assign cgType.SymbolicWidth = SLibEvalSymbolicWidth(cgTypeIdx, TLC_FALSE)
       %addtorecord ::CompiledModel.CGTypes.CGType[cgTypeIdx] ...
         SLSymbolicWidth SLibEvalSymbolicWidth(cgTypeIdx, TLC_TRUE)
    %endif
    %return cgType.SymbolicWidth
  %else
    %return "%<LibCGTypeWidth(cgTypeIdx)>"
  %endif
%endfunction
 
%%Function:LibCGTypeSymbolicDims============================================
%%Abstract:
%%ReturnthesymbolicdimensionsofaCGType
%%
%function LibCGTypeSymbolicDims(cgTypeIdx) void
  %assign cgType = ::CompiledModel.CGTypes.CGType[cgTypeIdx]
  %% TODO: Process symbolic dimensions here, like LibCGTypeSymbolicWidth.
  %return cgType.Dimensions
%endfunction
 
%%Function:LibCGTypeSymbolicVectorDims================
%%Abstract:
%%Returnsthesymbolicdimensionsindexspecification(asastring)ofa
%%CGType;e.g.,[3,7]=>"[3][7]",[3]=>"[3]",[1]=>"".
%%TopTester:test/toolbox/simulink/blocks/tenable.m
%%
%function LibCGTypeSymbolicVectorDims(cgTypeIdx) void
  %assign width = LibCGTypeSymbolicWidth(cgTypeIdx)
  %if "1" == width && !LibCGTypeIsMatrix(cgTypeIdx)
    %return ""
  %elseif LibCGTypeIsStdContainer(cgTypeIdx)
    %return ""
  %else
    %assign dims = LibCGTypeSymbolicDimensions(cgTypeIdx)
    %assign isScalar = TLC_TRUE
    %assign nonSingletonDimsCount = 0
    %assign retDims = ""
    %foreach dimIdx = SIZE(dims, 1)
      %if dims[dimIdx] != "1"
        %assign isScalar = TLC_FALSE
        %assign nonSingletonDimsCount = nonSingletonDimsCount + 1
      %endif
      %assign retDims = retDims + "[%]"
    %endforeach
    %if isScalar && !LibCGTypeIsMatrix(cgTypeIdx)
      %return ""
    %elseif nonSingletonDimsCount == 1
      %% Vector case
      %return "[" + width + "]"
    %else
      %return retDims
    %endif
  %endif
%endfunction
 
%%Function:LibCGTypeDimensions===============================================
%%Abstract:
%%Returndimensions
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function LibCGTypeDimensions(idx) void
  %if idx < ::CompiledModel.DataTypes.NumSLBuiltInDataTypes
    %return 1
  %endif
  %if LibCGTypeIsMatrix(idx)
    %return ::CompiledModel.CGTypes.CGType[idx].Dimensions
  %elseif LibCGTypeIsPointer(idx) || LibCGTypeIsRenamed(idx)
    %return LibCGTypeDimensions(LibCGTypeBaseIndex(idx))
  %else
    %return 1
  %endif
%endfunction
 
%%Function:SLibEvalSymbolicDimensions========================================
%%Abstract:
%%ReturnsthesymbolicdimensionsforagivenCGTypeindex.Itwillusethe
%%customstorageobjectidentifier,ifaUseParamIdentifierisfalse.
%%OtherwiseitwillusetheSimulinkparameteridentifier.
%%
%function SLibEvalSymbolicDimensions(aCGTypeIdx, aUseParamIdentifier) void
  %assign prevVal = ::UseParamIdentifierForSymbolicDim
  %assign ::UseParamIdentifierForSymbolicDim = aUseParamIdentifier
  %assign fcnName = "SLibCGType" + "%<aCGTypeIdx>" + "SymbolicDimensions"
  %assign symDims = %<fcnName>()
  %assign ::UseParamIdentifierForSymbolicDim = prevVal
  %return symDims
%endfunction
 
%%Function:LibCGTypeSymbolicDimensions=======================================
%%Abstract:
%%Returnssymbolicdimensions.Thereturntypeisarrayofstrings.
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/dimensionVariants/tDimensionVariants5.m
%%
%function LibCGTypeSymbolicDimensions(idx) void
  %if idx < ::CompiledModel.DataTypes.NumSLBuiltInDataTypes
    %return ["1"]
  %endif
  %% When we fall into this case, the idx is the CGType index of a dynamic
  %% matrix. Such a matrix is assumed by certain parts of code generation
  %% infrastructure to be a symbolic dimension, and will look something like:
  %% { Dimensions [-1, -1]; SymbolicDimensions ["", ""]; SymbolicWidth "" }
  %% Note the absence of names in SymbolicDimensions field, which would
  %% normally be an expression. The empty names in SymbolicDimensions field is
  %% normally considered an error. Will probably need to revisit this if we
  %% come up with a case where we get an symbolic-sized array of emxArray
  %% pointers.
  %%
  %% At the moment I believe we can only get a single emxArray pointer here,
  %% and we just return that it has width 1.
  %%
  %if LibCGTypeIsEmxArray(idx) || LibCGTypeIsConvertedToEmxArray(idx)
    %return ["1"]
  %endif
  %if LibCGTypeIsMatrix(idx) && ...
    ISFIELD(::CompiledModel.CGTypes.CGType[idx], "SymbolicDimensions")
    %if ISEMPTY(::CompiledModel.CGTypes.CGType[idx].SymbolicDimensions)
      %assign ::CompiledModel.CGTypes.CGType[idx].SymbolicDimensions = ...
        SLibEvalSymbolicDimensions(idx, TLC_FALSE)
      %addtorecord ::CompiledModel.CGTypes.CGType[idx] ...
        SLSymbolicDimensions SLibEvalSymbolicDimensions(idx, TLC_TRUE)
    %endif
    %return ::CompiledModel.CGTypes.CGType[idx].SymbolicDimensions
  %else
    %assign dims = LibCGTypeDimensions(idx)
    %assign ndims = SIZE(dims, 1)
    %assign symbolicDims = Vector(%<ndims>) [""@%<ndims>]
    %foreach dim = ndims
      %assign symbolicDims[%<dim>] = "%"
    %endforeach
  %endif
  %return symbolicDims
%endfunction
 
%%Function:LibCGTypeBaseIndex================================================
%%Abstract:
%%Returnbaseindex
%%
%function LibCGTypeBaseIndex(cgTypeIdx) void
  %return CGMODEL_ACCESS("CGType.BaseIdx", cgTypeIdx)
%endfunction
 
%%Function:SLibCGTypeToSLType================================================
%%Abstract:
%%ReturnstheSLTypeindexforagivenCGTypeindex.Itreturns-1if
%%noSLTypeexistsoroptionallyreportsanerror
%%TopTester:test/toolbox/simulink/variants/vssSigObj/tVSSSigObj.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortFcnCall3.m
%%
%function SLibCGTypeToSLType(aCGTypeIdx, aReportError) void
  %assign slTypeIdx = CGMODEL_ACCESS("CGType.GetSLTypeIdxForCGType", aCGTypeIdx)
  %if ((slTypeIdx == -1) && aReportError)
    %assign constructor = CGMODEL_ACCESS("CGType.Constructor", aCGTypeIdx)
    %assign errMsg = "invalid SLTypeIdx %<slTypeIdx> for %<constructor>"
    %<LibReportFatalError(errMsg)>
  %endif
  %return slTypeIdx
%endfunction
 
%%Function:LibCGTypeToSLType================================================
%%Abstract:
%%ReturnstheSLTypeindexforagivenCGTypeindexandreportsanerrorif
%%noSLTypeexists.
%%
%function LibCGTypeToSLType(aCGTypeIdx) void
  %return SLibCGTypeToSLType(aCGTypeIdx, TLC_TRUE)
%endfunction
 
%%Function:LibCGTypeSLBaseType=================================================
%%Abstract:
%%ReturnstheSimulinkbasetypeofaCGtype.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/variants/tCSCDefine.m
%%
%function LibCGTypeSLBaseType(cgTypeIdx) void
  %foreach i = cgTypeIdx
    %if ::CompiledModel.CGTypes.CGType[cgTypeIdx].SLTypeIdx > -1
      %return ::CompiledModel.CGTypes.CGType[cgTypeIdx].SLTypeIdx
    %elseif LibCGTypeIsEmxArray(cgTypeIdx)
        %% When we enter here cgTypeIdx corresponds to emxArray*. We are looking
        %% for the base simulink type. This first call to LibCGTypeBaseIndex
        %% strips off the pointer to give the structure type.
        %assign cgTypeIdx = LibCGTypeBaseIndex(cgTypeIdx)
        %% Now we go from the struct type to the base simulink type.
        %assign cgTypeIdx = LibCGTypeBaseIndex(cgTypeIdx)
    %else
      %if LibCGTypeIsMatrix(cgTypeIdx) || LibCGTypeIsComplex(cgTypeIdx) || ...
        LibCGTypeIsPointer(cgTypeIdx) || LibCGTypeIsRenamed(cgTypeIdx)
        %assign cgTypeIdx = LibCGTypeBaseIndex(cgTypeIdx)
      %else
        %assign constructor = CGMODEL_ACCESS("CGType.Constructor", cgTypeIdx)
        %assign errMsg = "invalid SLTypeIdx -1 for %<constructor>"
        %<LibReportFatalError(errMsg)>
      %endif
    %endif
  %endforeach
  %return cgTypeIdx
%endfunction
 
%%Function:LibCGTypeName=====================================================
%%Abstract:
%%ReturnstheCGTypename
%%TopTester:test/toolbox/simulink/variants/vssSigObj/tVSSSigObj.m
%%
%function LibCGTypeName(cgTypeIdx) void
  %return LibOptStdCGTypeName(cgTypeIdx, TLC_FALSE)
%endfunction
   
%%Function:LibOptStdCGTypeName
%%Abstract:
%%ReturnstheCGTypename
%%
%%SpecifytheuseStdContainerNameargumentaswhethertoreturnstdcontainername
%%ifthetypeisapre-loweringstdcontainertype
%%
%function LibOptStdCGTypeName(cgTypeIdx, useStdContainerName) void
  %foreach i = cgTypeIdx+1
    %assign cgTypeRec = ::CompiledModel.CGTypes.CGType[cgTypeIdx]
    %if ISFIELD(cgTypeRec, "Name")
      %return cgTypeRec.Name
    %elseif useStdContainerName && LibCGTypeIsStdContainer(cgTypeIdx)
      %return LibCGTypeStdContainerName(cgTypeIdx)
    %else
      %assign isComplex = TLC_FALSE
      %if LibCGTypeIsMatrix(cgTypeIdx)
        %assign cgTypeIdx = LibCGTypeBaseIndex(cgTypeIdx)
      %elseif LibCGTypeIsComplex(cgTypeIdx)
        %assign isComplex = TLC_TRUE
        %assign cgTypeRec = ::CompiledModel.CGTypes.CGType[LibCGTypeBaseIndex(cgTypeIdx)]
      %elseif LibCGTypeIsEmxArray(cgTypeIdx)
        %% cgTypeIdx corresponds to an emxArray* pointer. The emxArray* does
        %% not have a name; so, strip off the pointer type, to get the
        %% structure, which does have a named type.
        %%
        %assign cgTypeRec = ::CompiledModel.CGTypes.CGType[LibCGTypeBaseIndex(cgTypeIdx)]
        %if ISFIELD(cgTypeRec, "Name")
          %% Now we have to add back the pointer level that we stripped off.
          %return cgTypeRec.Name + "*"
        %endif
      %else
        %assign slTypeIdx = cgTypeRec.SLTypeIdx
        %if slTypeIdx < 0 || slTypeIdx >= ::CompiledModel.DataTypes.NumDataTypes
          %assign constructor = CGMODEL_ACCESS("CGType.Constructor", cgTypeIdx)
          %assign errMsg = "invalid SLTypeIdx %<slTypeIdx> for %<constructor>"
          %<LibReportFatalError(errMsg)>
        %endif
        %if (isComplex)
          %return LibGetDataTypeComplexNameFromId(slTypeIdx)
        %else
          %return LibGetDataTypeNameFromId(slTypeIdx)
        %endif
      %endif
    %endif
  %endforeach
  %return "#error"
%endfunction
 
%%Function:LibAliasedThruCGTypeName===========================================
%%Abstract:
%%ReturnstheCGTypenamestrippingoffaliases
%%TopTester:test/toolbox/simulink/variants/inlineVariants/wiperexample/twipervariant.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/ivGeneral/tRootOutportStorageClass.m
%%
%function LibAliasedThruCGTypeName(cgTypeIdx) void
  %foreach i = cgTypeIdx+1
    %assign cgTypeRec = ::CompiledModel.CGTypes.CGType[cgTypeIdx]
    %assign isComplex = TLC_FALSE
    %if LibCGTypeIsMatrix(cgTypeIdx)
      %assign cgTypeIdx = LibCGTypeBaseIndex(cgTypeIdx)
    %elseif LibCGTypeIsComplex(cgTypeIdx)
      %assign isComplex = TLC_TRUE
      %assign cgTypeRec = ::CompiledModel.CGTypes.CGType[LibCGTypeBaseIndex(cgTypeIdx)]
    %elseif LibCGTypeIsRenamed(cgTypeIdx)
      %return LibCGTypeName(LibCGTypeBaseIndex(cgTypeIdx))
    %else
      %assign slTypeIdx = cgTypeRec.SLTypeIdx
      %if slTypeIdx < 0 || slTypeIdx >= ::CompiledModel.DataTypes.NumDataTypes
        %assign constructor = CGMODEL_ACCESS("CGType.Constructor", cgTypeIdx)
        %assign errMsg = "invalid SLTypeIdx %<slTypeIdx> for %<constructor>"
        %<LibReportFatalError(errMsg)>
      %endif
      %if (isComplex)
        %return LibGetDataTypeComplexNameFromId(slTypeIdx)
      %else
        %return LibGetDataTypeNameFromId(slTypeIdx)
      %endif
    %endif
  %endforeach
  %return "#error"
%endfunction
 
%%Function:SLibGetRecordOriginalCGTypeIdx====================================
%%Abstract:
%%Returnstheoriginal(notstorage)CGtypeindexforagivendatarecord
%%
%function SLibGetRecordOriginalCGTypeIdx(rec) void
  %return ISFIELD(rec, "OriginalCGTypeIdx") ? ...
    rec.OriginalCGTypeIdx : rec.CGTypeIdx
%endfunction
 
%%Function:SLibGetRecordContainerCGTypeIdx===================================
%%Abstract:
%%ReturnsthecontainerorimplementationCGtypeindexforagiven
%%datarecord.
%%
%%ForoptimizationreasonsifContainerCGTypeIdxisthesameas
%%CGTypeIdxtheformergetsoptimizedaway.Forthisreason
%%iftheformerisnotfoundthelaterisused.
%%TopTester:test/toolbox/simulink/variants/vssSigObj/tVSSSigObj.m
%%
%function SLibGetRecordContainerCGTypeIdx(rec) void
  %if ISFIELD(rec, "ContainerCGTypeIdx") && ...
      rec.ContainerCGTypeIdx >= 0
    %return rec.ContainerCGTypeIdx
  %elseif (ISFIELD(rec, "RecordType") && rec.RecordType == "ZcSignalInfo")
    %% There is no CGType on ZcSignalInfo. Go to the VarGroup to get the type.
    %return SLibVarGroupElementType(rec.VarGroupIdx[0], rec.VarGroupIdx[1])
  %else
    %return rec.CGTypeIdx
  %endif
%endfunction
 
%%Function:SLibGetRecordContainerCGType======================================
%%Abstract:
%%ReturnsthecontainerorimplementationCGtyperecordforagiven
%%datarecord.
%%
%function SLibGetRecordContainerCGType(rec) void
  %return ::CompiledModel.CGTypes.CGType[SLibGetRecordContainerCGTypeIdx(rec)]
%endfunction
 
%%Function:SLibGetRecordContainerTypeName====================================
%%Abstract:
%%Returnsthecontainerorimplementationtypenameforagiven
%%datarecord.
%%
%function SLibGetRecordContainerTypeName(rec) void
  %return SLibGetRecordContainerOptStdTypeName(rec, TLC_FALSE)
%endfunction
 
%%Function:SLibGetRecordContainerOptStdTypeName
%%Abstract:
%%Returnsthecontainerorimplementationtypenameforagiven
%%datarecord.
%%
%%SpecifytheuseStdContainerNameargumentaswhethertoreturnstdcontainername
%%ifthetypeisapre-loweringstdcontainertype.
%%
%function SLibGetRecordContainerOptStdTypeName(rec, useStdContainerName) void
  %assign containerCgTypeIdx = SLibGetRecordContainerCGTypeIdx(rec)
  %if LibCGTypeIsEnum(SLibGetRecordOriginalCGTypeIdx(rec)) && ...
      !(useStdContainerName && LibCGTypeIsStdContainer(containerCgTypeIdx))
    %return LibOptStdCGTypeName(SLibGetRecordOriginalCGTypeIdx(rec), useStdContainerName)
  %else
    %return LibOptStdCGTypeName(containerCgTypeIdx, useStdContainerName)
  %endif
%endfunction
 
%%Function:SLibGetRecordContainerBaseTypeName================================
%%Abstract:
%%Returnsthecontainerorimplementationbasetypenameforagiven
%%datarecord.
%%
%function SLibGetRecordContainerBaseTypeName(rec) void
  %return LibCGTypeName(LibCGTypeScalarBaseType(SLibGetRecordContainerCGTypeIdx(rec)))
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibBlockInputSignalAliasedThruDataTypeId
%%Abstract:
%%ReturnthedatatypeIDtheinputsignalisaliasedthruto.
%%
%function LibBlockInputSignalAliasedThruDataTypeId(idx)
  %% See Also:
  %% LibGetDataTypeIdAliasedThruToFromId
  %return LibGetDataTypeIdAliasedThruToFromId(...
    LibBlockInputSignalDataTypeId(idx))
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibBlockOutputSignalAliasedThruDataTypeId
%%Abstract:
%%ReturnthedatatypeIDtheoutputsignalisaliasedthruto
%%
%function LibBlockOutputSignalAliasedThruDataTypeId(idx)
  %% See Also:
  %% LibGetDataTypeIdAliasedThruToFromId
  %return LibGetDataTypeIdAliasedThruToFromId(...
    LibBlockOutputSignalDataTypeId(idx))
%endfunction
 
%%Function:LibIsBuiltInDataType=============================================
%%Abstract:
%%DoestheinputdatatypeIDcorrespondtoabuiltintypeafter
%%resolvingthrualiases?
%%
%function LibIsBuiltInDataType(id) void
  %return LibGetDataTypeIdAliasedThruToFromId(id) < ::CompiledModel.DataTypes.NumSLBuiltInDataTypes
%endfunction
 
%%Function:LibIsFundamentalBuiltInDataType==================================
%%Abstract:
%%DoestheinputdatatypeIDcorrespondtoabuiltintype,without
%%resolvingthrualiases?
%%
%function LibIsFundamentalBuiltInDataType(id) void
  %return id >= 0 && id < ::CompiledModel.DataTypes.NumSLBuiltInDataTypes
%endfunction
 
%%Function:LibIsDataTypeLogSupported=========================================
%%Abstract:
%%Issignalloggingsupportedforthisdatatype
%%TopTester:test/toolbox/simulink/variants/string/tStringSupport.m
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/tStringSupport.m
%%
%function LibIsDataTypeLogSupported(dTypeId, logIfConvertTLCFcnExists) void
  %if LibIsHalfDataType(dTypeId)
    %return 0
  %elseif LibIsDataTypeBuiltinOrFixpt(dTypeId)
    %return 1
  %elseif LibIsEnumDataType(dTypeId)
    %return 0
  %elseif logIfConvertTLCFcnExists
    %return (LibConvertBetweenTLCFcnName(dTypeId) != "")
  %else
    %return 0
  %endif
%endfunction
 
%%Function:LibIsDataTypeFixpt================================================
%%Abstract:
%%Isfixptdatatype
%%
%function LibIsDataTypeFixpt(dTypeId) void
  %assign curDT = FixPt_GetDataTypeFromIndex(dTypeId)
  %%
  %if curDT.IsFixedPoint
    %return 1
  %else
    %return 0
  %endif
%endfunction
 
%%Function:LibIsDataTypeBuiltinOrFixpt=======================================
%%Abstract:
%%Isbuiltinorfixptdatatype
%%
%function LibIsDataTypeBuiltinOrFixpt(dTypeId) void
  %if LibIsBuiltInDataType(dTypeId)
    %return 1
  %else
    %return LibIsDataTypeFixpt(dTypeId)
  %endif
%endfunction
 
%%Function:LibIsBuiltInWordSize=======================================
%%Abstract:
%%testiftheinputisofanysizeofthebuilt-indatatype
%function LibIsBuiltInWordSize(wordSize)
  %if wordSize == 8 || wordSize == 16 || wordSize == 32
    %return 1
  %endif
  %return 0
%endfunction
 
%%Function:LibMaxCodeGenWordSize=======================================
%%Abstract:
%%Basedontheenabledfeature,determingthevalidwordsize
%function LibMaxCodeGenWordSize()
  %%assign maxBits = 128
  %return 128
%endfunction
 
%%Function:LibIsMultiWordValue(in)=======================================
%%Abstract:
%%"in"isastring,whichcouldbeavariableorvalue,including
%%signalwordvalueandmultiwordvalue,i.e.,{{xUL,xUL}}.
%%returntrueifinisamultiwordvalue.
%function LibIsMultiWordValue(in)
  %%simply looking for "{". Since varaible could not have "{" as a name.
  %assign qualifier = "{"
  %if (TYPE(in) == "String")
    %if !ISEMPTY(FEVAL("strfind",in,qualifier))
      %return TLC_TRUE
    %endif
  %endif
  %return TLC_FALSE
%endfunction %%LibIsMultiWordValue
 
%%Function:LibIsDataTypeMultiWordFixpt=======================================
%%Abstract:
%%fixpttypeisgeneratedasastructofmultiword
%function LibIsDataTypeMultiWordFixpt(dTypeId)
  %if LibIsBuiltInDataType(dTypeId)
    %return 0
  %else
    %assign curDT = FixPt_GetDataTypeFromIndex(dTypeId)
    %%
    %return FixPt_DataTypeIsMultiWord(curDT)
  %endif
%endfunction
 
%%Function:LibIsDataTypeNewLongestFixpt=======================================
%%Abstract:
%%Anynon-built-intypewith33+or24bits,andisofthesamelengthoftargetlong
%%orlonglong.Thisalsomeanstargetlongscannotberepresentedbybuilt-in-types,
%%andtSS_LONG/tSS_ULONGortSS_LONG_LONG/tSS_ULONG_LONGhavebeenadded(defined)forthem.
%function LibIsDataTypeNewLongestFixpt(dTypeId)
  %if LibIsBuiltInDataType(dTypeId)
    %return 0
  %else
    %assign curDT = FixPt_GetDataTypeFromIndex(dTypeId)
    %%can handle case where IntegerSizes.LongNumBits == 24 or IntegerSizes.LongLongNumBits == 64
    %%any fixpt type of same size as a none built-in long/long long is aliased to the new type
    %%so that they can be inlined if necessary; only mulitword can't be inlined
    %if curDT.IsFixedPoint && !LibIsBuiltInWordSize(IntegerSizes.LongNumBits) ...
      && (LibGetDataTypeIdAliasedToFromId(dTypeId) == ::CompiledModel.tSS_LONG ...
          || LibGetDataTypeIdAliasedToFromId(dTypeId) == ::CompiledModel.tSS_ULONG)
      %return 1
    %elseif curDT.IsFixedPoint && !LibIsBuiltInWordSize(IntegerSizes.LongLongNumBits) ...
      && (LibGetDataTypeIdAliasedToFromId(dTypeId) == ::CompiledModel.tSS_LONG_LONG ...
          || LibGetDataTypeIdAliasedToFromId(dTypeId) == ::CompiledModel.tSS_ULONG_LONG)
      %return 1
    %else
      %return 0
    %endif
  %endif
%endfunction
 
%%Function:LibIsNonBuiltInTypeNeededForFixpt===================================
%%Abstract:
%%Returntrueifthepassedinfixptneedtoberepresentedasamultiword
%%orhardwareimplementationhasanone-built-inlongs,andthefixpttype's
%%wordsizeisthesameasthenewhardwarelong/longlong
%%
%function LibIsNonBuiltInTypeNeededForFixpt(dTypeId)
  %return LibIsDataTypeMultiWordFixpt(dTypeId) || ...
    LibIsDataTypeNewLongestFixpt(dTypeId)
%endfunction
 
%%Function:LibIsAliasDataType================================================
%%Abstract:
%%DoestheinputdatatypeIDcorrespondtoanaliastype?
%%
%function LibIsAliasDataType(id) void
  %return LibGetDataTypeIdAliasedThruToFromId(id) != id
%endfunction
 
%%Function:LibDataTypeNumElements============================================
%%Abstract:
%%Howmanyelementsdoesthedatatypehave?
%%
%function LibDataTypeNumElements(id) void
  %return ::CompiledModel.DataTypes.DataType[id].NumElements
%endfunction
 
%%Function:LibDataTypeIsBus==================================================
%%Abstract:
%%Isthedatatypeanonvirtualbus?
%%
%function LibDataTypeIsBus(id) void
  %return ::CompiledModel.DataTypes.DataType[id].IsBus
%endfunction
 
%%Function:LibDataTypeIsAnonymousStruct======================================
%%Abstract:
%%Isthedatatypeaanonymousstructtype?
%%
%function LibDataTypeIsAnonymousStruct(id) void
  %return LibIsStructDataType(id) && !LibIsDataTypeFixpt(id) /
  && !SLibDataTypeHasObject(id)
%endfunction
 
%%Function:SLibDataTypeHasObject=============================================
%%Abstract:
%%Doesthisdatatypehaveaworkspaceobject?
%%
%function SLibDataTypeHasObject(id) void
  %return ::CompiledModel.DataTypes.DataType[id].HasObject != 0
%endfunction
 
%%Function:LibDataTypeElementName===========================================
%%Abstract:
%%Returnthenameoftheidx'thelementofdatatype
%%
%function LibDataTypeElementName(id, idx) void
  %return ::CompiledModel.DataTypes.DataType[id].Elements[idx].Name
%endfunction
 
%%Function:LibDataTypeElementDescription=====================================
%%Abstract:
%%ReturntheDescriptionoftheidx'thelementofdatatype
%function LibDataTypeElementDescription(id, idx) void
  %return ::CompiledModel.DataTypes.DataType[id].Elements[idx].Description
%endfunction
 
%%Function:LibDataTypeElementUnit===========================================
%%Abstract:
%%ReturntheUnitsoftheidx'thelementofdatatype
%function LibDataTypeElementUnit(id, idx) void
  %assert CGMODEL_ACCESS("CGModel.SLUnit") > 0
  %return LibGetRecordUnitExpr(::CompiledModel.DataTypes.DataType[id].Elements[idx])
%endfunction
 
%%Function:LibDataTypeElementASCIIEscapedUnits===============================
%%Abstract:
%%ReturntheEscapedUnitsoftheidx'thelementofdatatype
%%Notethattheseunitshavebeenescapedtosupportunicodestrings
%%ingeneratedcode.Theymustbeunescapedwhenpassedbacktoc++code.
%function LibDataTypeElementASCIIEscapedUnits(id, idx) void
  %assert CGMODEL_ACCESS("CGModel.SLUnit") > 0
  %return SLibGetRecordASCIIEscapedUnitExpr(::CompiledModel.DataTypes.DataType[id].Elements[idx])
%endfunction
 
%%Function:LibDataTypeElementDocUnits========================================
%%Abstract:
%%ReturntheDocUnitsoftheidx'thelementofdatatype
%function LibDataTypeElementDocUnits(id, idx) void
  %return ::CompiledModel.DataTypes.DataType[id].Elements[idx].DocUnits
%endfunction
 
%%Function:LibDataTypeElementComment=========================================
%%Abstract:
%%Returnformattedcommentforbuselement
%%
%function LibDataTypeElementComment(id, idx) void
  %assign eComment = ""
  %if (ConfigSet.SimulinkDataObjDesc == 1)
    %assign eDesc = LibDataTypeElementDescription(id, idx)
    %% write out comment if desc is not empty
    %if !ISEMPTY(eDesc)
      %assign eComment = "/* " + eDesc + " *//n"
    %endif
  %endif
  %return eComment
%endfunction
 
%%Function:LibDataTypeElementDataTypeId=====================================
%%Abstract:
%%Returnthedatatypeidoftheidx'thelementofdatatype
%%
%function LibDataTypeElementDataTypeId(id, idx) void
  %assign element = ::CompiledModel.DataTypes.DataType[id].Elements[idx]
  %return LibGetRecordDataTypeId(element)
%endfunction
 
%%Function:LibDataTypeElementContainerName===================================
%%Abstract:
%%Returntheimplementation(container)typenameoftheidx'thelement
%%ofagivenstrutureddatatype
%%
%function LibDataTypeElementContainerName(id, idx) void
  %assign element = ::CompiledModel.DataTypes.DataType[id].Elements[idx]
  %return SLibGetRecordContainerOptStdTypeName(element, TLC_TRUE)
%endfunction
 
%%Function:LibDataTypeElementPadding========================================
%%Abstract:
%%Returnthepaddingoftheidx'thelementofdatatype
%%
%function LibDataTypeElementPadding(id, idx) void
  %return ::CompiledModel.DataTypes.DataType[id].Elements[idx].Padding
%endfunction
 
%%Function:LibDataTypeElementIsComplex======================================
%%Abstract:
%%Returnwhethertheidx'thelementofdatatypeiscomplex
%%
%function LibDataTypeElementIsComplex(id, idx) void
  %assign element = ::CompiledModel.DataTypes.DataType[id].Elements[idx]
  %return LibGetRecordIsComplex(element)
%endfunction
 
%%Function:LibDataTypeElementIsFixPt========================================
%%Abstract:
%%Returnwhethertheidx'thelementofdatatypeisFixedpointdatatype
%%
%function LibDataTypeElementIsFixPt(id, idx) void
  %return ::CompiledModel.DataTypes.DataType[LibDataTypeElementDataTypeId(id,idx)].IsFixedPoint
%endfunction
 
%%Function:LibDataTypeElementSymbolicWidth===================================
%%Abstract:
%%Returnsthesymbolicwidthoftheidx'thelementofdatatype
%%
%function LibDataTypeElementSymbolicWidth(id, idx) void
  %assign element = ::CompiledModel.DataTypes.DataType[id].Elements[idx]
  %return LibGetSymbolicRecordWidth(element)
%endfunction
 
%%Function:LibDataTypeElementVectorDims=====================================
%%Abstract:
%%Returnthedimensionsoftheidx'thelementofdatatypeasastring
%%includingthebrackets,ifitisavectorormatrix.
%%
%function LibDataTypeElementVectorDims(id, idx) void
  %assign element = ::CompiledModel.DataTypes.DataType[id].Elements[idx]
  %return LibGetRecordVectorDims(element)
%endfunction
 
%%Function:LibDataTypeElementVectorWidth================================
%%Abstract:
%%Returnthewidthoftheidx'thelementofdatatypeasastring
%%includingthebrackets,ifitisavector.
%%
%function LibDataTypeElementVectorWidth(id, idx) void
  %assign element = ::CompiledModel.DataTypes.DataType[id].Elements[idx]
  %return LibGetRecordVectorWidth(element)
%endfunction
 
%%Function:LibDataTypeElementWidth==========================================
%%Abstract:
%%Returnthewidthoftheidx'thelementofdatatype
%%
%function LibDataTypeElementWidth(id, idx) void
  %assign element = ::CompiledModel.DataTypes.DataType[id].Elements[idx]
  %return LibGetRecordWidth(element)
%endfunction
 
%%Function:LibDataTypeElementNumDimensions==================================
%%Abstract:
%%ReturnthenumberofDimensionsoftheidx'thelementofdatatype
%%
%function LibDataTypeElementNumDimensions(id, idx) void
  %assign element = ::CompiledModel.DataTypes.DataType[id].Elements[idx]
  %return LibGetRecordNumDimensions(element)
%endfunction
 
%%Function:LibDataTypeElementDimensions=====================================
%%Abstract:
%%ReturnthenumberofDimensionsoftheidx'thelementofdatatype
%%
%function LibDataTypeElementDimensions(id, idx) void
  %assign element = ::CompiledModel.DataTypes.DataType[id].Elements[idx]
  %return LibGetRecordDimensions(element)
%endfunction
 
%%Function:LibDataTypeElementOffset=========================================
%%Abstract:
%%Returntheoffsetoftheidx'thelementofdatatype
%%
%function LibDataTypeElementOffset(id, idx) void
  %return ::CompiledModel.DataTypes.DataType[id].Elements[idx].Offset
%endfunction
 
%%Function:LibDataTypeElementMax============================================
%%Abstract:
%%ReturntheMaxoftheidx'thelementofdatatype
%%
%function LibDataTypeElementMax(id, idx) void
  %return DataTypes.DataType[id].Elements[idx].Max
%endfunction
 
%%Function:LibDataTypeElementMin============================================
%%Abstract:
%%ReturntheMinoftheidx'thelementofdatatype
%%
%function LibDataTypeElementMin(id, idx) void
  %return DataTypes.DataType[id].Elements[idx].Min
%endfunction
 
%%Function:LibDataTypeElementIsStdContainer============================================
%%Abstract:
%%Returnwhethertheidx'thelementofdatatypeisstdcontainertype
%%
%function LibDataTypeElementIsStdContainer(id, idx) void
  %assign element = ::CompiledModel.DataTypes.DataType[id].Elements[idx]
  %return LibGetRecordIsStdContainer(element)
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibIsStringDataType=====================
%%Abstract:
%%ReturnTLC_TRUEiftheinputdatatypeIDcorrespondstoastring
%%type.Otherwise,returnTLC_FALSE.
%function LibIsStringDataType(id) void
  %assign dtId = LibGetDataTypeIdAliasedThruToFromId(id)
  %assign dt = ::CompiledModel.DataTypes.DataType[dtId]
  %if ISFIELD(dt, "IsStringType")
    %return dt.IsStringType
  %else
    %return TLC_FALSE
  %endif
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibGetStringTypeMaxLength=====================
%%Abstract:
%%Returnthemaximumlengthofastringtypeor0fordynamicstringtypes
%%Return-1iftheinputdatatypeisnotstring
%function LibGetStringTypeMaxLength(id) void
  %if LibIsStringDataType(id)
    %assign dtId = LibGetDataTypeIdAliasedThruToFromId(id)
    %assign dt = ::CompiledModel.DataTypes.DataType[dtId]
    %if ISFIELD(dt, "Object")
      %return dt.Object.ObjectProperties.MaximumLength
    %else
      %return 0
    %endif
  %else
    %return -1
  %endif
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibIsStructDataType====================
%%Abstract:
%%ReturnTLC_TRUEiftheinputdatatypeIDcorrespondstoastructure
%%type.Otherwise,returnTLC_FALSE.
%function LibIsStructDataType(id) void
  %return LibDataTypeNumElements(id) > 0
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibIsDataTypeCGClassOrContainClass====================
%%Abstract:
%%ReturnTLC_TRUEwhenoneofthefollowingistrue:
%%(1)TheinputdatatypeIDcorrespondstoaCGclasstype
%%(2)TheinputdatatypeIDcorrespondstoaContainertypethatisClassType
%%(3)Theinputdatatypecorrespondstoastructurethatcontains(1)or(2)
%%Otherwise,returnTLC_FALSE.
%function LibIsDataTypeCGClassOrContainClass(id) void
  %assign dt = ::CompiledModel.DataTypes.DataType[id]
  %assign isClass = TLC_FALSE
   
  %%needed this for bus, since it is a struct containing classes
  %if LibIsStructDataType(id)
    %assign numElements = dt.NumElements
    %foreach eIdx = numElements
      %assign eDtId = LibDataTypeElementDataTypeId(dt.Id, eIdx)
      %if LibIsDataTypeCGClassType(eDtId)
        %return TLC_TRUE
      %endif
    %endforeach
    %return TLC_FALSE
  %else
    %return ( ( ISFIELD(dt,"CGTypeIdx") && LibCGTypeIsClass">LibCGTypeIsClass(dt.CGTypeIdx) ) || (ISFIELD(dt,"ContainerCGTypeIdx") && LibCGTypeIsClass">LibCGTypeIsClass(dt.ContainerCGTypeIdx) ) )
  %endif
 
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibIsDataTypeCGClassType====================
%%Abstract:
%%ReturnTLC_TRUEwhenoneofthefollowingistrue:
%%(1)TheinputdatatypeIDcorrespondstoaCGclasstype
%%(2)TheinputdatatypeIDcorrespondstoaContainertypethatisClassType
%%Otherwise,returnTLC_FALSE.
%function LibIsDataTypeCGClassType(id) void
  %assign dt = ::CompiledModel.DataTypes.DataType[id]
  %return ( ( ISFIELD(dt,"CGTypeIdx") && LibCGTypeIsClass">LibCGTypeIsClass(dt.CGTypeIdx) ) || (ISFIELD(dt,"ContainerCGTypeIdx") && LibCGTypeIsClass">LibCGTypeIsClass(dt.ContainerCGTypeIdx) ) )
 
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibDoesDataTypeNeedConstructor===========
%%Abstract:
%%Returnswhetherifaconstructorisneeded.Thiscanalsobedefault
%%constructorthatcanbeessentiallyomitted.
%%ReturnTLC_TRUEwhenoneofthefollowingistrue:
%%(1)TheinputdatatypeIDcorrespondstoaCGclasstype
%%(2)Theinputdatatypecorrespondstoanopaquetypethathasexplicitconstructor
%%Otherwise,returnTLC_FALSE.
%function LibDoesDataTypeNeedConstructor(id) void
  %return !ISEMPTY(SLibDataTypeConstructFcnName(id)) || LibIsDataTypeCGClassType(id)
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibDoesDataTypeMemberNeedConstructor===========
%%Abstract:
%%Returnswhetherifaconstructorisneededformemberofstruct.
%%ReturnTLC_TRUEwhenthedatatypeisastruct,andone(ormore)ofitsmemeber
%%needsconstructor(LibDoesDataTypeNeedConstructor)
%%Otherwise,returnTLC_FALSE.
%function LibDoesDataTypeMemberNeedConstructor(id) void
  %if LibIsStructDataType(id)
    %assign dt = ::CompiledModel.DataTypes.DataType[id]
    %assign numElements = dt.NumElements
    %foreach eIdx = numElements
      %assign eDtId = LibDataTypeElementDataTypeId(dt.Id, eIdx)
      %if LibDoesDataTypeNeedConstructor(eDtId)
        %return TLC_TRUE
      %endif
    %endforeach
    %return TLC_FALSE
  %else
    %return TLC_FALSE
  %endif
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibIsDataTypeContainerClass===========
%%Abstract:
%%Returnswhetherthisisascalartypecorrespondingtoamatrixvlue.
%%ReturnTLC_TRUEwhenoneofthefollowingistrue:
%%(1)TheinputdatatypeIDcorrespondstoaCGclasstype
%%(2)Theinputdatatypecorrespondstoanopaquetypethatcorrespondstocontainer
%%Otherwise,returnTLC_FALSE.
%function LibIsDataTypeContainerClass(id) void
  %return !ISEMPTY(SLibDataTypeContainedDataFcn(id)) || LibIsDataTypeCGClassType(id)
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibIsDataTypeMessage====================
%%Abstract:
%%ReturnTLC_TRUEifthedatatypecorrespondstomessage
%%Otherwise,returnTLC_FALSE.
%%Thisisbycheckingifthename(orelement'snameofstruct)iscorresponding
%%toaspecificidentifier
%function LibIsDataTypeMessage(id) void
  %assign dt = ::CompiledModel.DataTypes.DataType[id]
 
  %if LibIsStructDataType(id)
    %assign numElements = dt.NumElements
    %foreach eIdx = numElements
      %assign eDtId = LibDataTypeElementDataTypeId(dt.Id, eIdx)
      %if LibIsDataTypeMessage(eDtId)
        %return TLC_TRUE
      %endif
    %endforeach
    %return TLC_FALSE
  %else
    %return ( ( ISFIELD(dt,"Name") && dt.Name == "___internal_slMsg_reserved_identifier___") )
  %endif
 
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibIsHalfDataType=====================
%%Abstract:
%%ReturnTLC_TRUEiftheinputdatatypeIDcorrespondstoahalfprecision
%%type.Otherwise,returnTLC_FALSE.
%function LibIsHalfDataType(id) void
  %assign dt = ::CompiledModel.DataTypes.DataType[id]
  %assign retVal = FixPt_DataTypeIsHalf(dt)
  %return retVal
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibIsBuiltInOrCustomFloatDatatype=====
%%Abstract:
%%ReturnTLC_TRUEiftheinputdatatypeIDcorrespondstoa
%%Built-inFloat:tSS_SINGLEortSS_DOUBLE
%%CustomFloat:tSS_HALF(Bfloat16inthefuture)
%%Otherwise,returnTLC_FALSE.
%function LibIsBuiltInOrCustomFloatDatatype(id) void
  %assign dTypeId = LibGetDataTypeIdAliasedThruToFromId(id)
  %return (dTypeId == tSS_DOUBLE || dTypeId == tSS_SINGLE || LibIsHalfDataType(dTypeId))
%endfunction
 
 
%%DocFunction{OtherUsefulFunctions}:LibIsEnumDataType=====================
%%Abstract:
%%ReturnTLC_TRUEiftheinputdatatypeIDcorrespondstoanenumerated
%%type.Otherwise,returnTLC_FALSE.
%function LibIsEnumDataType(id) void
  %assign dtId = LibGetDataTypeIdAliasedThruToFromId(id)
  %return ::CompiledModel.DataTypes.DataType[dtId].IsEnumType
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibGetEnumTypeStorageType=============
%%Abstract:
%%Forenumerateddatatypes,getthestoragetypeIDinthegeneratedcode.
%%
%function LibGetEnumTypeStorageType(id) void
  %assign dtId = LibGetDataTypeIdAliasedThruToFromId(id)
  %return ::CompiledModel.DataTypes.DataType[dtId].EnumStorageTypeId
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibIsEnumTypeStoredAsInt==============
%%Abstract:
%%Forenumerateddatatypes,returnTLC_TRUEifenumeratedtypeisstoredas
%%anint.Otherwise,returnTLC_FALSE.
%%
%function LibIsEnumTypeStoredAsInt(id) void
  %assign storageType = LibGetEnumTypeStorageType(id)
  %return (storageType == -1)
%endfunction
 
%%Function:FcnGetEnumTypeNumEnums===========================================
%%Abstract:
%%Forenumerateddatatypes,getnumberofenumerations
%%
%function FcnGetEnumTypeNumEnums(id) void
  %assign dtId = LibGetDataTypeIdAliasedThruToFromId(id)
  %return ::CompiledModel.DataTypes.DataType[dtId].NumEnumerations
%endfunction
 
%%Function:FcnGetEnumTypeIndexOfDefaultValue================================
%%Abstract:
%%Forenumerateddatatypes,getindexofdefaultvalue
%%
%function FcnGetEnumTypeIndexOfDefaultValue(id) void
  %assign dtId = LibGetDataTypeIdAliasedThruToFromId(id)
 
  %return ::CompiledModel.DataTypes.DataType[dtId].IndexOfDefault
%endfunction
 
%%Function:FcnGetEnumTypeDefaultCodeGenString===============================
%%Abstract:
%%Forenumerateddatatypes,getdefaultenumerationcodegenerationstring
%%
%function FcnGetEnumTypeDefaultCodeGenString(id) void
  %assign dtId = LibGetDataTypeIdAliasedThruToFromId(id)
 
  %return SLibGetEnumTypeCodeGenStringFromIndex(id, FcnGetEnumTypeIndexOfDefaultValue(id))
%endfunction
 
%%Function:SLibGetEnumTypeCodeGenStringFromIndexForVariantPreprocessor============================
%%Abstract:
%%Forenumerateddatatypes,getenumeralstringforaspecificenumeration
%%itdoesnotincludetheenumerationname
%%
%function SLibGetEnumTypeCodeGenStringFromIndexForVariantPreprocessor(id, enumIdx) void
  %assign dtId = LibGetDataTypeIdAliasedThruToFromId(id)
  %assert(dtId < ::CompiledModel.DataTypes.NumDataTypes)
  %return ::CompiledModel.DataTypes.DataType[dtId].Enumeration[enumIdx].String
%endfunction
 
 
%%Function:FcnGetEnumTypeDefaultValue=======================================
%%Abstract:
%%Forenumerateddatatypes,getdefaultenumerationvalue
%%
%function FcnGetEnumTypeDefaultValue(id) void
  %assign dtId = LibGetDataTypeIdAliasedThruToFromId(id)
  %return SLibGetEnumTypeValueFromIndex(id, FcnGetEnumTypeIndexOfDefaultValue(id))
%endfunction
 
%%Function:SLibGetEnumTypeStringFromIndex===================================
%%Abstract:
%%Forenumerateddatatypes,getoriginalstringforaspecificenumeration
%%(doesnotincludeclassnameasprefix)
%%
%function SLibGetEnumTypeStringFromIndex(id, enumIdx) void
  %assign dtId = LibGetDataTypeIdAliasedThruToFromId(id)
  %return ::CompiledModel.DataTypes.DataType[dtId].Enumeration[enumIdx].String
%endfunction
 
%%Function:SLibGetEnumTypeCodeGenStringFromIndex============================
%%Abstract:
%%Forenumerateddatatypes,getcodegenerationstringforaspecificenumeration
%%(mayincludeclassnameasprefix,dependingonhowtypeisdefined)
%%
%function SLibGetEnumTypeCodeGenStringFromIndex(id, enumIdx) void
  %assign dtId = LibGetDataTypeIdAliasedThruToFromId(id)
  %return ::CompiledModel.DataTypes.DataType[dtId].Enumeration[enumIdx].CodeGenString
%endfunction
 
%%Function:SLibGetEnumTypeValueFromIndex====================================
%%Abstract:
%%Forenumerateddatatypes,getvalueforaspecificenumeration
%%
%function SLibGetEnumTypeValueFromIndex(id, enumIdx) void
  %assign dtId = LibGetDataTypeIdAliasedThruToFromId(id)
  %return ::CompiledModel.DataTypes.DataType[dtId].Enumeration[enumIdx].Value
%endfunction
 
%%Function:SLibGetEnumTypeCodeGenStringFromValue============================
%%Abstract:
%%Forenumerateddatatypes,getcodegenerationstringfromunderlyingvalue
%%
%function SLibGetEnumTypeCodeGenStringFromValue(id, enumValue) void
  %assign dtId = LibGetDataTypeIdAliasedThruToFromId(id)
  %assign dt = ::CompiledModel.DataTypes.DataType[dtId]
  %assign enumIdx = SLibGetEnumTypeIndexFromValue(id, enumValue)
  %return dt.Enumeration[enumIdx].CodeGenString
%endfunction
 
%%Function:SLibGetEnumTypeIndexFromValue===================================
%%Abstract:
%%Forenumerateddatatypes,getindexfromunderlyingvalue
%%
%function SLibGetEnumTypeIndexFromValue(id, enumValue) void
  %assign dtId = LibGetDataTypeIdAliasedThruToFromId(id)
  %assign dt = ::CompiledModel.DataTypes.DataType[dtId]
  %foreach enumIdx = dt.NumEnumerations
    %if (dt.Enumeration[enumIdx].Value == enumValue)
      %return enumIdx
    %endif
  %endforeach
  %<LibReportFatalError("Enumeration value not found in enumerated data type")>
%endfunction
 
%%Function:SLibGetEnumTypeMinValue=================================
%%Abstract:
%%Forenumerateddatatypes,getminimumunderlyingvalue
%%
%function SLibGetEnumTypeMinValue(id) void
  %assign dtId = LibGetDataTypeIdAliasedThruToFromId(id)
  %assign dt = ::CompiledModel.DataTypes.DataType[dtId]
  %assign minValue = dt.Enumeration[0].Value
 
  %foreach enumIdx = dt.NumEnumerations
    %if (dt.Enumeration[enumIdx].Value < minValue)
      %assign minValue = dt.Enumeration[enumIdx].Value
    %endif
  %endforeach
 
  %return minValue
%endfunction
 
%%Function:SLibGetEnumTypeMaxValue=================================
%%Abstract:
%%Forenumerateddatatypes,getmaximumunderlyingvalue
%%
%function SLibGetEnumTypeMaxValue(id) void
  %assign dtId = LibGetDataTypeIdAliasedThruToFromId(id)
  %assign dt = ::CompiledModel.DataTypes.DataType[dtId]
  %assign maxValue = dt.Enumeration[0].Value
 
  %foreach enumIdx = dt.NumEnumerations
    %if (dt.Enumeration[enumIdx].Value > maxValue)
      %assign maxValue = dt.Enumeration[enumIdx].Value
    %endif
  %endforeach
 
  %return maxValue
%endfunction
 
%%Function:SLibConvertBetweenEnumType=======================================
%%Abstract:
%%Convertbetweenenumerateddatatypes
%%
%%Arguments:
%%outDType=desiredoutputdatatype
%%inDType=actualinputdatatype
%%inLabel=inputsignal
%%options=options
%%outLabel=outputsignal
%function SLibConvertBetweenEnumType(outDType,inDType,inLabel,options,outLabel) Output
  %assign outDTypeName = LibGetDataTypeNameFromId(outDType)
  %if outDType == tSS_BOOLEAN
    %assign gnd = SLibGetEnumTypeCodeGenStringFromIndex(inDType, 0)
    %<outLabel> = (%<outDTypeName>) %<inLabel>;
  %elseif LibIsEnumDataType(outDType) %% Output data type is an enumerated data type
    %assign numStrings = FcnGetEnumTypeNumEnums(outDType)
    /* Convert to enumerated data type '%<outDTypeName>' */
    switch (%<inLabel>) {
      %foreach enumIdx = numStrings
        %assign enumValue = SLibGetEnumTypeValueFromIndex(outDType, enumIdx)
        %%
        %% Check if we have already generated a case for this enumValue
        %assign writeOutCase = TLC_TRUE
        %foreach tmpIdx = enumIdx
          %if (enumValue == SLibGetEnumTypeValueFromIndex(outDType, tmpIdx))
            %% Repeated value found, don't write it out
            %assign writeOutCase = TLC_FALSE
            %continue
          %endif
        %endforeach
        %%
        %if writeOutCase
          %assign enumString = SLibGetEnumTypeCodeGenStringFromIndex(outDType, enumIdx)
          case %<enumValue>:
          %<outLabel> = %<enumString>;
          break;
        %endif
      %endforeach
      default:
      %assign assertText = "false && /"Invalid value for enumerated data type '%<outDTypeName>'./""
      %<LibGenMathFcnCall("utAssert",tSS_BOOLEAN,assertText,"")>;
      /* Assigning default enumeration string */
      %<outLabel> = %<FcnGetEnumTypeDefaultCodeGenString(outDType)>;
    }
  %else
      %<outLabel> = (%<outDTypeName>) %<inLabel>;
  %endif
  %return 1
%endfunction
 
 
%%Function:LibDataTypeIsShared=========================================
%%Abstract:
%%Returnwhetheradatatypewillbetrackedinthesharedlocation
%%ifwearegeneratingcodethere.
%%
%function LibDataTypeIsShared(dtIdx)
  %if ISFIELD(::CompiledModel.DataTypes.DataType[dtIdx], "IsShared")
    %return ::CompiledModel.DataTypes.DataType[dtIdx].IsShared
  %else
    %return TLC_FALSE
  %endif
 
%endfunction
 
%%Function:LibHeaderFileForDataType=========================================
%%Abstract:
%%Returntheheaderfileforadatatype
%%
%function LibHeaderFileForDataType(dt)
  %return LibHeaderForDataTypeIdx(dt.Id)
%endfunction
 
%%Function:LibHeaderFileFromOPForDataType=========================================
%%Abstract:
%%Returntheheaderfileforadatatype
%%The"FromOP"meansthisonefishesitoutfromtheObjectProperties
%%
%function LibHeaderFileFromOPForDataType(dt)
  %return LibHeaderFromOPForDataTypeIdx(dt.Id)
%endfunction
 
%%Function:LibSetHeaderFileForDataType=========================================
%%Abstract:
%%Settheheaderfileforadatatype
%%
%function LibSetHeaderFileForDataType(dt, val) void
  %<LibSetHeaderForDataTypeIdx(dt.Id, val)>;
%endfunction
 
%%Function:LibDataTypeDependsOnHeaderFiles====================================
%%Abstract:
%%Returnsanarrayofincludefilesthat'dt'dependson.
%%ThecallerwilladdthesetotheRequiredIncludessectionof
%%theheaderfile'dt'isbeingwrittento.
%%'dtHeaderFile'istheheaderfile'dt'itselfisbeingwrittento,
%%whichweusetoensurethefiledoesn'tincludeitself.
%%Example:dtisstructtypes1.
%%s1hasfieldsa1anda2.
%%a1anda2arealiastypes,exportedtoa1.handa2.hrespectively.
%%Return['a1.h','a2.h']
%%
%function LibDataTypeDependsOnHeaderFiles(dt, dtHeaderFile)
  %assign dependsOnHeaderFiles = []
  %if LibIsAliasDataType(dt.Id)
    %% An alias type depends on the type it is aliased to.
    %assign aliasedToId = LibGetDataTypeIdAliasedToFromId(dt.Id)
    %% Note this gets either imported or exported header file, if any
    %assign dependsOnHeaderFileQuoted = LibHeaderForDataTypeIdx(aliasedToId)
    %% Include the header file if there is one. Noted it is quoted, but
    %% we want to return an array with unquoted header files.
    %if dependsOnHeaderFileQuoted != ""
      %assign sz = SIZE(dependsOnHeaderFileQuoted)
      %assign len = sz[1]
      %assign dependsOnHeaderFile = Substring(dependsOnHeaderFileQuoted, 1, len-1)
      %if dependsOnHeaderFile != dtHeaderFile
        %assign dependsOnHeaderFiles = AddToHeaderFiles(dependsOnHeaderFiles, dependsOnHeaderFile)
      %endif
    %endif
  %elseif LibIsStructDataType(dt.Id)
    %% A struct type depends on its element types
    %assign numElements = dt.NumElements
    %foreach eIdx = numElements
      %assign eDtId = LibDataTypeElementDataTypeId(dt.Id, eIdx)
      %% Note this gets either imported or exported header file, if any
      %assign dependsOnHeaderFileQuoted = LibHeaderForDataTypeIdx(eDtId)
      %% Include the header file if there is one. Noted it is quoted, but
      %% we want to return an array with unquoted header files.
      %% AddToHeaderFiles eliminates duplicates, so we don't add the same
      %% header file in multiple iterations of this loop.
      %if dependsOnHeaderFileQuoted != ""
        %assign sz = SIZE(dependsOnHeaderFileQuoted)
        %assign len = sz[1]
        %assign dependsOnHeaderFile = Substring(dependsOnHeaderFileQuoted, 1, len-1)
        %if dependsOnHeaderFile != dtHeaderFile
          %assign dependsOnHeaderFiles = AddToHeaderFiles(dependsOnHeaderFiles, dependsOnHeaderFile)
        %endif
      %endif
      %if LibIsDataTypeMultiWordFixpt(eDtId)
        %assign dependsOnHeaderFiles = AddToHeaderFiles(dependsOnHeaderFiles, SLibCoderMultiwordTypesFilename())
      %endif
    %endforeach
  %endif
  %return dependsOnHeaderFiles
%endfunction
 
%%Function:LibRemoveDependsOnHeaderFiles====================================
%%Abstract:
%%Computesdependenciesof'dt'forthepurposeofremovingthesefrom
%%headerFiles(whicharethe(quoted)headerfilesincludedfromthetop-levelmodel_types.h).
%%Example:model_types.hincludes"a1.h"thatinturnincludes"a2.h"and"a3.h".
%%Let'ssaywe'rebeingcalledwithtypea1(definedin"a1.h").
%%Let'ssaythepassed-inheaderFilesarrayconsistsof['"a1.h"','"a2.h"','"a3.h"'].
%%Thenthereturnedarray,aftersubtractingoutthedependentheaderfiles,
%%is['"a1.h"'].
%%Thepassed-in'dtHeaderFile'istheheaderfile'dt'itselfisbeingwrittento
%%("a1.h"inthisexample),whichweusetoensurewedon'tremovethetop-levelone.
%%
%function LibRemoveDependsOnHeaderFiles(dt, headerFiles, dtHeaderFile)
  %if LibIsAliasDataType(dt.Id)
    %% An alias type depends on the type it is aliased to.
    %assign aliasedToId = LibGetDataTypeIdAliasedToFromId(dt.Id)
    %assign dependsOnHeaderFile = LibHeaderForDataTypeIdx(aliasedToId)
    %if dependsOnHeaderFile != "" && dependsOnHeaderFile != dtHeaderFile
      %assign headerFiles = RemoveFromHeaderFiles(headerFiles, dependsOnHeaderFile)
    %endif
  %elseif LibIsStructDataType(dt.Id)
    %% A struct type depends on its element types
    %assign numElements = dt.NumElements
    %foreach eIdx = numElements
      %assign eDtId = LibDataTypeElementDataTypeId(dt.Id, eIdx)
      %assign dependsOnHeaderFile = LibHeaderForDataTypeIdx(eDtId)
      %if dependsOnHeaderFile != "" && dependsOnHeaderFile != dtHeaderFile
        %assign headerFiles = RemoveFromHeaderFiles(headerFiles, dependsOnHeaderFile)
      %endif
    %endforeach
  %endif
  %return headerFiles
%endfunction
 
%%Function:LibPackageForDataType=============================================
%%Abstract:
%%Returnthepackageforadatatype
%%
%function LibPackageForDataType(dt)
  %if dt.HasObject == 0
    %return ""
  %else
    %return dt.Object.Package
  %endif
%endfunction
 
%%Function:LibClassForDataType===============================================
%%Abstract:
%%Returntheclassforadatatype
%%
%function LibClassForDataType(dt)
  %if dt.HasObject == 0
    %return ""
  %else
    %return dt.Object.Class
  %endif
%endfunction
 
%%Function:LibDescriptionForDataTypeIdx====================================
%%Abstract:
%%ReturntheDataDescriptionstringfromthedatatypeindex
%%
%function LibDescriptionForDataTypeIdx(id) void
  %if !SLibDataTypeHasObject(id)
    %return ""
  %else
    %return ::CompiledModel.DataTypes.DataType[id].Object.ObjectProperties.Description
  %endif
%endfunction
 
%%Function:LibHeaderForDataTypeIdx====================================
%%Abstract:
%%ReturntheheaderfileforDataTypefromthedatatypeindex
%%
%function LibHeaderForDataTypeIdx(id) void
  %if ISFIELD(::CompiledModel.DataTypes.DataType[id], "HeaderFile")
    %return ::CompiledModel.DataTypes.DataType[id].HeaderFile
  %else
    %return ""
  %endif
%endfunction
 
%%Function:LibHeaderFromOPForDataTypeIdx====================================
%%Abstract:
%%ReturntheheaderfileforDataTypefromthedatatypeindex
%%The"FromOP"meansthisfishesitoutfromtheObjectProperties.
%%
%function LibHeaderFromOPForDataTypeIdx(id) void
  %if ::CompiledModel.DataTypes.DataType[id].HasObject == 0
    %return ""
  %else
    %if ISFIELD(::CompiledModel.DataTypes.DataType[id].Object.ObjectProperties, "HeaderFile")
      %return ::CompiledModel.DataTypes.DataType[id].Object.ObjectProperties.HeaderFile
    %else
      %return ""
    %endif
  %endif
%endfunction
 
%%Function:LibSetHeaderForDataTypeIdx====================================
%%Abstract:
%%SettheheaderfileforDataTypefromthedatatypeindex
%%
%function LibSetHeaderForDataTypeIdx(id, val) void
  %assign ::CompiledModel.DataTypes.DataType[id].HeaderFile = val
%endfunction
 
%%Function:SLibDataTypeConstructFcnName=======================================
%%Abstract:
%%ReturnthenameofConstructTLCfunctionforthisdatatype
%%
%function SLibDataTypeConstructFcnName(id) void
  %if ISFIELD(::CompiledModel.DataTypes.DataType[id], "ConstructFcnName")
    %return ::CompiledModel.DataTypes.DataType[id].ConstructFcnName
  %else
    %return ""
  %endif
%endfunction
 
%%Function:SLibDataTypeContainedDataFcn=======================================
%%Abstract:
%%ReturnthenameofConstructTLCfunctionforthisdatatype
%%
%function SLibDataTypeContainedDataFcn(id) void
  %if ISFIELD(::CompiledModel.DataTypes.DataType[id], "ContainedData")
    %return ::CompiledModel.DataTypes.DataType[id].ContainedData
  %else
    %return ""
  %endif
%endfunction
 
%%Function:SLibDataTypeDestructFcnName=======================================
%%Abstract:
%%ReturnthenameofDestructTLCfunctionforthisdatatype
%%
%function SLibDataTypeDestructFcnName(id) void
  %if ISFIELD(::CompiledModel.DataTypes.DataType[id], "DestructFcnName")
    %return ::CompiledModel.DataTypes.DataType[id].DestructFcnName
  %else
    %return ""
  %endif
%endfunction
 
%%Function:SLibDataTypeDeepCopyFcnName=======================================
%%Abstract:
%%ReturnthenameofDeepCopyTLCfunctionforthisdatatype
%%
%function SLibDataTypeDeepCopyFcnName(id) void
  %if ISFIELD(::CompiledModel.DataTypes.DataType[id], "DeepCopyFcnName")
    %return ::CompiledModel.DataTypes.DataType[id].DeepCopyFcnName
  %else
    %return ""
  %endif
%endfunction
 
%%Function:LibConvertBetweenTLCFcnName=======================================
%%Abstract:
%%ReturnthenameofConvertBetweenTLCfunction
%%
%function LibConvertBetweenTLCFcnName(id) void
  %if ISFIELD(::CompiledModel.DataTypes.DataType[id], "ConvertBetweenTLCFcnName")
    %return ::CompiledModel.DataTypes.DataType[id].ConvertBetweenTLCFcnName
  %else
    %return ""
  %endif
%endfunction
 
 
 
%%Function:LibConvertBetweenTLCFcnFile=======================================
%%Abstract:
%%ReturnthefileofConvertBetweenTLCfunction
%%
%function LibConvertBetweenTLCFcnFile(id) void
  %if ISFIELD(::CompiledModel.DataTypes.DataType[id], "ConvertBetweenTLCFcnFile")
    %return ::CompiledModel.DataTypes.DataType[id].ConvertBetweenTLCFcnFile
  %else
    %return ""
  %endif
%endfunction
 
 
 
%%Function:LibIsPositiveTLCFcnName===========================================
%%Abstract:
%%ReturnthenameofIsPositiveTLCfunction
%%
%function LibIsPositiveTLCFcnName(id) void
  %if ISFIELD(::CompiledModel.DataTypes.DataType[id], "IsPositiveTLCFcnName")
    %return ::CompiledModel.DataTypes.DataType[id].IsPositiveTLCFcnName
  %else
    %return ""
  %endif
%endfunction
 
 
%%Function:LibIsPositiveTLCFcnFile===========================================
%%Abstract:
%%ReturnthefileofIsPositiveTLCfunction
%%
%function LibIsPositiveTLCFcnFile(id) void
  %if ISFIELD(::CompiledModel.DataTypes.DataType[id], "IsPositiveTLCFcnFile")
    %return ::CompiledModel.DataTypes.DataType[id].IsPositiveTLCFcnFile
  %else
    %return ""
  %endif
%endfunction
 
 
%%Function:LibSignTLCFcnName=================================================
%%Abstract:
%%ReturnthenameofSignTLCfunction
%%
%function LibSignTLCFcnName(id) void
  %if ISFIELD(::CompiledModel.DataTypes.DataType[id], "SignTLCFcnName")
    %return ::CompiledModel.DataTypes.DataType[id].SignTLCFcnName
  %else
    %return ""
  %endif
%endfunction
 
 
%%Function:LibSignTLCFcnFile=================================================
%%Abstract:
%%ReturnthefileofSignTLCfunction
%%
%function LibSignTLCFcnFile(id) void
  %if ISFIELD(::CompiledModel.DataTypes.DataType[id], "SignTLCFcnFile")
    %return ::CompiledModel.DataTypes.DataType[id].SignTLCFcnFile
  %else
    %return ""
  %endif
%endfunction
 
 
%%DocFunction{OtherUsefulFunctions}:LibGetDataTypeNameFromId===============
%%Abstract:
%%ReturnthedatatypenamecorrespondingtoadatatypeID.
%%
%function LibGetDataTypeNameFromId(id) void
  %assign dtName = ::CompiledModel.DataTypes.DataType[id].Name
  %% Data type name can be "string" in code generated for sim-target like rapid accelerator
  %% Change it back to a char_T that is accepted by C
  %if dtName == "string"
    %assign dtName = "char_T"
  %endif
  %return dtName
%endfunction
 
 
%%DocFunction{OtherUsefulFunctions}:LibGetDataTypeSLNameFromId===============
%%Abstract:
%%ReturntheSimulinkdatatypenamecorrespondingtoadatatypeID.
%%
%function LibGetDataTypeSLNameFromId(id) void
  %return ::CompiledModel.DataTypes.DataType[id].DTName
%endfunction
 
 
%%DocFunction{OtherUsefulFunctions}:LibGetDataTypeSLSizeFromId===============
%%Abstract:
%%Returnthesize(asSLknowsit)correspondingtoadatatypeID.
%%
%function LibGetDataTypeSLSizeFromId(id) void
  %return ::CompiledModel.DataTypes.DataType[id].Size
%endfunction
 
 
%%DocFunction{OtherUsefulFunctions}:LibGetDataTypeIdAliasedThruToForNonBusDtype==
%%Abstract:
%%Returnaliasedthrutodatatypeidifthesignalisnotabus.Otherwise
%%donotaliasthru.
%function LibGetDataTypeIdAliasedThruToForNonBusDtype(id) void
  %assert(id >= 0)
  %if LibDataTypeIsBus(id)
    %return id
  %else
    %return ::CompiledModel.DataTypes.DataType[id].IdAliasedThruTo
  %endif
%endfunction
 
 
%%DocFunction{OtherUsefulFunctions}:LibGetDataTypeIdAliasedThruToFromId====
%%Abstract:
%%ReturnthedatatypeIdAliasedThruTocorrespondingtoadatatypeID.
%%Forexample,if"yourfloat"wasanaliasto"myfloat",and"myfloat"
%%wasanaliasto"double",thentheIdAliasedThruToforboth"yourfloat"
%%and"myfloat"wouldbe0(sincetheIDfor"double"is0)
%function LibGetDataTypeIdAliasedThruToFromId(id) void
  %return CGMODEL_ACCESS("SLType.GetSLTypeAliasedThroughToIdx", id)
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibGetDataTypeIdAliasedToFromId========
%%Abstract:
%%ReturnthedatatypeIdAliasedTocorrespondingtoadatatypeID.
%%Forexample,if"yourfloat"wasanaliasto"myfloat",and"myfloat"
%%wasanaliasto"double",thentheIdAliasedTofor"yourfloat"
%%wouldbetheIDfor"myfloat"andtheIdAliasedTofor"myfloat"would
%%be0(sincetheIDfor"double"is0)
%function LibGetDataTypeIdAliasedToFromId(id) void
  %return ::CompiledModel.DataTypes.DataType[id].IdAliasedTo
%endfunction
 
 
%%DocFunction{OtherUsefulFunctions}:LibGetDataTypeStorageIdFromId========
%%Abstract:
%%ReturnthedatatypeStorageIdcorrespondingtoadatatypeID.
%%Forexample,iftheinputidistheidfora16bit,signedfixedpoint
%%datatype,thenthestorageidwouldcorrespondtoint16
%function LibGetDataTypeStorageIdFromId(id) void
  %return ::CompiledModel.DataTypes.DataType[id].StorageId
%endfunction
 
 
%%DocFunction{OtherUsefulFunctions}:LibGetDataTypeEnumFromId===============
%%Abstract:
%%ReturnthedatatypeenumcorrespondingtoadatatypeID.Forexample
%%id==tSS_DOUBLE=>enum="SS_DOUBLE".Ifiddoesnotcorrespondtoa
%%builtindatatype,thisfunctionreturns""
%%
%function LibGetDataTypeEnumFromId(id) void
  %return ::CompiledModel.DataTypes.DataType[id].Enum
%endfunction
 
 
%%DocFunction{OtherUsefulFunctions}:LibGetDataTypeComplexNameFromId========
%%Abstract:
%%ReturnthenameofthecomplexdatatypecorrespondingtoadatatypeID.
%%Forexample,ifid==tSS_DOUBLEthenthisfunctionreturns"creal_T"
%%
%function LibGetDataTypeComplexNameFromId(id) void
  %return ::CompiledModel.DataTypes.DataType[id].ComplexName
%endfunction
 
 
%%DocFunction{OtherUsefulFunctions}:LibGetRecordDataTypeId=================
%%Abstract:
%%ReturnthedatatypeIDforagivendatarecord.
%%
%function LibGetRecordDataTypeId(rec) void
  %if ISFIELD(rec, "DataTypeIdx")
    %assign idx = rec.DataTypeIdx
  %elseif ISFIELD(rec, "DataTypeId")
    %assign idx = rec.DataTypeId
  %else
    %assign idx = LibGetRecordCGTypeIdx(rec)
    %assign idx = LibCGTypeToSLType(idx)
  %endif
  %return ::CompiledModel.DataTypes.DataType[idx].Id
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibGetRecordStorageDataTypeId===============
%%Abstract:
%%ReturnthestoragedatatypeIDforagivendatarecord.
%%
%function LibGetRecordStorageDataTypeId(rec) void
  %return LibGetDataTypeStorageIdFromId(LibGetRecordDataTypeId(rec))
%endfunction
 
 
%%DocFunction{OtherUsefulFunctions}:LibGetRecordContainerDataTypeId========
%%Abstract:
%%ReturnthecontainerdatatypeIDforagivendatarecord.
%%
%function LibGetRecordContainerDataTypeId(rec) void
  %if ISFIELD(rec, "DataTypeIdx")
    %assign idx = rec.DataTypeIdx
  %elseif ISFIELD(rec, "DataTypeId")
    %assign idx = rec.DataTypeId %% some write out the DataTypeIdx as DataTypeId
  %else
    %assign idx = SLibGetRecordContainerCGTypeIdx(rec)
    %if idx >= ::CompiledModel.DataTypes.NumSLBuiltInDataTypes
      %assign idx = LibCGTypeToSLType(idx)
    %endif
  %endif
  %return ::CompiledModel.DataTypes.DataType[idx].Id
%endfunction
 
%function SLibGetVectorDimsForCGType(cgTypeIdx)
  %if cgTypeIdx < ::CompiledModel.DataTypes.NumSLBuiltInDataTypes
    %return ""
  %else
    %return LibCGTypeSymbolicVectorDims(cgTypeIdx)
  %endif
%endfunction
 
 
%%DocFunction{OtherUsefulFunctions}:LibGetRecordVectorDims============
%%Abstract:
%%Returnthedimensionindexspecificationforagivendatarecord.
%%
%function LibGetRecordVectorDims(rec)
  %assign cgTypeIdx = SLibGetRecordContainerCGTypeIdx(rec)
  %return SLibGetVectorDimsForCGType(cgTypeIdx)
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibGetRecordVectorWidth===========
%%Abstract:
%%Returnthewidthforagivendatarecord.
%%
%function LibGetRecordVectorWidth(rec)
  %assign cgTypeIdx = SLibGetRecordContainerCGTypeIdx(rec)
  %if cgTypeIdx < ::CompiledModel.DataTypes.NumSLBuiltInDataTypes
    %return ""
  %else
    %return LibCGTypeSymbolicVectorDims(cgTypeIdx)
  %endif
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibGetRecordWidth======================
%%Abstract:
%%Returnthewidthforagivendatarecord.
%%
%function LibGetRecordWidth(rec) void
  %if ISFIELD(rec, "Width")
    %return rec.Width
  %elseif ISFIELD(rec, "CGTypeIdx")
    %return LibCGTypeWidth(LibGetRecordCGTypeIdx(rec))
  %else
    %assign errTxt = "Width is not contained within the specified record"
    %<LibReportFatalError(errTxt)>
  %endif
  %return 1
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibRecordHasSymbolicWidth===============
%%Abstract:
%%Returnstrueifagivendatarecordhasasymbolicwidth.
%%
%function LibRecordHasSymbolicWidth(rec) void
  %if ISFIELD(rec, "RecordType") && rec.RecordType == "ZcSignalInfo"
    %return 0
  %endif
 
  %assign cgTypeIdx = SLibGetRecordContainerCGTypeIdx(rec)
  %assign cgType = ::CompiledModel.CGTypes.CGType[cgTypeIdx]
  %return ISFIELD(cgType, "SymbolicWidth")
%endfunction %% LibRecordHasSymbolicWidth
 
%%DocFunction{OtherUsefulFunctions}:LibGetRecordSymbolicWidth===============
%%Abstract:
%%Returnthesymbolicwidthforagivendatarecord.
%%EventuallythisfunctionwillbereplacedbyLibGetRecordSymbolicDims.
%%
%function LibGetRecordSymbolicWidth(rec) void
  %assign cgTypeIdx = SLibGetRecordContainerCGTypeIdx(rec)
  %if SLibIsNdIndexingFeatureOn()
    %return LibGetRecordSymbolicDims(rec)
  %% The next case should only happen when dynamic allocation is enabled by a
  %% feature flag. We get here if we have variable-size signal, even though
  %% there is no corresponding generated code for such In this case, the record
  %% points to the dynamic matrix type in the code generation intermediate
  %% representation. We expect that this will be a single pointer, so we
  %% return 1 for a symbolic width. The code generator adds ConvertedToEmxArrayType
  %% in such a case to the rtw file, and we use that here.
  %elseif LibCGTypeIsConvertedToEmxArray(cgTypeIdx)
    %return "1"
  %else
    %return LibCGTypeSymbolicWidth(cgTypeIdx)
  %endif
%endfunction %% LibGetRecordSymbolicWidth
 
%%DocFunction{OtherUsefulFunctions}:LibGetRecordSymbolicDims===============
%%Abstract:
%%Returnthesymbolicdimensionsforagivendatarecord.
%%EventuallythisfunctionwillreplaceLibGetRecordSymbolicWidth.
%%
%function LibGetRecordSymbolicDims(rec) void
  %assign cgTypeIdx = SLibGetRecordContainerCGTypeIdx(rec)
  %assign recWidth = LibCGTypeSymbolicWidth(cgTypeIdx)
  %if recWidth == "1"
     %return recWidth
  %else
     %return LibCGTypeSymbolicDims(cgTypeIdx)
  %endif
%endfunction %% LibGetRecordSymbolicDims
 
%%DocFunction{OtherUsefulFunctions}:LibGetRecordNumDimensions==============
%%Abstract:
%%Returnthenumberofdimensionsforagivendatarecord.
%%
%function LibGetRecordNumDimensions(rec) void
  %if ISFIELD(rec, "NumDimensions")
    %assign dimensions = rec.NumDimensions
  %elseif ISFIELD(rec, "CGTypeIdx")
    %assign dimensions = LibCGTypeNumDimensions(LibGetRecordCGTypeIdx(rec))
  %else
    %assign errTxt = "NumDimensions is not contained within the specified record"
    %<LibReportFatalError(errTxt)>
  %endif
  %return dimensions
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibGetRecordNumDimsFromContainerCgTypeIdx===
%%Abstract:
%%Returnthenumberofdimensionsforagivendatarecordfromthecontainer
%%CGTypeindex.
%%
%function LibGetRecordNumDimsFromContainerCgTypeIdx(rec) void
  %return LibCGTypeNumDimensions(SLibGetRecordContainerCGTypeIdx(rec))
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibGetRecordDimensions=================
%%Abstract:
%%Returnthedimensionsforagivendatarecord.
%%
%function LibGetRecordDimensions(rec) void
  %if ISFIELD(rec, "Dimensions")
    %assign dimensions = rec.Dimensions
  %elseif ISFIELD(rec, "CGTypeIdx")
    %assign dimensions = LibCGTypeDimensions(LibGetRecordCGTypeIdx(rec))
  %else
    %assign errTxt = "Dimensions is not contained within the specified record"
    %<LibReportFatalError(errTxt)>
  %endif
  %return dimensions
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibGetRecordSymbolicDimensions=========
%%Abstract:
%%Returnthesymbolicdimensionsforagivendatarecord.
%%
%function LibGetRecordSymbolicDimensions(rec) void
  %if ISFIELD(rec, "CGTypeIdx")
    %assign dimensions = LibCGTypeSymbolicDimensions(LibGetRecordCGTypeIdx(rec))
  %else
    %assign errTxt = ...
      "Symbolic dimensions are not contained within the specified record"
    %<LibReportFatalError(errTxt)>
  %endif
  %return dimensions
%endfunction
 
 
%%DocFunction{OtherUsefulFunctions}:LibGetRecordIsComplex==================
%%Abstract:
%%Return1ifthespecifieddatarecordiscomplex.Otherwise,return0
%%TopTester:test/toolbox/simulink/variants/vssSigObj/tVSSSigObj.m
%%
%function LibGetRecordIsComplex(rec)
   
  %if ISFIELD(rec, "RecordType") && rec.RecordType == "ZcSignalInfo"
    %return 0
  %endif
 
  %if ISFIELD(rec, "ComplexSignal")
    %if TYPE(rec.ComplexSignal) == "Number"
      %return rec.ComplexSignal
    %else
      %return (rec.ComplexSignal == "yes")
    %endif
  %elseif ISFIELD(rec, "IsComplex")
    %return rec.IsComplex
  %elseif ISFIELD(rec, "CGTypeIdx")
    %return LibCGTypeIsComplex(LibGetRecordCGTypeIdx(rec))
  %else
    %assign errTxt = "ComplexSignal is not contained within specified record."
    %<LibReportFatalError(errTxt)>
  %endif
  %return 0
%endfunction
 
%%Function:LibGetRecordDataTypeName=========================================
%%Abstract:
%%Returnthedatatypenameforaspecifiedrecord.
%%
%%Arguments:
%%rec-TLCrecord
%%reim-Returnthedatatypenameorthecomplexdatatypename
%%dependingifrecisacomplexrecordandthevalueofreim.
%%AssumingName="real_T"andComplexName="creal_T",forexample,
%%creal_Tisreturnedforacomplexrecordifreimisspecifiedas
%%tRealPartortImagPart.Otherwisereal_Tisreturned.
%%TopTester:test/toolbox/simulink/blocks/lib_MathOperations/Gain/rtw/tdtgain4.m
%%
%function LibGetRecordDataTypeName(rec, reim)
  %return LibGetRecordOptStdDataTypeName(rec, reim, TLC_FALSE)
%endfunction
 
%%Function:LibGetRecordOptStdDataTypeName
%%Abstract:
%%Returnthedatatypenameforaspecifiedrecord.
%%
%%Arguments:
%%rec-TLCrecord
%%reim-Returnthedatatypenameorthecomplexdatatypename
%%dependingifrecisacomplexrecordandthevalueofreim.
%%AssumingName="real_T"andComplexName="creal_T",forexample,
%%creal_Tisreturnedforacomplexrecordifreimisspecifiedas
%%tRealPartortImagPart.Otherwisereal_Tisreturned.
%%useStdContainerName-Whethertoreturnstdcontainernameifthetypeis
%%apre-loweringstdcontainertype.
%%
%function LibGetRecordOptStdDataTypeName(rec, reim, useStdContainerName)
  %if ISFIELD(rec, "CGTypeIdx")
    %assign cgTypeIdx = SLibGetRecordContainerCGTypeIdx(rec)
    %if reim != ""
      %assign cgTypeIdx = LibCGTypeScalarBaseType(cgTypeIdx)
    %endif
    %return LibOptStdCGTypeName(cgTypeIdx, useStdContainerName)
  %else
    %if reim == "" && LibGetRecordIsComplex(rec)
      %return LibGetDataTypeComplexNameFromId(LibGetRecordDataTypeId(rec))
    %else
      %return LibGetDataTypeNameFromId(LibGetRecordDataTypeId(rec))
    %endif
  %endif
%endfunction
 
 
%%Function:LibGetRecordAliasedThruDataTypeName================================
%%Abstract:
%%Returnthealiasedthrudatatypenameforaspecifiedrecord.
%%
%%Arguments:
%%rec-TLCrecord
%%reim-Returnthedatatypenameorthecomplexdatatypename
%%dependingifrecisacomplexrecordandthevalueofreim.
%%AssumingName="real_T"andComplexName="creal_T",forexample,
%%creal_Tisreturnedforacomplexrecordifreimisspecifiedas
%%tRealPartortImagPart.Otherwisereal_Tisreturned.
%%TopTester:test/toolbox/simulink/blocks/lib_MathOperations/Gain/rtw/tdtgain4.m
%%
%function LibGetRecordAliasedThruDataTypeName(rec, reim)
  %assign id = LibGetDataTypeIdAliasedThruToFromId(LibGetRecordDataTypeId(rec))
  %if reim == "" && LibGetRecordIsComplex(rec)
    %return LibGetDataTypeComplexNameFromId(id)
  %else
    %return LibGetDataTypeNameFromId(id)
  %endif
%endfunction
 
%%Function:LibGetRecordCompositeDataTypeName================================
%%Abstract:
%%Returnthecompositedatatypenameforaspecifiedrecord.Thatis,
%%returnComplexNameifitexists,otherwise,returnName.
%%
%function LibGetRecordCompositeDataTypeName(rec) void
  %return LibGetRecordCompositeOptStdDataTypeName(rec, TLC_FALSE)
%endfunction
 
%%Function:LibGetRecordCompositeOptStdDataTypeName
%%Abstract:
%%Returnthecompositedatatypenameforaspecifiedrecord.Thatis,
%%returnComplexNameifitexists,otherwise,returnName.
%%
%%SpecifytheuseStdContainerNameargumentaswhethertoreturnstdcontainername
%%ifthetypeisapre-loweringstdcontainertype.
%%
%function LibGetRecordCompositeOptStdDataTypeName(rec, useStdContainerName) void
  %return LibGetRecordOptStdDataTypeName(rec, "", useStdContainerName)
%endfunction
 
 
%%Function:SLibGetDtGroundName===============================================
%%Abstract:
%%Returnsthenameusedforagroundorcomplexgrounddependingthe
%%datatypeID,thevalueofreimandcomplexity.SeeLibGetGroundNamefor
%%moredetails.
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/tStringSupport.m
%%
%function SLibGetDtGroundName(dtID, isComplex, reim)
  %assign dtRec = ::CompiledModel.DataTypes.DataType[dtID]
 
  %assign isGroundComplex = ...
          (reim == "" && isComplex)
 
  %% Complex grounds are not expected from IR
  %if ISFIELD(dtRec, "GroundVariableName") && ...
    !isGroundComplex
    %assign name = dtRec.GroundVariableName
  %else
    %if LibIsStructDataType(dtID) || ...
      LibDoesDataTypeNeedConstructor(dtID)
      %<SLibSetDataTypeGroundReqInMemory(dtID)>
    %endif
    %if isGroundComplex
      %assign name = dtRec.ComplexGroundName
    %else
      %assign name = dtRec.GroundName
    %endif
    %if name == ""
      %assign strTxt = reim == "" ? "Complex" : ""
      %assign errTxt = "The name for ground has been requested, however, " ...
        "it has not been set by SLibSetDataType%<strTxt>GroundName()."
      %<LibReportFatalError(errTxt)>
    %endif
  %endif
  %return name
%endfunction
 
 
%%Function:LibGetGroundName==================================================
%%Abstract:
%%Foragivenrecordandreal/imaginaryspecifier,returnthenameusedfor
%%groundorcomplexgrounddependingtherecordtypeandthevalueofreim.
%%Specifically,return:
%%
%%Name-Recordnotcomplex
%%Name-Recordcomplex,andreimequalstRealPartortImagPart
%%ComplexName-Recordcomplexandreimisnull
%%
%%NotethatthemodelnameisaddedasaprefixtobothNameandComplexName.
%%thisavoidsnameclashingwhenlinkingmultiplemodelsintothesame
%%executable.
%%
%%Arguments:
%%rec-recordcontainingadatatypeindex
%%reim-tRealPart,tImagPartor""
%%
%function LibGetGroundName(rec, reim) void
  %assign dtID = LibGetRecordDataTypeId(rec)
  %assign isComplex = LibGetRecordIsComplex(rec)
  %return SLibGetDtGroundName(dtID, isComplex, reim)
%endfunction
 
 
%%Function:LibGetGroundValue================================================
%%Abstract:
%%Foragivenrecordandreal/imaginaryspecifier,returnthevalueusedfor
%%grounddependingontherecordtypeandthevalueofreim.
%%Specifically,return:
%%
%%value-Recordnotcomplex
%%value-Recordcomplex,andreimequalstRealPartortImagPart
%%ERROR-Recordcomplexandreimisnull(complexvaluesareundefined)
%%
%%Notethevaluemaybeastringoranactualnumericvalue.Forexample,
%%groundis0.0fortSS_DOUBLE,butitmaybe"0x08"forafixed-point
%%8-bitintegerwithabias.
%%
%%Arguments:
%%rec-recordcontainingadatatypeindex
%%reim-tRealPart,tImagPartor""
%%
%function LibGetGroundValue(rec, reim) void
  %assign value = SLibGetGroundValueStrictOpt(rec, reim, 1)
  %return value
%endfunction
 
%%Function:SLibGetDtGroundValue==============================================
%%Abstract:
%%Returnsthevlaueusedforagroundorcomplexgrounddependingthe
%%datatypeID,thevalueofreimandcomplexity.
%%SeeSLibGetGroundValueStrictOptformoredetails.
%%
%function SLibGetDtGroundValue(dtID, isComplex, reim, isStrict) void
  %if reim == "" && isComplex
    %% complex ground value undefined
    %assign errTxt = "Complex ground values are undefined."
    %<LibReportFatalError(errTxt)>
  %endif
  %% non-complex ground or real/imaginary part of complex ground
  %return SLibGetGroundValueFromIdStrictOpt(dtID, isStrict)
%endfunction
 
%%Function:SLibGetGroundValueStrictOpt===============================
%%Abstract:
%%ExtendLibGetGroundValue
%%withanoptiontobe"strict"or"robust"abouttheregistrationof
%%groundsbycustomdatatypes.
%%In"strict"mode,anerrorwill
%%occurifgroundhasnotbeenproperlyregisteredinTLCfor
%%thedatatype.
%%In"robust"mode,ifgroundhasnotbeenproperlyregistered
%%thenadefaultvalueofzerowillbereturn(withnoerroror
%%warning).
%%
%function SLibGetGroundValueStrictOpt(rec, reim, isStrict) void
  %assign dataTypeID = LibGetRecordDataTypeId(rec)
  %assign isComplex = LibGetRecordIsComplex(rec)
  %return SLibGetDtGroundValue(dataTypeID, isComplex, reim, isStrict)
%endfunction
 
%%Function:FcnCacheGroundInitForStruct
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/variants/variantBus/tVariantBusGecks.m
%%TopTester:test/toolbox/simulink/variants/variantBus/tBusErrors.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/ivGeneral/-tGotoFromWithVariableConditions.m
%%Toptetser:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/tStringSupport.m
%%
%function FcnCacheGroundInitForStruct(dtIdx) void
  %assign dt = ::CompiledModel.DataTypes.DataType[dtIdx]
  %assert (LibIsStructDataType(dtIdx) && ISFIELD(dt, "NeedGroundInit") && dt.NeedGroundInit)
   
  %assign numElements = dt.NumElements
  %assign padded = 0
  %assign gndHasFloats = 0
  %openfile gndValue
  {
    %foreach eIdx = numElements
      %assign padding = LibDataTypeElementPadding(dtIdx, eIdx)
      %if eIdx < (numElements - 1) || padding > 0
        %assign comma = ","
      %else
        %assign comma = ""
      %endif
       
      %assign eDtId = LibDataTypeElementDataTypeId(dtIdx, eIdx)
      %assign eName = LibDataTypeElementName(dtIdx, eIdx)
      %assign eIsComplex = LibDataTypeElementIsComplex(dtIdx, eIdx)
      %assign groundInit = ::CompiledModel.DataTypes.DataType[eDtId].GroundInit
 
      %assign eDtRec = ::CompiledModel.DataTypes.DataType[eDtId]
      %if ISEMPTY(groundInit) && (LibIsStructDataType(eDtId) && ...
        ISFIELD(eDtRec, "NeedGroundInit") && eDtRec.NeedGroundInit)
        %<FcnCacheGroundInitForStruct(eDtId)>
        %assign groundInit = ::CompiledModel.DataTypes.DataType[eDtId].GroundInit
      %endif
 
      %if !ISEMPTY(groundInit)
        %% For struct data type, eGround here is GroundInit,
        %% not GroundValue
        %assign eGround = groundInit
      %else
        %assign eGround = SLibGetIRorTLCGround(eDtId, 1, TLC_TRUE)
      %endif
      %if eIsComplex
        %assign eGround = "{%<eGround>, %<eGround>}"
      %endif
      %assign eWidth = LibDataTypeElementWidth(dtIdx, eIdx)
      %assign isStdContainer = LibDataTypeElementIsStdContainer(dtIdx, eIdx)
      %%Special handling for string class (let else branch handle it)
      %%What about other classes?
      %if eWidth == 1 && !(LibIsDataTypeCGClassType(eDtId) && LibIsStringDataType(eDtId))
        %<eGround>/
      %else
        %% Use empty string as ground value for string element
        %if LibIsStringDataType(eDtId)
          ""/
        %else
          %% add an additional {} around std container, this is required when the base type is struct or complex type
          %if isStdContainer
          { {
          %else
          {
          %endif
            %foreach elem = eWidth
              %if elem > 0
                , /
              %endif
              %<eGround>/
            %endforeach
          %if isStdContainer
          } }
          %else
          }
          %endif
        %endif
      %endif
      %<comma> /* %<eName> */
      %if padding > 0
        %if eIdx < (numElements - 1)
          %assign comma = ", "
        %else
          %assign comma = ""
        %endif
        %if padding == 1
          0U%<comma> /* sl_padding%<padded> */
        %else
          {
            %foreach j = padding
              %if j < (padding - 1)
                %assign padcomma = ", "
              %else
                %assign padcomma = ""
              %endif
              0U%<padcomma>/
            %endforeach
          }%<comma> /* sl_padding%<padded> */
        %endif
        %assign padded = padded + 1
      %endif
    %endforeach
  } /
  %closefile gndValue
  %assign dt.GroundInit = gndValue
  %assign dt.NeedGroundInit = 0
%endfunction
 
%%Function:LibGetGroundInitFromId==========================================
%%Abstract:
%%Returnsthevalueusedforgroundinitializationforthedatatypeid
%%passedin.
%%Specifically,return:
%%
%%value-groundvalueofdatatypeidpassedin
%%ERROR-groundvaluerequestedforadatatypethathasnotsetit'sground
%%value
%%
%%Notethevaluemaybeastringoranactualnumericvalue.Forexample,
%%groundis0.0fortSS_DOUBLE,butitmaybe"0x08"forafixed-point
%%8-bitintegerwithabias.
%%
%%Arguments:
%%dTypeId-datatypeIdwhosegroundvalueisdesired
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/variants/vssSigObj/tVSSSigObj.m
%%
%function LibGetGroundInitFromId(dTypeId) void
  %assign dtRec = ::CompiledModel.DataTypes.DataType[dTypeId]
  %assign groundInit = dtRec.GroundInit
  %if ISEMPTY(groundInit) && ...
    (LibIsStructDataType(dTypeId) && ISFIELD(dtRec, "NeedGroundInit") && dtRec.NeedGroundInit)
    %<FcnCacheGroundInitForStruct(dTypeId)>
    %assign groundInit = ::CompiledModel.DataTypes.DataType[dTypeId].GroundInit
  %endif
  %if ISEMPTY(groundInit)
    %assign groundInit = LibGetGroundValueFromId(dTypeId)
  %endif
  %return groundInit
%endfunction
 
 
%%Function:LibGetGroundValueFromId==========================================
%%Abstract:
%%Returnsthevalueusedforgroundforthedatatypeidpassedin.
%%Specifically,return:
%%
%%value-groundvalueofdatatypeidpassedin
%%ERROR-groundvaluerequestedforadatatypethathasnotsetit'sground
%%value
%%
%%Notethevaluemaybeastringoranactualnumericvalue.Forexample,
%%groundis0.0fortSS_DOUBLE,butitmaybe"0x08"forafixed-point
%%8-bitintegerwithabias.
%%
%%Arguments:
%%dTypeId-datatypeIdwhosegroundvalueisdesired
%%
%function LibGetGroundValueFromId(dTypeId) void
  %assign value = SLibGetGroundValueFromIdStrictOpt(dTypeId,1)
  %return value
%endfunction
%%
%%Function:SLibGetGroundValueFromIdStrictOpt===============================
%%Abstract:
%%WrapperaroundSLibGetIRorTLCGround
%%IfwehaveaIRgroundnameavailable,thatwillbereturned
%%Else,theTLCgroundnameorvaluewillbereturned
%function SLibGetGroundValueFromIdStrictOpt(dTypeId,isStrict) void
  %return SLibGetIRorTLCGround(dTypeId, isStrict, TLC_FALSE)
%endfunction
 
%%FunctionSLibGetIRorTLCGround
%%Abstract:
%%ExtendLibGetGroundValueFromId
%%withanoptiontobe"strict"or"robust"abouttheregistrationof
%%groundsbycustomdatatypes.
%%In"strict"mode,anerrorwill
%%occurifgroundhasnotbeenproperlyregisteredinTLCfor
%%thedatatype.
%%In"robust"mode,ifgroundhasnotbeenproperlyregistered
%%thenadefaultvalueofzerowillbereturn(withnoerroror
%%warning).
%%If"onlyGetTLCGround"istrue,IRgroundnamewillnotbeconsidered
%%TopTester:test/toolbox/simulink/blocks/buses/tbus.m
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/-tStringSupport.m
%%
%function SLibGetIRorTLCGround(dTypeId, isStrict, onlyGetTLCGround) void
  %assign dtRec = ::CompiledModel.DataTypes.DataType[dTypeId]
  %assign useIRGroundName = ...
    !onlyGetTLCGround && LibIsStructDataType(dTypeId) && ISFIELD(dtRec, "GroundVariableName")
 
  %if (useIRGroundName)
    %assign value = dtRec.GroundVariableName
    %return value
  %else
    %assign value = dtRec.GroundValue
    %if LibIsStructDataType(dTypeId) || LibDoesDataTypeNeedConstructor(dTypeId)
      %<SLibSetDataTypeGroundReqInMemory(dTypeId)>
    %endif
    %% must check that the value was set for this data type
    %if ISEQUAL(value, "")
      %if isStrict
        %assign errTxt = "The value for ground has been requested " ...
          "without being set by SLibSetDataTypeGroundValue()"
        %<LibReportFatalError(errTxt)>
      %else
        %assign value = 0
      %endif
    %endif
  %endif
  %return value
%endfunction
 
 
%%Function:SLibIsSignedFromId================================================
%%Abstract:
%%ReturnwhetherthedatatypecorrespondingtoadatatypeIDissigned
%%
%function SLibIsSignedFromId(id) void
  %switch LibGetDataTypeIdAliasedThruToFromId(id)
    %case tSS_UINT8
    %case tSS_UINT16
    %case tSS_UINT32
    %case tSS_BOOLEAN
      %return 0
      %%break
    %case tSS_INT8
    %case tSS_INT16
    %case tSS_INT32
    %case tSS_DOUBLE
    %case tSS_SINGLE
      %return 1
      %%break
    %default
      %if LibIsHalfDataType(LibGetDataTypeIdAliasedThruToFromId(id))
        %return 1
      %endif
      %assign errTxt = "Invalid data type %<dtypeName>."
      %<LibBlockReportFatalError([], errTxt)>
      %break
  %endswitch
%endfunction
 
 
%%Function:SLibIsUnsignedFromId==============================================
%%Abstract:
%%ReturnwhetherthedatatypecorrespondingtoadatatypeIDisan
%%unsigned
%%
%function SLibIsUnsignedFromId(id) void
  %return !SLibIsSignedFromId(id)
%endfunction
 
%%Function:SLibGetMLidentFcnFromId==========================================
%%Abstract:
%%Thisfunctionreturnsamx-functioncallwhichcheckamxArraydatatype
%%forcompatibilitywiththeTLCdatatypeid.
%%TopTester:test/toolbox/simulink/blocks/lib_MathOperations/Gain/rtw/tGainBlk_Codegencheck_RapidAccel.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmVariantsRSim.m
%%
%function SLibGetMLidentFcnFromId(id) void
  %switch LibGetDataTypeIdAliasedThruToFromId(id)
    %case tSS_DOUBLE
      %return "mxIsDouble"
    %case tSS_SINGLE
      %return "mxIsSingle"
    %case tSS_UINT8
      %return "mxIsUint8"
    %case tSS_UINT16
      %return "mxIsUint16"
    %case tSS_UINT32
      %return "mxIsUint32"
    %case tSS_BOOLEAN
      %return "mxIsLogical"
    %case tSS_INT8
      %return "mxIsInt8"
    %case tSS_INT16
      %return "mxIsInt16"
    %case tSS_INT32
      %return "mxIsInt32"
    %default
      %return "mxIsNumeric"
  %endswitch
%endfunction %% SLibGetMLidentFcnFromId
 
 
%%Function:SLibGetANCICDataTypeFromId========================================
%%Abstract:
%%ThisfunctionreturnstheequivalentANCIdatatypetothespecified
%%TLCdatatypeid.
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%
%function SLibGetANSICDataTypeFromId(id) void
  %switch LibGetDataTypeIdAliasedThruToFromId(id)
    %case tSS_DOUBLE
      %return ::AnsiDataTypeName.tSS_DOUBLE
    %case tSS_SINGLE
      %return ::AnsiDataTypeName.tSS_SINGLE
    %case tSS_UINT8
      %return ::AnsiDataTypeName.tSS_UINT8
    %case tSS_UINT16
      %return ::AnsiDataTypeName.tSS_UINT16
    %case tSS_UINT32
      %return ::AnsiDataTypeName.tSS_UINT32
    %case tSS_BOOLEAN
      %return ::AnsiDataTypeName.tSS_BOOLEAN
    %case tSS_INT8
      %return ::AnsiDataTypeName.tSS_INT8
    %case tSS_INT16
      %return ::AnsiDataTypeName.tSS_INT16
    %case tSS_INT32
      %return ::AnsiDataTypeName.tSS_INT32
    %default
      %return "numeric"
  %endswitch
%endfunction %% SLibGetANCICDataTypeFromId
 
 
%%Function:SLibGetMLDataTypeFromId===========================================
%%Abstract:
%%Thisfunctionreturnstheequivalentmatlabdatatypetothespecified
%%TLCdatatypeid.
%%TopTester:test/toolbox/simulink/variants/tg1220866_test.m
%%
%function SLibGetMLDataTypeFromId(id) void
  %switch LibGetDataTypeIdAliasedThruToFromId(id)
    %case tSS_DOUBLE
      %return "double"
    %case tSS_SINGLE
      %return "single"
    %case tSS_UINT8
      %return "uint8"
    %case tSS_UINT16
      %return "uint16"
    %case tSS_UINT32
      %return "uint32"
    %case tSS_BOOLEAN
      %return "boolean"
    %case tSS_INT8
      %return "int8"
    %case tSS_INT16
      %return "int16"
    %case tSS_INT32
      %return "int32"
    %default
      %return "numeric"
  %endswitch
%endfunction %% SLibGetMLDataTypeFromId
 
 
%%Function:SLibGetIdFromMLDataType===========================================
%%Abstract:
%%ReturntheTLCdatatypeidforthespecifiedMATLABdatatypename.
%%
%function SLibGetIdFromMLDataType(dtName)
  %switch dtName
    %case "double"
      %return tSS_DOUBLE
    %case "single"
      %return tSS_SINGLE
    %case "int32"
      %return tSS_INT32
    %case "int16"
      %return tSS_INT16
    %case "int8"
      %return tSS_INT8
    %case "uint32"
      %return tSS_UINT32
    %case "uint16"
      %return tSS_UINT16
    %case "uint8"
      %return tSS_UINT8
    %case "boolean"
    %case "logical"
      %return tSS_BOOLEAN
    %case "half"
      %return tSS_HALF
    %default
      %assign errTxt = "Unknown data type for: %<dtName>"
      %<LibReportFatalError(errTxt)>
  %endswitch
%endfunction %% SLibGetIdFromMLDataType
 
 
%%Function:SLibIsUnsignedBuiltinFromId=======================================
%%Abstract:
%%ReturnwhetherthedatatypecorrespondingtoadatatypeIDisan
%%unsignedbuiltin
%%
%function SLibIsUnsignedBuiltinFromId(id) void
  %if LibIsBuiltInDataType(id)
    %return SLibIsUnsignedFromId(id)
  %else
    %return 0
  %endif
%endfunction
 
 
 
%%Function:SLibIsIntegerFromId===============================================
%%Abstract:
%%ReturnwhetherthedatatypecorrespondingtoadatatypeIDisan
%%integer
%%TopTester:test/toolbox/simulink/variants/inlineVariants/ivGeneral/tIVfcnCall_neg.m
%%
%function SLibIsIntegerFromId(id) void
  %switch LibGetDataTypeIdAliasedThruToFromId(id)
    %case tSS_UINT8
    %case tSS_UINT16
    %case tSS_UINT32
    %case tSS_BOOLEAN
    %case tSS_INT8
    %case tSS_INT16
    %case tSS_INT32
    %case tSS_TIMER_UINT32_PAIR
      %return 1
      %%break
    %case tSS_DOUBLE
    %case tSS_SINGLE
      %return 0
      %%break
    %default
      %if LibIsHalfDataType(LibGetDataTypeIdAliasedThruToFromId(id))
        %return 0
      %endif
      %assign errTxt = "Invalid data type %<dtypeName>."
      %<LibBlockReportFatalError([], errTxt)>
      %break
  %endswitch
%endfunction
 
 
%%Function:LibGetNumDataTypesInModel=========================================
%%Abstract:
%%Returnnumberofdatatypesinamodel.Thisincludebuilt-inannon
%%built-indatatypes.
%%
%function LibGetNumDataTypesInModel()
  %return ::CompiledModel.DataTypes.NumDataTypes
%endfunction
 
 
%%Function:LibBooleanDataTypeEnabled=========================================
%%Abstract:
%%Returnwhetherbooleandatatypesareenabledinmodelornot.
%%
%function LibStrictBooleanCheckEnabled()
  %return ::CompiledModel.DataTypes.StrictBooleanCheckEnabled
%endfunction
 
 
 
%%--------------------------%
%%SystemLibraryfunctions%
%%--------------------------%
 
%%Function:SLibGetCGTypeFromSLTypeId========================================
%%Abstract:
%%ReturnstheCGtypeindexforaSimulinktypeindex.
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/tStringSupport.m
%%
%function SLibGetCGTypeFromSLTypeId(aSLTypeIdx)
  %assign loopLimit = ::CompiledModel.CGTypes.NumCGTypes - aSLTypeIdx
  %foreach idx = loopLimit
    %assign cgTypeIdx = aSLTypeIdx + idx
    %if ::CompiledModel.CGTypes.CGType[cgTypeIdx].SLTypeIdx == aSLTypeIdx
      %return cgTypeIdx
    %endif
  %endforeach
  %return -1
%endfunction
 
%%Function:fcnSetDataTypeName================================================
%%Abstract:
%%Setthedatatypenameforaspecifiedrecord.Forexample,doubleis
%%issetto"real_T".
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/tStringSupport.m
%%
%function fcnSetDataTypeName(dataTypeRec, name, aSetCGTypeName) void
  %assert ISFIELD(dataTypeRec, "Name")
 
  %if ISEQUAL(dataTypeRec.Name,"") || ISEQUAL(dataTypeRec.Name,dataTypeRec.DTName)
    %assign dataTypeRec.Name = name
    %if aSetCGTypeName
      %assign cgTypeIdx = SLibGetCGTypeFromSLTypeId(dataTypeRec.Id)
      %if 0 <= cgTypeIdx
        %assert dataTypeRec.Id <= cgTypeIdx
        %assign cgTypeRec = ::CompiledModel.CGTypes.CGType[cgTypeIdx]
        %assert cgTypeRec.SLTypeIdx == dataTypeRec.Id
        %if ISFIELD(cgTypeRec, "Name")
          %assign cgTypeRec.Name = name
        %endif
      %endif
    %endif
  %elseif !ISEQUAL(dataTypeRec.Name, name)
    %% This can happen if an s-function rename the data type more than once
    %assign errTxt = "Invalid data type name change from " ...
      "'%<dataTypeRec.Name>' to '%<name>'"
    %<LibReportFatalError(errTxt)>
  %endif
%endfunction %% fcnSetDataTypeName
 
 
%%Function:SLibSetDataTypeName===============================================
%%Abstract:
%%Setthedatatypenameforaspecifiedrecord.Forexample,doubleis
%%issetto"real_T".
%%
%function SLibSetDataTypeName(dataTypeRec, name) void
  %<fcnSetDataTypeName(dataTypeRec, name, TLC_TRUE)>
%endfunction %% SLibSetDataTypeName
 
 
%%Function:SLibSetDataTypeConvertBetweenTLCFcnName===========================
%%Abstract:
%%SettheConvertBetweenTLCfunctiontypenameforaspecifiedrecord.
%%TopTester:test/toolbox/simulink/variants/vssSigObj/tVSSSigObj.m
%%
%function SLibSetDataTypeConvertBetweenTLCFcnName(dataTypeRec, name) void
  %if !ISFIELD(dataTypeRec, "ConvertBetweenTLCFcnName")
    %assign errTxt = "Unable to find 'ConvertBetweenTLCFcnName' field in the data type record " ...
      "for %<dataTypeRec.DTName>"
    %<LibReportFatalError(errTxt)>
  %endif
  %if ISEQUAL(dataTypeRec.ConvertBetweenTLCFcnName,"")
    %assign dataTypeRec.ConvertBetweenTLCFcnName = name
  %elseif !ISEQUAL(dataTypeRec.ConvertBetweenTLCFcnName, name)
    %assign errTxt = "Invalid data type ConvertBetween TLC function name " ...
      "from '%<dataTypeRec.ConvertBetweenTLCFcnName>' to '%<name>'"
    %<LibReportFatalError(errTxt)>
  %endif
%endfunction %% SLibSetDataTypeConvertBetweenTLCFcnName
 
 
%%Function:SLibSetDataTypeConvertBetweenTLCFcnFile===========================
%%Abstract:
%%SettheConvertBetweenTLCfunctiontypefileforaspecifiedrecord.
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmFunctionCallSplitBlock_hidden_VC1.m
%%
%function SLibSetDataTypeConvertBetweenTLCFcnFile(dataTypeRec, file) void
  %if !ISFIELD(dataTypeRec, "ConvertBetweenTLCFcnFile")
    %assign errTxt = "Unable to find 'ConvertBetweenTLCFcnFile' field in the data type record " ...
      "for %<dataTypeRec.Name>"
    %<LibReportFatalError(errTxt)>
  %endif
  %if ISEQUAL(dataTypeRec.ConvertBetweenTLCFcnFile,"")
    %assign dataTypeRec.ConvertBetweenTLCFcnFile = file
  %elseif !ISEQUAL(dataTypeRec.ConvertBetweenTLCFcnFile, file)
    %assign errTxt = "Invalid data type ConvertBetween TLC function file " ...
      "from '%<dataTypeRec.ConvertBetweenTLCFcnFile>' to '%<file>'"
    %<LibReportFatalError(errTxt)>
  %endif
%endfunction %% SLibSetDataTypeConvertBetweenTLCFcnFile
 
 
%%Function:SLibSetDataTypeIsPositiveTLCFcnName===============================
%%Abstract:
%%SettheIsPositiveTLCfunctiontypenameforaspecifiedrecord.
%%TopTester:test/toolbox/simulink/variants/vssSigObj/tVSSSigObj.m
%%
%function SLibSetDataTypeIsPositiveTLCFcnName(dataTypeRec, name) void
  %if !ISFIELD(dataTypeRec, "IsPositiveTLCFcnName")
    %assign errTxt = "Unable to find 'IsPositiveTLCFcnName' field in the data type record " ...
      "for %<dataTypeRec.DTName>"
    %<LibReportFatalError(errTxt)>
  %endif
  %if ISEQUAL(dataTypeRec.IsPositiveTLCFcnName,"")
    %assign dataTypeRec.IsPositiveTLCFcnName = name
  %elseif !ISEQUAL(dataTypeRec.IsPositiveTLCFcnName, name)
    %assign errTxt = "Invalid data type IsPositive TLC function name " ...
      "from '%<dataTypeRec.IsPositiveTLCFcnName>' to '%<name>'"
    %<LibReportFatalError(errTxt)>
  %endif
%endfunction %% SLibSetDataTypeIsPositiveTLCFcnName
 
 
%%Function:SLibSetDataTypeIsPositiveTLCFcnFile===============================
%%Abstract:
%%SettheIsPositiveTLCfunctiontypefileforaspecifiedrecord.
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmFunctionCallSplitBlock_hidden_VC1.m
%%
%function SLibSetDataTypeIsPositiveTLCFcnFile(dataTypeRec, file) void
  %if !ISFIELD(dataTypeRec, "IsPositiveTLCFcnFile")
    %assign errTxt = "Unable to find 'IsPositiveTLCFcnFile' field in the data type record " ...
      "for %<dataTypeRec.Name>"
    %<LibReportFatalError(errTxt)>
  %endif
  %if ISEQUAL(dataTypeRec.IsPositiveTLCFcnFile,"")
    %assign dataTypeRec.IsPositiveTLCFcnFile = file
  %elseif !ISEQUAL(dataTypeRec.IsPositiveTLCFcnFile, file)
    %assign errTxt = "Invalid data type IsPositive TLC function file " ...
      "from '%<dataTypeRec.IsPositiveTLCFcnFile>' to '%<file>'"
    %<LibReportFatalError(errTxt)>
  %endif
%endfunction %% SLibSetDataTypeIsPositiveTLCFcnFile
 
 
%%Function:SLibSetDataTypeSignTLCFcnName==============================
%%Abstract:
%%SettheSignTLCfunctiontypenameforaspecifiedrecord.
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmFunctionCallSplitBlock_hidden_VC1.m
%%
%function SLibSetDataTypeSignTLCFcnName(dataTypeRec, name) void
  %if !ISFIELD(dataTypeRec, "SignTLCFcnName")
    %assign errTxt = "Unable to find 'SignTLCFcnName' field in the data type record " ...
      "for %<dataTypeRec.DTName>"
    %<LibReportFatalError(errTxt)>
  %endif
  %if ISEQUAL(dataTypeRec.SignTLCFcnName,"")
    %assign dataTypeRec.SignTLCFcnName = name
  %elseif !ISEQUAL(dataTypeRec.SignTLCFcnName, name)
    %assign errTxt = "Invalid data type Sign TLC function name " ...
      "from '%<dataTypeRec.SignTLCFcnName>' to '%<name>'"
    %<LibReportFatalError(errTxt)>
  %endif
%endfunction %% SLibSetDataTypeSignTLCFcnName
 
 
%%Function:SLibSetDataTypeSignTLCFcnFile==============================
%%Abstract:
%%SettheSignTLCfunctiontypefileforaspecifiedrecord.
%%
%function SLibSetDataTypeSignTLCFcnFile(dataTypeRec, file) void
  %if !ISFIELD(dataTypeRec, "SignTLCFcnFile")
    %assign errTxt = "Unable to find 'SignTLCFcnFile' field in the data type record " ...
      "for %<dataTypeRec.Name>"
    %<LibReportFatalError(errTxt)>
  %endif
  %if ISEQUAL(dataTypeRec.SignTLCFcnFile,"")
    %assign dataTypeRec.SignTLCFcnFile = file
  %elseif !ISEQUAL(dataTypeRec.SignTLCFcnFile, file)
    %assign errTxt = "Invalid data type Sign TLC function file " ...
      "from '%<dataTypeRec.SignTLCFcnFile>' to '%<file>'"
    %<LibReportFatalError(errTxt)>
  %endif
%endfunction %% SLibSetDataTypeSignTLCFcnFile
 
 
%%Function:SLibSetDataTypeEnum===============================================
%%Abstract:
%%Setthedatatypeenumforaspecifiedrecord.
%%
%function SLibSetDataTypeEnum(dataTypeRec, enum) void
  %if !ISFIELD(dataTypeRec, "Enum")
    %assign errTxt = "Unable to find 'Enum' field in the data type record " ...
      "for %<dataTypeRec.DTName>"
    %<LibReportFatalError(errTxt)>
  %endif
  %if ISEQUAL(dataTypeRec.Enum,"")
    %assign dataTypeRec.Enum = enum
  %elseif !ISEQUAL(dataTypeRec.Enum, enum)
    %assign errTxt = "Invalid data type enum change from " ...
      "'%<dataTypeRec.Enum>' to '%<enum>'"
    %<LibReportFatalError(errTxt)>
  %endif
%endfunction %% SLibSetDataTypeEnum
 
 
%%Function:SLibSetDataTypeComplexName========================================
%%Abstract:
%%Setthecomplexdatatypenameforaspecifiedrecord.Forexample,
%%complexdoubleissetto"creal_T".
%%
%function SLibSetDataTypeComplexName(dataTypeRec, name) void
  %if ISEQUAL(dataTypeRec.ComplexName, "")
    %assign dataTypeRec.ComplexName = name
  %elseif !ISEQUAL(dataTypeRec.ComplexName, name)
    %assign errTxt = "Invalid complex data type name change from " ...
      "'%<dataTypeRec.ComplexName>' to '%<name>'"
    %<LibReportFatalError(errTxt)>
  %endif
%endfunction %% SLibSetDataTypeComplexName
 
 
%%Function:SLibSetDataTypeGroundName=========================================
%%Abstract:
%%Setthenametobeusedforgroundforaparticulardatatype.Notethat
%%anerrorisproducedifyouattempttochangethename.
%%
%function SLibSetDataTypeGroundName(dataTypeRec, name) void
  %if dataTypeRec.GroundName == ""
    %assign dataTypeRec.GroundName = name
  %elseif dataTypeRec.GroundName != name
    %assign errTxt = "Invalid ground name change from " ...
      "'%<dataTypeRec.GroundName>' to '%<name>'"
    %<LibReportFatalError(errTxt)>
  %endif
%endfunction
 
 
%%Function:SLibSetDataTypeComplexGroundName==================================
%%Abstract:
%%Setthenametobeusedforgroundforaparticularcomplexdatatype.
%%Notethatanerrorisproducedifyouattempttochangethename.
%%TopTester:test/toolbox/simulink/variants/vssSigObj/tVSSSigObj.m
%%
%function SLibSetDataTypeComplexGroundName(dataTypeRec, name) void
  %if dataTypeRec.ComplexGroundName == ""
    %assign dataTypeRec.ComplexGroundName = name
  %elseif dataTypeRec.ComplexGroundName != name
    %assign errTxt = "Invalid complex ground name change from " ...
      "'%<dataTypeRec.ComplexGroundName>' to '%<name>'"
    %<LibReportFatalError(errTxt)>
  %endif
%endfunction
 
 
%%Function:SLibSetDataTypeGroundValue========================================
%%Abstract:
%%Setthegroundvaluetobeusedforaparticulardatatype.Anerror
%%isproducedifyouattempttochangethevalueofaparticularground.
%%TopTester:test/toolbox/simulink/variants/vssSigObj/tVSSSigObj.m
%%
%function SLibSetDataTypeGroundValue(dataTypeRec, value) void
  %if ISEQUAL(dataTypeRec.GroundValue, "")
    %assign dataTypeRec.GroundValue = value
  %elseif !ISEQUAL(dataTypeRec.GroundValue, value)
    %assign errTxt = "Invalid ground value change from " ...
      "'%<dataTypeRec.GroundValue>' to '%<value>'"
    %<LibReportFatalError(errTxt)>
  %endif
%endfunction
 
%function SLibSetDataTypeGroundHasNonZero(dataTypeRec, gndHasNonZero) void
  %assign dataTypeRec.GroundHasNonZero = gndHasNonZero
%endfunction
 
%function SLibGetDataTypeGroundHasNonZero(dataTypeRec)
  %return dataTypeRec.GroundHasNonZero
%endfunction
 
%function SLibSetDataTypeGroundHasFloats(dataTypeRec, gndHasFloats) void
  %assign dataTypeRec.GroundHasFloats = gndHasFloats
%endfunction
 
%%Function:SLibSetDataTypeGroundInit=========================================
%%Abstract:
%%Settheinitializationgroundvaluetobeusedforaparticulardatatype.
%%Anerrorisproducedifyouattempttochangethevalueofaparticular
%%ground.
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/tStringSupport.m
%%
%function SLibSetDataTypeGroundInit(dataTypeRec, value) void
  %if ISEMPTY(dataTypeRec.GroundInit)
    %assign dataTypeRec.GroundInit = value
  %elseif !ISEQUAL(dataTypeRec.GroundInit, value)
    %assign errTxt = "Invalid ground initialization value change from " ...
      "'%<dataTypeRec.GroundInit>' to '%<value>'"
    %<LibReportFatalError(errTxt)>
  %endif
%endfunction
 
 
%%Function:SLibSetDataTypeGroundReqInMemory==================================
%%Abstract:
%%Markagroundrequiredinmemory.
%%
%function SLibSetDataTypeGroundReqInMemory(dataTypeId) void
  %assign dtRec = ::CompiledModel.DataTypes.DataType[dataTypeId]
  %assign dtRec.GroundReqInMemory = 1
%endfunction
 
 
%%Function:SLibSetDataTypeComplexGroundReqInMemory===========================
%%Abstract:
%%Markacomplexgroundrequiredinmemory.
%%
%function SLibSetDataTypeComplexGroundReqInMemory(dataTypeId) void
  %assign dtRec = ::CompiledModel.DataTypes.DataType[dataTypeId]
  %assign dtRec.ComplexGroundReqInMemory = 1
%endfunction
 
 
%%Function:SLibGetDataTypeGroundReqInMemory==================================
%%Abstract:
%%isagroundrequiredinmemory?
%%
%function SLibGetDataTypeGroundReqInMemory(dataTypeId) void
  %assign dtRec = ::CompiledModel.DataTypes.DataType[dataTypeId]
  %return dtRec.GroundReqInMemory
%endfunction
 
 
%%Function:SLibGetDataTypeComplexGroundReqInMemory===========================
%%Abstract:
%%Isacomplexgroundrequiredinmemory?
%%
%function SLibGetDataTypeComplexGroundReqInMemory(dataTypeId) void
  %assign dtRec = ::CompiledModel.DataTypes.DataType[dataTypeId]
  %return dtRec.ComplexGroundReqInMemory
%endfunction
 
 
%%Function:SLibGetRecordDataTypeID===========================================
%%Abstract:
%%ReturnthedatatypeIDforagivenrecord.
%%
%function SLibGetRecordDataTypeId(rec) void
  %return LibGetRecordDataTypeId(rec)
%endfunction
 
 
%%Function:SLibGetRecordIsComplex============================================
%%Abstract:
%%Return1ifthespecifiedrecordiscomplex.Otherwise,return0
%%
%function SLibGetRecordIsComplex(rec)
  %return LibGetRecordIsComplex(rec)
%endfunction
 
 
%%Function:SLibGetRecordDataTypeName=========================================
%%Abstract:
%%Returnthedatatypenameforaspecifiedrecord.
%function SLibGetRecordDataTypeName(rec, reim)
  %return SLibGetRecordOptStdDataTypeName(rec, reim, TLC_FALSE)
%endfunction
 
%%Function:SLibGetRecordOptStdDataTypeName
%%Abstract:
%%Returnthedatatypenameforaspecifiedrecord.
%%
%%SpecifytheuseStdContainerNameargumentaswhethertoreturnstdcontainername
%%ifthetypeisapre-loweringstdcontainertype
%%
%function SLibGetRecordOptStdDataTypeName(rec, reim, useStdContainer)
  %return LibGetRecordOptStdDataTypeName(rec, reim, useStdContainer)
%endfunction
 
%%Function:SLibGetRecordCompositeDataTypeName================================
%%Abstract:
%%Returnthecompositedatatypenameforaspecifiedrecord.Thatis,
%%returnComplexNameifitexists,otherwise,returnName.
%%
%function SLibGetRecordCompositeDataTypeName(rec) void
  %return LibGetRecordCompositeDataTypeName(rec)
%endfunction
 
 
%%Function:SLibGetGroundName=================================================
%%Abstract:
%%Foragivenrecordandreal/imaginaryspecifier,returnthenameusedfor
%%groundorcomplexgrounddependingtherecordtypeandthevalueofreim.
%%
%function SLibGetGroundName(rec, reim) void
  %return LibGetGroundName(rec, reim)
%endfunction
 
 
%%Function:SLibGetGroundValue================================================
%%Abstract:
%%Foragivenrecordandreal/imaginaryspecifier,returnthevalueusedfor
%%grounddependingontherecordtypeandthevalueofreim.
%%
%function SLibGetGroundValue(rec, reim) void
  %return LibGetGroundValue(rec, reim)
%endfunction
 
%%Function:SLibGetGroundValueFromId==========================================
%%Abstract:
%%Returnsthevalueusedforgroundforthedatatypeidpassedin.
%function SLibGetGroundValueFromId(dTypeId) void
  %return LibGetGroundValueFromId(dTypeId)
%endfunction
 
%%Function:SLibGetStoredIntegerZeroFromId=====================================
%%Abstract:
%%Returnsthestoredintegervalueforthedatatypeofrecordpassedin.
%function SLibGetStoredIntegerZeroFromId(dataTypeId) void
  %assign storageDataTypeId = ...
    LibGetDataTypeStorageIdFromId(...
    LibGetDataTypeIdAliasedThruToFromId(dataTypeId))
  %%
  %if LibIsBuiltInDataType(storageDataTypeId)
    %assign value = 0
  %else
    %assign value = LibGetGroundValueFromId(storageDataTypeId)
  %endif
  %return value
%endfunction
 
%%Function:SLibGetStoredIntegerZeroValue=====================================
%%Abstract:
%%Returnsthestoredintegervalueforthedatatypeofrecordpassedin.
%function SLibGetStoredIntegerZeroValue(rec,reim) void
  %if reim == "" && LibGetRecordIsComplex(rec)
    %assign errTxt = "Complex stored integer zero values are undefined."
    %<LibReportFatalError(errTxt)>
  %else
    %% non-complex ground or real/imaginary part of complex ground
    %assign dataTypeId = LibGetRecordDataTypeId(rec)
    %assign value = SLibGetStoredIntegerZeroFromId(dataTypeId)
  %endif
  %return value
%endfunction
 
 
%%Function:SLibGetDefaultInitialValueFromId=====================================
%%Abstract:
%%Returnsthedefaultinitialvalueforthedatatypeofrecordpassedin.
%%Thisfunctioncurrentlyjustmakesatrivialcalltoanotherfunction,but
%%thisextralayerthisfunctioninsertslaysthepathforfutureimprovements.
%%Currently,thisfunctionjustreturnstheGround-Value.TheGround-Value
%%istheStored-Integer-ValuethatbestrepresentsReal-World-Valuezero.
%%Inordertogethigherefficiencyinthegeneratedcode,atafuture
%%time,thedefaultinitialvaluemaybeswitchedtojust
%%theStored-Integerwithvaluezero,irregardlessofwhetherornotthat
%%correspondstoReal-World-Valuezero.Thevaluesaremainlydifferent
%%fordatatypeswithnon-zerobias.Thisfuturechangeislikelytobe
%%basedonanoptimizationsetting.
%%
%function SLibGetDefaultInitialValueFromId(dataTypeId) void
  %% %assign value = SLibGetStoredIntegerZeroFromId(dataTypeId)
  %assign value = SLibGetGroundValueFromIdStrictOpt(dataTypeId,0)
  %return value
%endfunction
 
%%Function:SLibGetDefaultInitialValue=====================================
%%Abstract:
%%Abstract:
%%Returnsthedefaultinitialvalueforthedatatypeofrecordpassedin.
%%Thisfunctioncurrentlyjustmakesatrivialcalltoanotherfunction,but
%%thisextralayerthisfunctioninsertslaysthepathforfutureimprovements.
%%Currently,thisfunctionjustreturnstheGround-Value.TheGround-Value
%%istheStored-Integer-ValuethatbestrepresentsReal-World-Valuezero.
%%Inordertogethigherefficiencyinthegeneratedcode,atafuture
%%time,thedefaultinitialvaluemaybeswitchedtojust
%%theStored-Integerwithvaluezero,irregardlessofwhetherornotthat
%%correspondstoReal-World-Valuezero.Thevaluesaremainlydifferent
%%fordatatypeswithnon-zerobias.Thisfuturechangeislikelytobe
%%basedonanoptimizationsetting.
%%
%%Notethatfuturechangetothisalsomeanschangetofunction
%%SLibDefaultInitialValueIsAllZeroBits.
%%
%function SLibGetDefaultInitialValue(rec,reim) void
  %% %assign value = SLibGetStoredIntegerZeroValue(rec,reim)
  %assign value = SLibGetGroundValueStrictOpt(rec,reim,0)
  %return value
%endfunction
 
%function SLibGetDefaultInitialValueByCGTypeIdx(typeIdx, reim) void
  %createrecord rec { CGTypeIdx typeIdx }
 
  %return SLibGetDefaultInitialValue(rec, reim)
%endfunction
 
 
%%Function:SLibGetCastedValue================================================
%%Abstract:
%%Thisfunctioncastsanumericvaluebasedonitsdatatype.Nonbuilt-in
%%datatypesarereturned"untouched".Notethatthisfunctionisuseful
%%formakingappropriateTLCtypes.
%%
%%Forexample,
%%
%%SLibGetCastedValue(Gain,2)
%%==>returns2asaTLC"Number"ifGainisan"signedinteger"
%%
%%SLibGetCastedValue(Gain,2)
%%==>returns2asaTLC"Unsigned"ifGainisan"unsignedinteger"
%%
%%SLibGetCastedValue(Gain,2)
%%==>returns2.0asaTLC"Real"ifGainisa"real"datatype
%%
%%SLibGetCastedValue(Gain,2)
%%==>returns2asaTLC"String"ifGainisanunknowndatatype
%%
%%Arguments:
%%rec=TLCrecordcontainingdatatypeinformation
%%numericValue=numericvaluetoformat
%%
%function SLibGetCastedValue(rec, numericValue)
  %return(SLibGetCastedValueFromId(LibGetRecordDataTypeId(rec), numericValue))
%endfunction
 
 
%%Function:SLibGetCastedValueFromId==========================================
%%Abstract:
%%Thisfunctioncastsanumericvaluebasedonitsdatatype.Nonbuilt-in
%%datatypesarereturned"untouched".Notethatthisfunctionisuseful
%%formakingappropriateTLCtypes.
%%
%%Forexample,
%%
%%SLibGetCastedValue(tSS_INT8,2)
%%==>returns2asaTLC"Number"ifGainisan"signedinteger"
%%
%%SLibGetCastedValue(tSS_UINT16,2)
%%==>returns2asaTLC"Unsigned"ifGainisan"unsignedinteger"
%%
%%SLibGetCastedValue(tSS_DOUBLE,2)
%%==>returns2.0asaTLC"Real"ifGainisa"real"datatype
%%
%%SLibGetCastedValue(myDTid,2)
%%==>returns2asaTLC"String"ifGainisanunknowndatatype
%%
%%Arguments:
%%dtypeId=datatypeid
%%numericValue=numericvaluetoformat
%%TopTester:variants/inlineVariants/variantSource/systemtests/tmg1317695_VC1.m
%%TopTester:test/toolbox/simulink/blocks/lib_Discrete/DiscreteTimeIntegrator/rtw/tNumerics_dtdiscints.m
%%
%function SLibGetCastedValueFromId(dTypeId, numericValue)
  %% See Also:
  %% SLibGetFormattedValue
  %%
  %switch LibGetDataTypeIdAliasedThruToFromId(dTypeId)
    %case tSS_DOUBLE
 
      %% real
      %return CAST("Real", numericValue)
 
    %case tSS_SINGLE
 
      %% real32
      %return CAST("Real32", numericValue)
 
    %case tSS_UINT8
    %case tSS_UINT16
    %case tSS_UINT32
    %case tSS_BOOLEAN
 
      %% unsigned integer
      %return CAST("Unsigned", numericValue)
 
    %case tSS_INT8
    %case tSS_INT16
    %case tSS_INT32
 
      %% signed integer
      %return CAST("Number", numericValue)
 
    %default
      %if LibIsHalfDataType(LibGetDataTypeIdAliasedThruToFromId(dTypeId))
        %% real16
        %return CAST("Real16", numericValue)
      %endif
      %% unknown type
      %return numericValue
 
  %endswitch
%endfunction
 
 
%%DocFunction{OtherUsefulFunctions}:LibMinIntValue=========================
%%Abstract:
%%Forabuilt-inintegerdatatype,thisfunctionreturnstheformatted
%%minimumvalueofthatdatatype
%%
%function LibMinIntValue(dtype) void
  %assign dtypeName = LibGetDataTypeNameFromId(LibGetDataTypeIdAliasedThruToFromId(dtype))
  %switch LibGetDataTypeIdAliasedThruToFromId(dtype)
    %case tSS_UINT8
    %case tSS_UINT16
    %case tSS_UINT32
      %return "((%<dtypeName>)(0U))"
    %case tSS_INT8
    %case tSS_INT16
    %case tSS_INT32
      %assign limitId = "MIN_%<dtypeName>"
      %return "%"
      %%break
    %default
      %assign errTxt = "Invalid data type %<dtypeName>."
      %<LibBlockReportFatalError([], errTxt)>
      %break
  %endswitch
%endfunction %% LibMinIntValue
 
 
%%DocFunction{OtherUsefulFunctions}:LibMaxIntValue=========================
%%Abstract:
%%Forabuilt-inintegerdatatype,thisfunctionreturnstheformatted
%%maximumvalueofthatdatatype
%%
%function LibMaxIntValue(dtype) Output
  %assign dtypeName = LibGetDataTypeNameFromId(LibGetDataTypeIdAliasedThruToFromId(dtype))
  %switch LibGetDataTypeIdAliasedThruToFromId(dtype)
    %case tSS_UINT8
    %case tSS_UINT16
    %case tSS_UINT32
    %case tSS_INT8
    %case tSS_INT16
    %case tSS_INT32
      %assign limitId = "MAX_%<dtypeName>"
      %return "%"
      %%break
    %default
      %assign errTxt = "Invalid data type %<dtypeName>."
      %<LibBlockReportFatalError([], errTxt)>
      %break
  %endswitch
%endfunction
 
%%Function:SLibReplaceEnumLiteralValueWithTypeLimitId===================
%%Abstract:
%%Foranenumerationdatatypeandanumericalvalue,thisfunctionwill
%%returnthecorrespondingtypelimitIDifthevalueisatypelimit.
%%Otherwisethesameinputvalueisreturned.
%%
%%Forexample,
%%
%%SLibReplaceEnumLiteralValueWithTypeLimitId(Int32TypeId,-2147483648)
%%==>returnsMIN_int32_T
%%
%%SLibReplaceEnumLiteralValueWithTypeLimitId(Int32TypeId,-2147483647)
%%==>returns-2147483647
%%
%%Arguments:
%%rec=Datatypeid
%%numericValue=Numericvalue
%%TopTester:test/toolbox/simulink/blocks/tselect_EnumIndex.m
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/tStringSupport.m
%%
%function SLibReplaceEnumLiteralValueWithTypeLimitId(id, numericValue)
  %% See Also:
  %% SLibGetFormattedValueFromId, SLibGetFormattedValue,
  %% SLibGetCastedValue
  %%
  %assign aliasedThroughDataType = LibGetDataTypeIdAliasedThruToFromId(id)
 
  %assert LibIsEnumDataType(aliasedThroughDataType)
  %assign enumStorageTypeId = LibGetEnumTypeStorageType(aliasedThroughDataType)
  %if enumStorageTypeId >= 0
    %assign aliasedThroughDataType = enumStorageTypeId
  %elseif LibIsEnumTypeStoredAsInt(aliasedThroughDataType)
    %assign aliasedThroughDataType = tSS_INT32
  %else
    %assert TLC_FALSE
  %endif
 
  %switch aliasedThroughDataType
    %case tSS_INT32
      %% Currently we only handle the integer 32 bit case, to avoid the
      %% C4146 Visual Studio C compiler warning. See g1652846 for details.
 
      %% signed integer
      %if numericValue == int32MinValue
        %% suppress compiler warning when using largest negative
        %% 2s-complement number for 32-bit integers
        %return "%<LibMinIntValue(aliasedThroughDataType)>"
      %endif
  %endswitch
  %% default case
  %return numericValue
%endfunction
 
%%Function:SLibGetFormattedValueFromId=======================================
%%Abstract:
%%Forabuilt-indatatype,thisfunctionreturnstheformattedvalueof
%%anumericvaluebasedonitscorrespondingdatatypeid.
%%Valuesthatarenotassociatedwithaknownbuilt-indatatypesare
%%returned"untouched".
%%
%%Forexample,
%%
%%SLibGetFormattedValueFromId(Gain,2)
%%==>returns2ifGainisan"signedinteger"datatype
%%
%%SLibGetFormattedValueFromId(Gain,2)
%%==>returns2UifGainisan"unsignedinteger"datatype
%%
%%SLibGetFormattedValueFromId(Gain,2)
%%==>returns2.0ifGainisa"real"datatype
%%
%%SLibGetFormattedValueFromId(Gain,2)
%%==>returnsEnumNameifGainisanenumerateddatatype
%%
%%SLibGetFormattedValueFromId(Gain,2)
%%==>returns2ifGainisanunknowndatatype
%%
%%Arguments:
%%rec=datatypeid
%%numericValue=numericvaluetoformat
%%Toptetser:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmVSSfeedingInactiveVS_VC1.m
%%TopTester:variants/inlineVariants/variantSource/systemtests/tmg1293017_VC1.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tvss_code_variants.m
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/inlineVariants/tInlineVariants4.m
%%
%function SLibGetFormattedValueFromId(id, numericValue)
  %% See Also:
  %% SLibGetFormattedValue, SLibGetCastedValue,
  %% SLibReplaceEnumLiteralValueWithTypeLimitId
  %%
  %assign dTypeName = LibGetDataTypeNameFromId(LibGetDataTypeIdAliasedThruToFromId(id))
  %switch LibGetDataTypeIdAliasedThruToFromId(id)
      %% For double and single, we need to track any usage of inf or nan
    %case tSS_DOUBLE
 
      %% real
      %<LibCheckValue(0, numericValue)>
      %return "%<CAST("Real", numericValue)>"
 
    %case tSS_SINGLE
 
      %% real32
      %<LibCheckValue(0, numericValue)>
      %return "%<CAST("Real32", numericValue)>"
 
    %case tSS_UINT8
 
      %% unsigned character
      %if IntegerSizes.IntNumBits == 8
        %return "%<CAST("Unsigned", numericValue)>"
      %elseif IntegerSizes.IntNumBits >= 8
        %return "((uint8_T)%<CAST("Unsigned", numericValue)>)"
      %else
        %return "((uint8_T)%<CAST("Unsigned", numericValue)>L)"
      %endif
 
    %case tSS_UINT16
 
      %% unsigned short
      %if IntegerSizes.IntNumBits == 16
        %return "%<CAST("Unsigned", numericValue)>"
      %elseif IntegerSizes.IntNumBits >= 16
        %return "((uint16_T)%<CAST("Unsigned", numericValue)>)"
      %else
        %return "((uint16_T)%<CAST("Unsigned", numericValue)>L)"
      %endif
 
    %case tSS_UINT32
 
      %% unsigned integer
      %if IntegerSizes.IntNumBits == 32
        %return "%<CAST("Unsigned", numericValue)>"
      %elseif IntegerSizes.IntNumBits >= 32
        %return "((uint32_T)%<CAST("Unsigned", numericValue)>)"
      %else
        %return "((uint32_T)%<CAST("Unsigned", numericValue)>L)"
      %endif
 
    %case tSS_INT8
 
      %% signed character
      %if IntegerSizes.IntNumBits <= 8 && numericValue == -128
        %return "%<LibMinIntValue(id)>"
      %elseif IntegerSizes.IntNumBits >= 8
        %return "%<CAST("Number", numericValue)>"
      %else
        %return "((int8_T)%<CAST("Number", numericValue)>L)"
      %endif
 
    %case tSS_INT16
 
      %% signed short
      %if IntegerSizes.IntNumBits <= 16 && numericValue == -32768
        %return "%<LibMinIntValue(id)>"
      %elseif IntegerSizes.IntNumBits >= 16
        %return "%<CAST("Number", numericValue)>"
      %else
        %return "((int16_T)%<CAST("Number", numericValue)>L)"
      %endif
 
    %case tSS_INT32
 
      %% signed integer
      %if numericValue == int32MinValue
        %% suppress compiler warning when using largest negative
        %% 2s-complement number for 32-bit integers
        %return "%<LibMinIntValue(id)>"
      %elseif IntegerSizes.IntNumBits >= 32
        %return "%<CAST("Number", numericValue)>"
      %else
        %return "((int32_T)%<CAST("Number", numericValue)>L)"
      %endif
 
    %case tSS_LONG
    %case tSS_ULONG
      %return "%<numericValue>"
 
    %case tSS_LONG_LONG
    %case tSS_ULONG_LONG
      %return "%<numericValue>"
 
    %case tSS_BOOLEAN
 
      %% boolean
      %return (numericValue != 0) ? "%" : "%"
 
    %default
      %% Handle half precision
      %if LibIsHalfDataType(LibGetDataTypeIdAliasedThruToFromId(id))
        %% real16
        %<LibCheckValue(0, numericValue)>
        %return "%<CAST("Real16", numericValue)>"
      %endif
      %% use variable to hold zero value of a struct type
      %% when bias!=0 we still need to use groundName as variable to intialize. But its value
      %% could be fix64_gnd={3} instead of fix64_gnd={0}. Actual value are computed in fixptlib.tlc.
      %% value can change but var name never changes, thus don't consider bias!= case here,
      %% it should be taken care of in fixptlib.tlc when compute the ground value for the struct type.
      %if LibIsDataTypeMultiWordFixpt(id) && TYPE(numericValue)=="Number" && numericValue == 0
        %if LibIsStructDataType(id)
          %<SLibSetDataTypeGroundReqInMemory(id)>
        %endif
        %return "%<::CompiledModel.DataTypes.DataType[id].GroundName>"
      %endif
      %% Write out enumeration string for enumerated values
      %if LibIsEnumDataType(id)
        %return "%<SLibGetEnumTypeCodeGenStringFromValue(id, numericValue)>"
      %endif
      %% unknown type
      %return "%<numericValue>"
 
  %endswitch
%endfunction
 
%%Function:SLibGetFormattedValue=============================================
%%Abstract:
%%Forabuilt-indatatype,thisfunctionreturnstheformattedvalueof
%%anumericvaluebasedonitscorrespondingdatatyperecord.
%%Valuesthatarenotassociatedwithaknownbuilt-indatatypesare
%%returned"untouched".
%%
%%Arguments:
%%rec=TLCrecordcontainingdatatypeinformation
%%numericValue=numericvaluetoformat
%%
%function SLibGetFormattedValue(rec, numericValue)
  %% See Also:
  %% SLibGetFormattedValueFromId, SLibGetCastedValue
  %%
  %return SLibGetFormattedValueFromId(LibGetRecordDataTypeId(rec), numericValue)
%endfunction
 
%%LibComplexConvertBetween====================================================
%%Abstract:
%%ApplyConvertBetweentodatathatmaybecomplex
%%
%%Arguments:
%%dstId=typebeingconvertedto
%%srcId=typebeingconvertedfrom
%%cmplx=whetherthesignaliscomplex
%%input=inputsignal
%%options=options
%%output=outputsignal
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/-tStringSupport.m
%%
%function LibComplexConvertBetweenForSrcId(dstId, srcId, cmplx, input, ...
  options, output) Output
  %assign ConvertBetweenFcn = ...
     LibConvertBetweenTLCFcnName(srcId)
  %if !cmplx
    %assign status = %<ConvertBetweenFcn>(dstId,srcId,input,options,output)
    %return status
  %else
    %assign realInput = "%<input>.%<tRealPart>"
    %assign imagInput = "%<input>.%<tImagPart>"
    %assign realOutput = "%<output>.%<tRealPart>"
    %assign imagOutput = "%<output>.%<tImagPart>"
    %assign status = %<ConvertBetweenFcn>(dstId,srcId,realInput,options,realOutput)
    %if status != 1
      %return status
    %endif
    %assign status = %<ConvertBetweenFcn>(dstId,srcId,imagInput,options,imagOutput)
    %return status
  %endif
%endfunction
 
%%SLibDeepCopyData====================================================
%%Abstract:
%%ApplyDeepCopyortoopaquedata
%%
%%Arguments:
%%id=typeofdata
%%data=databeingdestructedinplace
%%
%function SLibDeepCopyData(id, dst, src) Output
  %assign DeepCopyFcn = SLibDataTypeDeepCopyFcnName(id)
  %assign status = 1
  %if !ISEMPTY(DeepCopyFcn)
    %assign status = %<DeepCopyFcn>(id, dst, src)
  %endif
  %return status
%endfunction
 
%%LibOutputExprCast============================================================
%%Abstract:
%%Returnwhetherornotablock'soutputexpressionneedstobeexplicitly
%%casttothedatatypeoftheblock'soutput;thisneedstobedoneforC
%%topreventimplicitupcastsofshortintegertypes
%%TopTester:test/toolbox/simulink/blocks/CPPCodeGen/tsmlk_core_cpp_coverage.m
%%
%function LibOutputExprCast(srcBlk, idx)
  %assign cast = ""
  %if !SLibBlockIntegerDowncastRequired(srcBlk)
    %return cast
  %endif
  %assign dtype = LibGetRecordDataTypeId(srcBlk.DataOutputPort[idx])
  %assign storageId = ::CompiledModel.DataTypes.DataType[dtype].StorageId
  %% If the datatype is known to resolve to a builtin, do it for short
  %% integers
  %if LibIsBuiltInDataType(storageId)
    %if SLibIsIntegerFromId(storageId)
      %if ::CompiledModel.IntegerSizesExists
        %switch storageId
          %case tSS_UINT8
          %case tSS_INT8
            %if 8 < IntegerSizes.IntNumBits
              %assign cast = "(%<LibGetDataTypeNameFromId(storageId)>)"
            %endif
            %break
          %case tSS_INT16
          %case tSS_UINT16
            %if 16 < IntegerSizes.IntNumBits
              %assign cast = "(%<LibGetDataTypeNameFromId(storageId)>)"
            %endif
            %break
          %default
            %break
        %endswitch
      %% If IntegerSizes target property does not exist, go with default
      %else
        %switch storageId
          %case tSS_UINT8
          %case tSS_UINT16
          %case tSS_INT8
          %case tSS_INT16
            %assign cast = "(%<LibGetDataTypeNameFromId(storageId)>)"
            %break
          %default
            %break
        %endswitch
      %endif
    %endif
  %% If it doesn't resolve to a builtin, just cast to the output type
  %% unless a structure type
  %elseif !LibIsStructDataType(dtype)
    %assign cast = "(%<LibGetDataTypeNameFromId(dtype)>)"
  %endif
  %return cast
%endfunction
 
%%Function:SLibConvertBetweenBuiltin=========================================
%%Abstract:
%%Convertbetweenbuiltindatatypes
%%
%%Arguments:
%%outDType=desiredoutputdatatype
%%inDType=actualinputdatatype
%%inLabel=inputsignal
%%options=options
%%outLabel=outputsignal
%function SLibConvertBetweenBuiltin(outDType,inDType,inLabel,options,outLabel) Output
  %if outDType == tSS_BOOLEAN
    %if inDType == tSS_BOOLEAN
      %<outLabel> = %<inLabel>;
    %else
      %assign zero = SLibGetFormattedValueFromId(inDType, 0)
      %<outLabel> = %<inLabel> != %<zero>;
    %endif
  %else
    %assign outDTypeName = LibGetDataTypeNameFromId(outDType)
    %<outLabel> = (%<outDTypeName>) %<inLabel>;
  %endif
  %return 1
%endfunction
 
%%Function:SLibIsPositiveBuiltin=============================================
%%Abstract:
%%Convertbetweenbuiltindatatypes
%%
%%Arguments:
%%inDType=typeofinput
%%inLabel=inputsignal
%%options=options
%%outLabel=outputsignal
%%
%function SLibIsPositiveBuiltin(inDType, inLabel, options, outLabel) Output
  %if inDType == tSS_BOOLEAN
    %<outLabel> = %<inLabel>;
  %else
    %assign zero = SLibGetFormattedValueFromId(inDType, 0)
    %<outLabel> = %<inLabel> > %<zero>;
  %endif
  %return 1
%endfunction
 
%%Function:SLibSignBuiltin===================================================
%%Abstract:
%%Convertbetweenbuiltindatatypes
%%
%%Arguments:
%%inDType=typeofinput
%%inLabel=inputsignal
%%options=options
%%outLabel=outputsignal
%%
%function SLibSignBuiltin(inDType, inLabel, options, outLabel) Output
  %if inDType == tSS_BOOLEAN
    %<outLabel> = %<inLabel>;
  %else
     %assign zero = SLibGetFormattedValueFromId(inDType, 0)
     if (%<inLabel> > %<zero>) {
       %<outLabel> = 1;
     } else if (%<inLabel> < %<zero>) {
       %<outLabel> = -1;
     } else {
       %<outLabel> = 0;
     }
  %endif
  %return 1
%endfunction
 
%%Function:SLibSigToLogDataType==============================================
%%Abstract:
%%Convenientutilitytoreturnsignaldatatypeaslogdatatype
%%ifsignaldatatypeisbuiltin,otherwisereturnthespecified
%%loggingdatatypetobeused
%%
%function SLibSigToLogDataType(sigDataType, usedLogDataType) void
  %if LibIsBuiltInDataType(sigDataType)
    %return sigDataType
  %else
    %return usedLogDataType
  %endif
%endfunction
 
 
%%Function:SLibHandleSaturateOnOverflow======================================
%%Abstract:
%%Convenientutilitytoprocessablock'ssaturateonoverflowflag;
%%returnwhetherornottogeneratesaturatingcode.
%%
%function SLibHandleSaturateOnOverflow(block) void
  %if block.ParamSettings.SaturateOnOverflow == "Needed"
    %assign doSaturate = 1
  %else
    %assign doSaturate = 0
  %endif
  %return doSaturate
%endfunction
 
%%Function:SetOrderedDataTypeIdx=============================================
%%Considertocreatesections:
%%built-intypes
%%fixpointtypes
%%enumtypes
%%non-anonymousbuses
%%anonymousstructtypes
%%TopTester:test/toolbox/simulink/variants/variantBus/vss/-tDefaultVariants.m
%%
%function GetOrderedDataTypeIdx(DtIdxMap) void
 
  %with ::CompiledModel
 
    %createrecord DtIdxAnonymousStructs { }
 
    %% All types excluding anonymous struct types
    %foreach dtIdx = ::CompiledModel.DataTypes.NumDataTypes
      %if (LibDataTypeIsAnonymousStruct(dtIdx) == TLC_FALSE)
        %addtorecord DtIdxMap Dt { idx %<dtIdx> }
      %else
        %addtorecord DtIdxAnonymousStructs Dt { idx %<dtIdx> }
      %endif
    %endforeach
 
    %% append anonymous struct types
    %if !ISEMPTY(DtIdxAnonymousStructs)
      %foreach idx = SIZE(DtIdxAnonymousStructs.Dt, 1)
        %addtorecord DtIdxMap Dt {idx DtIdxAnonymousStructs.Dt[idx].idx}
      %endforeach
    %endif
  %endwith
 
%endfunction
 
%%Function:FcnIsDataTypeTargetInt=======================================
%%Abstract:
%%Anytypethatisequivalenttotargetintegertype
%%
%function FcnIsDataTypeTargetInt(dTypeId)
  %if ((dTypeId < 0) || (dTypeId >= ::CompiledModel.DataTypes.NumDataTypes) ...
      || (LibIsBuiltInDataType(dTypeId)))
    %return 0
  %else
    %assign aliasDT = LibGetDataTypeIdAliasedToFromId(dTypeId)
    %if ((aliasDT == ::CompiledModel.tSS_INTEGER) ...
        || (aliasDT == ::CompiledModel.tSS_UINTEGER))
      %return 1
    %else
      %return 0
    %endif
  %endif
%endfunction%% FcnIsDataTypeTargetInt
 
%%Function:FcnMapIfEquivToTargetInt=====================================
%%Abstract:
%%Mapnon-builtintypestotSS_INTEGER/tSS_UINTEGER
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/tValueVariants.m
%%
%function FcnMapIfEquivToTargetInt(dTypeId) void
  %if (LibIsBuiltInDataType(dTypeId) || LibIsAliasDataType(dTypeId))
    %return
  %elseif ::CompiledModel.DataTypes.DataType[dTypeId].IsFixedPoint
    %assign tgtIntBitStr = "sfix" + "%<IntegerSizes.IntNumBits>"
    %assign tgtUIntBitStr = "ufix" + "%<IntegerSizes.IntNumBits>"
    %assign dt = ::CompiledModel.DataTypes.DataType[dTypeId]
    %if dt.DTName == tgtIntBitStr
      %assign dt.IdAliasedTo = ::CompiledModel.tSS_INTEGER
    %elseif dt.DTName == tgtUIntBitStr
      %assign dt.IdAliasedTo = ::CompiledModel.tSS_UINTEGER
    %endif
  %endif
%endfunction%% FcnRegisterTargetIntType
 
%%Function:SLibSetupDatatypeInfo=============================================
%%Abstract:
%%SetupvariablesandfieldspertainingtoDatatypeinformation
%%TopTester:test/toolbox/simulink/variants/string/tStringSupport.m
%%Toptetser:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/-tStringSupport.m
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/tValueVariants.m
%%
%function SLibSetupDatatypeInfo() void
  %%
  %% Map DataTypeTable
  %%
 
  %% reserve for target defined oversized(>32, or 24) long type
  %% unconditionally populate 64 bit, big long type and long long type
  %<LibAddToCompiledModel("tSS_LONG", INT32MIN)>
  %<LibAddToCompiledModel("tSS_ULONG", INT32MIN+3)>
  %<LibAddToCompiledModel("tSS_LONG_LONG", INT32MIN+4)>
  %<LibAddToCompiledModel("tSS_ULONG_LONG", INT32MIN+5)>
 
  %% reserve for function prototypes that contain void or size_t args
  %% Right now, this is used for TFL queries of memcpy, memset, and memcmp
  %<LibAddToCompiledModel("tSS_VOID", INT32MIN+1)>
  %<LibAddToCompiledModel("tSS_SIZET", INT32MIN+2)>
 
  %% reserve unsigned int for completeness. This is used to map unsized
  %% args in TFL queries
  %<LibAddToCompiledModel("tSS_UINTEGER", INT32MIN+6)>
 
 
  %%Find Largest Multiword bits
  %assign LargestMultiwordBits = %<SLibGetLargestMultiwordDataTypeNeeded()>
  %<LibAddToCompiledModel("LargestMultiwordBits", LargestMultiwordBits)>
  %<LibAddToCompiledModel("DeclaredFixedPointWordSizeUsage", 0)>
  %<DeclareFixedPointWordSizeUsage(::CompiledModel.CGTypes.DeclareUsedMultiWordBits)>
 
  %% Code generation needs special half precision headers
  %<LibAddToCompiledModel("DeclaredHalfPrecisionUsage", TLC_FALSE)>
 
  %createrecord dtIdxMap { }
  %<GetOrderedDataTypeIdx(dtIdxMap)>
 
  %with ::CompiledModel
    %foreach dtIdx0 = ::CompiledModel.DataTypes.NumDataTypes
      %assign dtIdx = dtIdxMap.Dt[dtIdx0].idx
      %assign dt = ::CompiledModel.DataTypes.DataType[dtIdx]
      %%
      %% A "Name" identifier is added to all DataType records with
      %% a null default value. An error will occur if a block uses a
      %% non-built-in data type without setting "Name" according to
      %% SLibSetDataTypeName.
      %%
      %% Additionally, ground is defined for each built-in data type.
      %% Custom data types can be defined similarly from within a block's
      %% BlockInstanceSetup or BlockTypeSetup function. Again, an error
      %% will occur if a block sources to an undefined ground.
      %%
      %<LibAddIdentifier(dt, "Name", "")>
      %<LibAddIdentifier(dt, "ConvertBetweenTLCFcnName", "")>
      %<LibAddIdentifier(dt, "IsPositiveTLCFcnName", "")>
      %<LibAddIdentifier(dt, "SignTLCFcnName", "")>
      %<LibAddIdentifier(dt, "ConvertBetweenTLCFcnFile", "")>
      %<LibAddIdentifier(dt, "IsPositiveTLCFcnFile", "")>
      %<LibAddIdentifier(dt, "SignTLCFcnFile", "")>
      %<LibAddIdentifier(dt, "Enum", "")>
      %<LibAddIdentifier(dt, "GroundName", "")>
      %<LibAddIdentifier(dt, "GroundValue", "")>
      %<LibAddIdentifier(dt, "GroundInit", "")>
      %<LibAddIdentifier(dt, "GroundReqInMemory", 0)>
      %<LibAddIdentifier(dt, "GroundHasFloats", 0)>
      %<LibAddIdentifier(dt, "ComplexName", "")>
      %<LibAddIdentifier(dt, "ComplexGroundName", "")>
      %<LibAddIdentifier(dt, "ComplexGroundReqInMemory", 0)>
      %%
      %% Setup all built-in and pre-defined (fcn_call, pointer, integer
      %% and action) types.
      %%
      %switch dt.DTName
        %case "double"
          %<fcnSetDataTypeName(dt, "real_T", TLC_FALSE)>
          %<SLibSetDataTypeEnum(dt, "SS_DOUBLE")>
          %<SLibSetDataTypeConvertBetweenTLCFcnName(dt, ...
            "SLibConvertBetweenBuiltin")>
          %<SLibSetDataTypeIsPositiveTLCFcnName(dt, "SLibIsPositiveBuiltin")>
          %<SLibSetDataTypeSignTLCFcnName(dt, "SLibSignBuiltin")>
          %<LibAddToCompiledModel("tSS_DOUBLE", dt.Id)>
          %assign gndName = "%<::CompiledModel.Name>_RGND"
          %<SLibSetDataTypeGroundName(dt, gndName)>
          %<SLibSetDataTypeGroundValue(dt, 0.0)>
          %<SLibSetDataTypeGroundHasFloats(dt, 1)>
          %<SLibSetDataTypeComplexName(dt, "creal_T")>
          %<SLibSetDataTypeComplexGroundName(dt, gndName + "_Complex")>
          %break
        %case "single"
          %<fcnSetDataTypeName(dt, "real32_T", TLC_FALSE)>
          %<SLibSetDataTypeEnum(dt, "SS_SINGLE")>
          %<SLibSetDataTypeConvertBetweenTLCFcnName(dt, ...
            "SLibConvertBetweenBuiltin")>
          %<SLibSetDataTypeIsPositiveTLCFcnName(dt, "SLibIsPositiveBuiltin")>
          %<SLibSetDataTypeSignTLCFcnName(dt, "SLibSignBuiltin")>
          %<LibAddToCompiledModel("tSS_SINGLE", dt.Id)>
          %assign gndName = "%<::CompiledModel.Name>_R32GND"
          %<SLibSetDataTypeGroundName(dt, gndName)>
          %<SLibSetDataTypeGroundValue(dt, "0.0F")>
          %<SLibSetDataTypeGroundHasFloats(dt, 1)>
          %<SLibSetDataTypeComplexName(dt, "creal32_T")>
          %<SLibSetDataTypeComplexGroundName(dt, gndName + "_Complex")>
          %break
        %case "half"
          %<FixPt_RegisterHalfAsBuiltInType(dtIdx)>
          %break
        %case "boolean"
          %<fcnSetDataTypeName(dt, "boolean_T", TLC_FALSE)>
          %<SLibSetDataTypeEnum(dt, "SS_BOOLEAN")>
          %<SLibSetDataTypeConvertBetweenTLCFcnName(dt, ...
            "SLibConvertBetweenBuiltin")>
          %<SLibSetDataTypeIsPositiveTLCFcnName(dt, "SLibIsPositiveBuiltin")>
          %<SLibSetDataTypeSignTLCFcnName(dt, "SLibSignBuiltin")>
          %<LibAddToCompiledModel("tSS_BOOLEAN", dt.Id)>
          %assign gndName = "%<::CompiledModel.Name>_BGND"
          %<SLibSetDataTypeGroundName(dt, gndName)>
          %<SLibSetDataTypeGroundValue(dt, "%")>
          %% complex boolean undefined
          %break
        %case "int8"
          %<fcnSetDataTypeName(dt, "int8_T", TLC_FALSE)>
          %<SLibSetDataTypeEnum(dt, "SS_INT8")>
          %<SLibSetDataTypeConvertBetweenTLCFcnName(dt, ...
            "SLibConvertBetweenBuiltin")>
          %<SLibSetDataTypeIsPositiveTLCFcnName(dt, "SLibIsPositiveBuiltin")>
          %<SLibSetDataTypeSignTLCFcnName(dt, "SLibSignBuiltin")>
          %<LibAddToCompiledModel("tSS_INT8", dt.Id)>
          %assign gndName = "%<::CompiledModel.Name>_I8GND"
          %<SLibSetDataTypeGroundName(dt, gndName)>
          %<SLibSetDataTypeGroundValue(dt, 0)>
          %<SLibSetDataTypeComplexName(dt, "cint8_T")>
          %<SLibSetDataTypeComplexGroundName(dt, gndName + "_Complex")>
          %break
        %case "uint8"
          %<fcnSetDataTypeName(dt, "uint8_T", TLC_FALSE)>
          %<SLibSetDataTypeEnum(dt, "SS_UINT8")>
          %<SLibSetDataTypeConvertBetweenTLCFcnName(dt, ...
            "SLibConvertBetweenBuiltin")>
          %<SLibSetDataTypeIsPositiveTLCFcnName(dt, "SLibIsPositiveBuiltin")>
          %<SLibSetDataTypeSignTLCFcnName(dt, "SLibSignBuiltin")>
          %<LibAddToCompiledModel("tSS_UINT8", dt.Id)>
          %assign gndName = "%<::CompiledModel.Name>_U8GND"
          %<SLibSetDataTypeGroundName(dt, gndName)>
          %<SLibSetDataTypeGroundValue(dt, 0U)>
          %<SLibSetDataTypeComplexName(dt, "cuint8_T")>
          %<SLibSetDataTypeComplexGroundName(dt, gndName + "_Complex")>
          %break
        %case "int16"
          %<fcnSetDataTypeName(dt, "int16_T", TLC_FALSE)>
          %<SLibSetDataTypeEnum(dt, "SS_INT16")>
          %<SLibSetDataTypeConvertBetweenTLCFcnName(dt, ...
            "SLibConvertBetweenBuiltin")>
          %<SLibSetDataTypeIsPositiveTLCFcnName(dt, "SLibIsPositiveBuiltin")>
          %<SLibSetDataTypeSignTLCFcnName(dt, "SLibSignBuiltin")>
          %<LibAddToCompiledModel("tSS_INT16", dt.Id)>
          %assign gndName = "%<::CompiledModel.Name>_I16GND"
          %<SLibSetDataTypeGroundName(dt, gndName)>
          %<SLibSetDataTypeGroundValue(dt, 0)>
          %<SLibSetDataTypeComplexName(dt, "cint16_T")>
          %<SLibSetDataTypeComplexGroundName(dt, gndName + "_Complex")>
          %break
        %case "uint16"
          %<fcnSetDataTypeName(dt, "uint16_T", TLC_FALSE)>
          %<SLibSetDataTypeEnum(dt, "SS_UINT16")>
          %<SLibSetDataTypeConvertBetweenTLCFcnName(dt, ...
            "SLibConvertBetweenBuiltin")>
          %<SLibSetDataTypeIsPositiveTLCFcnName(dt, "SLibIsPositiveBuiltin")>
          %<SLibSetDataTypeSignTLCFcnName(dt, "SLibSignBuiltin")>
          %<LibAddToCompiledModel("tSS_UINT16", dt.Id)>
          %assign gndName = "%<::CompiledModel.Name>_U16GND"
          %<SLibSetDataTypeGroundName(dt, gndName)>
          %<SLibSetDataTypeGroundValue(dt, 0U)>
          %<SLibSetDataTypeComplexName(dt, "cuint16_T")>
          %<SLibSetDataTypeComplexGroundName(dt, gndName + "_Complex")>
          %break
        %case "int32"
          %<fcnSetDataTypeName(dt, "int32_T", TLC_FALSE)>
          %<SLibSetDataTypeEnum(dt, "SS_INT32")>
          %<SLibSetDataTypeConvertBetweenTLCFcnName(dt, ...
            "SLibConvertBetweenBuiltin")>
          %<SLibSetDataTypeIsPositiveTLCFcnName(dt, "SLibIsPositiveBuiltin")>
          %<SLibSetDataTypeSignTLCFcnName(dt, "SLibSignBuiltin")>
          %<LibAddToCompiledModel("tSS_INT32", dt.Id)>
          %assign gndName = "%<::CompiledModel.Name>_I32GND"
          %<SLibSetDataTypeGroundName(dt, gndName)>
          %<SLibSetDataTypeGroundValue(dt, 0)>
          %<SLibSetDataTypeComplexName(dt, "cint32_T")>
          %<SLibSetDataTypeComplexGroundName(dt, gndName + "_Complex")>
          %break
        %case "uint32"
          %<fcnSetDataTypeName(dt, "uint32_T", TLC_FALSE)>
          %<SLibSetDataTypeEnum(dt, "SS_UINT32")>
          %<SLibSetDataTypeConvertBetweenTLCFcnName(dt, ...
            "SLibConvertBetweenBuiltin")>
          %<SLibSetDataTypeIsPositiveTLCFcnName(dt, "SLibIsPositiveBuiltin")>
          %<SLibSetDataTypeSignTLCFcnName(dt, "SLibSignBuiltin")>
          %<LibAddToCompiledModel("tSS_UINT32", dt.Id)>
          %assign gndName = "%<::CompiledModel.Name>_U32GND"
          %<SLibSetDataTypeGroundName(dt, gndName)>
          %<SLibSetDataTypeGroundValue(dt, 0U)>
          %<SLibSetDataTypeComplexName(dt, "cuint32_T")>
          %<SLibSetDataTypeComplexGroundName(dt, gndName + "_Complex")>
          %break
        %case "fcn_call"
          %<fcnSetDataTypeName(dt, "fcn_call_T", TLC_FALSE)>
                %<SLibSetDataTypeEnum(dt, "SS_FCN_CALL")>
                %<LibAddToCompiledModel("tSS_FCN_CALL", dt.Id)>
          %break
        %case "pointer"
          %<fcnSetDataTypeName(dt, "pointer_T", TLC_FALSE)>
          %<SLibSetDataTypeEnum(dt, "SS_POINTER")>
          %<SLibSetDataTypeGroundValue(dt, 0)>
          %<LibAddToCompiledModel("tSS_POINTER", dt.Id)>
          %break
        %case "integer"
          %<fcnSetDataTypeName(dt, "int_T", TLC_FALSE)>
          %<SLibSetDataTypeEnum(dt, "SS_INTEGER")>
          %<LibAddToCompiledModel("tSS_INTEGER", dt.Id)>
          %break
        %case "action"
          %<fcnSetDataTypeName(dt, "action_T", TLC_FALSE)>
          %break
        %case "timer_uint32_pair"
          %<fcnSetDataTypeName(dt, "timer_uint32_pair_T", TLC_FALSE)>
          %<SLibSetDataTypeEnum(dt, "SS_TIMER_UINT32_PAIR")>
          %<LibAddToCompiledModel("tSS_TIMER_UINT32_PAIR", dt.Id)>
          %break
        %default
          %<fcnSetDataTypeName(dt,dt.DTName, TLC_FALSE)>
          %assign aIdx = dt.IdAliasedThruTo
          %% Enumerated type
          %if LibIsEnumDataType(dtIdx)
            %<SLibSetDataTypeConvertBetweenTLCFcnName(dt, ...
              "SLibConvertBetweenEnumType")>
            %assign gndName = "%<::CompiledModel.Name>_%<dt.Name>GND"
            %<SLibSetDataTypeGroundName(dt, gndName)>
            %% Default enumerator
            %<SLibSetDataTypeGroundValue(dt, FcnGetEnumTypeDefaultCodeGenString(dtIdx))>
          %% Structure type
          %elseif LibIsStructDataType(dtIdx)
            %assign gndName = "%<::CompiledModel.Name>_rtZ%<dt.Name>"
            %<SLibSetDataTypeGroundName(dt, "%<gndName>")>
            %<SLibSetDataTypeGroundValue(dt, "%<gndName>")>
            %assign gndHasFloats = 0
            %foreach eIdx = dt.NumElements
              %assign eDtId = LibDataTypeElementDataTypeId(dtIdx, eIdx)
              %assign gndHasFloats = gndHasFloats || ...
                  ::CompiledModel.DataTypes.DataType[eDtId].GroundHasFloats
            %endforeach
            %assign dt.GroundHasFloats = gndHasFloats
            %addtorecord dt NeedGroundInit 1
          %elseif LibIsStringDataType(dtIdx) && !LibIsDataTypeCGClassType(dtIdx)
            %% For c-string (non-classes)
            %% Use 0 ('/0') as the ground value for char_T
            %assign gndName = "%<::CompiledModel.Name>_STRING_GND"
            %<SLibSetDataTypeGroundName(dt, gndName)>
            %<SLibSetDataTypeGroundValue(dt, "0")>
          %elseif LibDoesDataTypeNeedConstructor(dtIdx)
            %assign gndName = "%<::CompiledModel.Name>_rtZ_%<dt.Name>"
            %assign gndName = FEVAL("strrep",gndName,"::","_")
            %<SLibSetDataTypeGroundName(dt, gndName)>
            %<SLibSetDataTypeGroundValue(dt, "%<gndName>")>
          %% Alias type
          %elseif aIdx != dtIdx
            %assign aDt = ::CompiledModel.DataTypes.DataType[aIdx]
            %<SLibSetDataTypeEnum(dt, aDt.Enum)>
            %<SLibSetDataTypeConvertBetweenTLCFcnName(dt, ...
              aDt.ConvertBetweenTLCFcnName)>
            %<SLibSetDataTypeIsPositiveTLCFcnName(dt, ...
              aDt.IsPositiveTLCFcnName)>
            %<SLibSetDataTypeSignTLCFcnName(dt, ...
              aDt.SignTLCFcnName)>
            %<SLibSetDataTypeConvertBetweenTLCFcnFile(dt, ...
              aDt.ConvertBetweenTLCFcnFile)>
            %<SLibSetDataTypeIsPositiveTLCFcnFile(dt, ...
              aDt.IsPositiveTLCFcnFile)>
            %<SLibSetDataTypeSignTLCFcnFile(dt, ...
              aDt.SignTLCFcnFile)>
            %assign gndName = "%<::CompiledModel.Name>_%<dt.Name>GND"
            %<SLibSetDataTypeGroundName(dt, gndName)>
            %<SLibSetDataTypeGroundValue(dt, aDt.GroundValue)>
            %<SLibSetDataTypeGroundInit(dt, aDt.GroundInit)>
            %<SLibSetDataTypeGroundHasNonZero(dt, aDt.GroundHasNonZero)>
            %<SLibSetDataTypeGroundHasFloats(dt, aDt.GroundHasFloats)>
            %if LibGetDataTypeComplexNameFromId(aIdx) != ""
              %assign cName = "c%<dt.Name>"
              %<SLibSetDataTypeComplexName(dt, cName)>
              %<SLibSetDataTypeComplexGroundName(dt, gndName + "_Complex")>
            %endif
          %% Simulink.OpaqueType
          %elseif LibPackageForDataType(dt) == "Simulink" && ...
                  LibClassForDataType(dt) == "OpaqueType"
            %<SLibSetDataTypeGroundValue(dt, 0)>
          %endif
          %<FcnMapIfEquivToTargetInt(dtIdx)>
          %break
      %endswitch
      %<FixPt_DataTypeSetup(dtIdx)>
    %endforeach
    %% Add tSS_INVALID_DATA_TYPE_ID = -10
    %<LibAddToCompiledModel("tSS_INVALID_DATA_TYPE_ID", -10)>
  %endwith
 
%endfunction %% SLibSetupDatatypeInfo
 
 
%function LibDumpFixptOddSizeTypedefs() void
  %if ISFIELD(::CompiledModel, "FixptOddSizeTypedefs") && !WHITE_SPACE(CompiledModel.FixptOddSizeTypedefs)
    %return "/n%<::CompiledModel.FixptOddSizeTypedefs>"
  %else
    %return ""
  %endif
%endfunction
 
%%Function:SLibUpdateAlignmentForBusTypeHelper===============================
%%Abstract:
%function SLibUpdateAlignmentForBusTypeHelper(aTypeIdx, align) void
  %foreach idx = LibCGTypeNumMembers(aTypeIdx)
    %assign mCGTIdx = LibCGTypeMemberCGTypeIdx(aTypeIdx, idx)
    %if SLibCGTypeIsStructStrict(mCGTIdx)
      %<SLibUpdateAlignmentForBusTypeHelper(mCGTIdx, align)>
    %else
      %assign dtIdx = ::CompiledModel.CGTypes.CGType[aTypeIdx].SLTypeIdx
      %assign memberDT = ::CompiledModel.DataTypes.DataType[dtIdx]
      %if !ISFIELD(memberDT, "Alignment")
        %% Add Alignment field in the Bus type
        %% Should add it to the DataTypes.DataType record, not the CGType!
        %addtorecord ::CompiledModel.DataTypes.DataType[dtIdx] Alignment align
      %elseif ::CompiledModel.DataTypes.DataType[dtIdx].Alignment < align
          %assign ::CompiledModel.DataTypes.DataType[dtIdx].Alignment = align
      %endif
    %endif
  %endforeach
%endfunction
 
 
%%Function:SLibUpdateAlignmentForBusType=====================================
%%Abstract:
%%IfaCGTypeisastruct,itsmembercanalsobeastruct(orBus).Inthis
%%case,thealignmentshouldbepropagatedtothefieldsofthesub-structure.
%%TopTester:test/toolbox/simulink/variants/vssSigObj/tVSSSigObj.m
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibUpdateAlignmentForBusType() void
  %foreach idx = ::CompiledModel.CGTypes.NumCGTypes
    %% deal with model parameters
    %assign cgType = ::CompiledModel.CGTypes.CGType[idx]
    %if SLibCGTypeIsStructStrict(idx)
      %if cgType.SLTypeIdx > 0
        %assign dtIdx = cgType.SLTypeIdx
        %assign SLdt = ::CompiledModel.DataTypes.DataType[dtIdx]
        %assign align = LibCGTypeStructAlignment(idx)
        %% Setting the DataType Alignment field regardless of DataScope -
        %% imported types shouldn't show up in generated code
        %if (ISFIELD(SLdt,"Object") ...
             && ISFIELD(SLdt.Object,"ObjectProperties") ...
             && ISFIELD(SLdt.Object.ObjectProperties,"Alignment") ...
             && SLdt.Object.ObjectProperties.Alignment > LibCGTypeStructAlignment(idx))
 
          %assign align = SLdt.Object.ObjectProperties.Alignment
        %endif
        %if align>0
          %if !ISFIELD(SLdt, "Alignment")
            %% Add Alignment field in the Bus type
            %% Should add it to the DataTypes.DataType record, not the CGType!
            %addtorecord ::CompiledModel.DataTypes.DataType[dtIdx] Alignment align
          %elseif ::CompiledModel.DataTypes.DataType[dtIdx].Alignment < align
            %assign ::CompiledModel.DataTypes.DataType[dtIdx].Alignment = align
          %endif
        %endif
      %endif
 
      %% deal with each member
      %foreach mIdx = LibCGTypeNumMembers(idx)
        %assign memberAlignment = LibCGTypeMemberAlignment(idx, mIdx)
        %assign memberCGTypeIdx = LibCGTypeMemberCGTypeIdx(idx, mIdx)
        %if memberAlignment > 0 && ...
          SLibCGTypeIsStructStrict(memberCGTypeIdx) %% struct member is a struct
          %<SLibUpdateAlignmentForBusTypeHelper(memberCGTypeIdx, memberAlignment)>
          %
        %endif
      %endforeach %% each member
    %endif %% current CGType is a struct
  %endforeach %% each CGType
 
  %% Local BlockIO may also have Bus types that need to be updated with alignment.
  %foreach idx = ::CompiledModel.BlockOutputs.NumLocalBlockOutputs
    %assign lbo = ::CompiledModel.BlockOutputs.LocalBlockOutput[idx]
    %assign align = lbo.Alignment
    %if align > 0 %% has alignment requirement
      %if SLibCGTypeIsStructStrict(lbo.CGTypeIdx)
        %<SLibUpdateAlignmentForBusTypeHelper(lbo.CGTypeIdx, align)>
        %assign ::CompiledModel.BlockOutputs.LocalBlockOutput[idx].Alignment = -1
      %endif
    %endif
  %endforeach
 
%endfunction
%%
 
%%Function:Substring==========================================
%%Abstract:
%%Utilityfunctionthatreturnsthesubstring
%%froms[start]upto(butnotincluding)s[end].
%%Example:
%%s="Gotit?Good!"
%%Substring(s,0,7)is"Gotit?"
%%Substring(s,8,14)is"Good!"
%%
%function Substring(s, start, end)
  %assign ret = ""
  %assign len = end-start
  %foreach i = len
    %assign ret = ret + s[start+i]
  %endforeach
  %return ret
%endfunction
 
%%Function:IsDuplicateHeaderFile======================================
%%Abstract:Isthegivenheaderfileinthegivenarrayofheaderfiles?
%%
%function IsDuplicateHeaderFile(headerFiles, headerFile)
  %assign numHeaderFiles = SIZE(headerFiles, 1)
  %if numHeaderFiles == 0
    %return TLC_FALSE
  %else
    %assign duplicate = TLC_FALSE
    %foreach idx = numHeaderFiles
      %if headerFiles[idx] == headerFile
        %assign duplicate = TLC_TRUE
        %break
      %endif
    %endforeach
    %return duplicate
  %endif
%endfunction
 
%%Function:AddToHeaderFiles======================================
%%Abstract:AddthegivenheaderfiletotheheaderFilesarray(checkingfirstfordups)
%%
%function AddToHeaderFiles(headerFiles, headerFile)
  %assign duplicate = IsDuplicateHeaderFile(headerFiles, headerFile)
  %if !duplicate
    %assign headerFiles = headerFiles + "%<headerFile>"
  %endif
  %return headerFiles
%endfunction
 
%%Function:RemoveFromHeaderFiles======================================
%%Abstract:RemovethegivenheaderfilefromtheheaderFilesarray
%%
%function RemoveFromHeaderFiles(headerFiles, headerFile)
  %assign newHeaderFiles = []
  %assign numHeaderFiles = SIZE(headerFiles, 1)
  %foreach idx = numHeaderFiles
     %if headerFiles[idx] != headerFile
       %assign newHeaderFiles = newHeaderFiles + headerFiles[idx]
     %endif
  %endforeach
  %return newHeaderFiles
%endfunction
 
%%Function:SLibGetContainerSLTypeComplexName============================
%%Abstract:
%%GivenanSLdatatype,returnsthecomplexnameofit'scontainerif
%%oneexists.Otherwise,returnsitscomplexname
%function SLibGetContainerSLTypeComplexName(slDataType) void
  %if ISFIELD(slDataType, "ContainerSLTypeIdx") && ...
    slDataType.ContainerSLTypeIdx >= 0
    %assign containerTypeIdx = slDataType.ContainerSLTypeIdx
    %return LibGetDataTypeComplexNameFromId(containerTypeIdx)
  %else
    %return slDataType.ComplexName
  %endif
%endfunction
 
%%Function:SLibWriteDatatypeTypedefs==========================================
%%Abstract:
%%Writedatatypetypedefs,e.g.tothe_types.hfile
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tMdlRefWithFcnOnDataAsVSSChoice.m
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/-tStringSupport.m
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/tValueVariants.m
%%TopTester:test/toolbox/simulink/variants/tVariantGecks6.m
%%TopTester:test/toolbox/simulink/variants/tVariantGecks2.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants3.m
%%TopTester:test/toolbox/simulink/blocks/A/assignment/tassign_1.m
%%
%function SLibWriteDatatypeTypedefs() void
  
  %% Special case- When a Custom storage class file is not being generated to the shared area,
  %% and it depends on a type present in model.h(This case happens when compact file packaging
  %% is enabled for a model), we generate the type to model_types.h. The function
  %% SLibGenCustomNonSharedHeaderFileForCSC determines if we need to generate model_types.h
  %% file based on the above mentioned conditions. This function is not currently present in
  %% C++(the logic is too involved, requires moving parts of code in data_customdata.tlc to c++).
  %% Hence the typedef buffer is populated by C++ and emitted by TLC.
  %assign fileContents = GET_FILE_REP_SCRATCH_BUFFER_CONTENTS("TypedefsToModelTypesOrHeader")
  %if !ISEMPTY(fileContents)
    %if SLibGenCustomNonSharedHeaderFileForCSC()
      %assign modelTypesFile = LibGetMdlTypesHdrBaseName()
      %assign typesFile = LibCreateSourceFile("SystemHeader", "Simulink", modelTypesFile)
      %<SLibSetModelFileAttribute(typesFile, "Typedefs", fileContents)>
    %else
      %assign modelHdrFile = LibGetMdlPubHdrBaseName()
      %assign hdrFile = LibCreateSourceFile("SystemHeader", "Simulink", modelHdrFile)
      %<SLibSetModelFileAttribute(hdrFile, "Typedefs", fileContents)>
    %endif
  %endif
 
  %assign variantFileContents = GET_FILE_REP_SCRATCH_BUFFER_CONTENTS("VariantTypedefsToModelTypesOrHeader")
  %if !ISEMPTY(variantFileContents)
    %if SLibGenCustomNonSharedHeaderFileForCSC()
      %assign modelTypesFile = LibGetMdlTypesHdrBaseName()
      %assign typesFile = LibCreateSourceFile("SystemHeader", "Simulink", modelTypesFile)
      %<SLibSetModelFileAttribute(typesFile, "Defines", variantFileContents)>
    %else
      %assign modelHdrFile = LibGetMdlPubHdrBaseName()
      %assign hdrFile = LibCreateSourceFile("SystemHeader", "Simulink", modelHdrFile)
      %<SLibSetModelFileAttribute(hdrFile, "ModelTypesDefines", variantFileContents)>
    %endif
  %endif
 
 
  %createrecord dtIdxMap { }
  %<GetOrderedDataTypeIdx(dtIdxMap)>
   
  %foreach dtIdx0 = ::CompiledModel.DataTypes.NumDataTypes
    %% Get the type
    %assign dtIdx = dtIdxMap.Dt[dtIdx0].idx
    %assign dt = ::CompiledModel.DataTypes.DataType[dtIdx]
    %assign dtIsUserProvided = dt.IsUserProvided
 
    %% If the type is an imported shared type, add its file
    %% to the generated files list. This will ensure that the
    %% file appears in the code gen report. Fix for regression
    %% g1861492.
    %if dtIsUserProvided && dt.IsShared
      %assign dtHeaderFileQuoted = LibHeaderFileForDataType(dt)
      %assign sz = SIZE(dtHeaderFileQuoted)
      %assign len = sz[1]
      %assign dtHeaderFile = Substring(dtHeaderFileQuoted, 1, len-1)
       
      %<SLibAddGeneratedFileToList(dtHeaderFile,"custom","header","")>
    %endif
  %endforeach
 
  %% Remove this function in R2020b. Geck: g1722190
  %if CGMODEL_ACCESS("CGModel.NonSharedTypesInIR") && (::CompiledModel.SharedTypesInIR)
    %return
  %endif
  
  %% headerFiles will represent the list of header files we write out to model_types.h
  %% fullHeaderFiles will also include header files that are included in a nested way
  %% (i.e., if we include a.h and that includes b.h, then fullHeaderFiles will
  %% have both a.h and b.h in it)
   
  %assign headerFiles = []
  %assign fullHeaderFiles = []
 
  %% objInfoArr will be an array of objInfo records,
  %% one for each type exported to _sharedutils
  %createrecord objInfoArr { NumInfo 0 }
 
  %% ObjInfoArrNonShared will be an array of objInfo records
  %% one for each Auto type that is not exported to _sharedutils
  %% Check whether clashes exist
  %createrecord objInfoArrNonShared { NumInfo 0 }
 
  %createrecord fixptStructType{}
 
  %createrecord dtIdxMap { }
  %<GetOrderedDataTypeIdx(dtIdxMap)>
 
  %with ::CompiledModel
 
    %% Figure out if replacement types is on. This can live outside the main loop.
    %if ISFIELD(ConfigSet,"ReplacementTypes")
      %assign RTWReplacementTypesON = FEVAL("rtwprivate","rtwattic","AtticData","isReplacementOn")
    %else
      %assign RTWReplacementTypesON = TLC_FALSE
    %endif
 
    %assign genToShared = (::CompiledModel.GenUtilsSrcInSharedLocation == 1)
    %% Loop through the types
    %foreach dtIdx0 = ::CompiledModel.DataTypes.NumDataTypes
 
      %% Get the type
      %assign dtIdx = dtIdxMap.Dt[dtIdx0].idx
      %assign dt = ::CompiledModel.DataTypes.DataType[dtIdx]
      %assign dtIsUserProvided = dt.IsUserProvided
 
      %% Skip the handling of data types that are not used in the code
      %if dt.Skip
        %continue
      %endif
 
      %% Include 'slMsgSvc.h' for slMessage data payload struct
      %% Type names matches the ones inside MsgCompSolver
      %if !ISEMPTY(FEVAL("regexp", dt.Name, "^slMsg//w+"))
        %assign headerFiles = AddToHeaderFiles(headerFiles, "/"slMsgSvc.h/"")
        %assign unquotedSlMsgSvc = "slMsgSvc.h"
        %assign fullHeaderFiles = AddToHeaderFiles(fullHeaderFiles, unquotedSlMsgSvc)
      %endif
 
      %% See if this type is subject to data type replacement
      %if ISEQUAL(TYPE(RTWReplacementTypesON),"Boolean") && RTWReplacementTypesON
        %% Skip the data types which are also a replacement data type.
        %% The reason is, the typedefs for these will be emitted to rtwtypes.h instead.
        %if dt.Name == ConfigSet.ReplacementTypes.double || ...
          dt.Name == ConfigSet.ReplacementTypes.single || ...
          dt.Name == ConfigSet.ReplacementTypes.int32 || ...
          dt.Name == ConfigSet.ReplacementTypes.int16 || ...
          dt.Name == ConfigSet.ReplacementTypes.int8 || ...
          dt.Name == ConfigSet.ReplacementTypes.uint32 || ...
          dt.Name == ConfigSet.ReplacementTypes.uint16 || ...
          dt.Name == ConfigSet.ReplacementTypes.uint8 || ...
          dt.Name == ConfigSet.ReplacementTypes.boolean || ...
          dt.Name == ConfigSet.ReplacementTypes.int || ...
          dt.Name == ConfigSet.ReplacementTypes.uint || ...
          dt.Name == ConfigSet.ReplacementTypes.char
          %continue
        %endif
      %endif
 
      %% Open the buffer into which we'll write the type
      %openfile tmpBuffer
 
      %% Get the HeaderFile.
      %% There are two copies of HeaderFile, one at the top level of the DataType and
      %% one buried in the ObjectProperties. We're getting the top-level one here.
      %% This has already been defaulted as needed and quoted if necessary.
      %% If nonempty, it'll be of the form "a1.h" or , i.e. either quoted
      %% or angle-bracketed. See the C++ code in rtwgen_datatypes.cpp where
      %% the defaulting and quoting happens.
      %assign dtHeaderFileQuoted = LibHeaderFileForDataType(dt)
 
      %% See if we're generating to a shared location
      %assign dtIsShared = dt.IsShared
      %assign generateCmplxTypedef = 0
 
      %% One final check: If we're in Compact file format,
      %% and not generating to a shared location, throw an error
      %if (dtIsShared && !dtIsUserProvided) && SLibIsCompactFileFormat() && !genToShared
        %<SLibReportErrorWithIdAndArgs("RTW:tlc:SharedTypeInCompactFormat", "%<dt.Name>")>
      %endif
 
      %if dtIsShared
        %% We'll need both the quoted and unquoted header file,
        %% and also the base filename without the trailing .h.
        %% For example:
        %% dtHeaderFileQuoted "a.h" or
        %% dtHeaderFile a.h
        %% dtHeaderFileBase a
 
        %assign sz = SIZE(dtHeaderFileQuoted)
        %assign len = sz[1]
        %assign dtHeaderFile = Substring(dtHeaderFileQuoted, 1, len-1)
        %assign dtHeaderFileBase = Substring(dtHeaderFile, 0, len-4)
      %endif
 
      %% If a header file was given, add it to the headerFiles and fullHeaderFiles arrays
      %% (checking first for dups)
      %if dtHeaderFileQuoted != ""
        %assign headerFiles = AddToHeaderFiles(headerFiles, dtHeaderFileQuoted)
        %% Use the unquoted one for fullHeaderFiles, because at the point genSharedUtilsHeader
        %% subtracts this out, it is dealing with unquoted names.
        %assign fullHeaderFiles = AddToHeaderFiles(fullHeaderFiles, dtHeaderFile)
      %endif
 
      %assign typedefBuffer = ""
      %% We'll write the type in all cases except when they're importing from a header file
      %if !dtIsUserProvided
        %% This will become part of a comment
        %assign descStr = SLibGetDescriptionForData(::CompiledModel.DataTypes.DataType[dtIdx])
        %assign descStr = ISEMPTY(descStr) ? "" : "/* " + descStr + " */"
 
        %assign needGuard = !dtIsShared
 
        %% Emit alias types
        %% fixpt type with wordsize fits in target's new long type, is aliased to the target new long type
        %% in this case aDt.name == dt.Name, so no need to generate alias typedef again
        %if LibIsAliasDataType(dtIdx)
          %assign aIdx = dt.IdAliasedTo
          %if (dt.DefinedInLegacyCode == 0) || LibIsModelReferenceSimTarget()
            %assign aDt = DataTypes.DataType[aIdx]
 
            %if !LibIsAliasDataType(aIdx)
              %assign complexName = SLibGetContainerSLTypeComplexName(aDt)
            %else
              %assign complexName = aDt.ComplexName
            %endif
 
            %assign generateCmplxTypedef = SupportComplex && complexName != ""
            %% For exported types, the file guard suffices.
            %% For types going to model_types.h, put out a type guard.
            %if needGuard
              #ifndef DEFINED_TYPEDEF_FOR_%<dt.Name>_
              #define DEFINED_TYPEDEF_FOR_%<dt.Name>_
            %endif
            %<descStr>
            typedef %<aDt.Name> %<dt.Name>;
            %if generateCmplxTypedef
              typedef %<complexName> %<dt.ComplexName>;
            %endif
            %if needGuard
              #endif
            %endif
          %endif
 
        %% Emit enumeration types
        %elseif LibIsEnumDataType(dtIdx)
 
          %% For exported types, the file guard suffices.
          %% For types going to model_types.h, put out a type guard.
          %if needGuard
            #ifndef DEFINED_TYPEDEF_FOR_%<dt.Name>_
            #define DEFINED_TYPEDEF_FOR_%<dt.Name>_
          %endif
          %if (LibIsEnumTypeStoredAsInt(dtIdx))
            typedef enum {
 
            %% By default we only initialize the first enumeration.
            %% However, if we need to initialize any of the other enumerations
            %% we will initialize all of them (in accordance with MISRA Rule 9.3).
            %assign initAllEnums = TLC_FALSE
            %assign firstEnumValue = SLibGetEnumTypeValueFromIndex(dtIdx, 0)
            %foreach enumIdx = FcnGetEnumTypeNumEnums(dtIdx)
              %if (SLibGetEnumTypeValueFromIndex(dtIdx, enumIdx) != (firstEnumValue+enumIdx))
                %assign initAllEnums = TLC_TRUE
                %break
              %endif
            %endforeach
            %%
            %% Now generate the typedef
            %%
            %assign lastIdx = FcnGetEnumTypeNumEnums(dtIdx)-1
            %assign eol = ","
            %foreach enumIdx = FcnGetEnumTypeNumEnums(dtIdx)
              %assign enumString = SLibGetEnumTypeCodeGenStringFromIndex(dtIdx, enumIdx)
              %if (initAllEnums || (enumIdx == 0))
                %assign enumInitValue = SLibGetEnumTypeValueFromIndex(dtIdx, enumIdx)
                %assign valueString = " = %<SLibReplaceEnumLiteralValueWithTypeLimitId(dtIdx, enumInitValue)>"
              %else
                %assign valueString = ""
              %endif
              %%
              %% Add comment next to default value
              %if enumIdx == FcnGetEnumTypeIndexOfDefaultValue(dtIdx)
                %assign defaultComment = " /* Default value */"
              %else
                %assign defaultComment = ""
              %endif
              %%
              %% Don't add ',' after last enumeration
              %if (enumIdx == lastIdx)
                %assign eol = ""
              %endif
              %%
              %<enumString>%<valueString>%<eol>%<defaultComment>
            %endforeach
            } %<dt.Name>; %<descStr>
          %else
            %% Typedef enumerated data type to storage type
            %assign storageTypeId = LibGetEnumTypeStorageType(dtIdx)
            %assign storageTypeName = LibGetDataTypeNameFromId(storageTypeId)
            typedef %<storageTypeName> %<dt.Name>; %<descStr>
            %% Generate #define for each enumeration string
            %foreach enumIdx = FcnGetEnumTypeNumEnums(dtIdx)
              %assign enumString = SLibGetEnumTypeCodeGenStringFromIndex(dtIdx, enumIdx)
              %assign enumValue = SLibGetEnumTypeValueFromIndex(dtIdx, enumIdx)
              %assign enumValue = SLibReplaceEnumLiteralValueWithTypeLimitId(dtIdx, enumValue)
 
              %%
              %% Add comment next to default value
              %%
              %if enumIdx == FcnGetEnumTypeIndexOfDefaultValue(dtIdx)
                %assign defaultComment = " /* Default value */"
              %else
                %assign defaultComment = ""
              %endif
              %%
              %% Generate a #define for each enumeration string
              #define %<enumString> ((%<dt.Name>)%<enumValue>) %<defaultComment>
            %endforeach
          %endif
          %if needGuard
            #endif
          %endif
 
        %% Emit struct types
        %elseif LibIsStructDataType(dtIdx)
          %assign numElements = dt.NumElements
          %assign padded = 0
          %%keep a record of the generated types to avoid generating duplicated structural equivalent types
          %if LibIsDataTypeMultiWordFixpt(dtIdx)
            %% Suppress generation of fixed-point types
            %closefile tmpBuffer
            %continue
          %endif
 
          %% For exported types, the file guard suffices.
          %% For types going to model_types.h, put out a type guard.
          %if needGuard
            #ifndef DEFINED_TYPEDEF_FOR_%<dt.Name>_
            #define DEFINED_TYPEDEF_FOR_%<dt.Name>_
          %endif
          %<descStr>
          %% Align the whole structure if necessary
          %assign alignWholeStruct = !fieldAlign && structAlign
          %assign SAlign = ""
          %if ISFIELD(dt, "Alignment") && alignWholeStruct
            %assign SAlign = SLibGetAlignmentSyntax(::CompiledModel.Name, dt.Name, "", ...
              dt.Alignment, "DATA_ALIGNMENT_WHOLE_STRUCT")
          %endif
          %if SAlign != ""
            %if structDAFlag.position == "DATA_ALIGNMENT_PREDIRECTIVE"
              typedef %<SAlign> struct {
            %elseif structDAFlag.position == "DATA_ALIGNMENT_PRECEDING_STATEMENT"
              %<SAlign>
              typedef struct {
            %else
              typedef struct {
            %endif
          %else
            typedef struct {
          %endif
 
          %foreach eIdx = numElements
            %assign eName = LibDataTypeElementName(dtIdx, eIdx)
            %assign eDtId = LibDataTypeElementDataTypeId(dtIdx, eIdx)
            %assign eComment = LibDataTypeElementComment(dtIdx, eIdx)
            %assign eDtNm = LibDataTypeElementContainerName(dtIdx, eIdx)
            %assign arrayDim = LibDataTypeElementVectorDims(dtIdx, eIdx)
            %% Verify that an exported type doesn't depend on an Auto type
            %if dtIsShared && (LibIsStructDataType(eDtId) || LibIsEnumDataType(eDtId) || LibIsAliasDataType(eDtId))
              %if SLibDataTypeHasObject(eDtId) && !LibDataTypeIsShared(eDtId)
                %assign args = ["%<dt.Name>", "%<eDtNm>", "%<dt.Name>", "%<eDtNm>"]
                  %<SLibReportErrorWithIdAndArgs("RTW:tlc:ExportTypeDependsOnNonExported", args)>
              %endif
            %endif
 
            %% Deal with alignment.
            %% Must consider nested structure
            %assign align = ""
            %if fieldAlign && !LibIsStructDataType(eDtId) && ...
                ISFIELD(dt, "Alignment")
              %assign align = SLibGetAlignmentSyntax(::CompiledModel.Name, eName, eDtNm, ...
                                                     ::CompiledModel.DataTypes.DataType[dtIdx].Alignment, ...
                                                     "DATA_ALIGNMENT_STRUCT_FIELD")
            %endif
 
            %% Add comments for this bus element
            %if !ISEMPTY(eComment)
              %<eComment>
            %endif
 
            %<align> %<eDtNm> %<eName>%<arrayDim>;
            %assign padding = LibDataTypeElementPadding(dtIdx, eIdx)
            %if padding == 1
              %<LibGetDataTypeNameFromId(tSS_UINT8)> sl_padding%<padded>;
              %assign padded = padded + 1
            %elseif padding > 0
              %<LibGetDataTypeNameFromId(tSS_UINT8)> sl_padding%<padded>[%<padding>];
              %assign padded = padded + 1
            %endif
          %endforeach
 
          %% Align the whole structure if necessary
          %if SAlign != ""
            %if structDAFlag.position == "DATA_ALIGNMENT_POSTDIRECTIVE"
              } %<dt.Name> %<SAlign>;
            %elseif structDAFlag.position == "DATA_ALIGNMENT_FOLLOWING_STATEMENT"
              } %<dt.Name>;
              %<SAlign>
            %else
              } %<dt.Name>;
            %endif
          %else
            } %<dt.Name>;
          %endif
 
          %if LibIsDataTypeMultiWordFixpt(dtIdx)
          %% generate multiword complex type
          typedef struct {
            %<dt.Name> re;
            %<dt.Name> im;
          } c%<dt.Name>;
          %endif
          %if needGuard
            #endif
          %endif
 
        %endif %% Struct
      %endif %% if we're writing the type
 
      %% Close the buffer
      %closefile tmpBuffer
 
      %% Take care of the case of exporting the type to a separate file
      %% or to check for clashes
      %% Add this type to the array of records describing types being exported
      %% to _sharedutils.
      %% We're checking IsShared OR has an object here, because anonymous struct
      %% types are shared, but have to associated data type object.
      %if dtIsShared || dt.HasObject
        %assign dtChecksum = ::CompiledModel.DataTypes.DataType[dtIdx].Checksum
        %assign dtChecksumStr = ...
          "%,%,%,%"
 
        %if !dtIsUserProvided
          %assign dtDependencies = ::CompiledModel.DataTypes.DataType[dtIdx].Dependencies
          %assign numDtDepends = SIZE(dtDependencies, 1)
          %assign depVecStr = ""
          %assign depBuiltinVec = ""
          %assign depComplexVec = ""
          %assign depMultiwordVec = ""
          %foreach idxDep = numDtDepends
            %assign thisIdx = dtDependencies[idxDep]
            %assign isBuiltin = "0"
            %if LibIsFundamentalBuiltInDataType(thisIdx)
              %assign isBuiltin = "1"
            %endif
            %assign isComplex = "0"
            %assign isMultiword = "0"
            %if LibIsDataTypeMultiWordFixpt(thisIdx)
              %assign isMultiword = "1"
            %endif
            %if idxDep == 0
              %assign depVecStr = ::CompiledModel.DataTypes.DataType[thisIdx].Name
              %assign depBuiltinVec = isBuiltin
              %assign depComplexVec = isComplex
              %assign depMultiwordVec = isMultiword
            %else
              %assign depVecStr = depVecStr + "," + ::CompiledModel.DataTypes.DataType[thisIdx].Name
              %assign depBuiltinVec = depBuiltinVec + "," + isBuiltin
              %assign depComplexVec = depComplexVec + "," + isComplex
              %assign depMultiwordVec = depMultiwordVec + "," + isMultiword
            %endif
          %endforeach
        %else
          %assign definition = ""
          %assign depVecStr = ""
          %assign depComplexVec = "0"
          %assign depMultiwordVec = "0"
          %assign depBuiltinVec = "0"
        %endif
 
        %if dtIsShared
          %assign objInfoArr.NumInfo = objInfoArr.NumInfo + 1
          %addtorecord objInfoArr objInfo { name dt.Name; ...
          kind "type"; ...
          manglename dt.Name; ...
          file dtHeaderFile; ...
          checksum dtChecksumStr; ...
          definition "%<tmpBuffer>"; ...
          dependencies depVecStr; ...
          isComplex depComplexVec; ...
          isMultiword depMultiwordVec; ...
          builtin depBuiltinVec; ...
          typeUserProvided dtIsUserProvided; ...
          genComplexTypedef generateCmplxTypedef}
          %if !dtIsUserProvided
            %<SLibAddGeneratedFileToList(dtHeaderFile,"utility","header","")>
          %else
            %<SLibAddGeneratedFileToList(dtHeaderFile,"custom","header","")>
          %endif
        %else
          %assign objInfoArrNonShared.NumInfo = objInfoArrNonShared.NumInfo + 1
          %addtorecord objInfoArrNonShared objInfo { name dt.Name; ...
            kind "type"; ...
            manglename dt.Name; ...
            file " "; ...
            checksum dtChecksumStr; ...
            definition "%<tmpBuffer>"; ...
            dependencies depVecStr; ...
            isComplex depComplexVec; ...
            isMultiword depMultiwordVec; ...
            builtin depBuiltinVec; ...
            typeUserProvided dtIsUserProvided; ...
            genComplexTypedef generateCmplxTypedef}
        %endif
 
        %if !genToShared && (dtIsShared && !dtIsUserProvided) && !(::CompiledModel.SharedTypesInIR)
          %% Create the file as typename.h
          %assign fileName = dtHeaderFileBase
          %assign fileH = LibCreateSourceFileAtPath("Header", "Simulink", fileName, dtHeaderFileBase)
 
          %% Write out the header file dependencies, if any, to the RequiredIncludes section.
          %% SLibSetModelFileAttribute takes care of de-duping the RequiredIncludes section.
          %assign dependsOnHeaderFiles = LibDataTypeDependsOnHeaderFiles(dt, dtHeaderFile)
          %assign numDependsOnHeaderFiles = SIZE(dependsOnHeaderFiles, 1)
          %foreach idx = numDependsOnHeaderFiles
            %<SLibSetModelFileAttribute(fileH, "RequiredIncludes", dependsOnHeaderFiles[idx])>
          %endforeach
 
          %% Remove header files we are including here from the top-level includes
          %% (since those are now redundant). Do not remove from fullHeaderFiles.
          %assign headerFiles = LibRemoveDependsOnHeaderFiles(dt, headerFiles, dtHeaderFileQuoted)
 
          %% Write the tmpBuffer (containing the type definition) to the file
          %% This'll append to existing contents if any (i.e. if >1 type is being
          %% written to the same file, we'll concatenate the buffers)
          %% We also write "coder_types.h" to the RequiredIncludes section
          %if !WHITE_SPACE(tmpBuffer)
            %<SLibSetModelFileDeferredIncludeCoderTypes(fileH, TLC_TRUE)>
            %<SLibSetModelFileAttribute(fileH, "Typedefs", tmpBuffer)>
          %endif
          %% Put this file with the "utility" group
          %<SLibSetModelFileAttribute(fileH, "Group", "utility")>
          %% Set the "please indent me properly" flag,
          %<SLibSetModelFileIndent(fileH, TLC_TRUE)>
          %% Mark this as a shared type.
          %<SLibSetModelFileSharedType(fileH, TLC_TRUE)>
        %endif
      %endif
 
      %if !dtIsShared
        %% Figure out what file we'll be writing this typedef to (typically model_types.h)
        %assign typesFile = SLibGetFileRecForCode("mdl_data_typedef")
 
        %% This puts the contents of tmpBuffer into the typedefs section of the specified file (model_types.h)
        %% We use the function that also writes "coder_types.h" to the RequiredIncludes
        %% section, on the assumption that the typedefs we are writing to the file might depend on "coder_types.h".
        %if !WHITE_SPACE(tmpBuffer)
          %<SLibSetModelFileDeferredIncludeCoderTypes(typesFile, TLC_TRUE)>
          %<SLibSetModelFileAttribute(typesFile, "Typedefs", tmpBuffer)>
        %endif
   %endif
   %endforeach
 
    %% Check for clashes with shared types
    %if !(::CompiledModel.SharedTypesInIR)
      %if genToShared
        %% Check non-shared data have no conflict with existing shared data in slprj
        %assign sharedHdrInfo = FEVAL("rtwprivate", "add2FileMap", ::CompiledModel.Name, ::CompiledModel.RTWInfoMatFile.sharedSourcesDir, objInfoArrNonShared, 4, 1, "traperror")
        %if TYPE(sharedHdrInfo)!="Scope" || sharedHdrInfo.status != 1
          %assign errmsg = sharedHdrInfo.errorMessage
          %<SLibReportErrorWithIdAndArgs("RTW:tlc:ErrWhenGenSharedType", errmsg)>
        %endif
      %endif
 
      %% After the loop over types, call add2FileMap to add the exported-to-sharedutils types
      %% to the file map. (See matlab/toolbox/rtw/rtw/private/add2FileMap.m)
      %% Temporary - pass actual cgtInfo (info about .cgt templates) in the future
 
      %if objInfoArr.NumInfo > 0
        %if genToShared
          %assign sharedHdrInfo = FEVAL("rtwprivate", "add2FileMap", ::CompiledModel.Name, CompiledModel.RTWInfoMatFile.sharedSourcesDir, objInfoArr, 1, 1)
        %else
          %assign sharedHdrInfo = FEVAL("rtwprivate", "add2FileMap", ::CompiledModel.Name, "", objInfoArr, 2, 1)
        %endif
        %if TYPE(sharedHdrInfo)!="Scope" || sharedHdrInfo.status != 1
          %assign errmsg = FEVAL("lasterr")
          %<SLibReportErrorWithIdAndArgs("RTW:tlc:ErrWhenGenSharedType", errmsg)>
        %else
          %<SLibSynchronizeFileRepWithFileRecords()>
 
          %% For every header file that did not need to be regenerated, make sure the file
          %% is still registered as generated. This will allow for better error reporting
          %% when file names collide (see geck 705830)
          %foreach idx = sharedHdrInfo.numNotGeneratedFiles
            %assign thisFile = sharedHdrInfo.notGeneratedFileList[idx].Name
            %assign thisFileKind = sharedHdrInfo.notGeneratedFileList[idx].Kind
            %assign thisUserProvided = sharedHdrInfo.notGeneratedFileList[idx].UserProvidedType
            %if thisFileKind == "type" && !thisUserProvided
              %assign thisFileName = thisFile
              %assign thisMdlFile = SLibAddModelFile("SystemHeader", "TFL callback", thisFileName)
              %<SLibSetModelFileSharedType(thisMdlFile, TLC_TRUE)>
              %<SLibSetModelFileAttribute(thisMdlFile, "Filter", TLC_TRUE)>
            %endif
          %endforeach
        %endif
      %endif
    %endif
 
    %% Now collect the include directives we need to write, e.g. for exported or imported types
    %% Note we no longer explicitly add "rtwtypes.h" to this list, instead
    %% relying on the RequiredIncludes mechanism
    %openfile tmpBuffer
    %assign numHeaderFiles = SIZE(headerFiles, 1)
    %if numHeaderFiles > 0
      %foreach idx = numHeaderFiles
          #include %
      %endforeach
    %endif
    %closefile tmpBuffer
 
    %% Also remember the header file information. For this, we pass fullHeaderFiles.
    %assign numFullHeaderFiles = SIZE(fullHeaderFiles, 1)
    %addtorecord DataTypes numHeaderFiles numFullHeaderFiles
    %addtorecord DataTypes headerFiles fullHeaderFiles
 
    %% This writes the include directives to the model_type.h file.
    %% "data_typedef_incl" is a codeGroupName, as defined in the file packaging table.
    %<SLibCacheCodeToFile("data_typedef_incl", tmpBuffer)>
  %endwith
%endfunction %% SLibWriteDatatypeTypedefs
 
 
%%Function:SLibSfunRegisterAndSetDataType==================================
%%Abstract:
%%SettheDataTypethedatatypeforansfunction,input,output,orDWork.
%%Registerthedatatypeifnecessary,suchasforfixedpointdatatypes.
%%
%%Arguments:
%%categoryStrstring"input","output",or"dwork"
%%SimstrucLabelstringgeneratedcodeRValueforsimstruct
%%elementIndexLabelstringgeneratedcodeRValueforindexof
%%input,output,dwork
%%origDataTypeIndexintegerdatatypeindexwrittento.rtwfile
%%modeForUnknownStrstringHowtohandlecasewhendatatypeisunknown
%%"namedObject","none","warning","error"
%%TopTester:test/toolbox/simulink/blocks/lib_MathOperations/Gain/rtw/tGainBlk_Codegencheck_RapidAccel.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/codeGen/subsystemBuild/tIVSubsystemBuild_1.m
%%
%function SLibSfunRegisterAndSetDataType(...
  categoryStr, ...
  SimstrucLabel, ...
  elementIndexLabel, ...
  origDataTypeIndex, ...
  modeForUnknownStr) Output
  %%
  if (ssGetSimMode(%<SimstrucLabel>) != SS_SIMMODE_SIZES_CALL_ONLY) {
  %switch categoryStr
      %%
    %case "input"
      %%
      %assign dataTypeSetFuncStr = "ssSetInputPortDataType"
      %%
      %break
      %%
    %case "output"
      %%
      %assign dataTypeSetFuncStr = "ssSetOutputPortDataType"
      %%
      %break
      %%
    %case "dwork"
      %%
      %assign dataTypeSetFuncStr = "ssSetDWorkDataType"
      %%
      %break
      %%
    %default
      %%START_ASSERT
      %<LibReportFatalError("Unknown category, %<category>, for setting sfunction data type.")>
      %%END_ASSERT
  %endswitch
  %%
  %if LibIsFundamentalBuiltInDataType(origDataTypeIndex)
    %assign dtEnum = LibGetDataTypeEnumFromId(origDataTypeIndex)
    %<dataTypeSetFuncStr>(%<SimstrucLabel>, %<elementIndexLabel>, %<dtEnum>);
  %else
    %%
    %assign curDT = FixPt_GetDataTypeFromIndex(origDataTypeIndex)
    %%
    #if defined (MATLAB_MEX_FILE)
    %if LibIsHalfDataType(origDataTypeIndex)
      DTypeId halfID = ssRegisterDataTypeHalfPrecision(
      %<SimstrucLabel>,
      0/* 0 means do NOT obey data type override setting for this subsystem */);
      %<dataTypeSetFuncStr>(%<SimstrucLabel>, %<elementIndexLabel>, halfID );
    %elseif curDT.IsFixedPoint && !LibIsAliasDataType(origDataTypeIndex)
      %% NOTE:
      %% The source code for user written fixed-point C S-Functions must
      %% contain two extra #includes.
      %% First, at the beginning of the C file, just after the standard
      %% #include "simstruc.h"
      %% also put
      %% #include "fixedpoint.h"
      %% Second, at the end of the C file, just after the standard
      %% # include "simulink.c"
      %% also put
      %% # include "fixedpoint.c"
      %%
      {
        DTypeId dataTypeIdReg =
        %if FixPt_DataTypeIsFloat(curDT)
          ssRegisterDataTypeFxpScaledDouble(
        %else
          ssRegisterDataTypeFxpFSlopeFixExpBias(
        %endif
        %<SimstrucLabel>,
        %<curDT.IsSigned>,
        %<curDT.RequiredBits>,
        %<curDT.FracSlope>,
        %<curDT.FixedExp>,
        %<curDT.Bias>,
        0 /* false means do NOT obey data type override setting for this subsystem */ );
 
        %<dataTypeSetFuncStr>(%<SimstrucLabel>, %<elementIndexLabel>, dataTypeIdReg );
      }
    %else
      %assign dtEnum = LibGetDataTypeEnumFromId(origDataTypeIndex)
      %%
      %if dtEnum == "SS_POINTER" || dtEnum == "SS_INTEGER" || dtEnum == "SS_FCN_CALL"
        %<dataTypeSetFuncStr>(%<SimstrucLabel>, %<elementIndexLabel>, %<dtEnum>);
      %else
        %switch modeForUnknownStr
            %%
          %case "namedObject"
            %%
            {
              DTypeId dataTypeIdReg;
 
              ssRegisterTypeFromNamedObject(
                %<SimstrucLabel>,
                "%<LibGetDataTypeNameFromId(origDataTypeIndex)>",
                &dataTypeIdReg);
 
              if(dataTypeIdReg == INVALID_DTYPE_ID) return;
              %<dataTypeSetFuncStr>(%<SimstrucLabel>, %<elementIndexLabel>, dataTypeIdReg );
            }
            %%
            %break
            %%
          %case "none"
            %%
            %break
            %%
          %default
            %%
            %openfile dataTypeRegFailMsg
User-defined data type %<LibGetDataTypeNameFromId(origDataTypeIndex)> is required
for %<categoryStr> %<elementIndexLabel>, but the information needed to define
this data type in the generated S-Function is unknown.
            %if modeForUnknownStr == "warning"
The generated code that normally specifies the data type of this
%<categoryStr> is being omitted. If additional custom code does not register
this user-define data type and set the data type of this %<categoryStr>,
then the generated code will be incomplete.
            %endif
            %closefile dataTypeRegFailMsg
            %if SLibInBlockScope()
              %assign block = SLibGetCurrentBlock()
              %if modeForUnknownStr == "warning"
                %<LibBlockReportWarning(block,dataTypeRegFailMsg)>
              %else
                %<LibBlockReportFatalError(block,dataTypeRegFailMsg)>
              %endif
            %else
              %if modeForUnknownStr == "warning"
                %<LibReportWarning(dataTypeRegFailMsg)>
              %else
                %<LibReportFatalError(dataTypeRegFailMsg)>
              %endif
          %endif
        %endswitch
      %endif
    %endif
    #endif
  %endif
  }
  %return
%endfunction %% SLibSfunRegisterAndSetDataType
 
%%Function:SLibGetLargestMultiwordDataTypeNeeded=============================
%%Abstract:
%%Determinesthelargestmultiworddatatypelengthneededingeneratedcode.
%%TopTester:test/toolbox/simulink/variants/vssSigObj/tVSSSigObj.m
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/tValueVariants.m
%%TopTester:test/toolbox/simulink/variants/tVariantGecks2.m
%%
%function SLibGetLargestMultiwordDataTypeNeeded() void
  %with ::CompiledModel
    %assign largestMultiwordBits = 0
    %if SLibIsERTTarget() && (::CompiledModel.ModelReferenceTargetType != "SIM")
      %%
      %% ERT and not Model Reference sim - Check for multiword type
      %% definition parameter to determine whether or not to include
      %% multiword type definitions in rtwtypes.h.
      %%
      %if ConfigSet.MultiwordTypeDef == "System defined"
        %%
        %% ERT Multiword type definition is "System defined" - Figure out
        %% if multiword types are needed, and if so, use hardcoded value
        %% of 256. If not needed, do not include multiword type definitions
        %% in rtwtypes.h (by setting the maximum number of bits to 0).
        %%
        %assign needsMultiword = TLC_FALSE
        %assign prodBitPerLargestInt = ConfigSet.ProdBitPerLong
        %assign targetBitPerLargestInt = ConfigSet.TargetBitPerLong
 
        %if (ConfigSet.ProdLongLongMode == 1)
           %assign prodBitPerLargestInt = ConfigSet.ProdBitPerLongLong
        %endif
 
        %if (ConfigSet.TargetLongLongMode == 1)
           %assign targetBitPerLargestInt = ConfigSet.TargetBitPerLongLong
        %endif
 
        %if prodBitPerLargestInt > targetBitPerLargestInt
          %assign needsMultiword = TLC_TRUE
        %endif
 
        %if ConfigSet.ProdHWDeviceType == "ASIC/FPGA->ASIC/FPGA"
          %assign needsMultiword = TLC_TRUE
        %endif
 
        %foreach dtIdx = ::CompiledModel.DataTypes.NumDataTypes
          %assign dt = ::CompiledModel.DataTypes.DataType[dtIdx]
          %if dt.IsFixedPoint && dt.RequiredBits > targetBitPerLargestInt
            %assign needsMultiword = TLC_TRUE
            %break
          %endif
        %endforeach
 
        %if needsMultiword
          %assign largestMultiwordBits = 256
        %else
          %assign largestMultiwordBits = 0
        %endif
      %else
        %%
        %% ERT Multiword type definition is User defined - Use the multiword
        %% length specified by the user in the ConfigSet.
        %%
        %assign largestMultiwordBits = ConfigSet.MultiwordLength
      %endif
    %else
      %%
      %% Not ERT or ERT and Model Reference sim - Always include multiword
      %% type definitions in rtwtypes.h and use MultiwordLength parameter
      %% from ConfigSet for maximum number of bits.
      %%
      %assign largestMultiwordBits = ConfigSet.MultiwordLength
    %endif
 
    %return largestMultiwordBits
  %endwith
 
%endfunction %% SLibGetLargestMultiwordDataTypeNeeded
 
%%Function:DeclareFixedPointWordSizeUsage====================================
%%Abstract:
%%Determinesthelargestblock-declaredfixedpointwordsizeusage.Usedby
%%front-endswhichgenerateTLCcode.
%%
%function DeclareFixedPointWordSizeUsage(maxSizeInBits) void
  %if maxSizeInBits > ::CompiledModel.DeclaredFixedPointWordSizeUsage
    %assign ::CompiledModel.DeclaredFixedPointWordSizeUsage = maxSizeInBits
  %endif
%endfunction
 
%%Function:DeclareHalfPrecisionUsage====================================
%%Abstract:
%%Determinesifhalfprecisionheaderisrequired.Usedby
%%front-endswhichgenerateTLCcode.
%%Forexample:
%%halfheaderwillbegeneratedwhenneedHalfHeaderisTLC_TRUE
%%
%function DeclareHalfPrecisionUsage(needHalfHeader) void
  %assign ::CompiledModel.DeclaredHalfPrecisionUsage = needHalfHeader
%endfunction
 
%%Function:SLibDeclareHalfPrecisionUsage===============================
%%Abstract:
%%ReturnsTLC_TRUEifhalfdatatypeisregistered,else
%%returnsTLC_FALSE
%%
%function SLibDeclareHalfPrecisionUsage() void
  %return ::CompiledModel.DeclaredHalfPrecisionUsage
%endfunction
 
%%Function:SLibGetTypeForBitfield===========================================
%%Abstract:
%%Thisfunctionreturnstheappropriatedatatypeforabitfield,
%%consideringtheuser'spreferenceandwhetherthebitfieldwillfit
%%
%%Forexample,
%%
%%SLibGetTypeForBitfield(1)
%%==>returns"unsignedchar"iftheusersaidtouse8-bitcontainers
%%
%%SLibGetTypeForBitfield(1)
%%==>returns"unsignedint"iftheusersaidso,orletitdefault
%%
%%SLibGetTypeForBitfield(9)
%%==>returns"unsignedint"eveniftheusersaidtouse8-bits
%%
%%Argument:
%%BitFieldWidth=widthofthecurrentbitfield
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/tValueVariants.m
%%
%function SLibGetTypeForBitfield(BitFieldWidth) void
  %% This optimization only applies to the BooleansAsBitfields optimization
  %% so only do the substitution if the bitfield is one bit.
  %if ISFIELD(ConfigSet,"BitfieldContainerType") && ...
        BitFieldWidth == 1
    %return ConfigSet.BitfieldContainerType
  %else
    %return "uint_T"
  %endif
 
%endfunction %%SLibGetTypeForBitfield
 
%%Function:SLibDeclareDataAsPointer===========================================
%%Abstract:
%%ReturnsTLC_TRUEifthedtIDpassedinshouldbedeclared
%%asapointer.Currentlythismeansthattheitiseitherastruct
%%thatisnotamulti-worddatatype,ordatawithadeepcopymethod
%%(memcpyisnotdesired)
%function SLibDeclareDataAsPointer(dtID) void
  %return (LibIsStructDataType(dtID) && !LibIsDataTypeMultiWordFixpt(dtID)) || ...
    !ISEMPTY(SLibDataTypeDeepCopyFcnName(dtID))
%endfunction
 
%%Function:SLibConvert2DMatrix==========================================
%%Abstract:
%%Generatethecodeforconvertingacol(row)major2Dmatrixtoa
%%row(col)major2Dmatrix(backwardcompatibilityforoldLCTgenerated
%%S-Functions)
%function SLibConvert2DMatrix(col2Row, typeId, width, dims, cMatStr, slMatStr, kind, isCplx, level) Output
  %<SLibMarshalNDArray(col2Row, typeId, width, dims, cMatStr, slMatStr, kind, isCplx, level)>
%endfunction
 
%%Function:SLibMarshalNDArray===========================================
%%Abstract:
%%Generatethecodeforconvertingacol(row)majorNDarraytoa
%%row(col)majorNDarray:
%%-col2Row:TLC_TRUEforcoltorowmajorconvertion,TLC_FALSEotherwise
%%-typeId:datatyperecordID
%%-width:totalnumberofelementsinthearray
%%-dims:dimensionsas[1xN]vector
%%-cMatStr:baseaddressoftherow-majorNDCarray
%%-slMatStr:baseaddressofthecol-majorNDSLarray
%%-kind:1(simpleconversionwithoutrecursion)or2(convertstructure'sfields)
%%-isCplx:TLC_TRUEforcomplexdata,TLC_FALSEotherwise
%%-level:manglerfortheautomaticvariable'snames
%function SLibMarshalNDArray(col2Row, typeId, width, dims, cMatStr, slMatStr, kind, isCplx, level) Output
%assign typeName = isCplx ? LibGetDataTypeComplexNameFromId(typeId) : LibGetDataTypeNameFromId(typeId)
%%
%if kind==1
  %% Simple transposition of the ND array
  %<SLibGenerateNDArrayMarshaling(col2Row, cMatStr, slMatStr, dims, typeName, level)>
  %%
%elseif kind==2
  %% Complex (non trivial) transposition
  %assign numDims = SIZE(dims,1)
  %assign isScalar = ISEQUAL(width, 1)
  %assign colMatStr = slMatStr
  %assign rowMatStr = cMatStr
  %%
  %if isScalar
    %assign colMatStr = slMatStr
    %assign rowMatStr = cMatStr
    %if level==0
      %assign colMatStr = "(*" + colMatStr + ")"
      %assign rowMatStr = "(*" + rowMatStr + ")"
    %endif
    %<SLibMarshalNDArrayForBus(col2Row, typeId, rowMatStr, colMatStr, level)>
  %elseif numDims >= 2
{
    int_T __idx%<level> = 0;
  %assign subs = []
  %foreach dimIdx = numDims
    %assign loopVar = "__idx%<level>_%"
    int_T %<loopVar>;
    for (%<loopVar> = 0; %<loopVar> < %; ++%<loopVar>) {
    %assign subs = subs + loopVar
  %endforeach
  %<typeName>* __cMatPtr%<level> = &%<rowMatStr>[__idx%<level>++];
  %<typeName>* __slMatPtr%<level> = &%<colMatStr>[%<FcnGenSubscriptsToIndex(subs, dims, TLC_TRUE)>];
  %<SLibMarshalNDArrayForBus(col2Row, typeId, "(*__cMatPtr%<level>)", "(*__slMatPtr%<level>)", level+1)>
  %foreach dimIdx = numDims
    }
  %endforeach
}
  %else
    %assign fakeBlk = BLOCK { Name "" }
    %assign rollThresh = 0 %%RollThreshold
    %roll iIdx=[0:%], iLcv=rollThresh, fakeBlk, "Roller", ""
      %assign iLoc = (iLcv == "") ? iIdx : iLcv
      %<SLibMarshalNDArrayForBus(col2Row, typeId, "%<cMatStr>[%<iLoc>]", "%<slMatStr>[%<iLoc>]", level+1)>
    %endroll
  %endif
%else
  %% No marshaling required but level > 0 then need to memcpy the fields
  %if level!=0
    %assign widthStr = width > 1 ? "%<width>*" : ""
    %if col2Row==TLC_TRUE
(void) %<LibGenMemFcnCall("memcpy", "%<cMatStr>", "%<slMatStr>", "%<widthStr>sizeof(%<typeName>)")>;
    %else
(void) %<LibGenMemFcnCall("memcpy", "%<slMatStr>", "%<cMatStr>", "%<widthStr>sizeof(%<typeName>)")>;
    %endif
  %endif
  %%
%endif
%endfunction
 
%%Function:SLibMarshalNDArrayForBus=====================================
%%Abstract:
%%WalkthroughaBus/Structhierarchyforgeneratingthecodeforeachfield
%%thatconvertsacol(row)majorNDarraytoarow(col)majorNDarray:
%%-col2Row:TLC_TRUEforcoltorowmajorconvertion,TLC_FALSEotherwise
%%-typeId:datatyperecordID
%%-cMatStr:baseaddressoftherow-majorNDCarray
%%-slMatStr:baseaddressofthecol-majorNDSLarray
%%-level:manglerfortheautomaticvariable'snames
%function SLibMarshalNDArrayForBus(col2Row, typeId, cMatStr, slMatStr, level) Output
%%
%foreach idxE = LibDataTypeNumElements(typeId)
  %assign eName = LibDataTypeElementName(typeId, idxE)
  %assign eDTypeId = LibGetDataTypeIdAliasedThruToFromId(LibDataTypeElementDataTypeId(typeId, idxE))
  %assign eWidth = LibDataTypeElementWidth(typeId, idxE)
  %assign eDims = LibDataTypeElementDimensions(typeId, idxE)
  %assign eIsCplx = LibDataTypeElementIsComplex(typeId, idxE)
  %%
  %assign eCMatStr = cMatStr + "." + eName
  %assign eSLMatStr = slMatStr + "." + eName
  %%
  %assign matInfo = FcnGetNDArrayMarshalingInfo(eDTypeId, eDims)
  %if matInfo==0
    %% This element doesn't need special care then just memcpy it in the
    %% generated code but need to pass the address of the element
    %% to the marshaling function
    %assign optAddr = eWidth==1 ? "&" : ""
    %assign eCMatStr = "%<optAddr>%<eCMatStr>"
    %assign eSLMatStr = "%<optAddr>%<eSLMatStr>"
  %else
    %if (eWidth > 1) && (SIZE(eDims, 1) > 1)
      %% Need a cast since the sub array of structure is accessed with a linear index
      %assign eDTypeName = eIsCplx ? LibGetDataTypeComplexNameFromId(eDTypeId) : LibGetDataTypeNameFromId(eDTypeId)
      %assign eCMatStr = "((%<eDTypeName>*)" + eCMatStr + ")"
      %assign eSLMatStr = "((%<eDTypeName>*)" + eSLMatStr + ")"
    %endif
  %endif
  %<SLibMarshalNDArray(col2Row, eDTypeId, eWidth, eDims, eCMatStr, eSLMatStr, matInfo, eIsCplx, level+1)>
%endforeach
%endfunction
 
%%Function:SLibGenerateNDArrayMarshaling================================
%%Abstract:
%%Helperforgeneratinganinlinedconvertiontochangeacol(row)major
%%NDarraytoarow(col)majorNDarray:
%%-col2Row:TLC_TRUEforcoltorowmajorconvertion,TLC_FALSEotherwise
%%-cMatStr:baseaddressoftherow-majorNDCarray
%%-slMatStr:baseaddressofthecol-majorNDSLarray
%%-dims:dimensionsas[1xN]vector
%%-typeName:datatypename
%%-level:manglerfortheautomaticvariable'snames
%function SLibGenerateNDArrayMarshaling(col2Row, cMatStr, slMatStr, dims, typeName, level) Output
{
  %if level > 0
  %<typeName>* __colMat%<level> = (%<typeName>*)%<slMatStr>;
  %<typeName>* __rowMat%<level> = (%<typeName>*)%<cMatStr>;
  %assign slMatStr = "__colMat%<level>"
  %assign cMatStr = "__rowMat%<level>"
%endif
  int_T __idx%<level> = 0;
  %assign numDims = SIZE(dims,1)
  %assign subs = []
  %foreach dimIdx = numDims
    %assign loopVar = "__idx%<level>_%"
    int_T %<loopVar>;
    for (%<loopVar> = 0; %<loopVar> < %; ++%<loopVar>) {
    %assign subs = subs + loopVar
  %endforeach
  %assign cMatAddr = "&%<cMatStr>[__idx%<level>++]"
  %assign slMatAddr = "&%<slMatStr>[%<FcnGenSubscriptsToIndex(subs, dims, TLC_TRUE)>]"
    %if col2Row==TLC_TRUE
    (void)%<LibGenMemFcnCall("memcpy", "%<cMatAddr>", "%<slMatAddr>", "sizeof(%<typeName>)")>;
    %else
    (void)%<LibGenMemFcnCall("memcpy", "%<slMatAddr>", "%<cMatAddr>", "sizeof(%<typeName>)")>;
    %endif
  %foreach dimIdx = numDims
    }
  %endforeach
}
%endfunction
 
%%Function:FcnGenSubscriptsToIndex======================================
%%Abstract:
%%Convertsubscriptstolinearindexforcol/rowmajorarray
%%-subs:subscriptsas[1xN]stringvector
%%-dims:dimensionsas[1xN]vector
%%-isColMajor:TLC_TRUEforcolumnmajorindexing
%function FcnGenSubscriptsToIndex(subs, dims, isColMajor)
  %assign linIdx = ""
  %assign revDimIdx = SIZE(dims,1)-1
  %foreach dimIdx = SIZE(dims,1)
    %assign idx = isColMajor ? revDimIdx : dimIdx
    %assign offset = ""
    %if dimIdx > 0
      %if dimIdx > 1
        %assign linIdx = "(" + linIdx + ")"
      %endif
      %assign offset = linIdx + "*% + "
%endif
    %assign linIdx = offset + "%"
    %assign revDimIdx = revDimIdx - 1
  %endforeach
  %return linIdx
%endfunction
 
%%Function:FcnGetNDArrayMarshalingInfo==================================
%%Abstract:
%%Returnsinformationaboutthe(potential)needformarshalingwhen
%%convertingfrom/tocolmajorto/fromrowmajor.
%%-typeId:datatyperecordID
%%-dims:dimensionsas[1xN]vector
%%Theoutputisoneofthefollowingvalues:
%%0->nomarshalingrequired
%%1->needsimplemarshaling
%%2->needcomplexmarshaling(busforinstance)
%function FcnGetNDArrayMarshalingInfo(typeId, dims) void
%if LibIsStructDataType(typeId) && FcnBusNeedNDArrayMarshaling(typeId, TLC_FALSE)
    %% Structure with ND leafs of sub-structures
    %return 2
%elseif (SIZE(dims,1)>=2) && (FcnProdVectorElement(dims)>1)
    %% Simple ND conversion
  %return 1
%else
  %return 0
%endif
%endfunction
 
%%Function:FcnBusNeedNDArrayMarshaling==================================
%%Abstract:
%%ReturnsinformationabouttheneedformarshalingBuswhen
%%convertingfrom/tocolmajorto/fromrowmajor.
%function FcnBusNeedNDArrayMarshaling(typeId, status) void
%foreach idxE = LibDataTypeNumElements(typeId)
  %assign dims = LibDataTypeElementDimensions(typeId, idxE)
  %if (SIZE(dims,1)>=2) && (FcnProdVectorElement(dims)>1)
    %% TRUE ND array
    %return TLC_TRUE
  %else
    %if LibIsStructDataType(typeId)
      %% Recurse on sub structure
      %assign status = status || ...
              FcnBusNeedNDArrayMarshaling(LibDataTypeElementDataTypeId(typeId, idxE), status)
    %endif
  %endif
%endforeach
%return status
%endfunction
 
%%Function:FcnProdVectorElement=========================================
%%Abstract:
%%SimilartotheMATLABfunctionprodbutforvectoronly
%function FcnProdVectorElement(vec) void
  %assign val = 1
  %foreach idx = SIZE(vec,1)
    %assign val = val * vec[idx]
  %endforeach
  %return val
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibGetUnitExprFromId===============
%%Abstract:
%%ReturntheunitnamecorrespondingtoaunitID.
%%
%function LibGetUnitExprFromId(id) void
  %return ::CompiledModel.Units.Unit[id].UnitExpr
%endfunction
 
 
%%DocFunction{OtherUsefulFunctions}:LibGetASCIIEscapedUnitExprFromId========
%%Abstract:
%%ReturntheunitnamecorrespondingtoaunitID.
%%Notethattheseunitshavebeenescapedtosupportunicodestrings
%%ingeneratedcode.Theymustbeunescapedwhenpassedbacktoc++code.
%%
%function LibGetASCIIEscapedUnitExprFromId(id) void
  %return ::CompiledModel.Units.Unit[id].ASCIIEscapedUnitExpr
%endfunction
 
 
%%DocFunction{OtherUsefulFunctions}:LibGetRecordUnitId=================
%%Abstract:
%%ReturntheunitIDforagivendatarecord.
%%
%function LibGetRecordUnitId(rec) void
  %assign idx = rec.UnitIdx
  %return ::CompiledModel.Units.Unit[idx].Id
%endfunction
 
 
%%Function:LibGetRecordUnitExpr=========================================
%%Abstract:
%%Returnthedatatypenameforaspecifiedrecord.
%%
%%Arguments:
%%rec-TLCrecord
%%
%function LibGetRecordUnitExpr(rec)
  %return LibGetUnitExprFromId(LibGetRecordUnitId(rec))
%endfunction
 
 
%%Function:SLibGetRecordUnitExpr=========================================
%%Abstract:
%%Returnthedatatypenameforaspecifiedrecord.
%function SLibGetRecordUnitExpr(rec)
  %return LibGetRecordUnitExpr(rec)
%endfunction
 
%%Function:SLibGetRecordASCIIEscapedUnitExpr=============================
%%Abstract:
%%Returntheescapedunitexpressionforaspecifiedrecord.
%function SLibGetRecordASCIIEscapedUnitExpr(rec)
  %return LibGetASCIIEscapedUnitExprFromId(LibGetRecordUnitId(rec))
%endfunction
 
 
%%Function:SLibGetRecordIsUnitsEnabled==================================
%%Abstract:
%%Returnwhetherornotunitsisenabled.
%function SLibGetRecordIsUnitsEnabled()
  %return ::CompiledModel.Units.isUnitsEnabled
%endfunction
 
%%Function:SLibIsUnknownType===========================
%%Abstract:
%%ReturnstrueifandonlyifthegivenCGtypeindexcorresponds
%%toanunknowntype.Thisfunctionalsoreturnstrueifthegiven
%%typeisamatrixandthebasetypeisanunknowntype.
%function SLibIsUnknownType(aCGTypeIdx) void
  %return LibCGTypeIsMatrix(aCGTypeIdx) ? ...
    LibCGTypeIsUnknown(LibCGTypeScalarBaseType(aCGTypeIdx)) : ...
    LibCGTypeIsUnknown(aCGTypeIdx)
%endfunction
 
%%Function:LibIsRowMajor
%%Abstract:
%%ReturntruewhenthecurrentmodelusestheRowMajorarraylayout.
%%
%function LibIsRowMajor()
    %assign isRowMajor = %
    %return isRowMajor
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibGetRecordIsOrContainsStdContainer
%%Abstract:
%%Returnstrueifthegivendatarecordcorrespondstoastdcontainertypeor
%%astructthatcontainsastdcontainertype.
%function LibGetRecordIsOrContainsStdContainer(rec) void
  %if LibGetRecordIsStdContainer(rec)
    %return TLC_TRUE
  %else
    %assign cgTypeIdx = SLibGetRecordContainerCGTypeIdx(rec)
    %return LibCGTypeContainsStdContainer(cgTypeIdx)
  %endif
%endfunction
 
%%DocFunction{OtherUsefulFunctions}:LibGetRecordIsStdContainer
%%Abstract:
%%Returnstrueifthegivendatarecordcorrespondstoastdcontainertypeor
%%acontainertypethatisastdcontainertype.
%function LibGetRecordIsStdContainer(rec) void
  %return (ISFIELD(rec, "CGTypeIdx") && LibCGTypeIsStdContainer(rec.CGTypeIdx)) || ...
          (ISFIELD(rec, "ContainerCGTypeIdx") && LibCGTypeIsStdContainer(rec.ContainerCGTypeIdx))
%endfunction
 
%%Endoflibrarycode
%%
 
%endif %% _DTYPELIB_
 
%%[EOF]dtypelib.tlc