%if EXISTS("_REGLIB_") == 0
%assign _REGLIB_ = 1
%<LibAddToCompiledModel("SFunctionRegistration", 0)>
%function FcnDynamicLog() void
%return ::CompiledModel.HasVariants
%endfunction
%function FcnSuitableForMemset(valueToSet, dataTypeId, storageClass) void
%if storageClass == "Custom"
%return 0
%endif
%if LibIsDataTypeCGClassOrContainClass(dataTypeId)
%return 0
%endif
%if LibIsEnumDataType(dataTypeId)
%return 0
%endif
%if !ISEMPTY(SLibDataTypeConstructFcnName(dataTypeId))
%return 0
%endif
%assign storageDataType = ...
LibGetDataTypeStorageIdFromId(...
LibGetDataTypeIdAliasedThruToFromId(dataTypeId))
%switch storageDataType
%case tSS_DOUBLE
%case tSS_SINGLE
%if InitFltsAndDblsToZero || ...
!SLibValueIsAllZeroBitsCrudeCheck(dataTypeId, valueToSet)
%return 0
%else
%return 1
%endif
%break
%case tSS_UINT8
%case tSS_UINT16
%case tSS_UINT32
%case tSS_INT8
%case tSS_INT16
%case tSS_INT32
%case tSS_BOOLEAN
%break
%default
%if LibIsHalfDataType(LibGetDataTypeIdAliasedThruToFromId(dataTypeId))
%if InitFltsAndDblsToZero || ...
!SLibValueIsAllZeroBitsCrudeCheck(dataTypeId, valueToSet)
%return 0
%else
%return 1
%endif
%endif
%if SLibValueIsAllZeroBitsCrudeCheck(dataTypeId, valueToSet)
%return 1
%else
%return 0
%endif
%endswitch
%if SLibValueIsAllZeroBitsCrudeCheck(dataTypeId, valueToSet)
%return 1
%elseif ( TYPE(valueToSet) == "Number" ) || ( TYPE(valueToSet) == "Unsigned" )
%switch storageDataType
%case tSS_UINT8
%case tSS_INT8
%if IntegerSizes.CharNumBits < 8
%return 0
%endif
%break
%case tSS_UINT16
%case tSS_INT16
%if IntegerSizes.CharNumBits < 16
%return 0
%endif
%break
%case tSS_UINT32
%case tSS_INT32
%if IntegerSizes.CharNumBits < 32
%return 0
%endif
%break
%case tSS_BOOLEAN
%default
%return 0
%endswitch
%if valueToSet >= 0
%return 1
%else
%return 0
%endif
%endif
%return 0
%endfunction
%function FcnPreferMemsetToAssignment(width, dataTypeId) void
%if LibIsEnumDataType(dataTypeId)
%return 0
%elseif !ISEQUAL(width,1)
%return 1
%else
%assign storageDataType = ...
LibGetDataTypeStorageIdFromId(...
LibGetDataTypeIdAliasedThruToFromId(dataTypeId))
%switch storageDataType
%case tSS_DOUBLE
%case tSS_SINGLE
%case tSS_UINT8
%case tSS_UINT16
%case tSS_UINT32
%case tSS_INT8
%case tSS_INT16
%case tSS_INT32
%case tSS_BOOLEAN
%return 0
%default
%if LibIsHalfDataType(LibGetDataTypeIdAliasedThruToFromId(dataTypeId))
%return 0
%endif
%return 1
%endswitch
%endif
%endfunction
%function FcnMemsetToZeroInitSuffice(dataTypeId) void
%assign retValue = 0
%assign dataTypeThruId = LibGetDataTypeIdAliasedThruToFromId(dataTypeId)
%if SLibDefaultInitialValueIsAllZeroBits(dataTypeThruId) && ...
ISEMPTY(SLibDataTypeConstructFcnName(dataTypeThruId))
%if FcnSuitableForMemset(0, dataTypeThruId, "")
%assign retValue = 1
%endif
%endif
%return retValue
%endfunction
%function FcnCastValueForMemsetUse(dTypeId, valueToSet) void
%if SLibValueIsAllZeroBitsCrudeCheck(dTypeId, valueToSet)
%assign retValue = 0
%else
%assign retValue = valueToSet
%endif
%return retValue
%endfunction
%function FcnSkipDataInitialValueInReg(datarec) void
%assert !ISEMPTY(datarec.InitialValue)
%assert (datarec.StorageClass != "ImportedExtern" && ...
datarec.StorageClass != "ImportedExternPointer")
%assign retValue = TLC_FALSE
%if (datarec.StorageClass == "Custom")
%assign cscDefn = SLibGetCSCDefForData(datarec)
%assign dataInit = SLibGetDataInitForData(cscDefn, datarec)
%if (dataInit == "Static" || dataInit == "None")
%assign retValue = TLC_TRUE
%endif
%endif
%if LibIsDataTypeCGClassType(LibGetRecordDataTypeId(datarec))
%assign retValue = TLC_TRUE
%endif
%if (EXISTS("SigObjWithICMapsFullyToOutportsWithIC") && ...
datarec.SigObjWithICMapsFullyToOutportsWithIC == "yes")
%assign retValue = TLC_TRUE
%endif
%return retValue
%endfunction
%function SLibEmitForLoopCounterCode(loopCount, idx) void
%assert TYPE(loopCount) == "String" || TYPE(loopCount) == "Number"
%assign indexDecl = "%<LibCGTypeName(::CompiledModel.CGTypes.IndexType)>" + " " + idx + ";"
%assign forEntry = "for (%<idx> = 0; %<idx> < %<loopCount>; %<idx>++)"
%return ["%<indexDecl>", "%<forEntry>"]
%endfunction
%function SLibEmitLibCustomInitCode(name, initCount, isComplex) Output
%assert TYPE(initCount) == "String"
%assign twoParts = IDNUM(initCount)
%assign isSymbolic = !ISEMPTY(twoParts[0])
%if "%<initCount>" == "1"
%if isComplex
%<LibCustomData(name,"initialize","",tRealPart)>
%<LibCustomData(name,"initialize","",tImagPart)>
%else
%<LibCustomData(name,"initialize","","")>
%endif
%elseif isSymbolic || %<initCount> >= RollThreshold
%assign sigIndexer = SLibGet1DArrayIndexer(initCount, "i", "", 0)
%openfile customLoopBuffer
%if isComplex
%<LibCustomData(name,"initialize",sigIndexer,tRealPart)>
%<LibCustomData(name,"initialize",sigIndexer,tImagPart)>
%else
%<LibCustomData(name,"initialize",sigIndexer,"")>
%endif
%closefile customLoopBuffer
%if !WHITE_SPACE(customLoopBuffer)
%assign loopCode = SLibEmitForLoopCounterCode(initCount, "i")
{
%
% {
%<customLoopBuffer>/
}
}
%endif
%else
%foreach initIdx = %<initCount>
%assign sigIndexer = SLibGet1DArrayIndexer(%<initCount>, "%<initIdx>", "", 0)
%if isComplex
%<LibCustomData(name,"initialize",sigIndexer,tRealPart)>
%<LibCustomData(name,"initialize",sigIndexer,tImagPart)>
%else
%<LibCustomData(name,"initialize",sigIndexer,"")>
%endif
%endforeach
%endif
%endfunction
%function SLibShouldSkipInitForRecord(rec) void
%return LibIsDataTypeCGClassType(LibGetRecordDataTypeId(rec))
%endfunction
%function SLibShouldForbidMemsetToZeroForRecord(rec) void
%return LibIsDataTypeCGClassOrContainClass(LibGetRecordDataTypeId(rec))
%endfunction
%function SLibRemoveZeroInitForData(datarec, valueToInit) void
%assign retVal = TLC_TRUE
%if SLibShouldSkipInitForRecord(datarec)
%return TLC_TRUE
%endif
%if (datarec.RecordType == "ExternalInput") || ...
(datarec.RecordType == "ExternalOutput") || ...
( (datarec.RecordType == "BlockOutput") && ...
(datarec.StorageClass != "Auto") && ...
(datarec.DrivesRootOutport == "yes") )
%if ZeroExternalMemoryAtStartup
%assign retVal = TLC_FALSE
%endif
%else
%if ZeroInternalMemoryAtStartup
%assign retVal = TLC_FALSE
%endif
%endif
%if retVal
%assign dTypeId = SLibGetRecordDataTypeId(datarec)
%assign isZero = SLibValueIsAllZeroBitsCrudeCheck(dTypeId, valueToInit)
%assign retVal = isZero
%endif
%if ::GenerateInitCodeRemoved
%assign retVal = !retVal
%endif
%return retVal
%endfunction
%function SLibGenCodeForResetWithInit()
%assign rootSystem = System[NumSystems-1]
%assign currentTid = rootSystem.CurrentTID
%return TYPE(currentTid) == "Number" && currentTid >= 0 && ...
ISFIELD(SampleTime[currentTid],"EventSourceName") && ...
SampleTime[currentTid].EventSourceType == "ResetWithInitEvent"
%endfunction
%function SLibRemoveZeroInitForDataDefault(datarec) void
%assign retVal = TLC_TRUE
%if SLibShouldSkipInitForRecord(datarec)
%return TLC_TRUE
%endif
%if (datarec.RecordType == "ExternalInput") || ...
(datarec.RecordType == "ExternalOutput") || ...
( (datarec.RecordType == "BlockOutput") && ...
(datarec.StorageClass != "Auto") && ...
(datarec.DrivesRootOutport == "yes") )
%if ZeroExternalMemoryAtStartup
%assign retVal = TLC_FALSE
%endif
%else
%if ZeroInternalMemoryAtStartup || SLibGenCodeForResetWithInit()
%assign retVal = TLC_FALSE
%endif
%endif
%if retVal
%if (datarec.RecordType=="ExternalOutput")
%assign dTypeId = LibBlockInputSignalDataTypeId(0)
%else
%assign dTypeId = SLibGetRecordDataTypeId(datarec)
%endif
%assign retVal = SLibDataTypeRequiresZeroInit(dTypeId, TLC_FALSE)
%endif
%if ::GenerateInitCodeRemoved
%assign retVal = !retVal
%endif
%return retVal
%endfunction
%function SLibZeroMemory(recordType) void
%assign retVal = TLC_FALSE
%if (recordType=="RTM") && (SLibHasSelfWithStaticInit() || (::GenCPP == 1 && !SLibIsRTMZeroInitCppEnabled()))
%assign retVal = TLC_FALSE
%elseif (recordType=="ExternalInput") || ...
(recordType=="ExternalOutput")
%if ZeroExternalMemoryAtStartup
%assign retVal = TLC_TRUE
%endif
%else
%if ZeroInternalMemoryAtStartup || SLibGenCodeForResetWithInit()
%assign retVal = TLC_TRUE
%endif
%endif
%if ::GenerateInitCodeRemoved
%assign retVal = !retVal
%endif
%return retVal
%endfunction
%function LibDumpModelInitializeSizes() Output
%<RTMSet("NumContStates", NumContStates)>; /* Number of continuous states */
%if NumContStates > 0
%<RTMSet("NumPeriodicContStates", NumPeriodicContStates)>; /* Number of periodic continuous states */
%endif
%<RTMSet("NumY", NumModelOutputs)>; /* Number of model outputs */
%<RTMSet("NumU", NumModelInputs)>; /* Number of model inputs */
%if DirectFeedthrough == "yes"
%<RTMSet("DirectFeedThrough", 1)>; /* The model is direct feedthrough */
%else
%<RTMSet("DirectFeedThrough", 0)>; /* The model is not direct feedthrough */
%endif
%<RTMSet("NumSampleTimes", NumRuntimeExportedRates)>; /* Number of sample times */
%<RTMSet("NumBlocks", NumNonVirtBlocksInModel)>; /* Number of blocks */
%if NumBlockSignals > 0
%<RTMSet("NumBlockIO", BlockOutputs.NumGlobalBlockOutputs)>; ...
/* Number of block outputs */
%endif
%if !LibParametersStructIsEmpty()
%assign nPrms = ::CompiledModel.NumPrmStructElements
%<RTMSet("NumBlockParams", nPrms)>; /* Sum of parameter "widths" */
%endif
%endfunction
%function LibDumpModelInitializeSampleTimes() Output
%if CodeFormat == "S-Function" && AllSampleTimesInherited == "yes"
%<RTMSetIdxed("SampleTime", 0, "INHERITED_SAMPLE_TIME")>;
%<RTMSetIdxed("OffsetTime", 0, "0.0")>;
%else
/* task periods */
%foreach tidIdx = NumRuntimeExportedRates
%assign period = SampleTime[tidIdx].PeriodAndOffset[0]
%<RTMSetIdxed("SampleTime", tidIdx, period)>;
%endforeach
/* task offsets */
%foreach tidIdx = NumRuntimeExportedRates
%assign offset = SampleTime[tidIdx].PeriodAndOffset[1]
%<RTMSetIdxed("OffsetTime", tidIdx, offset)>;
%endforeach
%endif
%endfunction
%function SLibBooleanZCTest(zcDir, trigSignal, prevZC,castRequired) void
%assign cast = castRequired ? "(ZCEventType) " : ""
%switch zcDir
%case "RISING_ZERO_CROSSING"
%return "%<cast>(%<trigSignal> && (%<prevZC> != POS_ZCSIG))"
%case "FALLING_ZERO_CROSSING"
%return "%<cast>(!%<trigSignal> && (%<prevZC> != ZERO_ZCSIG))"
%case "ANY_ZERO_CROSSING"
%return "%<cast>((%<trigSignal> != (%<prevZC> == POS_ZCSIG)) &&/n(%<prevZC> != UNINITIALIZED_ZCSIG))"
%endswitch
%endfunction
%function SLibUnsignedZCTest(zcDir, trigSignal, prevZC, castRequired) void
%assign cast = castRequired ? "(ZCEventType) " : ""
%switch zcDir
%case "RISING_ZERO_CROSSING"
%return "%<cast>((%<trigSignal> > 0) && (%<prevZC> != POS_ZCSIG))"
%case "FALLING_ZERO_CROSSING"
%return "%<cast>((%<trigSignal> == 0) && (%<prevZC> != ZERO_ZCSIG ))"
%case "ANY_ZERO_CROSSING"
%return "%<cast>(((%<trigSignal> > 0) != (%<prevZC> == POS_ZCSIG)) &&/n(%<prevZC> != UNINITIALIZED_ZCSIG))"
%endswitch
%endfunction
%function SLibGetSystemConstructionCode(aSystem) void
%assign fcnType = "ModelConstructor"
%assign prevActiveFcn = FcnGetActiveFcnForDecl()
%assign ::BlockFcn = fcnType
%assign codeFragment = SLibFcnGenCodeFragment(aSystem, fcnType)
%assign retVal = ""
%if !WHITE_SPACE(codeFragment)
%openfile retVal
%assign localVars = ...
FcnDeclareAccessedLocalVariables(aSystem) + ...
LibGetSystemLocalVars(aSystem, fcnType, "") + ...
SLibGetFcnLocalVars(aSystem, fcnType, "")
%if !WHITE_SPACE(localVars)
%if !GenerateClassInterface
{
%endif
%<localVars>
%<codeFragment>
%if !GenerateClassInterface
}
%endif
%else
%<codeFragment>
%endif
%closefile retVal
%endif
%assign ::BlockFcn = prevActiveFcn
%return retVal
%endfunction
%function SLibGetPrevZCStateInitCode(aSystem) void
%return SLibDumpInitializationCodeForFcn(aSystem, "ModelPrevZCStateInit")
%endfunction
%function SLibDumpOpaqueTypeConstructCode(aSystem) void
%assign fcnType = "OpaqueTypeConstruct"
%assign codeFragment = SLibFcnGenCodeFragment(aSystem, fcnType)
%assign buffer = ""
%openfile buffer
%if !WHITE_SPACE(codeFragment)
%assign localVars = SLibGetFcnLocalVars(aSystem, fcnType, "")
%if !WHITE_SPACE(localVars)
%if !GenerateClassInterface
{
%endif
%<localVars>
%<codeFragment>
%if !GenerateClassInterface
}
%endif
%else
%<codeFragment>
%endif
%endif
%foreach dtIdx = ::CompiledModel.DataTypes.NumDataTypes
%if !ISEMPTY(SLibDataTypeConstructFcnName(dtIdx)) && ...
SLibGetDataTypeGroundReqInMemory(dtIdx)
%assign fcnName = SLibDataTypeConstructFcnName(dtIdx)
%assign grdName = SLibGetDtGroundName(dtIdx, TLC_FALSE, "")
%<fcnName>(&%<grdName>);
%endif
%endforeach
%closefile buffer
%return buffer
%endfunction
%function SLibDumpOpaqueTypeDestructCode(aSystem, aFcnType, needGround) void
%assign codeFragment = SLibFcnGenCodeFragment(aSystem, aFcnType)
%assign buffer = ""
%openfile buffer
%if !WHITE_SPACE(codeFragment)
%assign localVars = SLibGetFcnLocalVars(aSystem, aFcnType, "")
%if !WHITE_SPACE(localVars)
%if !GenerateClassInterface
{
%endif
%<localVars>
%<codeFragment>
%if !GenerateClassInterface
}
%endif
%else
%<codeFragment>
%endif
%endif
%if needGround
%foreach dtIdx = ::CompiledModel.DataTypes.NumDataTypes
%if !ISEMPTY(SLibDataTypeDestructFcnName(dtIdx)) && ...
SLibGetDataTypeGroundReqInMemory(dtIdx)
%assign fcnName = SLibDataTypeDestructFcnName(dtIdx)
%assign grdName = SLibGetDtGroundName(dtIdx, TLC_FALSE, "")
%<fcnName>(&%<grdName>);
%endif
%endforeach
%endif
%closefile buffer
%return buffer
%endfunction
%function SLibDumpExternalInputsInitializationCode(aSystem) void
%return SLibDumpInitializationCodeForFcn(aSystem, "ModelExternalInputInit")
%endfunction
%function SLibDumpExternalOutputsInitializationCode(aSystem) void
%return SLibDumpInitializationCodeForFcn(aSystem, "ModelExternalOutputInit")
%endfunction
%function SLibDumpInitializationCodeForFcn(aSystem, aFcnType) void
%assign codeFragment = SLibFcnGenCodeFragment(aSystem, aFcnType)
%assign retVal = ""
%if !WHITE_SPACE(codeFragment)
%openfile retVal
%assign localVars = ...
LibGetSystemLocalVars(aSystem, aFcnType, "") + ...
SLibGetFcnLocalVars(aSystem, aFcnType, "")
%if !WHITE_SPACE(localVars)
{
%<localVars>
%<codeFragment>
}
%else
%<codeFragment>
%endif
%closefile retVal
%endif
%return retVal
%endfunction
%function SLibInitPrevZCSignalStates() void
%assign baseSystem = ::CompiledModel.System[GetBaseSystemIdx()]
%return SLibGetPrevZCStateInitCode(baseSystem)
%endfunction
%function SLibDumpModelRegPrevZCStates() Output
%if SLibGetUseRTMcgType()
%return
%endif
%assign prevZCStatesInRTM = FcnGetPrevZCSigStateType()
/* previous zero-crossing states */
{
%if UsingMalloc
%<prevZCStatesInRTM> *zc = (%<prevZCStatesInRTM> *) malloc(sizeof(%<::tPrevZCStateType>));
%<RTMChkMemAndReturnIfErr("zc")>;
%else
%assign addr = MultiInstanceERTCode ? "" : "&"
%<prevZCStatesInRTM> *zc = (%<prevZCStatesInRTM> *) %<addr>%<LibGetPreviousZCStruct()>;
%<SLibAccessArgHelper(rootSystem.Interface.ZCEventArgDef,"",rootSystem.CurrentTID)>
%endif
%<RTMSet("PrevZCSigState", "zc")>;
}
%endfunction
%function SLibDumpModelInitPrevZCStates() Output
/* previous zero-crossing states */
{
%if UsingMalloc && ::CompiledModel.HasSimStructVars == 0 && !SLibIsERTCodeFormat()
{
%<::tPrevZCStateType> *%<LibGetPreviousZCStruct()> = /
(%<::tPrevZCStateType> *) %<RTMGet("PrevZCSigState")>;
%<SLibInitPrevZCSignalStates()>/
}
%else
%<SLibInitPrevZCSignalStates()>/
%endif
}
%endfunction
%function LibDumpModelInitializePrevZCStates(bEmitReg, bEmitInit) Output
%if bEmitReg
%<SLibDumpModelRegPrevZCStates()>
%endif
%if bEmitInit
%<SLibDumpModelInitPrevZCStates()>
%endif
%endfunction
%function FcnDisableStateLogging(dlo) void
%assign dlo.StateSaveName = ""
%assign dlo.FinalStateName = ""
%return
%endfunction
%function FcnIsStateLoggingEnabled(dlo) void
%return (dlo.StateSaveName != "" || dlo.FinalStateName != "")
%endfunction
%function InitLogDataTypeConvertStructure(dTypeId) void
%if LibIsBuiltInDataType(dTypeId)
%assign needConvert = 0
%assign dTypeEnum = LibGetDataTypeEnumFromId(dTypeId)
%assign dTypeStorageEnum = dTypeEnum
%assign bitsPerChunk = 0
%assign numOfChunk = 0
%assign isSigned = 0
%assign fSlope = 1.0
%assign fixExp = 0
%assign bias = 0.0
%else
%assign needConvert = 1
%assign curDT = FixPt_GetDataTypeFromIndex(dTypeId)
%assign dTypeEnum = LibGetDataTypeEnumFromId(tSS_DOUBLE)
%assign dTypeStorageEnum = LibGetDataTypeEnumFromId(curDT.StorageId)
%if !FixPt_DataTypeIsFloat(curDT)
%assign bitsPerChunk = LargestIntegerNumBits
%assign numOfChunk = FixPt_NumChunks(curDT.RequiredBits)
%assign isSigned = curDT.IsSigned
%else
%assign bitsPerChunk = 0
%assign numOfChunk = 0
%assign isSigned = 0
%endif
%assign fSlope = curDT.FracSlope
%assign fixExp = curDT.FixedExp
%assign bias = curDT.Bias
%endif
%assign retVectStr = ["%<needConvert>", "%<dTypeEnum>", "%<dTypeStorageEnum>", "%<bitsPerChunk>", "%<numOfChunk>", "%<isSigned>", "%<fSlope>", "%<fixExp>", "%<bias>" ]
%return retVectStr
%endfunction
%function FcnLogStateSetup(bEmitReg, bEmitInit, dlo) Output
%assign cr = ""
%assign qt = "/""
%assign comma = ""
%assign sigPtrsStr = ""
%assign widthStr = ""
%assign dimsStr = ""
%assign isVarDimsStr = ""
%assign numDimsStr = ""
%assign dTypeStr = ""
%assign cmplxStr = ""
%assign preprocessingFcnPtrsStr = ""
%assign labelStr = ""
%assign labelLenStr = ""
%assign blkNameStr = ""
%assign crossMdlStr = ""
%assign blkNameLenStr= ""
%assign stateNameStr = ""
%assign dataTypeConvertInitStr = ""
%assign numLoggedStates = 0
%assign cr = "/n"
%assign nSig = "rt_LoggedStateSignalInfo.numSignals"
%assign nSigpp = "rt_LoggedStateSignalInfo.numSignals++"
%assign numLoggedRecords = 0
%foreach i = ::CompiledModel.ContStates.NumContStates
%assign cs = ::CompiledModel.ContStates.ContState[i]
%if cs.DataLoggingOn
%assign numLoggedRecords = numLoggedRecords + cs.Partitions.NumPartitions
%endif
%endforeach
%foreach i = ::CompiledModel.DWorks.NumDWorks
%assign dwRec = ::CompiledModel.DWorks.DWork[i]
%if (dwRec.UsedAs == "DSTATE" && dwRec.DataLoggingOn)
%if SLibIsGlobalDataRecWithNoExternalLinkage(dwRec)
%continue
%endif
%assign numLoggedRecords = numLoggedRecords + 1
%endif
%endforeach
%assign loggedRecordIdx = 0
%with ::CompiledModel.ContStates
%assign dTypeId = tSS_DOUBLE
%assign cmpxSig = 0
%assign label = "CSTATE"
%assign dtConvertParams = InitLogDataTypeConvertStructure(dTypeId)
%foreach i = NumContStates
%if (loggedRecordIdx < (numLoggedRecords-1)) || FcnDynamicLog()
%assign comma = ","
%else
%assign comma = ""
%endif
%assign cs = ContState[i]
%if !cs.DataLoggingOn
%continue
%endif
%assign offset = 0
%foreach recIdx = cs.Partitions.NumPartitions
%assign sigAddr = "&" + SLibContinuousState(cs, "", "", offset,NumSystems-1, TLC_FALSE)
%assign width = cs.Partitions.Partition[recIdx].Width
%assign stateName = cs.Partitions.Partition[recIdx].Name
%if cs.Partitions.Partition[recIdx].PathAlias == ""
%assign blkName = SLibGrBlockPath(cs.GrSrc)
%else
%assign blkName = cs.Partitions.Partition[recIdx].PathAlias
%endif
%if UsingMalloc
%assign lhs_eq = "((void **) %<RTMLoggingGet("LogXSignalPtrs")>)[%<numLoggedStates>] = "
%else
%if FcnDynamicLog()
%assign lhs_eq = "rt_LoggedStateSignalPtrs[%<nSig>] = "
%else
%assign lhs_eq = "rt_LoggedStateSignalPtrs[%<numLoggedStates>] = "
%endif
%endif
%assign sigPtrsStr = sigPtrsStr + cr + lhs_eq + "(void*)" + sigAddr + ";/n"
%if FcnDynamicLog()
%assign sigPtrsStr = sigPtrsStr + nSigpp + ";/n"
%endif
%assign sigPtrsStr = sigPtrsStr + cr
%assign widthStr = widthStr + cr + "%<width>%<comma>" + cr + cr
%assign numDimsStr = numDimsStr + cr + "1%<comma>" + cr + cr
%assign dimsStr = dimsStr + cr + "%<width>%<comma>" + cr + cr
%assign isVarDimsStr = isVarDimsStr + cr + "0%<comma>" + cr + cr
%assign dTypeStr = dTypeStr + cr + "%%<comma>" + cr + cr
%assign cmplxStr = cmplxStr + cr + "%<cmpxSig>%<comma>" + cr + cr
%assign labelStr = labelStr + cr + qt + label + qt + "%<comma>" + cr + cr
%assign blkNameStr = blkNameStr + cr + qt + STRING(blkName) + qt + "%<comma>" + cr + cr
%assign stateNameStr = stateNameStr + cr + qt + stateName + qt + "%<comma>" + cr + cr
%assign crossMdlStr = crossMdlStr + cr + "0%<comma>" + cr + cr
%assign preprocessingFcnPtrsStr = preprocessingFcnPtrsStr + cr + "%<SLibGetNullDefinitionFromTfl()>%<comma>" + cr + cr
%assign dataTypeConvertInitStr = dataTypeConvertInitStr + cr + ...
"{ %, %, %," + ...
" %, %, %," + ...
" %, %, %}%<comma>" + cr + cr
%assign numLoggedStates = numLoggedStates+1
%assign loggedRecordIdx = loggedRecordIdx + 1
%assign offset = offset + cs.Partitions.Partition[recIdx].Width
%endforeach
%endforeach
%endwith
%with ::CompiledModel.DWorks
%foreach i = NumDWorks
%if (DWork[i].UsedAs == "DSTATE" && DWork[i].DataLoggingOn)
%if SLibIsGlobalDataRecWithNoExternalLinkage(DWork[i])
%continue
%endif
%if (loggedRecordIdx < (numLoggedRecords-1)) || FcnDynamicLog()
%assign comma = ","
%else
%assign comma = ""
%endif
%assign label = "DSTATE"
%if DWork[i].Name != ""
%assign label = DWork[i].Name
%endif
%assign ds = DWork[i]
%assign vcRecord = SLibGetDataInlineVariantNetConditions(ds)
%assign ifCond = vcRecord.ifCond
%assign ifEndCond = vcRecord.endIfCond
%assign sigAddr = SLibGetGlobalDWorkAddr(i,TLC_FALSE)
%assign width = LibGetRecordSymbolicWidth(ds)
%assign stateName = ds.LogStateName
%assign dTypeId = LibGetDataTypeIdAliasedThruToFromId(...
LibGetRecordDataTypeId(ds))
%assign cmpxSig = SLibDWorkIsComplex(ds)
%if (!LibIsDataTypeLogSupported(dTypeId, TLC_FALSE))
%if FcnIsStateLoggingEnabled(dlo)
%assign warnTxt = "MAT-File logging is not supported for " ...
"states with data type '%<LibGetDataTypeNameFromId(dTypeId)>'."
%<LibReportWarning(warnTxt)>
%endif
%continue
%endif
%assign dtConvertParams = InitLogDataTypeConvertStructure(dTypeId)
%assign blkName = ...
ISFIELD(ds, "GrSrc") ? SLibGrBlockPath(ds.GrSrc) : "synthesized block"
%if UsingMalloc
%assign lhs_eq = "((void **) %<RTMLoggingGet("LogXSignalPtrs")>)[%<numLoggedStates>] = "
%else
%if FcnDynamicLog()
%assign lhs_eq = "rt_LoggedStateSignalPtrs[%<nSig>] = "
%else
%assign lhs_eq = "rt_LoggedStateSignalPtrs[%<numLoggedStates>] = "
%endif
%endif
%assign sigPtrsStr = sigPtrsStr + ifCond + cr + lhs_eq + "(void*)" + sigAddr + ";/n"
%if FcnDynamicLog()
%assign sigPtrsStr = sigPtrsStr + nSigpp + ";/n"
%endif
%assign sigPtrsStr = sigPtrsStr + ifEndCond + cr
%assign widthStr = widthStr + ifCond + cr + "%<width>%<comma>" + cr + ifEndCond + cr
%assign isVarDimsStr = isVarDimsStr + ifCond + cr + "0%<comma>" + cr + ifEndCond + cr
%assign numDimsStr = numDimsStr + ifCond + cr + "1%<comma>" + cr + ifEndCond + cr
%assign dimsStr = dimsStr + ifCond + cr + "%<width>%<comma>" + cr + ifEndCond + cr
%assign dTypeStr = dTypeStr + ifCond + cr + "%%<comma>" + cr + ifEndCond + cr
%assign cmplxStr = cmplxStr + ifCond + cr + "%<cmpxSig>%<comma>" + cr + ifEndCond + cr
%assign labelStr = labelStr + ifCond + cr + qt + label + qt + "%<comma>" + cr + ifEndCond + cr
%assign blkNameStr = blkNameStr + ifCond + cr + qt + STRING(blkName) + qt + "%<comma>" + cr + ifEndCond + cr
%assign stateNameStr = stateNameStr + ifCond + cr + qt + STRING(stateName) + qt + "%<comma>" + cr + ifEndCond + cr
%assign crossMdlStr = crossMdlStr + ifCond + cr + "0%<comma>" + cr + ifEndCond + cr
%assign preprocessingFcnPtrsStr = preprocessingFcnPtrsStr + ifCond + cr + "%<LibGetRecordPreprocessingFcnPtr(DWork[i])>%<comma>" + cr + ifEndCond + cr
%assign dataTypeConvertInitStr = dataTypeConvertInitStr + ifCond + cr + ...
"{ %, %, %," + ...
" %, %, %," + ...
" %, %, %}%<comma>" + cr + ifEndCond + cr
%assign numLoggedStates = numLoggedStates+1
%assign loggedRecordIdx = loggedRecordIdx + 1
%endif
%endforeach
%if FcnDynamicLog()
%assign widthStr = widthStr + "0" + cr
%assign numDimsStr = numDimsStr + "0" + cr
%assign dimsStr = dimsStr + "0" + cr
%assign isVarDimsStr = isVarDimsStr + "0" + cr
%assign dTypeStr = dTypeStr + "SS_DOUBLE" + cr
%assign cmplxStr = cmplxStr + "0" + cr
%assign labelStr = labelStr + qt + qt + cr
%assign blkNameStr = blkNameStr + qt + qt + cr
%assign stateNameStr = stateNameStr + qt + qt + cr
%assign crossMdlStr = crossMdlStr + "0" + cr
%assign preprocessingFcnPtrsStr = preprocessingFcnPtrsStr + "%<SLibGetNullDefinitionFromTfl()>" + cr + cr
%assign dataTypeConvertInitStr = dataTypeConvertInitStr + ...
"{ 0, SS_DOUBLE, SS_DOUBLE, 0, 0, 0, 0, 0, 0 }" + cr
%endif
%endwith
%if (numLoggedStates == 0)
%<FcnDisableStateLogging(dlo)>
%return
%endif
{
%if bEmitInit
%assign typeQ = "static "
%<typeQ> int_T rt_LoggedStateWidths[] =/
{
%<widthStr>
};
%<typeQ> int_T rt_LoggedStateNumDimensions[] =/
{
%<numDimsStr>
};
%<typeQ> int_T rt_LoggedStateDimensions[] =/
{
%<dimsStr>
};
%<typeQ> boolean_T rt_LoggedStateIsVarDims[] =/
{
%<isVarDimsStr>
};
%<typeQ> BuiltInDTypeId rt_LoggedStateDataTypeIds[] =/
{
%<dTypeStr>
};
%<typeQ> int_T rt_LoggedStateComplexSignals[] =/
{
%<cmplxStr>
};
%<typeQ> RTWPreprocessingFcnPtr rt_LoggingStatePreprocessingFcnPtrs[] =/
{
%<preprocessingFcnPtrsStr>
};
%<typeQ> const char_T *rt_LoggedStateLabels[] = {
%<labelStr>};
%<typeQ> const char_T *rt_LoggedStateBlockNames[] = {
%<blkNameStr>};
%<typeQ> const char_T *rt_LoggedStateNames[] = {
%<stateNameStr>};
%<typeQ> boolean_T rt_LoggedStateCrossMdlRef[] =/
{
%<crossMdlStr>
};
%<typeQ> RTWLogDataTypeConvert rt_RTWLogDataTypeConvert[] =/
{
%<dataTypeConvertInitStr>
};
%<typeQ> RTWLogSignalInfo rt_LoggedStateSignalInfo =/
{
%if FcnDynamicLog()
0,
%else
%<numLoggedStates>,
%endif
rt_LoggedStateWidths,
rt_LoggedStateNumDimensions,
rt_LoggedStateDimensions,
rt_LoggedStateIsVarDims,
%<SLibGetNullDefinitionFromTfl()>,
%<SLibGetNullDefinitionFromTfl()>,
rt_LoggedStateDataTypeIds,
rt_LoggedStateComplexSignals,
%<SLibGetNullDefinitionFromTfl()>,
rt_LoggingStatePreprocessingFcnPtrs,
{rt_LoggedStateLabels},
%<SLibGetNullDefinitionFromTfl()>,
%<SLibGetNullDefinitionFromTfl()>,
%<SLibGetNullDefinitionFromTfl()>,
{rt_LoggedStateBlockNames},
{rt_LoggedStateNames},
rt_LoggedStateCrossMdlRef,
rt_RTWLogDataTypeConvert
};
%endif
%if bEmitReg
%if UsingMalloc
void **rt_LoggedStateSignalPtrs = ...
(void **)malloc(sizeof(void *) * %<numLoggedStates>);
%else
static void * rt_LoggedStateSignalPtrs[%<numLoggedStates>];
%endif
%endif
%if bEmitReg
%if UsingMalloc
%<RTMChkMemAndReturnIfErr("rt_LoggedStateSignalPtrs")>;
%endif
%<RTMLoggingSet("LogXSignalPtrs", ...
"(LogSignalPtrsType) rt_LoggedStateSignalPtrs")>
%endif
%if bEmitInit
%<RTMLoggingSet("LogXSignalInfo", "&rt_LoggedStateSignalInfo")>
%<sigPtrsStr>/
%endif
}
%endfunction
%function FcnDisableOutputLogging(dlo) void
%assign dlo.OutputSaveName = ""
%return
%endfunction
%function FcnIsOutputLoggingEnabled(dlo) void
%return (dlo.OutputSaveName != "")
%endfunction
%function LibGetRecordPreprocessingFcnPtr(record) void
%assign returnString = "%<SLibGetNullDefinitionFromTfl()>"
%if !ISEMPTY(record) && ISFIELD(record, "PreprocessingFcnPtr") ...
&& record.PreprocessingFcnPtr != ""
%assign returnString = "&" + record.PreprocessingFcnPtr
%endif
%return returnString
%endfunction
%function FcnExtOutLoggable(extOut) void
%assign sysIdx = extOut.Block[0]
%assign blkIdx = extOut.Block[1]
%assign outportBlock = System[sysIdx].Block[blkIdx]
%with outportBlock
%assign dTypeId = LibGetDataTypeIdAliasedThruToFromId(...
LibBlockInputSignalDataTypeId(0))
%endwith
%return LibIsDataTypeLogSupported(dTypeId, TLC_FALSE) && ...
!(ISFIELD(extOut, "UseAccessFunctions") && extOut.UseAccessFunctions == 1) && ...
!(ISFIELD(extOut, "IsMessage") && extOut.IsMessage == 1)
%endfunction
%function FcnLogOutputSetup(bEmitReg, bEmitInit, dlo) Output
%assign typeQ = "static "
%assign nOutportBlks = ExternalOutputs.NumExternalOutputs
%assign comma = ","
%assign sigPtrsStr = ""
%assign nOutputsLogged = 0
%assign allVariantCondition = ""
%assign isAnyOutportUnconditional = TLC_FALSE
%assign nLoggableOutports = 0
%if (IsConfiguredForConditionalMATFileCode())
%assign indexInit = "int_T index = 0;"
%assign indexUpdate = "index = index + 1;"
%assign replaceIdx = TLC_TRUE
%else
%assign indexInit = ""
%assign indexUpdate = ""
%assign replaceIdx = TLC_FALSE
%endif
%foreach idx = nOutportBlks
%assign extOut = ExternalOutputs.ExternalOutput[idx]
%if FcnExtOutLoggable(extOut)
%assign nLoggableOutports = nLoggableOutports + 1
%endif
%endforeach
%if (nLoggableOutports == 1 && nOutportBlks == 1)
%assign comma = ""
%assign indexUpdate = ""
%endif
%if ISFIELD(VariantConditions, "CGVCEList")
%assign cgvceList = VariantConditions.CGVCEList
%else
%assign cgvceList = ""
%endif
%foreach idx = nOutportBlks
%assign extOut = ExternalOutputs.ExternalOutput[idx]
%assign sysIdx = extOut.Block[0]
%assign blkIdx = extOut.Block[1]
%assign outportBlock = System[sysIdx].Block[blkIdx]
%if ISFIELD(extOut, "LocalCGVCEIdx") && (extOut.LocalCGVCEIdx != -1)
%assign variantCondition = cgvceList[extOut.LocalCGVCEIdx]
%else
%assign variantCondition = ""
%endif
%assign ifCond = ""
%assign ifEndCond = ""
%if ISFIELD(outportBlock, "Inactive")
%continue
%endif
%with outportBlock
%assign dTypeId = LibGetDataTypeIdAliasedThruToFromId(...
LibBlockInputSignalDataTypeId(0))
%if !FcnExtOutLoggable(extOut)
%assign sigAddr = SLibGetNullDefinitionFromTfl()
%assign dTypeName = LibGetDataTypeNameFromId(dTypeId)
%if (ISFIELD(extOut, "UseAccessFunctions") && extOut.UseAccessFunctions == 1)
%assign warnTxt = "Unable to log signal driving this block " ...
"because MAT-File logging is not supported for " ...
"Access Functions."
%elseif (ISFIELD(extOut, "IsMessage") && extOut.IsMessage == 1)
%assign warnTxt = "Unable to log signal driving this block " ...
"because MAT-File logging is not supported for external message outputs."
%else
%assign warnTxt = "Unable to log signal driving this block " ...
"because MAT-File logging is not supported for " ...
"data type '%<dTypeName>'."
%endif
%if !isRAccel
%<LibBlockReportWarning(outportBlock, warnTxt)>
%else
%if !(::CompiledModel.DataLoggingOpts.CompiledLoggingSaveFormat == "Dataset")
%assign blockName = LibGetFormattedBlockPath(outportBlock)
%assign warnArgs = ["%<blockName>", "%<dTypeName>"]
%<SLibReportWarningWithIdAndArgs("RTW:tlc:RapidAcceleratorUnsupportedLoggingFormat", ...
warnArgs)>
%endif
%endif
%else
%assign width = LibGetRecordSymbolicWidth(extOut)
%if extOut.StorageClass == "Auto" && !SLibIsLegacyStorageClassForDataRecord(extOut)
%assign sigLoc = LibBlockDstSignalLocation("outportblk","","",0)
%assign sigAddr = "&%<sigLoc>"
%assign groupIdx = SLibGetCoderGroupIdForDataRecord(extOut)
%if (SLibIsCoderGroupInVolatileMemory(groupIdx))
%assign dtName = LibGetRecordIsComplex(extOut) ? LibGetDataTypeComplexNameFromId(dTypeId) : LibGetDataTypeNameFromId(dTypeId)
%assign cast = "(%<dtName> *)"
%assign sigAddr = cast + sigAddr
%endif
%elseif (extOut.StorageClass == "Custom" || SLibIsLegacyStorageClassForDataRecord(extOut))
%if !LibCustomDataIsAddressable(extOut)
%assign sigAddr = SLibGetNullDefinitionFromTfl()
%assign warnTxt = "Unable to log signal driving this block" + ...
" because the custom storage class is not addressable."
%<LibBlockReportWarning(outportBlock, warnTxt)>
%else
%assign sigAddr = SLibCG_EO_CSCAddr(idx, width, "", -1, "", 0)
%endif
%elseif extOut.StorageClass == "ImportedExternPointer"
%assign sigAddr = SLibGetNullDefinitionFromTfl()
%assign warnTxt = "Unable to log signal driving this block" + ...
" because of unsupported storage class ImportedExternPointer."
%<LibBlockReportWarning(outportBlock, warnTxt)>
%else
%assign varName = LibGetRecordIdentifier(extOut)
%if width != "1"
%assign varName = varName+"[0]"
%endif
%assign sigAddr = "&%<varName>"
%endif
%assign nOutputsLogged = nOutputsLogged+1
%if !ISEMPTY(variantCondition)
%assign ifCond = SLibIfVariantConditionForm(variantCondition)
%assign ifEndCond = SLibEndIfVariantConditionForm(variantCondition)
%else
%assign isAnyOutportUnconditional = TLC_TRUE
%endif
%endif
%endwith
%if UsingMalloc || MultiInstanceERTCode
%if UsingMalloc
%assign lhs_eq = "((void **) %<RTMLoggingGet("LogYSignalPtrs")>)[%<idx>] = "
%if replaceIdx
%assign lhs_eq = "((void **) %<RTMLoggingGet("LogYSignalPtrs")>)[index] = "
%endif
%else
%assign lhs_eq = "rt_LoggedOutputSignalPtrs[%<idx>] = "
%if replaceIdx
%assign lhs_eq = "rt_LoggedOutputSignalPtrs[index] = "
%endif
%endif
%assign sigPtrsStr = sigPtrsStr + "/n" + indexInit + ifCond + "/n" + lhs_eq + sigAddr + ";/n" + indexUpdate + ifEndCond
%assign indexInit = ""
%else
%if(sigAddr == SLibGetNullDefinitionFromTfl() && IsConfiguredForConditionalMATFileCode())
%continue
%else
%assign sigPtrsStr = sigPtrsStr + "/n" + ifCond + "/n" + sigAddr + comma + "/n" + ifEndCond
%endif
%endif
%if (nOutportBlks == nOutputsLogged + 1)
%assign comma = ""
%assign indexUpdate = ""
%endif
%endforeach
%if (nLoggableOutports == 0)
%<FcnDisableOutputLogging(dlo)>
%return
%endif
%if !ISEMPTY(cgvceList) && ISFIELD(ExternalOutputs,"SystemCGVCEIdx") && (ExternalOutputs.SystemCGVCEIdx != -1)
%assign allVariantCondition = cgvceList[ExternalOutputs.SystemCGVCEIdx]
%endif
%assign allIfCond = SLibIfVariantConditionForm(allVariantCondition)
%assign allIfEndCond = SLibEndIfVariantConditionForm(allVariantCondition)
%if (!isAnyOutportUnconditional)
%<allIfCond>
%endif
{
%if UsingMalloc
%if bEmitReg
void **rt_LoggedOutputSignalPtrs = (void **)malloc(%<nOutportBlks>*sizeof(void*));
%<RTMChkMemAndReturnIfErr("rt_LoggedOutputSignalPtrs")>;
%endif
%if bEmitInit
%<sigPtrsStr>/
%endif
%elseif MultiInstanceERTCode
%if bEmitReg
static void * rt_LoggedOutputSignalPtrs[%<nOutportBlks>];
%endif
%if bEmitInit
%<sigPtrsStr>
%endif
%else
%if bEmitReg && bEmitInit
static void * rt_LoggedOutputSignalPtrs[] = /
{/
%<sigPtrsStr>
};
%else
%assert 0
%endif
%endif
%if !ISEMPTY(sigPtrsStr) && !WHITE_SPACE(sigPtrsStr)
%assign groupId = SLibGetCoderGroupIdForDataRecord(extOut)
%if (groupId >= 0)
%assign group = ::CompiledModel.CoderDataGroup[groupId]
%assign groupArgDefFieldName = "CoderDataGroup" + group.Name + "ArgDef"
%assign groupArgDef = rootSystem.Interface.%<groupArgDefFieldName>
%<SLibAccessArgHelper(groupArgDef, "", rootSystem.CurrentTID)>
%endif
%endif
%if bEmitReg
%<RTMLoggingSet("LogYSignalPtrs", ...
"((LogSignalPtrsType)rt_LoggedOutputSignalPtrs)")>
%endif
}
%assign cr = ""
%assign qt = "/""
%assign comma = ""
%assign newcomma = ","
%assign widthStr = ""
%assign numDimsStr = ""
%assign dimsStr = ""
%assign isVarDimsStr = ""
%assign currSigDimsStr = ""
%assign currSigDimsInitStr = ""
%assign currSigDimsSetStr = ""
%assign currSigDimsSizeStr = ""
%assign dTypeStr = ""
%assign cmplxStr = ""
%assign preprocessingFcnPtrsStr = ""
%assign labelStr = ""
%assign labelLenStr = ""
%assign blkNameStr = ""
%assign blkNameLenStr= ""
%assign logSigInfoInitStr = ""
%assign logSigInfoVarsStr = ""
%assign dataTypeConvertInitStr = ""
%assign widthVar = "rt_LoggedOutputWidths"
%assign numDimsVar = "rt_LoggedOutputNumDimensions"
%assign dimsVar = "rt_LoggedOutputDimensions"
%assign isVarDimsVar = "rt_LoggedOutputIsVarDims"
%assign currSigDimsVar = "rt_LoggedCurrentSignalDimensions"
%assign currSigDimsSizeVar = "rt_LoggedCurrentSignalDimensionsSize"
%assign dTypeVar = "rt_LoggedOutputDataTypeIds"
%assign cmplxVar = "rt_LoggedOutputComplexSignals"
%assign preprocessingFcnPtrsVar = "rt_LoggingPreprocessingFcnPtrs"
%assign labelVar = "rt_LoggedOutputLabels"
%assign labelLenVar = "rt_LoggedOutputLabelLengths"
%assign blkNameVar = "rt_LoggedOutputBlockNames"
%assign blkNameLenVar = "rt_LoggedOutputBlockNameLengths"
%assign rt_RTWLogDataTypeConvertVar = "rt_RTWLogDataTypeConvert"
%assign nSignalInfos = 0
%if bEmitInit
{
%endif
%assign numDimsRunningCount = 0
%assign numOutportsLoggedIdx = 0
%assign numCurrSigDims = 0
%assign currSigDimsSize = ConfigSet.TargetBitPerInt/8
%foreach idx = nOutportBlks
%assign extOut = ExternalOutputs.ExternalOutput[idx]
%assign sysIdx = extOut.Block[0]
%assign blkIdx = extOut.Block[1]
%assign outportBlock = System[sysIdx].Block[blkIdx]
%if ISFIELD(extOut, "LocalCGVCEIdx") && (extOut.LocalCGVCEIdx != -1)
%assign variantCondition = cgvceList[extOut.LocalCGVCEIdx]
%else
%assign variantCondition = ""
%endif
%assign ifCond = ""
%assign ifEndCond = ""
%if ISFIELD(outportBlock, "Inactive")
%continue
%endif
%if !ISEMPTY(variantCondition)
%assign ifCond = SLibIfVariantConditionForm(variantCondition)
%assign ifEndCond = SLibEndIfVariantConditionForm(variantCondition)
%endif
%with System[sysIdx]
%with outportBlock
%assign dTypeId = LibGetDataTypeIdAliasedThruToFromId(...
LibBlockInputSignalDataTypeId(0))
%if !FcnExtOutLoggable(extOut)
%continue
%endif
%assign width = LibBlockInputSignalSymbolicWidth(0)
%assign numDims = LibBlockInputSignalNumDimensions(0)
%assign dims = LibBlockInputSignalSymbolicDimensions(0)
%assign preprocessingFcnPtrs = LibGetRecordPreprocessingFcnPtr(extOut)
%assign isVarDims = ISFIELD(extOut, "HasVarDims")
%assign cmpxSig = LibBlockInputSignalIsComplex(0)
%assign label = extOut.SigLabel
%assign blkName = LibGetBlockPath(outportBlock)
%assign dtConvertParams = InitLogDataTypeConvertStructure(dTypeId)
%endwith
%endwith
%assign nSignalInfos = nSignalInfos + 1
%assign widthStr = widthStr + comma + cr + width
%assign numDimsStr = numDimsStr + comma + cr + "%<numDims>"
%assign dimsStr = dimsStr + comma + cr
%assign preprocessingFcnPtrsStr = preprocessingFcnPtrsStr + comma + cr + "%<preprocessingFcnPtrs>"
%assign currSigDimsInitStr = currSigDimsInitStr + comma + cr
%assign currSigDimsSizeStr = currSigDimsSizeStr + comma + cr
%foreach dimsIdx = numDims
%assign dimsStr = dimsStr + "%"
%assign currSigDimsInitStr = currSigDimsInitStr + SLibGetNullDefinitionFromTfl()
%if isVarDims
%with System[sysIdx]
%with outportBlock
%assign currSigDims = SLibGetOutportSize(idx, numDims, "", -1, "", dimsIdx)
%endwith
%endwith
%assign currSigDimsStr = currSigDimsStr + "&%<currSigDims>"
%assign currSigDimsSizeStr = currSigDimsSizeStr + "%<currSigDimsSize>"
%else
%assign currSigDims = widthVar
%assign currSigDimsStr = currSigDimsStr + ...
"&%<currSigDims>[%]"
%assign currSigDimsSizeStr = currSigDimsSizeStr + "%<currSigDimsSize>"
%endif
%if dimsIdx != numDims-1
%assign dimsStr = dimsStr + ", "
%assign currSigDimsInitStr = currSigDimsInitStr + ", "
%assign currSigDimsSizeStr = currSigDimsSizeStr + ", "
%endif
%assign currSigDimsStr = "%<currSigDimsVar>[%<numCurrSigDims>] " + ...
"= %<currSigDimsStr>; /n"
%assign currSigDimsSetStr = currSigDimsSetStr + currSigDimsStr
%assign currSigDimsStr = ""
%assign numCurrSigDims = numCurrSigDims + 1
%endforeach
%assign isVarDimsStr = isVarDimsStr + comma + cr + "%<isVarDims>"
%assign dTypeStr = dTypeStr + comma + cr + "%"
%assign cmplxStr = cmplxStr + comma + cr + "%<cmpxSig>"
%assign dataTypeConvertInitStr = dataTypeConvertInitStr + comma + cr + ...
"{ %, %, %," + ...
" %, %, %," + ...
" %, %, %}"
%assign labelStr = labelStr + comma + cr + qt + STRING(label) + qt
%assign blkNameStr = blkNameStr + comma + cr + qt + STRING(blkName) + qt
%if dlo.NumOutputSaveNames != 1
%if nSignalInfos == 1
%assign pointerMathAddition = ""
%assign pointerMathAdditionDims = ""
%else
%assign pointerMathAddition = "+%<numOutportsLoggedIdx>"
%assign pointerMathAdditionDims = "+%<numDimsRunningCount>"
%endif
%assign numOutportsLoggedIdx = numOutportsLoggedIdx + 1
%assign numDimsRunningCount = numDimsRunningCount + numDims
%openfile tempBuffer
%<typeQ> const char_T *%<labelVar>_%<idx>[] = {"%<STRING(label)>"};
%<typeQ> const char_T *%<blkNameVar>_%<idx>[] = {"%<STRING(blkName)>"};
%closefile tempBuffer
%assign logSigInfoVarsStr = logSigInfoVarsStr + tempBuffer
%openfile tempBuffer
{
1,
%<widthVar>%<pointerMathAddition>,
%<numDimsVar>%<pointerMathAddition>,
%<dimsVar>%<pointerMathAdditionDims>,
%<isVarDimsVar>%<pointerMathAddition>,
%<currSigDimsVar>%<pointerMathAdditionDims>,
%<currSigDimsSizeVar>%<pointerMathAdditionDims>,
%<dTypeVar>%<pointerMathAddition>,
%<cmplxVar>%<pointerMathAddition>,
%<SLibGetNullDefinitionFromTfl()>,
%<preprocessingFcnPtrsVar>%<pointerMathAddition>,
{%<labelVar>_%<idx>},
%<SLibGetNullDefinitionFromTfl()>,
%<SLibGetNullDefinitionFromTfl()>,
%<SLibGetNullDefinitionFromTfl()>,
{%<blkNameVar>_%<idx>},
{%<SLibGetNullDefinitionFromTfl()>},
%<SLibGetNullDefinitionFromTfl()>,
%<rt_RTWLogDataTypeConvertVar>%<pointerMathAddition>
}/
%closefile tempBuffer
%assign logSigInfoInitStr = logSigInfoInitStr + "/n" + ifCond + tempBuffer + newcomma + ifEndCond
%if (nSignalInfos + 1 == nLoggableOutports)
%assign newcomma = ""
%endif
%endif
%assign comma = ","
%assign cr = "/n"
%endforeach
%if bEmitInit
%if nSignalInfos > 0
%<typeQ> int_T %<widthVar>[] =/
{
%<widthStr>
};
%<typeQ> int_T %<numDimsVar>[] =/
{
%<numDimsStr>
};
%<typeQ> int_T %<dimsVar>[] =/
{
%<dimsStr>
};
%<typeQ> boolean_T %<isVarDimsVar>[] =/
{
%<isVarDimsStr>
};
%<typeQ> void* %<currSigDimsVar>[] =/
{
%<currSigDimsInitStr>
};
%<typeQ> int_T %<currSigDimsSizeVar>[] =/
{
%<currSigDimsSizeStr>
};
%<typeQ> BuiltInDTypeId %<dTypeVar>[] =/
{
%<dTypeStr>
};
%<typeQ> int_T %<cmplxVar>[] =/
{
%<cmplxStr>
};
%<typeQ> RTWPreprocessingFcnPtr %<preprocessingFcnPtrsVar>[] =/
{
%<preprocessingFcnPtrsStr>
};
%if dlo.NumOutputSaveNames == 1
%<typeQ> const char_T *%<labelVar>[] = {
%<labelStr>};
%<typeQ> const char_T *%<blkNameVar>[] = {
%<blkNameStr>};
%else
%<logSigInfoVarsStr>
%endif
%<typeQ> RTWLogDataTypeConvert %<rt_RTWLogDataTypeConvertVar>[] =/
{
%<dataTypeConvertInitStr>
};
%else
%assign widthVar = SLibGetNullDefinitionFromTfl()
%assign numDimsVar = SLibGetNullDefinitionFromTfl()
%assign dimsVar = SLibGetNullDefinitionFromTfl()
%assign isVarDimsVar = SLibGetNullDefinitionFromTfl()
%assign currSigDimsVar = SLibGetNullDefinitionFromTfl()
%assign currSigDimsSizeVar = SLibGetNullDefinitionFromTfl()
%assign dTypeVar = SLibGetNullDefinitionFromTfl()
%assign cmplxVar = SLibGetNullDefinitionFromTfl()
%assign preprocessingFcnPtrsVar = SLibGetNullDefinitionFromTfl()
%assign labelVar = SLibGetNullDefinitionFromTfl()
%assign labelLenVar = SLibGetNullDefinitionFromTfl()
%assign blkNameVar = SLibGetNullDefinitionFromTfl()
%assign blkNameLenVar = SLibGetNullDefinitionFromTfl()
%assign rt_RTWLogDataTypeConvertVar = SLibGetNullDefinitionFromTfl()
%endif
%if dlo.NumOutputSaveNames == 1
%assign numberOfSignalInfosInEachStruct = nSignalInfos
%else
%assign numberOfSignalInfosInEachStruct = 1
%endif
%<typeQ> RTWLogSignalInfo rt_LoggedOutputSignalInfo[] =/
{
%if dlo.NumOutputSaveNames == 1
{
%<nSignalInfos>,
%<widthVar>,
%<numDimsVar>,
%<dimsVar>,
%<isVarDimsVar>,
%<currSigDimsVar>,
%<currSigDimsSizeVar>,
%<dTypeVar>,
%<cmplxVar>,
%<SLibGetNullDefinitionFromTfl()>,
%<preprocessingFcnPtrsVar>,
{%<labelVar>},
%<SLibGetNullDefinitionFromTfl()>,
%<SLibGetNullDefinitionFromTfl()>,
%<SLibGetNullDefinitionFromTfl()>,
{%<blkNameVar>},
{%<SLibGetNullDefinitionFromTfl()>},
%<SLibGetNullDefinitionFromTfl()>,
%<rt_RTWLogDataTypeConvertVar>
}
%else
%<logSigInfoInitStr>
%endif
};
%endif
%if bEmitInit
%<RTMLoggingSet("LogYSignalInfo", "rt_LoggedOutputSignalInfo")>
/* set currSigDims field */
%<currSigDimsSetStr>
}
%endif
%if (!isAnyOutportUnconditional)
%<allIfEndCond>
%endif
%endfunction
%function SLibDumpModelRegDataLoggingSetup(bEmitReg, bEmitInit) Output
%assert(!IsModelReferenceTarget())
%if bEmitReg
/* Setup for data logging */
{
%if UsingMalloc
RTWLogInfo *rt_DataLoggingInfo = ...
(RTWLogInfo *) malloc(sizeof(RTWLogInfo));
%<RTMChkMemAndReturnIfErr("rt_DataLoggingInfo")>;
rt_DataLoggingInfo->loggingInterval = NULL;
%else
static RTWLogInfo rt_DataLoggingInfo;
rt_DataLoggingInfo.loggingInterval = NULL;
%endif
%assign amps = UsingMalloc ? "" : "&"
%<RTMLoggingSet("RTWLogInfo", "%<amps>rt_DataLoggingInfo")>
}
%endif
/* Setup for data logging */
{
%assign dlo = ::CompiledModel.DataLoggingOpts
%assign needsMMI = 0
%if FcnIsStateLoggingEnabled(dlo) || ::isRAccel
/*
* Set pointers to the data and signal info each state
*/
%if ::CompiledModel.RTWStatesLogging == 0
%<FcnLogStateSetup(bEmitReg, bEmitInit, dlo)>/
%else
%assign needsMMI = 1
%endif
%else
%if bEmitReg
%<RTMLoggingSet("LogXSignalInfo", SLibGetNullDefinitionFromTfl())>
%<RTMLoggingSet("LogXSignalPtrs", SLibGetNullDefinitionFromTfl())>
%endif
%endif
%if bEmitInit
%<RTMLoggingSet("LogT", "/"%<dlo.TimeSaveName>/"")>
%<RTMLoggingSet("LogX", "/"%<dlo.StateSaveName>/"")>
%<RTMLoggingSet("LogXFinal", "/"%<dlo.FinalStateName>/"")>
%<RTMLoggingSet("LogVarNameModifier", "/"%<LogVarNameModifier>/"")>
%<RTMLoggingSet("LogFormat", dlo.SaveFormat)>
%<RTMLoggingSet("LogMaxRows", dlo.MaxRows)>
%<RTMLoggingSet("LogDecimation", dlo.Decimation)>
%if needsMMI
%if isRSim && !IsModelReferenceTarget()
%<RTMLoggingSet("MMI", "&(%<RSimRTWCAPIVarPtr>->mmi)")>
%else
%<RTMLoggingSet("MMI", "&(%<RTMGet("DataMapInfo")>.mmi)")>
%endif
%endif
%endif
%if FcnIsOutputLoggingEnabled(dlo)
/*
* Set pointers to the data and signal info for each output
*/
%<FcnLogOutputSetup(bEmitReg, bEmitInit, dlo)>/
%endif
%if bEmitInit
%assign maxLength = 509
%assign nOutportBlks = ExternalOutputs.NumExternalOutputs
%assign isConditionalLogCodeNeeded = IsConfiguredForConditionalMATFileCode()
%if (isConditionalLogCodeNeeded == TLC_TRUE)
/*
* Create conditional output log variable
*/
{
%if UsingMalloc
%if (SIZE(dlo.OutputSaveName,1) <= maxLength)
static char_T *rt_LogVarNames;
rt_LogVarNames = malloc(sizeof(char_T)*sizeof("%<dlo.OutputSaveName>,"));
%else
%assign len = SIZE(dlo.OutputSaveName,1)
static char_T *rt_LogVarNames;
rt_LogVarNames = malloc(sizeof(char_T)*%);
%endif
%else
%if (SIZE(dlo.OutputSaveName,1) <= maxLength)
static char_T rt_LogVarNames[sizeof("%<dlo.OutputSaveName>,")];
%else
%assign len = SIZE(dlo.OutputSaveName,1)
static char_T rt_LogVarNames[%];
%endif
%endif
%assign condLoggingLibInclCall = LibGenMemFcnCall("memset", "rt_LogVarNames"," '//0'", "sizeof(rt_LogVarNames)")
(void)memset(rt_LogVarNames, '/0',sizeof(rt_LogVarNames));
%foreach idx = nOutportBlks
%assign extOut = ExternalOutputs.ExternalOutput[idx]
%assign sysIdx = extOut.Block[0]
%assign blkIdx = extOut.Block[1]
%assign outportBlock = System[sysIdx].Block[blkIdx]
%if !FcnExtOutLoggable(extOut)
%continue
%endif
%if ISFIELD(VariantConditions, "CGVCEList")
%assign cgvceList = VariantConditions.CGVCEList
%else
%assign cgvceList = ""
%endif
%if ISFIELD(extOut, "LocalCGVCEIdx") && (extOut.LocalCGVCEIdx != -1)
%assign variantCondition = cgvceList[extOut.LocalCGVCEIdx]
%else
%assign variantCondition = ""
%endif
%assign outputPortVarName = extOut.OutputSaveNameOnPort
%assign ifCond = ""
%assign ifEndCond = ""
%if ISFIELD(outportBlock, "Inactive")
%continue
%else
%assign ifCond = SLibIfVariantConditionForm(variantCondition)
%assign ifEndCond = SLibEndIfVariantConditionForm(variantCondition)
%assign funcCall = "strcat" + "(rt_LogVarNames" + "," + "/"%<outputPortVarName>,/"" + ");"
%<ifCond>
%<funcCall>
%<ifEndCond>
%endif
%endforeach
if (strlen(rt_LogVarNames) > 0) {
rt_LogVarNames[strlen(rt_LogVarNames) - 1] = '/0';
}
%<RTMLoggingSet("LogY", "rt_LogVarNames")>
}
%elseif ((SIZE(dlo.OutputSaveName,1) <= maxLength) && (isConditionalLogCodeNeeded == TLC_FALSE))
%<RTMLoggingSet("LogY", "/"%<dlo.OutputSaveName>/"")>
%else
%assign len = SIZE(dlo.OutputSaveName,1)
%assign times = len/maxLength + 1
{
static char_T temp_str [%];
%foreach idx = times
%assign str = ""
%foreach idx2 = maxLength
%assign lenSoFar = idx*maxLength + idx2
%if lenSoFar >= len
%break
%endif
%assign str = str + dlo.OutputSaveName[lenSoFar]
%endforeach
(void) %<LibGenStringFcnCall2Args("strcpy",...
"&temp_str[%]", "/"%<str>/"")>;
%endforeach
%<RTMLoggingSet("LogY", "temp_str")>
}
%endif
%endif
%if (FcnIsOutputLoggingEnabled(dlo) == TLC_FALSE)
%if bEmitReg
%<RTMLoggingSet("LogYSignalInfo", SLibGetNullDefinitionFromTfl())>
%<RTMLoggingSet("LogYSignalPtrs", SLibGetNullDefinitionFromTfl())>
%endif
%endif
}
%endfunction
%function SLibInitDataInitialValue(dTypeId, var, val) Output
%if !ISEMPTY(SLibDataTypeConstructFcnName(dTypeId))
%elseif LibIsStructDataType(dTypeId)
%assign dTypeName = LibGetDataTypeNameFromId(dTypeId)
%assign tmpVar = "temp"
%if !LibIsDataTypeMultiWordFixpt(dTypeId)
%assign val = "{" + val + "}"
%endif
{
%<dTypeName> %<tmpVar> = %<val>;
%<var> = %<tmpVar>;
}
%else
%<var> = %<val>;
%endif
%return
%endfunction
%function FcnInitDataElementInitialValue(datarec, storageClass, dTypeId, ...
symWidth, isComplex, initValue, optionalDeref, dataId, idxExpr, elementIdx) Output
%assign vectIdxExpr = SLibGet1DArrayIndexer(symWidth, idxExpr, "", elementIdx)
%switch storageClass
%case "Auto"
%case "ExportedGlobal"
%case "ImportedExtern"
%case "ImportedExternPointer"
%if isComplex
%if LibIsNonBuiltInTypeNeededForFixpt(dTypeId)
%assign initRe = FcnGetNonBuiltInRe(initValue[elementIdx])
%assign initIm = FcnGetNonBuiltInIm(initValue[elementIdx])
%else
%assign initRe = REAL(initValue[elementIdx])
%assign initIm = IMAG(initValue[elementIdx])
%endif
%assign rval = SLibGetFormattedValue(datarec, initRe)
%if !SLibRemoveZeroInitForData(datarec, rval)
%assign var = optionalDeref + STRING(dataId) + vectIdxExpr+ "." +tRealPart
%<SLibInitDataInitialValue(dTypeId, var, rval)>/
%endif
%assign ival = SLibGetFormattedValue(datarec, initIm)
%if !SLibRemoveZeroInitForData(datarec, ival)
%assign var = optionalDeref + STRING(dataId) + vectIdxExpr +"." + tImagPart
%<SLibInitDataInitialValue(dTypeId, var, ival)>/
%endif
%else
%assign val = ""
%if ISEMPTY(SLibDataTypeConstructFcnName(dTypeId))
%assign val = SLibGetFormattedValue(datarec, initValue[elementIdx])
%endif
%if !SLibRemoveZeroInitForData(datarec, val)
%assign var = optionalDeref + STRING(dataId) + vectIdxExpr
%<SLibInitDataInitialValue(dTypeId, var, val)>/
%endif
%endif
%break
%case "Custom"
%if isComplex
%if LibIsNonBuiltInTypeNeededForFixpt(dTypeId)
%assign initRe = FcnGetNonBuiltInRe(initValue[elementIdx])
%assign initIm = FcnGetNonBuiltInIm(initValue[elementIdx])
%else
%assign initRe = REAL(initValue[elementIdx])
%assign initIm = IMAG(initValue[elementIdx])
%endif
%assign rval = SLibGetFormattedValue(datarec, initRe)
%assign ival = SLibGetFormattedValue(datarec, initIm)
%else
%assign val = SLibGetFormattedValue(datarec, initValue[elementIdx])
%endif
%if (datarec.CustomStorageClassVersion > 1)
%if isComplex
%if !SLibRemoveZeroInitForData(datarec, rval)
%<LibAccessCustomData(datarec,"set",vectIdxExpr,tRealPart,rval)>
%endif
%if !SLibRemoveZeroInitForData(datarec, ival)
%<LibAccessCustomData(datarec,"set",vectIdxExpr,tImagPart,ival)>
%endif
%else
%if !SLibRemoveZeroInitForData(datarec, val)
%<LibAccessCustomData(datarec,"set",vectIdxExpr,"",val)>
%endif
%endif
%else
%if isComplex
%if !SLibRemoveZeroInitForData(datarec, rval)
%assign var = LibCustomData(datarec,"contents",vectIdxExpr,tRealPart)
%<SLibInitDataInitialValue(dTypeId, var, rval)>/
%endif
%if !SLibRemoveZeroInitForData(datarec, ival)
%assign var = LibCustomData(datarec,"contents",vectIdxExpr,tImagPart)
%<SLibInitDataInitialValue(dTypeId, var, ival)>/
%endif
%else
%if !SLibRemoveZeroInitForData(datarec, val)
%assign var = LibCustomData(datarec,"contents",vectIdxExpr,"")
%<SLibInitDataInitialValue(dTypeId, var, val)>/
%endif
%endif
%endif
%break
%default
%assert TLC_FALSE
%endswitch
%endfunction
%function GetInitDataInitialValue(datarec, dataId) void
%assign storageClass = datarec.StorageClass
%assign dTypeId = LibGetRecordDataTypeId(datarec)
%assign symWidth = LibGetRecordSymbolicWidth(datarec)
%assign isComplex = SLibGetRecordIsComplex(datarec)
%assign initValue = datarec.InitialValue
%if ((ISEQUAL(storageClass, "ImportedExternPointer")) && ...
(ISEQUAL(symWidth, "1")))
%assign optionalDeref = "*"
%else
%assign optionalDeref = ""
%endif
%assign retVal = ""
%assert( (! (ISEQUAL(storageClass, "ImportedExtern") ||...
ISEQUAL(storageClass, "ImportedExternPointer"))) ||...
ISEQUAL(System[datarec.SigSrc[0]].Block[datarec.SigSrc[2]].Type, "ModelReference"))
%if LibRecordHasSymbolicWidth(datarec)
%assert SLibAllValuesMatch(initValue)
%assign loopCode = SLibEmitForLoopCounterCode(symWidth, "i")
%openfile retVal
%<FcnInitDataElementInitialValue(datarec, storageClass, dTypeId, ...
symWidth, isComplex, initValue, optionalDeref, dataId, "i", 0)>
%closefile retVal
%return ["%<retVal>", "%", "%"]
%elseif %<symWidth> > 1 && %<symWidth> >= RollThreshold && SLibAllValuesMatch(initValue)
%assign loopCode = SLibEmitForLoopCounterCode(symWidth, "i")
%openfile retVal
%<FcnInitDataElementInitialValue(datarec, storageClass, dTypeId, ...
symWidth, isComplex, initValue, optionalDeref, dataId, "i", 0)>
%closefile retVal
%return ["%<retVal>", "%", "%"]
%else
%openfile retVal
%foreach elementIdx = %<symWidth>
%<FcnInitDataElementInitialValue(datarec, storageClass, dTypeId, symWidth, ...
isComplex, initValue, optionalDeref, dataId, "", elementIdx)>
%endforeach
%closefile retVal
%return ["%<retVal>", "", ""]
%endif
%endfunction
%function FcnInitDataInitialValue(datarec, dataId) void
%assign retVal = ""
%assign initCode = GetInitDataInitialValue(datarec, dataId)
%openfile retVal
%if !ISEMPTY(initCode[1])
{
%
% {
%
}
}
%else
%
%endif
%closefile retVal
%return retVal
%endfunction
%function FcnIsImportedScopeCustomStorageCheck(dataRec) void
%if dataRec.StorageClass == "Custom"
%assign dataScope = SLibGetDataScope(dataRec.CSCDefn, dataRec)
%return dataScope == "Imported"
%endif
%return TLC_FALSE
%endfunction
%function FcnIsFileScopeCustomStorageCheck(dataRec) void
%if dataRec.StorageClass == "Custom"
%assign dataScope = SLibGetDataScope(dataRec.CSCDefn, dataRec)
%return (dataScope == "File") || ISFIELD(dataRec, "isFileScoped")
%endif
%return TLC_FALSE
%endfunction
%function FcnIsNotInterfaceableStorageClassCheck(dataRec) void
%if ::BlockFcn == "Output" || ::BlockFcn == "OutputUpdate"
%return TLC_FALSE
%endif
%assert ::BlockFcn == "Initialize" || ::BlockFcn == "Registration"
%if ::BlockFcn == "Initialize" && FcnIsFileScopeCustomStorageCheck(dataRec)
%assert !ZeroInternalMemoryAtStartup
%assign errTxt = "The auto-generated SIL block will be unable to " ...
"initialize '%<LibGetRecordIdentifier(dataRec)>' since its storage " ...
"class prohibits an external interface. This can cause a " ...
"simulation behaviour mismatch of the SIL block with its " ...
"source model or subsystem. " ...
"Please disable the 'Remove internal data zero initialization' " ...
"option in the Optimization pane of the models Configuration " ...
"Parameters dialog to addess this warning."
%<LibReportWarning(errTxt)>
%return TLC_TRUE
%endif
%return TLC_FALSE
%endfunction
%function FcnGetNonRootFileFunctionOwner(dataRec, sysIdxInitValue) void
%assign sysIdx = sysIdxInitValue
%assign csIdx = SLibGetSystemAndCallSideIndex(dataRec)
%assign fcnSys = System[System[csIdx[0]].NonInlinedParentSystemIdx]
%if (fcnSys.RTWSystemCode == 1 || fcnSys.RTWSystemCode == 2) && ...
!IsBaseSystem(::CompiledModel.System[fcnSys.FileNameOwnerIdx])
%assert fcnSys.SystemIdx == System[csIdx[0]].NonInlinedParentSystemIdx
%assign sysIdx = fcnSys.SystemIdx
%endif
%return sysIdx
%endfunction
%function FcnShouldSkipDataInitializationForConstant(bo, StorageClass) void
%if ISFIELD(bo, "TID") && ...
ISEQUAL(TID, "constant") && ...
StorageClass != "Auto" && ...
ISFIELD(bo, "InitInStart") && bo.InitInStart
%return TLC_TRUE
%endif
%return TLC_FALSE
%endfunction
%function FcnCacheStandaloneSubsyInitFromTempBuffers(comment) void
%foreach sysIdx = NumSystems
%assign sys = System[sysIdx]
%if LibIsSystemField(sys, "TempInitBuffer")
%assign stdSSBuffer = LibGetSystemField(sys, "TempInitBuffer")
%if !ISEMPTY(stdSSBuffer)
%<LibAddToSystemField(sys, "CachedInitializeDataBody", ...
"/n" + comment + "/n" + stdSSBuffer + "/n")>
%<LibSetSystemField(sys, "TempInitBuffer", "")>
%endif
%endif
%endforeach
%endfunction
%function FcnInitBlockIOWithExternalStorage(sc, comment, fieldsep, addressof, deref) void
%openfile rtnBuffer
%foreach boIdx = ::CompiledModel.BlockOutputs.NumExternalBlockOutputs
%assign bo = ::CompiledModel.BlockOutputs.ExternalBlockOutput[boIdx]
%if SLibOmitRecord(bo) || FcnIsNotInterfaceableStorageClassCheck(bo)
%continue
%endif
%if !SLibWriteOutInstForSignalRec(bo)
%continue
%endif
%assign id = LibGetRecordIdentifier(bo)
%with bo
%assign stdSSIdx = -1
%assign sysIdx = StandaloneParentSysIdxOfDataRec(bo)
%if sysIdx == -1 && FcnIsFileScopeCustomStorageCheck(bo)
%assign sysIdx = FcnGetNonRootFileFunctionOwner(bo, sysIdx)
%endif
%assign vcRecord = SLibGetDataInlineVariantNetConditions(bo)
%assign ifCond = vcRecord.ifCond
%assign ifEndCond = vcRecord.endIfCond
%if sysIdx != -1
%assign stdSSIdx = sysIdx
%assign stdSSBuffer = ""
%endif
%if StorageClass != sc
%continue
%endif
%assign initCount = LibGetRecordSymbolicWidth(bo)
%assign isSymbolic = (initCount != "%<LibGetRecordWidth(bo)>")
%assign dTypeId = LibGetRecordDataTypeId(bo)
%if !ISEMPTY(SLibDataTypeConstructFcnName(dTypeId))
%continue
%endif
%if SLibShouldSkipInitForRecord(bo)
%continue
%endif
%if ISEMPTY(InitialValue) || LibIsStringDataType(dTypeId)
%if (StorageClass == "Custom")
%if FcnIsImportedScopeCustomStorageCheck(bo)
%continue
%endif
%openfile initCode
%if !SLibGetIsReusable(bo) || ...
SLibHasReusableCSCWithoutReusableBuffer(bo) || ...
ISFIELD(bo, "IsAtRootInputOrOutput")
%<SLibEmitLibCustomInitCode(bo, initCount, LibGetRecordIsComplex(bo))>
%endif
%if ISFIELD(bo, "ReuseBufferName") && ...
bo.Identifier != bo.ReuseBufferName
%assign tempId = bo.Identifier
%assign bo.Identifier = bo.ReuseBufferName
%<SLibEmitLibCustomInitCode(bo, initCount, LibGetRecordIsComplex(bo))>
%assign bo.Identifier = tempId
%endif
%closefile initCode
%if !WHITE_SPACE(initCode)
%if stdSSIdx != -1
%openfile tmpBuffer
%endif
%<ifCond>
%<initCode>
%<ifEndCond>
%if stdSSIdx != -1
%closefile tmpBuffer
%assign stdSSBuffer = stdSSBuffer + tmpBuffer
%endif
%endif
%else
%if SLibRemoveZeroInitForDataDefault(bo)
%continue
%endif
%if stdSSIdx != -1
%openfile tmpBuffer
%endif
%<ifCond>
%assign dataTypeId = LibGetDataTypeIdAliasedThruToFromId(LibGetRecordDataTypeId(bo))
%if LibIsDataTypeMultiWordFixpt(dataTypeId)
%assign defaultInitialValue = SLibGetDtGroundName(dataTypeId, ...
LibGetRecordIsComplex(bo), tRealPart)
%else
%assign defaultInitialValue = SLibGetDefaultInitialValue(bo, tRealPart)
%endif
%if initCount == "1"
%if LibGetRecordIsComplex(bo)
%<id>%<fieldsep>%<tRealPart> = %<defaultInitialValue>;
%<id>%<fieldsep>%<tImagPart> = %<defaultInitialValue>;
%else
%<deref>%<id> = %<defaultInitialValue>;
%endif
%elseif isSymbolic || %<initCount> >= RollThreshold
%assign loopCode = SLibEmitForLoopCounterCode(initCount, "i")
{
%
% {
%if LibGetRecordIsComplex(bo)
%<id>[i]%<fieldsep>%<tRealPart> = %<defaultInitialValue>;
%<id>[i]%<fieldsep>%<tImagPart> = %<defaultInitialValue>;
%else
%<deref>%<id>[i] = %<defaultInitialValue>;
%endif
}
}
%else
%foreach initIdx = %<initCount>
%if LibGetRecordIsComplex(bo)
%<id>[%<initIdx>]%<fieldsep>%<tRealPart> = %<defaultInitialValue>;
%<id>[%<initIdx>]%<fieldsep>%<tImagPart> = %<defaultInitialValue>;
%else
%<deref>%<id>[%<initIdx>] = %<defaultInitialValue>;
%endif
%endforeach
%endif
%<ifEndCond>
%if stdSSIdx != -1
%closefile tmpBuffer
%assign stdSSBuffer = stdSSBuffer + tmpBuffer
%endif
%endif
%else
%if !FcnSkipDataInitialValueInReg(bo)
%if (Invariant != "yes")
%if SLibRemoveZeroInitForData(bo, InitialValue)
%if stdSSIdx != -1 && !WHITE_SPACE(stdSSBuffer)
%<LibAddToSystemField(System[stdSSIdx],"TempInitBuffer",...
stdSSBuffer)>
%endif
%continue
%endif
%endif
%if FcnIsImportedScopeCustomStorageCheck(bo)
%continue
%endif
%if FcnShouldSkipDataInitializationForConstant(bo, StorageClass)
%continue
%endif
%if stdSSIdx != -1
%openfile tmpBuffer
%endif
%assign initCode = GetInitDataInitialValue(bo, id)
%if !ISEMPTY(initCode[1])
%<ifCond>
{
%
% {
%
}
}
%<ifEndCond>
%else
%<ifCond>
%
%<ifEndCond>
%endif
%if stdSSIdx != -1
%closefile tmpBuffer
%assign stdSSBuffer = stdSSBuffer + tmpBuffer
%endif
%endif
%endif
%if stdSSIdx != -1 && !WHITE_SPACE(stdSSBuffer)
%<LibAddToSystemField(System[stdSSIdx],"TempInitBuffer",...
stdSSBuffer)>
%endif
%endwith
%endforeach
%undef stdSSIdx
%closefile rtnBuffer
%<FcnCacheStandaloneSubsyInitFromTempBuffers(comment)>
%if !WHITE_SPACE(rtnBuffer)
%return "/n" + comment + "/n" + rtnBuffer
%else
%return ""
%endif
%endfunction
%function SLibInitBlockIOWithExternalStorage(usingStatic) Output
%if !LibExportedGlobalSignalsInstanceIsEmpty()
%<FcnInitBlockIOWithExternalStorage("ExportedGlobal", ...
"/* exported global signals */", ".", "&", "")>
%endif
%if CustomStorageClasses.NumCustomStorageClasses > 0
%<FcnInitBlockIOWithExternalStorage("Custom", ...
"/* custom signals */", ".", "&", "")>
%endif
%endfunction
%function SLibInitBlockIO(ptrBlockIOLabel) Output
%assign startIdx = -1
%assign stdSSIdx = -1
%assign needMemsetToZero = 0
%if ::CompiledModel.HasStandaloneSubsystem
%foreach boIdx = BlockOutputs.NumGlobalBlockOutputs
%assign bo = BlockOutputs.GlobalBlockOutput[boIdx]
%if ISEMPTY(bo.SigSrc)
%continue
%endif
%assign standParent = StandaloneParentSysIdxOfDataRec(bo)
%if standParent != -1
%assign startIdx = boIdx
%assign stdSSIdx = standParent
%break
%endif
%endforeach
%if startIdx != -1
%foreach loopIdx = NumSystems - 1
%openfile ssInitBuf
%assign retVal = SLibInitBlockIOHelper("",startIdx,stdSSIdx)
%if retVal[2]
%assign needMemsetToZero = 1
%endif
%closefile ssInitBuf
%if !WHITE_SPACE(ssInitBuf)
%<LibAddToSystemField(System[stdSSIdx],"CachedInitializeDataBody",ssInitBuf)>
%endif
%if retVal[0] == -1
%break
%else
%assign stdSSIdx = retVal[0]
%assign startIdx = retVal[1]
%endif
%endforeach
%endif
%endif
%if !ISEMPTY(ptrBlockIOLabel)
%assign retVal = SLibInitBlockIOHelper(ptrBlockIOLabel, 0, -1)
%assign needMemsetToZero = retVal[2]
%endif
%return needMemsetToZero
%endfunction
%function GetFinalPassAndNextTransitionIndex(boIdx, standaloneSSIdx)
%assign nextStdIdx = -1
%assign nextStartIdx = -1
%assign skipRecord = TLC_FALSE
%assign finalPass = TLC_FALSE
%assert(boIdx <= BlockOutputs.NumGlobalBlockOutputs)
%if boIdx == BlockOutputs.NumGlobalBlockOutputs
%assign finalPass = TLC_TRUE
%else
%assign bo = BlockOutputs.GlobalBlockOutput[boIdx]
%if bo.RequiredInBlockIO[0] != 1 || bo.RequiredInBlockIO[1] != 0 || ...
!ISFIELD(bo, "VarGroupIdx") || ...
(ISFIELD(bo, "UseAccessFunctions") && bo.UseAccessFunctions == 1) || ...
SLibDataRecordIsInCoderGroup(bo)
%assign skipRecord = TLC_TRUE
%elseif StandaloneParentSysIdxOfDataRec(bo) != standaloneSSIdx
%if standaloneSSIdx == -1
%assign skipRecord = TLC_TRUE
%else
%assign finalPass = TLC_TRUE
%assign nextStdIdx = StandaloneParentSysIdxOfDataRec(bo)
%if nextStdIdx != -1
%assign nextStartIdx = boIdx
%else
%assign nextStartIdx = -1
%assign numLeft = BlockOutputs.NumGlobalBlockOutputs - (boIdx+1)
%foreach localIdx = numLeft
%assign lIdx = (boIdx+1) + localIdx
%assign lb = BlockOutputs.GlobalBlockOutput[lIdx]
%if ISEMPTY(lb.SigSrc)
%continue
%endif
%assign standParent = StandaloneParentSysIdxOfDataRec(lb)
%if standParent != -1
%assign nextStdIdx = standParent
%assign nextStartIdx = lIdx
%break
%endif
%endforeach
%endif
%endif
%endif
%endif
%return [%<finalPass>, %<skipRecord>, %<nextStdIdx>, %<nextStartIdx>]
%endfunction
%function SLibInitBlockIOForBufferHelper(bo, sysIdx, with_ppIf) void
%assign ret = ["", "", "", 0, "", 0]
%openfile csgInitBuffer
%openfile straightInitBuffer
%openfile useLoopVarInitBuffer
%assign ::CurrentModuleIdx = System[sysIdx].CGIRModuleIdx
%assign memsetToZeroNeeded = 0
%assign dTypeId = LibGetRecordDataTypeId(bo)
%if (!ISEMPTY(bo.InitialValue) || !ISEMPTY(SLibDataTypeConstructFcnName(dTypeId))) && ...
!LibIsStringDataType(dTypeId)
%if !FcnSkipDataInitialValueInReg(bo)
%if bo.Invariant == "yes" || ...
!SLibRemoveZeroInitForData(bo, bo.InitialValue)
%assign id = SLibGetBlockOutputIdentifierFromRecord(bo,sysIdx)
%selectfile csgInitBuffer
%assign ifCond = ""
%assign ifEndCond = ""
%if with_ppIf
%assign vcRecord = SLibGetDataInlineVariantNetConditions(bo)
%if vcRecord.hasConds
%assign ifCond = vcRecord.ifCond
%assign ifEndCond = vcRecord.endIfCond
%endif
%endif
%if with_ppIf
%<ifCond>
%endif
%<FcnInitDataInitialValue(bo, id)>
%if with_ppIf
%<ifEndCond>
%endif
%endif
%endif
%elseif !SLibRemoveZeroInitForDataDefault(bo)
%assign curDataTypeId = LibGetDataTypeIdAliasedThruToFromId(LibGetRecordDataTypeId(bo))
%assign curMemsetToZeroSuffice = FcnMemsetToZeroInitSuffice(curDataTypeId)
%if curMemsetToZeroSuffice
%assign memsetToZeroNeeded = 1
%else
%assign nterms = LibGetRecordSymbolicWidth(bo)
%assign hasSymbolicWidth = LibRecordHasSymbolicWidth(bo)
%if hasSymbolicWidth
%assign numElemInMemoryChunk = INT16MAX
%elseif LibGetRecordIsComplex(bo)
%assign numElemInMemoryChunk = 2 * %<nterms>
%else
%assign numElemInMemoryChunk = %<nterms>
%endif
%if hasSymbolicWidth || %<nterms> > 0
%assign ifCond = ""
%assign ifEndCond = ""
%if with_ppIf
%assign vcRecord = SLibGetDataInlineVariantNetConditions(bo)
%if vcRecord.hasConds
%assign ifCond = vcRecord.ifCond
%assign ifEndCond = vcRecord.endIfCond
%endif
%endif
%assign DataTypeDefaultInitValue = SLibGetDefaultInitialValueFromId(curDataTypeId)
%assign DataTypeName = SLibGetRecordContainerBaseTypeName(bo)
%if FcnSuitableForMemset(DataTypeDefaultInitValue, curDataTypeId, "") && ...
FcnPreferMemsetToAssignment(numElemInMemoryChunk, curDataTypeId)
%assign StartAddr = SLibGetBlockOutputFromRecord(bo,sysIdx)
%selectfile straightInitBuffer
%assign sanitizedInitValue = ...
FcnCastValueForMemsetUse(curDataTypeId, DataTypeDefaultInitValue)
%if hasSymbolicWidth
%assign memsetWidth = "(" + nterms + ")"
%else
%assign memsetWidth = "%<nterms>U"
%endif
%if LibGetRecordIsComplex(bo)
%assign memsetWidth = "2 * %<memsetWidth>"
%endif
%<ifCond>
(void) %<LibGenMemFcnCall("memset", StartAddr, sanitizedInitValue, ...
"%<memsetWidth>*sizeof(%<DataTypeName>)")>;
%<ifEndCond>
%else
%if LibIsDataTypeMultiWordFixpt(curDataTypeId)
%assign initValue = SLibGetDtGroundName(curDataTypeId, ...
LibGetRecordIsComplex(bo), tRealPart)
%else
%assign initValue = DataTypeDefaultInitValue
%endif
%assign id = SLibGetBlockOutputIdentifierFromRecord(bo, sysIdx)
%assign blockio = id
%if SLibIsContainerCGTypeND(bo)
%assign blockioNumDims = LibCGTypeNumDimensions(SLibGetRecordContainerCGTypeIdx(bo))
%assign blockio = LibGetAddressOfFirstElement(id, blockioNumDims)
%endif
%if bo.DeclareAsPointer == "yes"
%assign id = "(*%<id>)"
%endif
%if hasSymbolicWidth || (%<nterms> >= RollThreshold && %<nterms> > 1)
%selectfile useLoopVarInitBuffer
%<ifCond>
for (i = 0; i < %<nterms>; i++) {
%if LibGetRecordIsComplex(bo)
%<blockio>[i].%<tRealPart> = %<initValue>;
%<blockio>[i].%<tImagPart> = %<initValue>;
%else
%<blockio>[i] = %<initValue>;
%endif
}
%<ifEndCond>
%elseif %<nterms> > 1
%selectfile straightInitBuffer
%<ifCond>
%foreach initIdx = %<nterms>
%if LibGetRecordIsComplex(bo)
%<blockio>[%<initIdx>].%<tRealPart> = %<initValue>;
%<blockio>[%<initIdx>].%<tImagPart> = %<initValue>;
%else
%<blockio>[%<initIdx>] = %<initValue>;
%endif
%endforeach
%<ifEndCond>
%else
%selectfile straightInitBuffer
%<ifCond>
%if LibGetRecordIsComplex(bo)
%<id>.%<tRealPart> = %<initValue>;
%<id>.%<tImagPart> = %<initValue>;
%else
%<id> = %<initValue>;
%endif
%<ifEndCond>
%endif
%endif
%endif
%endif
%endif
%closefile csgInitBuffer
%closefile straightInitBuffer
%closefile useLoopVarInitBuffer
%assign ::CurrentModuleIdx = -1
%assign ret[0] = csgInitBuffer
%assign ret[1] = straightInitBuffer
%assign ret[2] = useLoopVarInitBuffer
%assign ret[3] = memsetToZeroNeeded
%return ret
%endfunction
%function SLibInitBlockIOHelper(ptrBlockIOLabel, startIdx, standaloneSSIdx) Output
%assign nextStartIdx = -2
%assign nextStdIdx = -2
%assign memsetToZeroNeeded = 0
%assign withSysIdx = standaloneSSIdx ? GetBaseSystemIdx() : standaloneSSIdx
%assign ::CurrentModuleIdx = System[withSysIdx].CGIRModuleIdx
%if ForceBlockIOInitOptimize
%assign unusedVar = SLibInitBlockIOHelperOld(ptrBlockIOLabel, startIdx, standaloneSSIdx)
%return [%<nextStdIdx>, %<nextStartIdx>, %<memsetToZeroNeeded>]
%endif
%assign blkioIsEmpty = ::CompiledModel.DWorkAndBlockIOCombined ? ...
SLibModelDWorkStructIsEmpty() : SLibModelBlockIOStructIsEmpty()
%if !blkioIsEmpty
%assign csgInitBuffer = ""
%assign straightInitBuffer = ""
%assign useLoopVarInitBuffer = ""
%assign vecLoopVarInitBufferIfConditions = []
%assign loopVarInitBufferEndIfCond = ""
%assign gaurdLoopVarInitBuffer = 1
%assign baseSystemIdx = GetBaseSystemIdx()
%assign numOutputsPlusOne = BlockOutputs.NumGlobalBlockOutputs + 1
%assign forbidMemset = TLC_FALSE
%foreach loopIdx = (numOutputsPlusOne - startIdx)
%assign boIdx = loopIdx + startIdx
%if boIdx != BlockOutputs.NumGlobalBlockOutputs && ...
ISEMPTY(BlockOutputs.GlobalBlockOutput[boIdx].SigSrc)
%continue
%endif
%assign fInfo = GetFinalPassAndNextTransitionIndex(boIdx, standaloneSSIdx)
%assign finalPass = fInfo[0]
%assign skipRecord = fInfo[1]
%assign nextStdIdx = fInfo[2]
%assign nextStartIdx = fInfo[3]
%if skipRecord
%continue
%endif
%if finalPass
%break
%endif
%assign bo = BlockOutputs.GlobalBlockOutput[boIdx]
%assign dtIdx = LibGetRecordDataTypeId(bo)
%if LibDoesDataTypeNeedConstructor(dtIdx) || LibDoesDataTypeMemberNeedConstructor(dtIdx)
%assign forbidMemset = TLC_TRUE
%endif
%assign ret = SLibInitBlockIOForBufferHelper(bo, baseSystemIdx, TLC_TRUE)
%if !bo.InitInStart
%assign csgInitBuffer = csgInitBuffer + ret[0]
%assign straightInitBuffer = straightInitBuffer + ret[1]
%assign useLoopVarInitBuffer = useLoopVarInitBuffer + ret[2]
%endif
%if !WHITE_SPACE(ret[2])
%assign vcRecord = SLibGetDataInlineVariantNetConditions(bo)
%if !vcRecord.hasConds
%assign gaurdLoopVarInitBuffer = 0
%endif
%if gaurdLoopVarInitBuffer == 0
%assign vecLoopVarInitBufferIfConditions = []
%assign loopVarInitBufferEndIfCond = ""
%else
%assign vecLoopVarInitBufferIfConditions = vecLoopVarInitBufferIfConditions + vcRecord.ifCond
%assign loopVarInitBufferEndIfCond = vcRecord.endIfCond
%endif
%endif
%if ret[3]
%assign memsetToZeroNeeded = ret[3]
%endif
%endforeach
%assign memsetToZeroNeeded = memsetToZeroNeeded && !forbidMemset
%if memsetToZeroNeeded && !::CompiledModel.DWorkAndBlockIOCombined && !SLibIsSelfStructured()
%if standaloneSSIdx == -1
%assign blockIOType = IsModelReferenceTarget() && !GenerateClassInterface ...
? ...
FcnSysVarGroupType(System[NumSystems-2],"BlockIO") : ::tBlockIOType
%assign systemIfCond = NumSystems-2 >= 0 ? SLibIfSystemVariantCondition(System[NumSystems-2]) : ""
%assign systemIfEndCond = NumSystems-2 >= 0 ? SLibEndIfSystemVariantCondition(System[NumSystems-2]) : ""
%<systemIfCond>
(void) %<LibGenMemFcnCall("memset", ptrBlockIOLabel, "0", ...
"sizeof(%<blockIOType>)")>;
%<systemIfEndCond>
%<SLibAccessArgHelper(System[baseSystemIdx].Interface.BlockIOArgDef,"","")>
%else
%assign type = FcnSysVarGroupType(System[standaloneSSIdx],"BlockIO")
%assign systemIfCond = SLibIfSystemVariantCondition(System[standaloneSSIdx])
%assign systemIfEndCond = SLibEndIfSystemVariantCondition(System[standaloneSSIdx])
%assign var = "(void *) &" + ...
FcnSysVarGroupNonreusedName(System[standaloneSSIdx],"BlockIO")
%<systemIfCond>
(void) %<LibGenMemFcnCall("memset", var, "0", "sizeof(%<type>)")>;
%<systemIfEndCond>
%endif
%endif
%if memsetToZeroNeeded && ::CompiledModel.DWorkAndBlockIOCombined && !SLibGetUseRTMcgType() &&...
standaloneSSIdx != -1 && ISEMPTY(System[standaloneSSIdx].Interface.DWorkArgDef)
%assign type = FcnSysVarGroupType(System[standaloneSSIdx],"DWork")
%assign var = "(void *) &" + ...
FcnSysVarGroupNonreusedName(System[standaloneSSIdx],"DWork")
%assign systemIfCond = SLibIfSystemVariantCondition(System[standaloneSSIdx])
%assign systemIfEndCond = SLibEndIfSystemVariantCondition(System[standaloneSSIdx])
%<systemIfCond>
(void) %<LibGenMemFcnCall("memset", var, "0", "sizeof(%<type>)")>;
%<systemIfEndCond>
%endif
%if !WHITE_SPACE(csgInitBuffer) ...
|| !WHITE_SPACE(straightInitBuffer) ...
|| !WHITE_SPACE(useLoopVarInitBuffer)
{
%if !WHITE_SPACE(useLoopVarInitBuffer)
%assign loopVarInitBufferIfCond = SLibGetMergedIfCondition(vecLoopVarInitBufferIfConditions)
%<SLibCreateLocalVariableWithConditions("%<LibCGTypeName(::CompiledModel.CGTypes.IndexType)> i;", loopVarInitBufferIfCond, loopVarInitBufferEndIfCond)>
%<useLoopVarInitBuffer>/
%endif
%<straightInitBuffer>/
%<csgInitBuffer>/
}
%endif
%endif
%assign needMemsetForCombinedDWorkAndBlockIO = memsetToZeroNeeded ...
&& ::CompiledModel.DWorkAndBlockIOCombined
%assign ::CurrentModuleIdx = -1
%return [%<nextStdIdx>, %<nextStartIdx>, %<needMemsetForCombinedDWorkAndBlockIO>]
%endfunction
%function SLibAtleastOneInputHasReusableCSCWithoutReuseBufferName() void
%foreach idx = ExternalInputs.NumExternalInputs
%assign extInp = ExternalInputs.ExternalInput[idx]
%if SLibHasReusableCSCWithoutReusableBuffer(extInp)
%return TLC_TRUE
%endif
%endforeach
%return TLC_FALSE
%endfunction
%function SLibAtleastOneOutputHasReusableCSCWithoutReuseBufferName() void
%foreach idx = ExternalOutputs.NumExternalOutputs
%assign extOut = ExternalOutputs.ExternalOutput[idx]
%if SLibHasReusableCSCWithoutReusableBuffer(extOut)
%return TLC_TRUE
%endif
%endforeach
%return TLC_FALSE
%endfunction
%function FcnIsInitedByExternalBlockOutput(extInp) void
%if extInp.StorageClass == "Custom" && SLibGetIsReusable(extInp)
%foreach boIdx = ::CompiledModel.BlockOutputs.NumExternalBlockOutputs
%assign bo = ::CompiledModel.BlockOutputs.ExternalBlockOutput[boIdx]
%if bo.StorageClass == "Custom" && ...
SLibGetIsReusable(bo) && ...
SLibHasReusableCSCWithoutReusableBuffer(bo) && ...
!SLibOmitRecord(bo) && ...
!FcnIsNotInterfaceableStorageClassCheck(bo) && ...
SLibWriteOutInstForSignalRec(bo) && ...
ISEMPTY(bo.InitialValue) && ...
!FcnIsImportedScopeCustomStorageCheck(bo)
%return TLC_TRUE
%endif
%endforeach
%endif
%return TLC_FALSE
%endfunction
%function SLibInitExternalInputRecord(localIn, fromSFcn, recIdx, useIRInitialization, forbidMemsetDueToOtherInputs) Output
%assign memsetToZeroNeeded = TLC_FALSE
%assign extInp = ::CompiledModel.ExternalInputs.ExternalInput[recIdx]
%assign dataTypeId = SLibGetRecordDataTypeId(extInp)
%assign memsetMightBeNeeded = (!localIn && ExternalInputs.NumExternalInputs > 1) ...
&& (!MultiInstanceERTCode || RootIOStructures)
%if (useIRInitialization && !LibCGTypeIsUnknown(extInp.CGTypeIdx) && (extInp.StorageClass != "Custom" || SLibGetIsReusable(extInp)))
%return memsetToZeroNeeded
%endif
%if (ISFIELD(extInp, "Inactive"))
%return memsetToZeroNeeded
%endif
%if (ISFIELD(extInp, "UseAccessFunctions") && extInp.UseAccessFunctions == 1)
%return memsetToZeroNeeded
%endif
%if !ISEMPTY(SLibDataTypeConstructFcnName(dataTypeId))
%return memsetToZeroNeeded
%endif
%assign vcRecord = SLibGetDataInlineVariantNetConditions(extInp)
%assign ifCond = vcRecord.ifCond
%assign ifEndCond = vcRecord.endIfCond
%assign dataTypeEnum = LibGetDataTypeEnumFromId(dataTypeId)
%if dataTypeEnum == "SS_FCN_CALL" || ...
(SLibFcnProtoCtrlActive() && extInp.RequiresGlobalAccess == "no" && !localIn)
%return memsetToZeroNeeded
%endif
%if !SLibWriteOutInstForSignalRec(extInp)
%return memsetToZeroNeeded
%endif
%if !ISEMPTY(SLibDataTypeConstructFcnName(dataTypeId))
%return memsetToZeroNeeded
%endif
%if (extInp.StorageClass == "Auto" || ...
extInp.StorageClass == "ExportedGlobal")
%assign AutoOrExportedGlobal = TLC_TRUE
%elseif (extInp.StorageClass == "ImportedExtern" || ...
extInp.StorageClass == "ImportedExternPointer")
%return memsetToZeroNeeded
%else
%assign AutoOrExportedGlobal = TLC_FALSE
%if FcnIsImportedScopeCustomStorageCheck(extInp)
%return memsetToZeroNeeded
%endif
%endif
%assign dTypeId = LibGetDataTypeIdAliasedThruToFromId(...
SLibGetRecordDataTypeId(extInp))
%assign width = LibGetRecordSymbolicWidth(extInp)
%assign hasSymbolicWidth = LibRecordHasSymbolicWidth(extInp)
%if localIn
%assign varName = "localIn%<recIdx>"
%elseif extInp.StorageClass == "Auto"
%assign varName = "%<SLibGetExternalInputStructForRecord(extInp)>%<UQualifier>%<LibGetRecordIdentifier(extInp)>"
%if PassExtInpByRef(extInp)
%assign varName = "(*%<varName>)"
%endif
%elseif extInp.StorageClass == "ExportedGlobal"
%assign varName = LibGetRecordIdentifier(extInp)
%else
%assign varName = ""
%endif
%if !ISEMPTY(extInp.InitialValue)
%if !FcnSkipDataInitialValueInReg(extInp)
%assign initValue = extInp.InitialValue
%if SLibRemoveZeroInitForData(extInp, initValue)
%return memsetToZeroNeeded
%endif
%if extInp.StorageClass == "Auto"
%<SLibAccessArgHelper(extInp,"","")>
%if SLibDataRecordIsInCoderGroup(extInp)
%assign coderGroupId = ...
SLibGetCoderGroupIdForDataRecord(extInp)
%<SLibCG_TrackCoderDataGroup(GetBaseSystemIdx(), ...
coderGroupId)>
%endif
%endif
%<FcnInitDataInitialValue(extInp, varName)>
%endif
%else
%if AutoOrExportedGlobal
%if !localIn && SLibRemoveZeroInitForDataDefault(extInp) && ...
!(fromSFcn && SLibCPPClassNeedERTSfcnZeroIOMemory())
%assign hasGroundVariable = TLC_FALSE
%if !LibIsDataTypeMultiWordFixpt(dTypeId) && ...
LibIsStructDataType(dataTypeId) && ...
ISFIELD(::CompiledModel.DataTypes.DataType[dataTypeId], "GroundVariableName")
%assign hasGroundVariable = TLC_TRUE
%endif
%if !hasGroundVariable
%return memsetToZeroNeeded
%endif
%endif
%if extInp.StorageClass == "Auto"
%<SLibAccessArgHelper(extInp,"","")>
%if SLibDataRecordIsInCoderGroup(extInp)
%assign coderGroupId = ...
SLibGetCoderGroupIdForDataRecord(extInp)
%<SLibCG_TrackCoderDataGroup(GetBaseSystemIdx(), ...
coderGroupId)>
%endif
%if memsetMightBeNeeded && !forbidMemsetDueToOtherInputs
%if FcnMemsetToZeroInitSuffice(dTypeId)
%assign memsetToZeroNeeded = 1
%return memsetToZeroNeeded
%endif
%endif
%endif
%if LibIsDataTypeMultiWordFixpt(dTypeId)
%assign initValue = SLibGetDtGroundName(dTypeId, ...
LibGetRecordIsComplex(extInp), tRealPart)
%else
%assign initValue = SLibGetDefaultInitialValue(extInp,tRealPart)
%endif
%<ifCond>
%if width == "1"
%if LibGetRecordIsComplex(extInp)
%<varName>.%<tRealPart> = %<initValue>;
%<varName>.%<tImagPart> = %<initValue>;
%else
%<varName> = %<initValue>;
%endif
%else
%assign memsetSuitable = ...
FcnSuitableForMemset(initValue, dTypeId, extInp.StorageClass)
%if !memsetSuitable
%assign extInpNumDims = LibGetRecordNumDimsFromContainerCgTypeIdx(extInp)
%assign varLhsAccess = LibGetAddressOfFirstElement(varName, extInpNumDims)
%if hasSymbolicWidth || %<width> >= RollThreshold
%assign loopCode = SLibEmitForLoopCounterCode(width, "i")
{
%
% {
%if LibGetRecordIsComplex(extInp)
%<varLhsAccess>[i].%<tRealPart> = %<initValue>;
%<varLhsAccess>[i].%<tImagPart> = %<initValue>;
%else
%<varLhsAccess>[i] = %<initValue>;
%endif
}
}
%else
%foreach initIdx = %<width>
%if LibGetRecordIsComplex(extInp)
%<varLhsAccess>[%<initIdx>].%<tRealPart> = %<initValue>;
%<varLhsAccess>[%<initIdx>].%<tImagPart> = %<initValue>;
%else
%<varLhsAccess>[%<initIdx>] = %<initValue>;
%endif
%endforeach
%endif
%else
%assign dTypeName = SLibGetRecordContainerBaseTypeName(extInp)
%if hasSymbolicWidth
%assign memsetWidth = "(" + width + ")"
%else
%assign memsetWidth = "%<width>U"
%endif
%if LibGetRecordIsComplex(extInp)
%assign memsetWidth = "2*%<memsetWidth>"
%endif
%assign sanitizedInitValue = ...
FcnCastValueForMemsetUse(dTypeId, initValue)
(void) %<LibGenMemFcnCall("memset", varName, sanitizedInitValue, ...
"%<memsetWidth>*sizeof(%<dTypeName>)")>;
%endif
%endif
%<ifEndCond>
%else
%if extInp.IsEliminated == "false"
%openfile tmpBuf
%if !FcnIsInitedByExternalBlockOutput(extInp)
%<SLibEmitLibCustomInitCode(extInp, width, LibGetRecordIsComplex(extInp))>
%endif
%if ISFIELD(extInp, "ReuseBufferName") && ...
extInp.Identifier != extInp.ReuseBufferName
%assign tempId = extInp.Identifier
%assign extInp.Identifier = extInp.ReuseBufferName
%<SLibEmitLibCustomInitCode(extInp, width, LibGetRecordIsComplex(extInp))>
%assign extInp.Identifier = tempId
%endif
%closefile tmpBuf
%if !WHITE_SPACE(tmpBuf)
%<ifCond>
%<tmpBuf>
%<ifEndCond>
%endif
%endif
%endif
%if extInp.Padding > 0
%if extInp.Padding > 1
%assign addrOf = ""
%else
%assign addrOf = "&"
%endif
(void) %<LibGenMemFcnCall("memset", ...
"%<addrOf>%<SLibGetExternalInputStructForRecord(extInp)>%<UQualifier>pad_%<LibGetRecordIdentifier(extInp)>", ...
"'a'", "%<extInp.Padding>U*sizeof(char)")>;
%endif
%endif
%return memsetToZeroNeeded
%endfunction
%function SLibInitExternalInputsHelper(usingStatic, localIn, fromSFcn, coderGroupVarGroupIdx) void
%assign isCoderGroupVarGroup = (coderGroupVarGroupIdx != -1)
%assign useIRInitialization = UseIRModelInitCode && (!fromSFcn) && ...
!SLibAtleastOneInputHasReusableCSCWithoutReuseBufferName() && !isCoderGroupVarGroup
%assign irInitBuffer = ""
%if UseIRModelInitCode
%assign irInitBuffer = SLibDumpExternalInputsInitializationCode(::CompiledModel.System[GetBaseSystemIdx()])
%endif
%openfile tlcInitBuffer
%assign needMemsetToZero = TLC_FALSE
%if ((NumModelInputs > 0) && ...
!SLibAutosarActive())
%assign forbidMemsetToZero = TLC_FALSE
%openfile NonMemsetBuffer
%if isCoderGroupVarGroup
%assign coderGroupVarGroup = ::CompiledModel.VarGroups.VarGroup[coderGroupVarGroupIdx]
%assert coderGroupVarGroup.Category == "HierarchicalCoderData"
%foreach elIdx = coderGroupVarGroup.NumVarGroupElements
%assign idnum = IDNUM(coderGroupVarGroup.VarGroupElements[elIdx])
%assign recType = idnum[0]
%if recType == "U"
%assign recIdx = idnum[1]
%assign extInp = ::CompiledModel.ExternalInputs.ExternalInput[recIdx]
%if SLibShouldForbidMemsetToZeroForRecord(extInp)
%assign forbidMemsetToZero = TLC_TRUE
%endif
%endif
%endforeach
%foreach elIdx = coderGroupVarGroup.NumVarGroupElements
%assign idnum = IDNUM(coderGroupVarGroup.VarGroupElements[elIdx])
%assign recType = idnum[0]
%if recType == "U"
%assign recIdx = idnum[1]
%assign extInp = ::CompiledModel.ExternalInputs.ExternalInput[recIdx]
%if !SLibDataRecordIsInCoderGroup(extInp)
%continue
%endif
%assign ret = SLibInitExternalInputRecord(localIn, fromSFcn, recIdx, useIRInitialization,forbidMemsetToZero)
%if ret
%assign needMemsetToZero = TLC_TRUE
%endif
%endif
%endforeach
%else
%foreach idx = ::CompiledModel.ExternalInputs.NumExternalInputs
%assign extInp = ::CompiledModel.ExternalInputs.ExternalInput[idx]
%if SLibShouldForbidMemsetToZeroForRecord(extInp)
%assign forbidMemsetToZero = TLC_TRUE
%endif
%endforeach
%foreach idx = ::CompiledModel.ExternalInputs.NumExternalInputs
%assign extInp = ::CompiledModel.ExternalInputs.ExternalInput[idx]
%if SLibDataRecordIsInCoderGroup(extInp)
%continue
%endif
%assign ret = SLibInitExternalInputRecord(localIn, fromSFcn, idx, useIRInitialization,forbidMemsetToZero)
%if ret
%assign needMemsetToZero = TLC_TRUE
%endif
%endforeach
%endif
%closefile NonMemsetBuffer
%if needMemsetToZero
%if !isCoderGroupVarGroup
%assign initAddr = (UQualifier == "." ? "&" : "") + ...
LibGetExternalInputStruct()
(void) %<LibGenMemFcnCall("memset", "(void *)" + initAddr, ...
" 0", " sizeof(%<::tInputType>)")>;
%endif
%endif
%if !WHITE_SPACE(NonMemsetBuffer)
%<NonMemsetBuffer>
%endif
%endif
%closefile tlcInitBuffer
%assign retBuffer = ["", 0]
%assign retBuffer[0] = useIRInitialization ? ...
irInitBuffer + "/n" + tlcInitBuffer : ...
tlcInitBuffer
%assign retBuffer[1] = needMemsetToZero
%return retBuffer
%endfunction
%function SLibInitExternalInputs(usingStatic, localIn, fromSFcn) Output
%assign ret = SLibInitExternalInputsHelper(usingStatic, localIn, fromSFcn, -1)
%assign initBuffer = ret[0]
%<initBuffer>/
%endfunction
%function SLibInitExternalInputSizes() Output
%with ::CompiledModel.System[NumSystems-1]
%if ((::CompiledModel.NumModelInputs > 0) && ...
(!IsModelReferenceTarget()) && ...
!SLibAutosarActive())
%foreach idx = ::CompiledModel.ExternalInputs.NumExternalInputs
%assign extInp = ::CompiledModel.ExternalInputs.ExternalInput[idx]
%if ISFIELD(extInp, "HasVarDims")
%if ISFIELD(extInp, "SizeVarGroupIdx")
%assert extInp.StorageClass == "Auto"
%assign sizeTypeIdx = SLibCGVarGroupMemberCGTypeIdx(...
extInp.SizeVarGroupIdx[0], ...
extInp.SizeVarGroupIdx[1])
%assign sizeVecLen = LibCGTypeWidth(sizeTypeIdx)
%foreach dimIdx = sizeVecLen
%<SLibGetInportSize(idx, sizeVecLen, "", -1, "", dimIdx)> = ...
%<SLibGetDefaultInitialValueByCGTypeIdx(...
sizeTypeIdx, tRealPart)>;
%endforeach
%elseif ISFIELD(extInp, "DimSizeDWork")
%assert extInp.StorageClass == "ExportedGlobal"
%assign dworkRec = ::CompiledModel.DWorks.DWork[extInp.DimSizeDWork]
%assign sizeVecLen = LibCGTypeWidth(LibGetRecordCGTypeIdx(dworkRec))
%foreach dimIdx = sizeVecLen
%<SLibCG_V(LibGetRecordIdentifier(dworkRec), TLC_FALSE, sizeVecLen, ...
"", -1, "", dimIdx)> = ...
%<SLibGetDefaultInitialValue(dworkRec, ...
tRealPart)>;
%endforeach
%endif
%endif
%endforeach
%endif
%endwith
%endfunction
%function FcnIgnoreExtOutForInit(extOut)
%assign sysIdx = extOut.Block[0]
%assign blkIdx = extOut.Block[1]
%assign outportBlock = System[sysIdx].Block[blkIdx]
%if (ISFIELD(outportBlock, "Inactive"))
%return TLC_TRUE
%endif
%if (ISFIELD(extOut, "UseAccessFunctions") && extOut.UseAccessFunctions == 1)
%return TLC_TRUE
%endif
%if (ISFIELD(extOut, "IsMessage") && extOut.IsMessage == 1)
%return TLC_TRUE
%endif
%assign dataTypeId = LibGetRecordDataTypeId(extOut)
%if !ISEMPTY(SLibDataTypeConstructFcnName(dataTypeId))
%return TLC_TRUE
%endif
%if SLibShouldSkipInitForRecord(extOut)
%return TLC_TRUE
%endif
%return TLC_FALSE
%endfunction
%function FcnInitializeExternalOutput(extOut)
%assign sysIdx = extOut.Block[0]
%assign blkIdx = extOut.Block[1]
%assign outportBlock = System[sysIdx].Block[blkIdx]
%if !SLibExternalOutputIsVirtual(outportBlock) && ...
(!SLibFcnProtoCtrlActive() || extOut.RequiresGlobalAccess == "yes")
%return TLC_TRUE
%endif
%return TLC_FALSE
%endfunction
%function SLibInitExternalOutputRecord(localOut, fromSFcn, recIdx, useIRInitialization, forbidMemsetDueToOtherOutputs) Output
%assign memsetToZeroNeeded = TLC_FALSE
%assign extOutp = ::CompiledModel.ExternalOutputs.ExternalOutput[recIdx]
%assign cgTypeIdx = extOutp.CGTypeIdx
%if (useIRInitialization && !SLibIsUnknownType(cgTypeIdx) && (extOutp.StorageClass != "Custom" || SLibGetIsReusable(extOutp)))
%return memsetToZeroNeeded
%endif
%assign memsetMightBeNeeded = (!localOut && ExternalOutputs.NumExternalOutputs > 1) ...
&& (!MultiInstanceERTCode || RootIOStructures)
%assign sysIdx = extOutp.Block[0]
%assign blkIdx = extOutp.Block[1]
%assign outportBlock = System[sysIdx].Block[blkIdx]
%if FcnIgnoreExtOutForInit(extOutp)
%return memsetToZeroNeeded
%endif
%assign ifCond = SLibIfVariantCondition(outportBlock)
%assign ifEndCond = SLibEndIfVariantCondition(outportBlock)
%with outportBlock
%if FcnInitializeExternalOutput(extOutp) || localOut
%assign rPart = "%<tRealPart>0"
%assign iPart = "%<tImagPart>0"
%assign dTypeId = ...
LibGetDataTypeIdAliasedThruToFromId(LibGetRecordDataTypeId(extOutp))
%assign uIsComplex = LibGetRecordIsComplex(extOutp)
%if (extOutp.StorageClass == "Auto" || extOutp.StorageClass == "ExportedGlobal")
%assign AutoOrExportedGlobal = TLC_TRUE
%elseif (extOutp.StorageClass == "ImportedExtern" || extOutp.StorageClass == "ImportedExternPointer")
%return memsetToZeroNeeded
%elseif !ISEMPTY(SLibDataTypeConstructFcnName(dTypeId))
%return memsetToZeroNeeded
%else
%assign AutoOrExportedGlobal = TLC_FALSE
%if FcnIsImportedScopeCustomStorageCheck(extOutp)
%return memsetToZeroNeeded
%endif
%endif
%assign outNumDims = LibGetRecordNumDimsFromContainerCgTypeIdx(extOutp)
%assign outWidth = LibGetRecordSymbolicWidth(extOutp)
%assign hasSymbolicWidth = LibRecordHasSymbolicWidth(extOutp)
%if AutoOrExportedGlobal
%if !localOut && SLibRemoveZeroInitForDataDefault(extOutp) && ...
!(fromSFcn && SLibCPPClassNeedERTSfcnZeroIOMemory())
%return memsetToZeroNeeded
%endif
%if extOutp.StorageClass == "Auto"
%<SLibAccessArgHelper(extOutp,"","")>
%if SLibDataRecordIsInCoderGroup(extOutp)
%assign coderGroupId = ...
SLibGetCoderGroupIdForDataRecord(extOutp)
%<SLibCG_TrackCoderDataGroup(GetBaseSystemIdx(), ...
coderGroupId)>
%endif
%if memsetMightBeNeeded && !forbidMemsetDueToOtherOutputs
%if FcnMemsetToZeroInitSuffice(dTypeId)
%assign memsetToZeroNeeded = TLC_TRUE
%return memsetToZeroNeeded
%endif
%endif
%endif
%if LibIsDataTypeMultiWordFixpt(dTypeId)
%assign defaultInitialValue = SLibGetDtGroundName(dTypeId, ...
LibGetRecordIsComplex(DataInputPort), tRealPart)
%else
%assign defaultInitialValue = SLibGetDefaultInitialValue(DataInputPort, tRealPart)
%endif
%<ifCond>
%if outWidth == "1"
%if localOut
%assign lhs = "localOut%<recIdx>"
%if uIsComplex
%assign lhs = lhs + "." + tRealPart
%endif
%<lhs> = %<defaultInitialValue>;
%if uIsComplex
%assign lhs = "localOut%<recIdx>" + "." + tImagPart
%<lhs> = %<defaultInitialValue>;
%endif
%elseif extOutp.StorageClass == "Auto"
%<LibBlockDstSignalLocation("outportblk","","",rPart)> = %<defaultInitialValue>;
%if uIsComplex
%<LibBlockDstSignalLocation("outportblk","","",iPart)> = %<defaultInitialValue>;
%endif
%elseif extOutp.StorageClass == "ExportedGlobal"
%assign lhs = LibGetRecordIdentifier(extOutp)
%if uIsComplex
%<lhs>.%<tRealPart> = %<defaultInitialValue>;
%<lhs>.%<tImagPart> = %<defaultInitialValue>;
%else
%<lhs> = %<defaultInitialValue>;
%endif
%endif
%else
%assign memsetSuitable = !localOut && ...
FcnSuitableForMemset(defaultInitialValue, dTypeId, "")
%if !memsetSuitable
%if hasSymbolicWidth || %<outWidth> >= RollThreshold
%assign loopCode = SLibEmitForLoopCounterCode(outWidth, "i")
{
%
% {
%if localOut
%assign sigIndexer = SLibGet1DArrayIndexer(outWidth, "i", "", 0)
%assign lhsVarAccess = LibGetAddressOfFirstElement(...
"localOut%<recIdx>", ...
outNumDims) + sigIndexer
%assign lhs = lhsVarAccess
%if uIsComplex
%assign lhs = lhs + "." + tRealPart
%endif
%<lhs> = %<defaultInitialValue>;
%if uIsComplex
%assign lhs = lhsVarAccess + "." + tImagPart
%<lhs> = %<defaultInitialValue>;
%endif
%elseif extOutp.StorageClass == "Auto"
%<LibBlockDstSignalLocation("outportblk","i","",rPart)> = %<defaultInitialValue>;
%if uIsComplex
%<LibBlockDstSignalLocation("outportblk","i","",iPart)> = %<defaultInitialValue>;
%endif
%elseif extOutp.StorageClass == "ExportedGlobal"
%assign lhs = LibGetAddressOfFirstElement(...
LibGetRecordIdentifier(extOutp), ...
outNumDims)
%if uIsComplex
%<lhs>[i].%<tRealPart> = %<defaultInitialValue>;
%<lhs>[i].%<tImagPart> = %<defaultInitialValue>;
%else
%<lhs>[i] = %<defaultInitialValue>;
%endif
%endif
}
}
%else
%foreach initIdx = %<outWidth>
%if localOut
%assign sigIndexer = SLibGet1DArrayIndexer(%<outWidth>, "%<initIdx>", "", 0)
%assign lhsVarAccess = LibGetAddressOfFirstElement(...
"localOut%<recIdx>", ...
outNumDims) + sigIndexer
%assign lhs = lhsVarAccess
%if uIsComplex
%assign lhs = lhs + "." + tRealPart
%endif
%<lhs> = %<defaultInitialValue>;
%if uIsComplex
%assign lhs = lhsVarAccess + sigIndexer + "." + tImagPart
%<lhs> = %<defaultInitialValue>;
%endif
%elseif extOutp.StorageClass == "Auto"
%<LibBlockDstSignalLocation("outportblk","%<initIdx>","",rPart)> = %<defaultInitialValue>;
%if uIsComplex
%<LibBlockDstSignalLocation("outportblk","%<initIdx>","",iPart)> = %<defaultInitialValue>;
%endif
%elseif extOutp.StorageClass == "ExportedGlobal"
%assign lhs = LibGetAddressOfFirstElement(...
LibGetRecordIdentifier(extOutp), ...
outNumDims)
%if uIsComplex
%<lhs>[%<initIdx>].%<tRealPart> = %<defaultInitialValue>;
%<lhs>[%<initIdx>].%<tImagPart> = %<defaultInitialValue>;
%else
%<lhs>[%<initIdx>] = %<defaultInitialValue>;
%endif
%endif
%endforeach
%endif
%else
%assign needMemset = TLC_TRUE
%assign dtName = SLibGetRecordContainerBaseTypeName(extOutp)
%if extOutp.StorageClass == "ExportedGlobal"
%assign srcLoc = LibGetAddressOfFirstElement(...
LibGetRecordIdentifier(extOutp), ...
outNumDims) +"[0]"
%else
%assign srcLoc = LibBlockDstSignalLocation("outportblk","","",0)
%endif
%if hasSymbolicWidth
%assign memsetWidth = "(" + outWidth + ")"
%else
%assign memsetWidth = "%<outWidth>U"
%endif
%if uIsComplex
%assign memsetWidth = "2*%<memsetWidth>"
%endif
%assign sanitizedInitValue = ...
FcnCastValueForMemsetUse(dTypeId, defaultInitialValue)
(void) %<LibGenMemFcnCall("memset", "&%<srcLoc>", sanitizedInitValue, ...
"%<memsetWidth>*sizeof(%<dtName>)")>;
%endif
%endif
%<ifEndCond>
%else
%openfile customDataBuf
%<SLibEmitLibCustomInitCode(extOutp, outWidth, LibGetRecordIsComplex(extOutp))>
%closefile customDataBuf
%if !WHITE_SPACE(customDataBuf)
%<ifCond>
%<customDataBuf>
%<ifEndCond>
%endif
%endif
%endif
%endwith
%return memsetToZeroNeeded
%endfunction
%function SLibInitExternalOutputsHelper(usingStatic,localOut, fromSFcn, coderGroupVarGroupIdx) Output
%assign isCoderGroupVarGroup = (coderGroupVarGroupIdx != -1)
%assign useIRInitialization = UseIRModelInitCode && RootOutputInitInIR && !fromSFcn && !SLibAtleastOneOutputHasReusableCSCWithoutReuseBufferName() && !isCoderGroupVarGroup
%assign irInitBuffer = ""
%if UseIRModelInitCode && RootOutputInitInIR
%assign irInitBuffer = SLibDumpExternalOutputsInitializationCode(::CompiledModel.System[GetBaseSystemIdx()])
%endif
%openfile tlcInitBuffer
%assign needMemsetToZero = TLC_FALSE
%assign forbidMemsetToZero = TLC_FALSE
%with ::CompiledModel.System[NumSystems-1]
%if ::CompiledModel.NumModelOutputs > 0 && !SLibAutosarActive()
%assign isCoderGroupVarGroup = (coderGroupVarGroupIdx != -1)
%openfile NonMemsetBuffer
%if isCoderGroupVarGroup
%assign coderGroupVarGroup = ::CompiledModel.VarGroups.VarGroup[coderGroupVarGroupIdx]
%assert coderGroupVarGroup.Category == "HierarchicalCoderData"
%foreach elIdx = coderGroupVarGroup.NumVarGroupElements
%assign idnum = IDNUM(coderGroupVarGroup.VarGroupElements[elIdx])
%assign recType = idnum[0]
%if recType == "Y"
%assign recIdx = idnum[1]
%assign extOutp = ::CompiledModel.ExternalOutputs.ExternalOutput[recIdx]
%if SLibShouldForbidMemsetToZeroForRecord(extOutp)
%assign forbidMemsetToZero = TLC_TRUE
%endif
%endif
%endforeach
%foreach elIdx = coderGroupVarGroup.NumVarGroupElements
%assign idnum = IDNUM(coderGroupVarGroup.VarGroupElements[elIdx])
%assign recType = idnum[0]
%if recType == "Y"
%assign recIdx = idnum[1]
%assign extOutp = ::CompiledModel.ExternalOutputs.ExternalOutput[recIdx]
%if !SLibDataRecordIsInCoderGroup(extOutp)
%continue
%endif
%assign ret = SLibInitExternalOutputRecord(localOut, fromSFcn, recIdx, useIRInitialization, forbidMemsetToZero)
%if ret
%assign needMemsetToZero = TLC_TRUE
%endif
%endif
%endforeach
%else
%foreach idx = ::CompiledModel.ExternalOutputs.NumExternalOutputs
%assign extOutp = ::CompiledModel.ExternalOutputs.ExternalOutput[idx]
%if SLibShouldForbidMemsetToZeroForRecord(extOutp)
%assign forbidMemsetToZero = TLC_TRUE
%endif
%endforeach
%foreach idx = ::CompiledModel.ExternalOutputs.NumExternalOutputs
%assign extOutp = ::CompiledModel.ExternalOutputs.ExternalOutput[idx]
%if SLibDataRecordIsInCoderGroup(extOutp)
%continue
%endif
%if LibCGTypeIsEmxArray(extOutp.CGTypeIdx) && extOutp.HasVarDims == 1
%continue
%endif
%assign ret = SLibInitExternalOutputRecord(localOut, fromSFcn, idx, useIRInitialization, forbidMemsetToZero)
%if ret
%assign needMemsetToZero = TLC_TRUE
%endif
%endforeach
%endif
%closefile NonMemsetBuffer
%if needMemsetToZero
%if !isCoderGroupVarGroup
%assign initAddr = (YQualifier == "." ? "&" : "") +...
LibGetExternalOutputStruct()
(void) %<LibGenMemFcnCall("memset", "(void *)" + initAddr, ...
" 0", " sizeof(%<tOutputType>)")>;
%endif
%endif
%if !WHITE_SPACE(NonMemsetBuffer)
%<NonMemsetBuffer>
%endif
%endif
%endwith
%closefile tlcInitBuffer
%assign retBuffer = ["", 0]
%assign retBuffer[0] = useIRInitialization ? ...
irInitBuffer + "/n" + tlcInitBuffer : ...
tlcInitBuffer
%assign retBuffer[1] = needMemsetToZero
%return retBuffer
%endfunction
%function SLibInitExternalOutputs(usingStatic,localOut, fromSFcn) Output
%assign ret = SLibInitExternalOutputsHelper(usingStatic,localOut, fromSFcn, -1)
%assign initBuffer = ret[0]
%<initBuffer>/
%endfunction
%function SLibInitExternalOutputSizes() Output
%with ::CompiledModel.System[NumSystems-1]
%if ::CompiledModel.NumModelOutputs > 0 && ...
!SLibAutosarActive()
%foreach idx = ::CompiledModel.ExternalOutputs.NumExternalOutputs
%assign extOut = ::CompiledModel.ExternalOutputs.ExternalOutput[idx]
%if ISFIELD(extOut, "SizeVarGroupIdx")
%assert ISFIELD(extOut, "HasVarDims")
%assign sizeTypeIdx = SLibCGVarGroupMemberCGTypeIdx(...
extOut.SizeVarGroupIdx[0], ...
extOut.SizeVarGroupIdx[1])
%assign sizeVecLen = LibCGTypeWidth(sizeTypeIdx)
%foreach dimIdx = sizeVecLen
%<SLibGetOutportSize(idx, sizeVecLen, "", -1, "", dimIdx)> = ...
%<SLibGetDefaultInitialValueByCGTypeIdx(...
sizeTypeIdx, tRealPart)>;
%endforeach
%endif
%endforeach
%endif
%endwith
%endfunction
%function FcnAddSharedDataInitProtection(dwRec, vcRecord) void
%if (dwRec.SharedLocalDSM && SLibMultiInstance())
%assign hasBeenInitId = SLibGetDataStoreForHasBeenInitIdentifier()
%assign vcRecord.ifCond = vcRecord.ifCond + "/n if (!%<hasBeenInitId>) {"
%assign vcRecord.endIfCond = "}/n" + vcRecord.endIfCond
%endif
%return vcRecord
%endfunction
%function FcnInitStatesWithExternalStorage(sc, comment, fieldsep, addressof, deref) void
%openfile rtnBuffer
%foreach dwIdx = ::CompiledModel.DWorks.NumDWorks
%assign dwRec = ::CompiledModel.DWorks.DWork[dwIdx]
%if SLibOmitRecord(dwRec) || 1 == dwRec.IsLocalScratchDWork
%continue
%endif
%assign id = LibGetRecordIdentifier(dwRec)
%assign symbolicWidth = LibGetRecordSymbolicWidth(dwRec)
%assign hasSymbolicWidth = LibRecordHasSymbolicWidth(dwRec)
%if FcnIsNotInterfaceableStorageClassCheck(dwRec)
%continue
%endif
%if !SLibWriteOutInstForSignalRec(dwRec)
%continue
%endif
%assign dTypeId = SLibGetRecordDataTypeId(dwRec)
%if !ISEMPTY(SLibDataTypeConstructFcnName(dTypeId))
%continue
%endif
%with dwRec
%if dwRec.SharedLocalDSMForHasBeenInit
%continue
%endif
%assign vcRecord = SLibGetDataInlineVariantNetConditions(dwRec)
%assign vcRecord = FcnAddSharedDataInitProtection(dwRec, vcRecord)
%assign ifCond = vcRecord.ifCond
%assign ifEndCond = vcRecord.endIfCond
%assign stdSSIdx = -1
%assign sysIdx = StandaloneParentSysIdxOfDataRec(dwRec)
%if sysIdx == -1 && FcnIsFileScopeCustomStorageCheck(dwRec)
%assign sysIdx = FcnGetNonRootFileFunctionOwner(dwRec, sysIdx)
%endif
%if sysIdx != -1
%assign stdSSIdx = sysIdx
%assign stdSSBuffer = ""
%endif
%if StorageClass != sc
%continue
%endif
%if StorageClass == "Custom"
%openfile initCode
%<SLibEmitLibCustomInitCode(dwRec, symbolicWidth, SLibDWorkIsComplex(dwRec))>
%if SLibIsAuxBufferForReusableCSC(dwRec)
%assign tempId = dwRec.Identifier
%assign dwRec.Identifier = dwRec.ReuseBufferName
%<SLibEmitLibCustomInitCode(dwRec, symbolicWidth, SLibDWorkIsComplex(dwRec))>
%assign dwRec.Identifier = tempId
%endif
%closefile initCode
%if !WHITE_SPACE(initCode)
%if stdSSIdx != -1
%openfile tmpBuffer
%endif
%<ifCond>
%<initCode>
%<ifEndCond>
%if stdSSIdx != -1
%closefile tmpBuffer
%assign stdSSBuffer = stdSSBuffer + tmpBuffer
%endif
%endif
%else
%if SLibRemoveZeroInitForDataDefault(dwRec)
%continue
%endif
%if stdSSIdx != -1
%openfile tmpBuffer
%endif
%<ifCond>
%if LibIsDataTypeMultiWordFixpt(dTypeId)
%assign defaultInitialValue = LibGetGroundName(dwRec, tRealPart)
%else
%assign defaultInitialValue = SLibGetDefaultInitialValue(dwRec, tRealPart)
%endif
%assign memsetSuitable = FcnSuitableForMemset(defaultInitialValue, dTypeId, "")
%if symbolicWidth == "1"
%if SLibDWorkIsComplex(dwRec)
%<id>%<fieldsep>%<tRealPart> = %<defaultInitialValue>;
%<id>%<fieldsep>%<tImagPart> = %<defaultInitialValue>;
%else
%<deref>%<id> = %<defaultInitialValue>;
%endif
%elseif !memsetSuitable
%if hasSymbolicWidth || %<symbolicWidth> >= RollThreshold
%assign loopCode = SLibEmitForLoopCounterCode(symbolicWidth, "i")
{
%
% {
%if SLibDWorkIsComplex(dwRec)
%<id>[i]%<fieldsep>%<tRealPart> = %<defaultInitialValue>;
%<id>[i]%<fieldsep>%<tImagPart> = %<defaultInitialValue>;
%else
%<deref>%<id>[i] = %<defaultInitialValue>;
%endif
}
}
%else
%foreach initIdx = %<symbolicWidth>
%if SLibDWorkIsComplex(dwRec)
%<id>[%<initIdx>]%<fieldsep>%<tRealPart> = %<defaultInitialValue>;
%<id>[%<initIdx>]%<fieldsep>%<tImagPart> = %<defaultInitialValue>;
%else
%<deref>%<id>[%<initIdx>] = %<defaultInitialValue>;
%endif
%endforeach
%endif
%else
%if hasSymbolicWidth
%assign memsetWidth = "(" + symbolicWidth + ")"
%else
%assign memsetWidth = "%<symbolicWidth>U"
%endif
%if SLibDWorkIsComplex(dwRec)
%assign memsetWidth = "2*%<memsetWidth>"
%endif
%assign dtName = SLibGetRecordContainerBaseTypeName(dwRec)
%assign sanitizedInitValue = ...
FcnCastValueForMemsetUse(dTypeId, defaultInitialValue)
(void) %<LibGenMemFcnCall("memset", "%<addressof>%<id>", ...
sanitizedInitValue, "%<memsetWidth>*sizeof(%<dtName>)")>;
%endif
%<ifEndCond>
%if stdSSIdx != -1
%closefile tmpBuffer
%assign stdSSBuffer = stdSSBuffer + tmpBuffer
%endif
%endif
%if stdSSIdx != -1 && !WHITE_SPACE(stdSSBuffer)
%<LibAddToSystemField(System[stdSSIdx],"TempInitBuffer",...
stdSSBuffer)>
%endif
%endwith
%endforeach
%closefile rtnBuffer
%<FcnCacheStandaloneSubsyInitFromTempBuffers(comment)>
%if !WHITE_SPACE(rtnBuffer)
%return "/n" + comment + "/n" + rtnBuffer
%else
%return ""
%endif
%endfunction
%function SLibInitStatesWithExternalStorage(usingStatic) Output
%if !SLibExportedGlobalDWorkIsEmpty()
%<FcnInitStatesWithExternalStorage("ExportedGlobal", ...
"/* exported global states */", ".", "&", "")>
%endif
%if !SLibCustomDataBufferIsEmpty("Definitions")
%<FcnInitStatesWithExternalStorage("Custom", ...
"/* custom states */", ".", "&", "")>
%endif
%endfunction
%function CacheStandaloneSystemDWorkInfo()
%assign counter = 0
%assign rootSSIdx = GetBaseSystemIdx()
%assign totalNumSys = GetNumSystemsForCodeGen()
%createrecord stdSSBuf {}
%foreach sysIdx = totalNumSys
%assign thisIdx = totalNumSys - 1 - sysIdx
%if thisIdx == rootSSIdx || System[thisIdx].StandaloneSubsystem
%if !(ISFIELD(System[thisIdx], "IndexInStandaloneSubsystemArray"))
%addtorecord System[thisIdx] IndexInStandaloneSubsystemArray counter
%endif
%addtorecord stdSSBuf DWorkBuff { ...
SystemIdx %<thisIdx>; ...
DWorkType ""; ...
DWorkVar ""; ...
haveFloat 0; ...
needMemset 0; ...
forbidMemset 0; ...
initBuffer ""; ...
emitMsgInit 0; ...
msgInitBuffer "" ...
emitStringInit 0; ...
stringInitBuffer "" ...
}
%if IsModelReferenceTarget() && (! GenerateClassInterface)
%assign baseSystem = ::CompiledModel.System[GetBaseSystemIdx()]
%assign varGroupType = FcnSysVarGroupType(baseSystem,"DWork")
%assign stdSSBuf.DWorkBuff[counter].DWorkType = varGroupType
%if IsModelRefScalableBuild()
%assign stdSSBuf.DWorkBuff[counter].DWorkVar = ...
FcnSysVarGroupNonreusedName(baseSystem, "DWork")
%else
%assign stdSSBuf.DWorkBuff[counter].DWorkVar = "localDW"
%endif
%elseif IsModelReferenceTarget() && GenerateClassInterface
%assign stdSSBuf.DWorkBuff[counter].DWorkType = "%<::tDWorkType>"
%assign stdSSBuf.DWorkBuff[counter].DWorkVar = "%<::tDWork>"
%elseif thisIdx == rootSSIdx
%assign stdSSBuf.DWorkBuff[counter].DWorkType = "%<::tDWorkType>"
%assign stdSSBuf.DWorkBuff[counter].DWorkVar = "%<LibGetDWorkStruct()>"
%else
%assign varGroupType = FcnSysVarGroupType(System[thisIdx],"DWork")
%assign stdSSBuf.DWorkBuff[counter].DWorkType = varGroupType
%assign stdSSBuf.DWorkBuff[counter].DWorkVar = ...
FcnSysVarGroupNonreusedName(System[thisIdx],"DWork")
%endif
%assign counter = counter+1
%endif
%endforeach
%assert((! IsModelReferenceTarget()) || (counter == 1))
%return stdSSBuf
%endfunction
%function SLibGetExtUIdentifier(extInp, idx, reim)
%if extInp.StorageClass == "Auto"
%assign varName = "%<LibGetExternalInputStruct()>%<UQualifier>%<LibGetRecordIdentifier(extInp)>"
%elseif extInp.StorageClass == "ExportedGlobal" || extInp.StorageClass == "ImportedExtern"
%assign varName = LibGetRecordIdentifier(extInp)
%elseif extInp.StorageClass == "ImportedExternPointer"
%assign varName = "(*%<LibGetRecordIdentifier(extInp)>)"
%endif
%assign width = LibGetRecordWidth(extInp)
%if width != 1
%assign varName = "%<varName>[%<idx>]"
%endif
%if LibGetRecordIsComplex(extInp)
%assign varName = "%<varName>."
%elseif reim == "im"
%assign errTxt = "Try to generate complex variable name but Inport block is set to accept real signal"
%<LibReportFatalError(errTxt)>
%else
%assign reim =""
%endif
%assign varName = "%<varName>%<reim>"
%return varName
%endfunction
%function LocalInitDworkVector(stdSSBuf, stdIdx, ...
initCount, name, initValue, isComplex, ppIf, ppFi, ...
aNdContainerTypeIdx) void
%assert TYPE(initCount) == "String"
%assign twoParts = IDNUM(initCount)
%assign isSymbolic = !ISEMPTY(twoParts[0])
%assign dWorkAccess = name
%if aNdContainerTypeIdx >= 0
%assign dWorkNumDims = LibCGTypeNumDimensions(aNdContainerTypeIdx)
%assign dWorkAccess = LibGetAddressOfFirstElement(name, dWorkNumDims)
%endif
%openfile tmpBuf
%<ppIf>
%if "%<initCount>" == "1"
%if %<isComplex>
%<name>.%<tRealPart> = %<initValue>;
%<name>.%<tImagPart> = %<initValue>;
%else
%<name> = %<initValue>;
%endif
%elseif isSymbolic || %<initCount> >= RollThreshold
%assign loopCode = SLibEmitForLoopCounterCode(initCount, "i")
{
%
% {
%if %<isComplex>
%<dWorkAccess>[i].%<tRealPart> = %<initValue>;
%<dWorkAccess>[i].%<tImagPart> = %<initValue>;
%else
%<dWorkAccess>[i] = %<initValue>;
%endif
}
}
%else
%foreach initIdx = %<initCount>
%if %<isComplex>
%<dWorkAccess>[%<initIdx>].%<tRealPart> = %<initValue>;
%<dWorkAccess>[%<initIdx>].%<tImagPart> = %<initValue>;
%else
%<dWorkAccess>[%<initIdx>] = %<initValue>;
%endif
%endforeach
%endif
%<ppFi>
%closefile tmpBuf
%assign stdSSBuf.DWorkBuff[stdIdx].initBuffer = ...
stdSSBuf.DWorkBuff[stdIdx].initBuffer + tmpBuf
%return stdSSBuf
%endfunction
%function SLibInitDWorkHelper(stdSSBuf, stdIdx, sysIdx, cross, dwRec, ignoreInitInStart, ppIf, ppFi) void
%if dwRec.StorageClass != "Auto" || SLibOmitRecord(dwRec) ...
|| 1 == dwRec.IsLocalScratchDWork
%return stdSSBuf
%endif
%if ISFIELD(dwRec,"Name") && FEVAL("strncmp", dwRec.Name, "msgQid", 6) ...
&& !::CompiledModel.MsgUsingIRBasedCG
%assign stdSSBuf.DWorkBuff[stdIdx].emitMsgInit = 1
%assign qname = SLibCG_GetVarGroupElementPath(dwRec.VarGroupIdx,...
sysIdx, cross)
%assign isComplex = SLibDWorkIsComplex(dwRec)
%assign msgStorageId = dwRec.InitialValue
%openfile tBuf
%if IsModelReferenceSimTarget() && ::CompiledModel.MessageModelRefSupport
%assign simstruct = RTMGet("MdlRefSfcnS")
%<qname> = slmsg_ssGetMsgQueueId(%<simstruct>, %<msgStorageId>);
%else
%<qname> = %<msgStorageId>;
%endif
%closefile tBuf
%assign stdSSBuf.DWorkBuff[stdIdx].msgInitBuffer = ...
stdSSBuf.DWorkBuff[stdIdx].msgInitBuffer + tBuf
%endif
%assign DataTypeIdx = SLibDWorkDataTypeId(dwRec)
%assign dwWidth = SLibDWorkWidth(dwRec)
%assign curDataTypeId = LibGetDataTypeIdAliasedThruToFromId(DataTypeIdx)
%if IsModelReferenceSimTarget() || ::isRAccel
%if LibIsStringDataType(curDataTypeId) || LibIsStructDataType(curDataTypeId)
%assign name = SLibCG_GetVarGroupElementPath(dwRec.VarGroupIdx, sysIdx, cross)
%openfile tBuf
%<SlibInitStringData(curDataTypeId, name, dwWidth)>
%closefile tBuf
%if !ISEMPTY(tBuf)
%assign stdSSBuf.DWorkBuff[stdIdx].emitStringInit = 1
%assign stdSSBuf.DWorkBuff[stdIdx].stringInitBuffer = stdSSBuf.DWorkBuff[stdIdx].stringInitBuffer + tBuf
%endif
%endif
%endif
%if SLibRemoveZeroInitForDataDefault(dwRec)
%return stdSSBuf
%endif
%assign curMemsetToZeroSuffice = FcnMemsetToZeroInitSuffice(curDataTypeId)
%if curMemsetToZeroSuffice && !stdSSBuf.DWorkBuff[stdIdx].forbidMemset
%if SLibZeroMemory("DWork")
%assign stdSSBuf.DWorkBuff[stdIdx].needMemset = 1
%endif
%return stdSSBuf
%endif
%if (curDataTypeId == tSS_DOUBLE || curDataTypeId == tSS_SINGLE)
%if InitFltsAndDblsToZero
%if ignoreInitInStart || !dwRec.InitInStart
%assign name = SLibCG_GetVarGroupElementPath(dwRec.VarGroupIdx, ...
sysIdx, cross)
%assign initCount = LibGetRecordSymbolicWidth(dwRec)
%assign isComplex = SLibDWorkIsComplex(dwRec)
%assign defaultInitialValue = SLibGetDefaultInitialValueFromId(DataTypeIdx)
%assign stdSSBuf.DWorkBuff[stdIdx].haveFloat = 1
%assign dWorkContainerTypeIdx = -1
%if SLibIsContainerCGTypeND(dwRec)
%assign dWorkContainerTypeIdx = dwRec.ContainerCGTypeIdx
%endif
%assign block = System[dwRec.SigSrc[0]].Block[dwRec.SigSrc[2]]
%with block
%if (dwRec.Origin == "RWORK") && (NumRWorkDefines > 0)
%foreach initIdx = NumRWorkDefines
%assign fieldname = name + ".%"
%assign initCount = "%"
%assign stdSSBuf = LocalInitDworkVector(stdSSBuf, stdIdx, ...
initCount, fieldname, defaultInitialValue, isComplex, ...
ppIf, ppFi, dWorkContainerTypeIdx)
%endforeach
%return stdSSBuf
%endif
%endwith
%assign stdSSBuf = LocalInitDworkVector(stdSSBuf, stdIdx, ...
initCount, name, defaultInitialValue, isComplex, ppIf, ppFi, ...
dWorkContainerTypeIdx)
%endif
%elseif SLibZeroMemory("DWork") && !stdSSBuf.DWorkBuff[stdIdx].forbidMemset
%assign stdSSBuf.DWorkBuff[stdIdx].needMemset = 1
%endif
%elseif SLibZeroMemory("DWork") && !stdSSBuf.DWorkBuff[stdIdx].forbidMemset
%assign stdSSBuf.DWorkBuff[stdIdx].needMemset = 1
%endif
%return stdSSBuf
%endfunction
%function SLibInitDWork(stdSSBuf) void
%if ForceBlockIOInitOptimize
%assert(!IsModelReferenceTarget())
%assign stdSSBuf = SLibInitDWorkOld(stdSSBuf)
%return stdSSBuf
%endif
%foreach dwIdx = ::CompiledModel.DWorks.NumDWorks
%assign dwRec = ::CompiledModel.DWorks.DWork[dwIdx]
%if SLibOmitRecord(dwRec) || 1 == dwRec.IsLocalScratchDWork
%continue
%endif
%if dwRec.SharedLocalDSMForHasBeenInit
%continue
%endif
%if (ISFIELD(dwRec, "UseAccessFunctions") && dwRec.UseAccessFunctions == 1) || ...
SLibDataRecordIsInCoderGroup(dwRec)
%continue
%endif
%assign idx = SLibGetSystemAndCallSideIndex(dwRec)
%if SigSrcLivesInStandaloneSS(idx)
%assign baseSystemIdx = StandaloneParentSysIdxOfDataRec(dwRec)
%else
%assign baseSystemIdx = GetBaseSystemIdx()
%endif
%assign stdIdx = System[baseSystemIdx].IndexInStandaloneSubsystemArray
%assign DataTypeIdx = SLibDWorkDataTypeId(dwRec)
%if SLibShouldForbidMemsetToZeroForRecord(dwRec) || LibIsDataTypeMessage(DataTypeIdx) || ...
CGMODEL_ACCESS("CGModel.isGpuCodeGen") == TLC_TRUE
%assign stdSSBuf.DWorkBuff[stdIdx].forbidMemset = 1
%endif
%endforeach
%foreach dwIdx = ::CompiledModel.DWorks.NumDWorks
%assign dwRec = ::CompiledModel.DWorks.DWork[dwIdx]
%if SLibOmitRecord(dwRec) || 1 == dwRec.IsLocalScratchDWork
%continue
%endif
%if dwRec.SharedLocalDSMForHasBeenInit
%continue
%endif
%if (ISFIELD(dwRec, "UseAccessFunctions") && dwRec.UseAccessFunctions == 1) || ...
SLibDataRecordIsInCoderGroup(dwRec)
%continue
%endif
%assign idx = SLibGetSystemAndCallSideIndex(dwRec)
%if SigSrcLivesInStandaloneSS(idx)
%assign baseSystemIdx = StandaloneParentSysIdxOfDataRec(dwRec)
%else
%assign baseSystemIdx = GetBaseSystemIdx()
%endif
%assign cross = System[baseSystemIdx].CrossNoArgFcnBound
%assign vcRecord = SLibGetDataInlineVariantNetConditions(dwRec)
%assign vcRecord = FcnAddSharedDataInitProtection(dwRec, vcRecord)
%assign ifCond = vcRecord.ifCond
%assign ifEndCond = vcRecord.endIfCond
%assign stdIdx = System[baseSystemIdx].IndexInStandaloneSubsystemArray
%assign stdSSBuf = SLibInitDWorkHelper(stdSSBuf, stdIdx, baseSystemIdx, cross, dwRec, TLC_FALSE, ifCond, ifEndCond)
%endforeach
%if stdSSBuf.DWorkBuff[0].needMemset && !SLibIsSelfStructured()
%assign baseSystemIdx = GetBaseSystemIdx()
%<SLibAccessArgHelper(System[baseSystemIdx].Interface.DWorkArgDef,"","")>
%endif
%return stdSSBuf
%endfunction
%function SLibMemsetDWorkInSelf() void
%assert SLibIsSelfStructured()
%assign selfCoderGroupIdx = SLibGetSelfCoderDataGroupIndex()
%assign selfCoderGroup = ::CompiledModel.CoderDataGroup[selfCoderGroupIdx]
%if !selfCoderGroup.IsSynthesized
%return ""
%endif
%openfile tempBuf
%if (!(ForceBlockIOInitOptimize && IsModelReferenceTarget()) && ...
!GenerateClassInterface)
%assign numSys = GetNumSystemsForCodeGen()
%assign baseSysIdx = GetBaseSystemIdx()
%assign numDWorks = ::CompiledModel.DWorks.NumDWorks
%foreach sysIdx = numSys
%assign currSys = System[sysIdx]
%assign currModIdx = currSys.CGIRModuleIdx
%assign currMod = ::CompiledModel.RTWCGModules.RTWCGModule[currModIdx]
%if !currMod.SimplifiedInterface
%continue
%endif
%if ISFIELD(currSys, "DWorkVarGroupIndex")
%assign dwVGIdx = currSys.DWorkVarGroupIndex[0]
%assert dwVGIdx >= 0
%assign dwVarGroup = ::CompiledModel.VarGroups.VarGroup[dwVGIdx]
%assign dwParentIdx = dwVarGroup.ParentVarGroupIdx
%assert dwParentIdx >= 0
%assign dwParentVG = ::CompiledModel.VarGroups.VarGroup[dwParentIdx]
%assert (dwParentVG.Category == "HierarchicalCoderData" && ...
dwParentVG.CoderDataGroupIndex == selfCoderGroupIdx)
%assign dwRec = ""
%assign needMemset = TLC_FALSE
%foreach dwIdx = numDWorks
%assign currDWRec = ::CompiledModel.DWorks.DWork[dwIdx]
%if ISFIELD(currDWRec, "VarGroupIdx") && currDWRec.VarGroupIdx[0] == dwVGIdx
%if ISEMPTY(dwRec)
%assign dwRec = currDWRec
%endif
%assign dtypeIdx = SLibDWorkDataTypeId(currDWRec)
%assign curDataTypeId = LibGetDataTypeIdAliasedThruToFromId(dtypeIdx)
%assign curMemsetToZeroSuffice = FcnMemsetToZeroInitSuffice(curDataTypeId)
%if curMemsetToZeroSuffice && !SLibOmitRecord(currDWRec)
%assign needMemset = TLC_TRUE
%endif
%if LibCGTypeIsMatrix(dwVarGroup.CGTypeIdx) && !currDWRec.InitInStart
%if currDWRec.Name == "sysIdxToRun"
%continue
%endif
%<LibReportFatalError("Should not be here. Matrix type not handled")>
%endif
%endif
%endforeach
%if !needMemset
%continue
%endif
%if !ISEMPTY(dwRec)
%assign vcRecord = SLibGetDataInlineVariantNetConditions(dwRec)
%else
%assign vcRecord = SLibVariantConditionRecord()
%endif
%assign dwCGTypeIdx = dwVarGroup.CGTypeIdx
%assign dwType = LibCGTypeName(dwCGTypeIdx)
%if LibCGTypeIsMatrix(dwCGTypeIdx)
%continue
%endif
%assign path = SLibCGIRVarGroupPath(dwParentIdx, baseSysIdx, currSys.CrossNoArgFcnBound)
%assign dworkAddr = "&(%<path>%<dwVarGroup.Name>)"
%assign sizeExpr = " sizeof(%<dwType>)"
%if vcRecord.hasConds
%<vcRecord.ifCond>
%endif
(void) %<LibGenMemFcnCall("memset", ...
"(void *) " + "%<dworkAddr>", ...
" 0", "%<sizeExpr>")>;
%if vcRecord.hasConds
%<vcRecord.endIfCond>
%endif
%endif
%endforeach
%endif
%closefile tempBuf
%return tempBuf
%endfunction
%function SLibDumpModelDataInitialization() Output
%assert !::CompiledModel.DWorkAndBlockIOCombined
%assert(!UsingMalloc)
/*
* initialize model vectors and cache them in SimStruct
*/
%assign ptrBlockIOLabel = "#error no valid pointer to BlockIO because it is empty"
%openfile tmpBuf
%if !LibBlockIOStructIsEmpty()
%assign ptrBlockIOLabel = "((void *) &%<LibGetBlockIOStruct()>)"
%if ::CompiledModel.HasSimStructVars == 0
%<RTMSet("BlockIO", ptrBlockIOLabel)>;
%endif
%endif
%assign needMemsetForCombinedDWorkAndBlockIO = SLibInitBlockIO(ptrBlockIOLabel)
%if ::isRAccel
%foreach boIdx = BlockOutputs.NumGlobalBlockOutputs
%assign bo = BlockOutputs.GlobalBlockOutput[boIdx]
%if ISFIELD(bo, "VarGroupIdx")
%assign fullName = SLibGetBlockOutputIdentifierFromRecord(bo, GetBaseSystemIdx())
%assign boDataTypeId = LibGetRecordDataTypeId(bo)
%assign boWidth = LibGetRecordWidth(bo)
%<SlibInitStringData(boDataTypeId, fullName, boWidth)>
%endif
%endforeach
%endif
%closefile tmpBuf
%if !WHITE_SPACE(tmpBuf)
/* block I/O */
{
%<tmpBuf>
}
%endif
%openfile tmpBuf
%if !LibExternalInputsStructIsEmpty()
%<RTMSet("U", "((void*) &%<LibGetExternalInputStruct()>)")>;
%endif
%<SLibInitExternalInputs(TLC_TRUE,0, 0)>/
%closefile tmpBuf
%if !WHITE_SPACE(tmpBuf)
/* external inputs */
{
%<tmpBuf>/
}
%endif
%if !LibExternalOutputsStructIsEmpty()
/* external outputs */
{
%<RTMSet("Y", "&%<LibGetExternalOutputStruct()>")>;
%<SLibInitExternalOutputs(1,0,0)>/
%if ::isRAccel
%foreach idx = ::CompiledModel.ExternalOutputs.NumExternalOutputs
%assign mo = ::CompiledModel.ExternalOutputs.ExternalOutput[idx]
%if ISFIELD(mo, "VarGroupIdx")
%assign modelOutput = LibGetExternalOutputStruct()
%assign fieldAccess = YQualifier
%assign varName = SLibVarGroupElementName(mo.VarGroupIdx[0], mo.VarGroupIdx[1])
%assign fullName = modelOutput + fieldAccess + varName
%assign moDataTypeId = LibGetRecordDataTypeId(mo)
%assign moWidth = LibGetRecordWidth(mo)
%<SlibInitStringData(moDataTypeId, fullName, moWidth)>
%endif
%endforeach
%endif
}
%endif
%if !LibParametersStructIsEmpty() && !FcnParamsAreGlobalStruct()
/* parameters */
%<RTMSet("DefaultParam", "(real_T *) &%<LibGetParametersStruct()>")>;
%endif
%if (NumContStates) > 0
%assign contStateTypeInRTM = FcnGetContStateType()
/* states (continuous)*/
{
%<contStateTypeInRTM> *x = (%<contStateTypeInRTM> *) &%<LibGetContinuousStateStruct()>;
%<RTMSet("ContStates", "x")>;
(void) %<LibGenMemFcnCall("memset", "(void *)x", "0", ...
"sizeof(%<::tContStateType>)")>;
}
%endif
%if !LibDWorkStructIsEmpty()
%assign stdSSBuf = CacheStandaloneSystemDWorkInfo()
%assert(SIZE(stdSSBuf.DWorkBuff, 1) == 1)
/* states (dwork) */
{
%assign stdSSBuf = SLibInitDWork(stdSSBuf)
void *dwork = (void *) &%<LibGetDWorkStruct()>;
%<RTMSet("RootDWork", "dwork")>;
%if !SLibGetUseRTMcgType() && stdSSBuf.DWorkBuff[0].needMemset ...
|| needMemsetForCombinedDWorkAndBlockIO == 1
(void) %<LibGenMemFcnCall("memset", "dwork", " 0", ...
" sizeof(%<::tDWorkType>)")>;
%assign baseSystemIdx = GetBaseSystemIdx()
%<SLibAccessArgHelper(System[baseSystemIdx].Interface.DWorkArgDef,"","")>
%endif
%if stdSSBuf.DWorkBuff[0].haveFloat
%/
%endif
%if stdSSBuf.DWorkBuff[0].emitMsgInit
%/
%endif
%if stdSSBuf.DWorkBuff[0].emitStringInit
%/
%endif
}
%endif
%openfile tmpBuf
%<SLibInitStatesWithExternalStorage(TLC_TRUE)>/
%closefile tmpBuf
%if !WHITE_SPACE(tmpBuf)
%<tmpBuf>/
%endif
%if (ModelIsLinearlyImplicit == "yes")
%assert( !IsModelReferenceTarget() )
%<FcnGenInitMassMatrixPrInRoot()>
%endif
%endfunction
%function SLibDumpTimingInfoRegistration() Output
%assert(!UsingMalloc)
/* timing info */
{
%assign nTs = "NSAMPLE_TIMES"
%assign nTs = SLibIsERTCodeFormat() ? NumRuntimeExportedRates : "NSAMPLE_TIMES"
static time_T mdlPeriod[%<nTs>];
static time_T mdlOffset[%<nTs>];
static time_T mdlTaskTimes[%<nTs>];
static int_T mdlTsMap[%<nTs>];
static int_T mdlSampleHits[%<nTs>];
%if isRSimWithSolverModule
static boolean_T mdlTNextWasAdjustedPtr[%<nTs>];
static int_T mdlPerTaskSampleHits[%<nTs> * %<nTs>];
static time_T mdlTimeOfNextSampleHit[%<nTs>];
%endif
{
int_T i;
for (i = 0; i < %<nTs>; i++) {
mdlPeriod[i] = 0.0;
mdlOffset[i] = 0.0;
mdlTaskTimes[i] = 0.0;
mdlTsMap[i] = i;
%if SLibSingleTasking()
mdlSampleHits[i] = 1;
%endif
}
}
%if !SLibSingleTasking()
mdlSampleHits[0] = 1;
%endif
%<RTMSet("SampleTimePtr", "&mdlPeriod[0]")>;
%<RTMSet("OffsetTimePtr", "&mdlOffset[0]")>;
%<RTMSet("SampleTimeTaskIDPtr", "&mdlTsMap[0]")>;
%<RTMSet("TPtr", "&mdlTaskTimes[0]")>;
%<RTMSet("SampleHitPtr", "&mdlSampleHits[0]")>;
%if isRSimWithSolverModule
%<RTMSet("TNextWasAdjustedPtr", "&mdlTNextWasAdjustedPtr[0]")>;
%<RTMSet("PerTaskSampleHitsPtr", "&mdlPerTaskSampleHits[0]")>;
%<RTMSet("TimeOfNextSampleHitPtr", "&mdlTimeOfNextSampleHit[0]")>;
%endif
}
%if ::CompiledModel.SolverType == "FixedStep"
%if ::CompiledModel.FixedStepOpts.SolverMode == "MultiTasking"
{
static int_T mdlPerTaskSampleHits[%<nTs> * %<nTs>];
(void) %<LibGenMemFcnCall("memset", "(void *)&mdlPerTaskSampleHits[0]", "0", ...
"%<NumRuntimeExportedRates> * %<NumRuntimeExportedRates> * sizeof(int_T)")>;
%<RTMSet("PerTaskSampleHitsPtr", "&mdlPerTaskSampleHits[0]")>;
}
%<RTMSolverSet("SolverMode", "SOLVER_MODE_MULTITASKING")>;
%else
%<RTMSolverSet("SolverMode", "SOLVER_MODE_SINGLETASKING")>;
%endif
%else
%<RTMSolverSet("SolverMode", "SOLVER_MODE_SINGLETASKING")>;
%endif
%endfunction
%function genAbsTolControlSetup() void
%assign zeroArray = FEVAL("zeros", 1, NumContStates)
%assign absTolControl = FEVAL("uint8", zeroArray)
%assign mdlAbsTolControl = ::CompiledModel.VariableStepOpts.AbsTolControl
%if NumContStates > 1
%foreach ix = NumContStates
%assign absTolControl[ix] = mdlAbsTolControl[ix]
%endforeach
%else
%assign absTolControl = mdlAbsTolControl
%endif
%foreach csIdx = ::CompiledModel.ContStates.NumContStates
%assign cs = ::CompiledModel.ContStates.ContState[csIdx]
%assign isMdlRef = FcnOwnerBlkType(cs) == "ModelReference"
%if !isMdlRef
%continue
%endif
%assert(isMdlRef)
%assign blk = System[cs.SigSrc[0]].Block[cs.SigSrc[2]]
%assign intrf = GetModelrefInterface(blk)
%if !EXISTS(intrf.refAbsTolControl)
%continue
%endif
%assert(EXISTS(intrf.refAbsTolControl))
%assign refAbsTolControl = intrf.refAbsTolControl
%assign csparts = cs.Partitions
%foreach csp = csparts.NumPartitions
%assign cstateIndices = csparts.Partition[csp].CStateIndices
%assign nci = SIZE(cstateIndices)[1]
%assign pwidth = csparts.Partition[csp].Width
%assign niter = nci/pwidth
%assign refOffset = 0
%foreach i_iter = niter
%foreach i_x = pwidth
%assign csiIndex = (i_iter*pwidth) + i_x
%if refAbsTolControl[refOffset+i_x] == 1
%assign absTolControl[cstateIndices[csiIndex] ] = FEVAL("uint8", 1)
%endif
%endforeach
%endforeach
%assign refOffset = refOffset + pwidth
%endforeach
%endforeach
%assign absTolControlStr = "static uint8_T absTolControl[%<NumContStates>] = {"
%assign comma = ""
%foreach i_x = NumContStates
%assign absTolControlStr = "%<absTolControlStr>%<comma> %"
%assign comma = ", "
%endforeach
%assign absTolControlStr = "%<absTolControlStr> };"
%return absTolControlStr
%endfunction
%function SLibDumpModelRegRSimSetup() Output
{
static ssSolverInfo slvrInfo;
%if NumContStates > 0
%if (ModelHasProjections == "yes") || (ModelIsLinearlyImplicit == "yes")
static struct _ssSFcnModelMethods3 mdlMethods3;
static struct _ssSFcnModelMethods2 mdlMethods2;
%endif
static boolean_T contStatesDisabled[%<NumContStates>];
%endif
%if SolverType == "VariableStep"
%assign nOutTimes = SIZE(VariableStepOpts.OutputTimes,1)
%assign outTimes = (nOutTimes == 0) ? SLibGetNullDefinitionFromTfl() : "outputTimes"
%assign nDU = SolverResetInfo.NumNonContDerivSignals
%assign dU = (nDU == 0) ? SLibGetNullDefinitionFromTfl() : "nonContDerivSigInfo"
%if NumContStates > 0
static real_T absTol[%<NumContStates>] = {/
%assign comma = ""
%foreach idx = NumContStates
%<comma>%/
%assign comma = ", "
%endforeach
};
%<genAbsTolControlSetup()>
%if NumContStates > 0 && SolverType == "VariableStep"
static real_T contStateJacPerturbBoundMinVec[%<NumContStates>];
static real_T contStateJacPerturbBoundMaxVec[%<NumContStates>];
%endif
%endif
%if NumNonsampledZCs > 0
%assign zcVectorLen = ::CompiledModel.ZCVectorlength
%assign zcAttributes = FEVAL("zeros", 1, zcVectorLen)
%assign zcEvents = FEVAL("zeros", 1, zcVectorLen)
%foreach idx = ZcRec. NumBlkZcRecs
%assign blkZcRec = ZcRec.BlkZcRec[idx]
%foreach zcsIdx = blkZcRec.NumZcSignalInfos
%assign zcs = blkZcRec.ZcSignalInfo[zcsIdx]
%assign needEvent = zcs.NeedsEvent
%assign needsSolverReset = zcs.NeedsSolverReset
%assign zcDir = zcs.ZcEventType
%assign zcVectorIndices = zcs.ZcVectorIndices
%assign zcWidth = zcs.Width
%assign jdx = 0
%foreach zcVectorIdx = SIZE(zcVectorIndices)[1]
%if jdx == zcWidth
%assign jdx = 0
%endif
%if zcs.ZcSignalType == "Hybrid"
%assign isDisc = zcs.IsElementDisc[jdx]
%elseif zcs.ZcSignalType == "Continuous"
%assign isDisc = 0
%else
%assign isDisc = 1
%endif
%if zcVectorLen == 1
%assign zcAttributes = "%<SLibGetZCAttributes(isDisc, needEvent, zcDir)>"
%assign zcEvents = "%<SLibGetZCEvents(needsSolverReset, 0, zcDir)>"
%else
%assign zcAttributes[zcVectorIndices[zcVectorIdx]] = SLibGetZCAttributes(isDisc, needEvent, zcDir)
%assign zcEvents[zcVectorIndices[zcVectorIdx]] = SLibGetZCEvents(needsSolverReset, 0, zcDir)
%endif
%assign jdx = jdx + 1
%endforeach
%endforeach
%endforeach
%assign comma = ""
static uint8_T zcAttributes[%<zcVectorLen>] = {/
%if zcVectorLen == 1
%<zcAttributes>/
%else
%foreach idx = zcVectorLen
%<comma>%/
%assign comma = ", "
%endforeach
%endif
};
%if ZcRec.OptimalSolverResetCausedByZc > 0
%assign comma = ""
static uint8_T zcEvents[%<zcVectorLen>] = {/
%if zcVectorLen == 1
%<zcEvents>/
%else
%foreach idx = zcVectorLen
%<comma>%/
%assign comma = ", "
%endforeach
%endif
};
%endif
%endif
%if nOutTimes > 0
static real_T %<outTimes>[%<nOutTimes>] = {/
%assign comma = ""
%foreach idx = nOutTimes
%<comma>%/
%assign comma = ", "
%endforeach
};
%endif
%if nDU > 0
%assign codebuf = ""
static ssNonContDerivSigInfo %<dU>[%<nDU>] = {
%assign comma = ""
%assign numSigs = SIZE(SolverResetInfo.NonContDerivSignal,1)
%assign arrayIdx = 0
%foreach idx = numSigs
%assign nonContSig = SolverResetInfo.NonContDerivSignal[idx]
%if ISFIELD(nonContSig,"MdlRefInfo")
%assign mdlRefInfo = nonContSig.MdlRefInfo
%assign mSysIdx = mdlRefInfo[0][0]
%assign bIdx = mdlRefInfo[0][1]
%assign instIdx = mdlRefInfo[0][2]
%assign port = mdlRefInfo[0][3]
%assign blk = System[mSysIdx].Block[bIdx]
%assign name = blk.ParamSettings.ReferencedModelName
%assign mangleName = FcnGetNoncontMangledName(name, mSysIdx, ...
bIdx, instIdx)
%foreach subIdx = nonContSig.NumMdlRefNonContSigs
%<comma>{0, %<SLibGetNullDefinitionFromTfl">SLibGetNullDefinitionFromTfl()>, %<SLibGetNullDefinitionFromTfl">SLibGetNullDefinitionFromTfl()>}
%openfile declbuf
%<dU>[%<arrayIdx>].sizeInBytes = ...
mr_%<mangleName>nonContOutputArray[%<port>][%<subIdx>].sizeInBytes;
%<dU>[%<arrayIdx>].pCurrVal = ...
(char *)mr_%<mangleName>nonContOutputArray[%<port>][%<subIdx>].currVal;
%closefile declbuf
%assign codebuf = codebuf + declbuf
%assign comma = ", "
%assign arrayIdx = arrayIdx + 1
%endforeach
%else
%assign sigSrc = nonContSig.SigSrc
%assign startEl = nonContSig.StartEl
%assign regLen = nonContSig.RegionLen
%assign idNum = IDNUM(sigSrc)
%assert (idNum[0] == "B")
%assign bo = BlockOutputs.GlobalBlockOutput[idNum[1]]
%assert (LibGetRecordWidth(bo) >= regLen)
%assert (LibGetRecordWidth(bo) > startEl)
%assert (bo.Invariant == "no")
%if ISFIELD(nonContSig, "ForEachSSIterIndices")
%assign ::UseConstantForVarGroupIdx = TLC_TRUE
%assign ::VarGroupIndexVector = nonContSig.ForEachSSIterIndices
%assign ::VarGroupIndexVectorSize = SIZE(::VarGroupIndexVector, 1)
%assign ::VarGroupIndexVectorIdx = ::VarGroupIndexVectorSize - 1
%endif
%assign name = SLibGetBlockOutputIdentifierFromRecord(bo,NumSystems-1)
%if ISFIELD(nonContSig, "ForEachSSIterIndices")
%assign ::UseConstantForVarGroupIdx = TLC_FALSE
%assign ::VarGroupIndexVectorIdx = ::VarGroupIndexVectorSize - 1
%endif
%assign opW = (LibGetRecordWidth(bo) == 1) ? "" : "[%<startEl>]"
%assign addr = "&%<name>%<opW>"
%assign dType = SLibGetRecordContainerTypeName(bo)
%assign sizeInBytes = "%<regLen>*sizeof(%<dType>)"
%<comma>{ %<sizeInBytes>, (char*)(%<addr>), %<SLibGetNullDefinitionFromTfl()> }
%assign comma = ", "
%assign arrayIdx = arrayIdx + 1
%endif
%endforeach
};
%<codebuf>
%endif
%if NumContStates > 0 && SolverType == "VariableStep"
/* Initialize cont state perturbation bound */
{
int i;
for (i = 0; i < %<NumContStates>; ++i){
contStateJacPerturbBoundMinVec[i] = 0;
contStateJacPerturbBoundMaxVec[i] = rtGetInf();
}
}
%endif
%if NumContStates > 0
%<RTMSolverSet("SolverRelTol", "%<VariableStepOpts.RelTol>")>;
%endif
%<RTMSet("StepSize", "%<VariableStepOpts.InitialStep>")>;
%<RTMSolverSet("MinStepSize", "%<VariableStepOpts.MinStep>")>;
%<RTMSolverSet("MaxNumMinSteps", "%<VariableStepOpts.MaxNumMinSteps>")>;
%assign minStepErr = ISEQUAL(VariableStepOpts.MinStepViolatedError,"yes")
%<RTMSolverSet("MinStepViolatedError", "%<minStepErr>")>;
%<RTMSolverSet("MaxStepSize", "%<VariableStepOpts.MaxStep>")>;
%<RTMSolverSet("SolverMaxOrder", "%<VariableStepOpts.MaxOrder>")>;
%<RTMSolverSet("SolverRefineFactor", "%<VariableStepOpts.Refine>")>;
%<RTMSet("OutputTimes", "%<outTimes>")>;
%<RTMSet("NumOutputTimes", "%<nOutTimes>")>;
%if VariableStepOpts.OutputTimesOption == "specified"
%<RTMSet("OutputTimesOnly", "1")>;
%else
%<RTMSet("OutputTimesOnly", "0")>;
%endif
%<RTMSet("OutputTimesIndex", "0")>;
%<RTMSet("ZCCacheNeedsReset", "%<SolverResetInfo.ZCCacheNeedsReset>")>;
%<RTMSet("DerivCacheNeedsReset", "%<SolverResetInfo.DerivCacheNeedsReset>")>;
%<RTMSet("NumNonContDerivSigInfos", "%<nDU>")>;
%<RTMSet("NonContDerivSigInfos", "%<dU>")>;
%endif
%<RTMSet("SolverInfo", "&slvrInfo")>;
%<RTMSolverSet("SolverName", "/"%<Solver>/"")>;
%assign isVarStepSolver = ISEQUAL(SolverType,"VariableStep")
%<RTMSolverSet("VariableStepSolver", "%<isVarStepSolver>")>;
%assign consCheck = ISEQUAL(SolverConsistencyChecking,"yes")
%<RTMSet("SolverConsistencyChecking", "%<consCheck>")>;
%assign adapZc = ISEQUAL(SolverZeroCrossDetection,"Adaptive")
%<RTMSet("SolverAdaptiveZcDetection", "%<adapZc>")>;
%assign robustReset = ISEQUAL(SolverResetMethod,"robust")
%<RTMSet("SolverRobustResetMethod", "%<robustReset>")>;
%assign updateJacobianAtReset = ISEQUAL(SolverUpdateJacobianAtReset,"yes")
%if updateJacobianAtReset
%<RTMuSet("SolverUpdateJacobianAtReset", "true")>;
%endif
%if SolverType == "VariableStep" && NumContStates > 0
%<RTMSolverSet("AbsTolVector", "absTol")>;
%<RTMSolverSet("AbsTolControlVector", "absTolControl")>;
%<RTMSolverSet("SolverAbsTol_Obsolete", "absTol")>;
%<RTMSolverSet("SolverAbsTolControl_Obsolete", "absTolControl")>;
%<RTMSolverSet("JacobianPerturbationBoundsMinVec", "contStateJacPerturbBoundMinVec")>;
%<RTMSolverSet("JacobianPerturbationBoundsMaxVec", "contStateJacPerturbBoundMaxVec")>;
%endif
%assign hasProj = ISEQUAL(ModelHasProjections, "yes") && (NumContStates > 0)
%assign isLinearlyImplicit = ISEQUAL(ModelIsLinearlyImplicit, "yes")
%<RTMSet("SolverStateProjection", "%<hasProj>")>;
%if hasProj || isLinearlyImplicit
(void) %<LibGenMemFcnCall("memset", "(void *)&mdlMethods2", "0", ...
"sizeof(mdlMethods2)")>;
%<RTMSet("ModelMethods2", "&mdlMethods2")>;
(void) %<LibGenMemFcnCall("memset", "(void *)&mdlMethods3", "0", ...
"sizeof(mdlMethods3)")>;
%<RTMSet("ModelMethods3", "&mdlMethods3")>;
%if hasProj
%<RTMSet("ModelProjection", "MdlProjection")>;
%endif
%if isLinearlyImplicit
%<RTMSet("MassMatrixType", "(ssMatrixType)%<ModelMassMatrixType>")>;
%<RTMSet("MassMatrixNzMax", "%<ModelMassMatrixNzMax>")>;
%<RTMSet("ModelMassMatrix", "MdlMassMatrix")>;
%<RTMSet("ModelForcingFunction", "MdlForcingFunction")>;
%endif
%endif
%<RTMSolverSet("SolverMassMatrixType", "(ssMatrixType)%<ModelMassMatrixType>")>;
%<RTMSolverSet("SolverMassMatrixNzMax", "%<ModelMassMatrixNzMax>")>;
%<RTMSet("ModelOutputs", "MdlOutputs")>;
%<RTMSet("ModelLogData", "rt_UpdateTXYLogVars")>;
%<RTMSet("ModelLogDataIfInInterval", "rt_UpdateTXXFYLogVars")>;
%<RTMSet("ModelUpdate", "MdlUpdate")>;
%if NumContStates > 0
%<RTMSet("ModelDerivatives", "MdlDerivatives")>;
%endif
%if NumNonsampledZCs > 0
%<RTMSet("SolverZcSignalAttrib", "zcAttributes")>;
%if ZcRec.OptimalSolverResetCausedByZc > 0
%<RTMSet("SolverZcEventsVector", "zcEvents")>;
%endif
%<RTMSet("SolverNumZcSignals", "%<ZCVectorlength>")>;
%<RTMSet("ModelZeroCrossings", "MdlZeroCrossings")>;
%<RTMSolverSet("SolverConsecutiveZCsStepRelTol", "%<VariableStepOpts.ConsecutiveZCsStepRelTol>")>;
%<RTMSolverSet("SolverMaxConsecutiveZCs", "%<VariableStepOpts.MaxConsecutiveZCs>")>;
%<RTMSolverSet("SolverConsecutiveZCsError", "%<VariableStepOpts.ConsecutiveZCsError>")>;
%<RTMSolverSet("SolverMaskedZcDiagnostic", "%<VariableStepOpts.MaskedZcDiagnostic>")>;
%<RTMSolverSet("SolverIgnoredZcDiagnostic", "%<VariableStepOpts.IgnoredZcDiagnostic>")>;
%if adapZc
%<RTMSolverSet("SolverZcThreshold","%<VariableStepOpts.ZcThreshold>")>;
%endif
%endif
%if NumContStates > 0 && isVarStepSolver
%<RTMSolverSet("SolverMaxConsecutiveMinStep", "%<VariableStepOpts.MaxConsecutiveMinStep>")>;
%<RTMSolverSet("SolverShapePreserveControl", "%<VariableStepOpts.ShapePreserveCtl>")>;
%endif
%<RTMSet("TNextTid","INT_MIN")>;
%<RTMSet("TNext", LibRealNonFinite("-inf"))>;
%<RTMSetSolverNeedsReset()>;
%<RTMSet("NumNonsampledZCs", "%<NumNonsampledZCs>")>;
%if NumContStates > 0
%<RTMSet("ContStateDisabled", "contStatesDisabled")>;
%endif
%if NumContStates > 0 && isVarStepSolver
%<RTMSolverSet("SolverMaxConsecutiveMinStep", "%<VariableStepOpts.MaxConsecutiveMinStep>")>;
%endif
%if isLinearlyImplicit
/* global mass matrix */
{
int_T *ir = %<LibGetMassMatrixGlobalIr()>;
int_T *jc = %<LibGetMassMatrixGlobalJc()>;
real_T *pr = %<LibGetMassMatrixGlobalPr()>;
%<RTMSet("MassMatrixIr", "ir")>;
%<RTMSet("MassMatrixJc", "jc")>;
%<RTMSet("MassMatrixPr", "pr")>;
(void) %<LibGenMemFcnCall("memset", "(void *)ir", "0", ...
"%<ModelMassMatrixNzMax>*sizeof(int_T)")>;
(void) %<LibGenMemFcnCall("memset", "(void *)jc", "0", ...
"(%<NumContStates>+1)*sizeof(int_T)")>;
(void) %<LibGenMemFcnCall("memset", "(void *)pr", "0", ...
"%<ModelMassMatrixNzMax>*sizeof(real_T)")>;
}
%endif
}
%endfunction
%function SLibGetSysRanBCDWork(dwIdx) void
%assign dwRec = ::CompiledModel.DWorks.DWork[dwIdx]
%assign block = System[dwRec.SigSrc[0]].Block[dwRec.SigSrc[2]]
%assert (block.Type == "SubSystem")
%createrecord optionalArgs { ...
IsMode TLC_FALSE ...
StartIdx 0 ...
DotName "" ...
Name SLibGetNameOfSubsysRanBCDWork() ...
}
%with FcnLoopInfo("", "", 0)
%assign dwork = FcnNonRollingDWork(dwRec, dwIdx, SLibDWorkWidth(dwRec), optionalArgs)
%endwith
%return dwork
%endfunction
%function SLibDumpExtModeReg(bEmitReg, bEmitInit) Output
%if EXISTS("ExtMode") && ExtMode == 1
%assign sysRanDWorkLen = SIZE(::CompiledModel.SubsystemRanBC.SysRanDWork, 1)
%assign needsAlwaysEnabled = TLC_FALSE
%assign needsAlwaysDisabled = TLC_FALSE
%openfile buf
%assign contextSysVector = ::CompiledModel.SubsystemRanBC.ContextSysIdx
%assign sysRanDWork = ::CompiledModel.SubsystemRanBC.SysRanDWork
%foreach i = sysRanDWorkLen
%assign dwIdx = sysRanDWork[contextSysVector[i]]
%if (dwIdx > -1)
%assign dwRec = ::CompiledModel.DWorks.DWork[dwIdx]
%if ISFIELD(dwRec, "VarGroupIdx")
%with ::CompiledModel.System[GetBaseSystemIdx()]
%assign sysDWork = SLibGetSysRanBCDWork(dwIdx)
%endwith
%assert (dwRec.Name == "SubsysRanBC")
%assign sigAddr = "(sysRanDType *)&"+ sysDWork
%else
%assign sigAddr = "&rtAlwaysDisabled"
%assign needsAlwaysDisabled = TLC_TRUE
%endif
%else
%assign sigAddr = "&rtAlwaysEnabled"
%assign needsAlwaysEnabled = TLC_TRUE
%endif
%if UsingMalloc
((const sysRanDType**)rteiGetSubSystemActiveVectorAddresses(%<RTMGet("RTWExtModeInfo")>))[%<i>] = %<sigAddr>;
%else
systemRan[%<i>] = %<sigAddr>;
%endif
%endforeach
%closefile buf
{
%if bEmitInit
%if needsAlwaysEnabled
static const sysRanDType rtAlwaysEnabled = SUBSYS_RAN_BC_ENABLE;
%endif
%if needsAlwaysDisabled
static const sysRanDType rtAlwaysDisabled = SUBSYS_RAN_BC_DISABLE;
%endif
%endif
%if bEmitReg
%if UsingMalloc
RTWExtModeInfo *rt_ExtModeInfo = ...
(RTWExtModeInfo *) malloc(sizeof(RTWExtModeInfo));
const sysRanDType **systemRan = (const sysRanDType **)malloc( %<sysRanDWorkLen> * sizeof(sysRanDType *) );
%<RTMChkMemAndReturnIfErr("rt_ExtModeInfo")>;
%<RTMChkMemAndReturnIfErr("systemRan")>;
%else
static RTWExtModeInfo rt_ExtModeInfo;
static const sysRanDType *systemRan[%<sysRanDWorkLen>];
%endif
%assign amps = UsingMalloc ? "" : "&"
%assign rteiO = "%<amps>rt_ExtModeInfo"
%if ::isRAccel
gblRTWExtModeInfo = %<rteiO>;
%endif
%<RTMSet("RTWExtModeInfo", "%<rteiO>")>;
rteiSetSubSystemActiveVectorAddresses(%<rteiO>, systemRan);
%endif
%if bEmitInit
%<buf>
%endif
%if bEmitInit
%assign amps = UsingMalloc ? "" : "&"
%assign rteiO = "%<amps>rt_ExtModeInfo"
rteiSetModelMappingInfoPtr(%<RTMGet("RTWExtModeInfo")>, ...
&%<RTMGet("ModelMappingInfo")>);
rteiSetChecksumsPtr(%<RTMGet("RTWExtModeInfo")>, ...
%<RTMGet("Checksums")>);
rteiSetTPtr(%<RTMGet">RTMGet("RTWExtModeInfo")>, %<RTMGet">RTMGet("TPtr")>);
%endif
}
%endif
%endfunction
%function SLibDumpModelChecksumReg () Output
%<RTMSetIdxed("ChecksumVal", 0, ModelChecksum[0])>;
%<RTMSetIdxed("ChecksumVal", 1, ModelChecksum[1])>;
%<RTMSetIdxed("ChecksumVal", 2, ModelChecksum[2])>;
%<RTMSetIdxed("ChecksumVal", 3, ModelChecksum[3])>;
%endfunction
%function FcnDumpSolverInfoObjectCreation(bEmitReg, bEmitInit) Output
%if GenRTModel
{
/* Setup solver object */
%if UsingMalloc
RTWSolverInfo *rt_SolverInfo = ...
(RTWSolverInfo *) malloc(sizeof(RTWSolverInfo));
%<RTMChkMemAndReturnIfErr("rt_SolverInfo")>;
%else
%if !SLibIsERTCodeFormat()
static RTWSolverInfo rt_SolverInfo;
%endif
%endif
%assign amps = UsingMalloc ? "" : "&"
%if !SLibIsERTCodeFormat() || UsingMalloc
%<RTMSet("RTWSolverInfo", "%<amps>rt_SolverInfo")>;
%endif
%if LibIsContinuous(0)
%assign stptr = "&%<RTMGet("SimTimeStep")>"
%<RTMSolverSet("SimTimeStepPtr", stptr)>;
%endif
%assign tptr = "&%<RTMGet("TPtr")>"
%<RTMSolverSet("TPtr", tptr)>;
%if RTMStepSizeForTIDIsReqFcn(0)
%assign sptr = "&%<RTMGet("StepSize0")>"
%<RTMSolverSet("StepSizePtr", sptr)>;
%elseif RTMStepSizeIsReqFcn()
%assign sptr = "&%<RTMGet("StepSize")>"
%<RTMSolverSet("StepSizePtr", sptr)>;
%endif
%if !SLibIsERTCodeFormat() || NumContStates > 0
%assign dxptr = "&%<RTMGet("dX")>"
%<RTMSolverSet("dXPtr", dxptr)>;
%assign csptr = "(real_T **) &%<RTMGet("ContStates")>"
%<RTMSolverSet("ContStatesPtr", csptr)>;
%assign ncsptr = "&%<RTMGet("NumContStates")>"
%<RTMSolverSet("NumContStatesPtr", ncsptr)>;
%if NumContStates > 0
%<RTMSolverSet("NumPeriodicContStatesPtr", "&%<RTMGet("NumPeriodicContStates")>")>;
%<RTMSolverSet("PeriodicContStateIndicesPtr", "&%<RTMGet("PeriodicContStateIndices")>")>;
%<RTMSolverSet("PeriodicContStateRangesPtr", "&%<RTMGet("PeriodicContStateRanges")>")>;
%endif
%endif
%<RTMSolverSet("ErrorStatusPtr", GetRTMErrorStatusPtr())>;
%if UsingMalloc && GenerateGRTWrapper
%assign mmptr = "&%<RTMGet("RTWRTModelMethodsInfo")>"
%<RTMSolverSet("ModelMethodsPtr", mmptr)>;
%endif
%if (SLibGetModelIsLinearlyImplicit() == "yes")
%assign ir = "%<LibGetMassMatrixGlobalIr()>"
%assign jc = "%<LibGetMassMatrixGlobalJc()>"
%assign pr = "%<LibGetMassMatrixGlobalPr()>"
%<RTMSolverSet("SolverMassMatrixIr", ir)>;
%<RTMSolverSet("SolverMassMatrixJc", jc)>;
%<RTMSolverSet("SolverMassMatrixPr", pr)>;
%endif
%<RTMSolverSet("RTModelPtr", "%<GetSimStructExpr(System[GetBaseSystemIdx()], ::tSimStruct)>")>;
}
%endif
%endfunction
%function LibDumpModelRegistration(usingStatic) Output
%assert(!UsingMalloc)
%assert(!IsModelReferenceTarget())
%<FcnDumpSolverInfoObjectCreation(usingStatic, TLC_TRUE)>/
%<SLibDumpTimingInfoRegistration()>/
%<SLibDumpModelDataInitialization()>/
%<SLibDumpModelMappingInfo()>/
%if ::isRAccel
ssSetIsRapidAcceleratorActive(%<::tSimStruct>, true);
%endif
/* Model specific registration */
%assign rootSSreg = RTMSet("RootSS", RTMGetModelSS())
%if !WHITE_SPACE(rootSSreg)
%<rootSSreg>;
%endif
%assign verStr = RTMSet("Version", "SIMSTRUCT_VERSION_LEVEL2")
%if !WHITE_SPACE(verStr)
%<verStr>;
%endif
%<RTMSet("ModelName", "/"%<Name>/"")>;
%<RTMSet("Path", "/"%<Name>/"")>;
%if isRSim && !isRSimWithSolverModule && StartTime < 0
%assign errTxt = "Start time must be non-negative number: %<StartTime>"
%<LibReportFatalError(errTxt)>
%endif
%<RTMSet("TStart", StartTime)>;
%if isRSimWithSolverModule
%assign stopTime = StopTime
%else
%if ISINF(StopTime)
%assign stopTime = "-1"
%elseif !ISFINITE(StopTime)
%assign errTxt = "Stop time must be 0.0, inf, or finite: %<StopTime>"
%<LibReportFatalError(errTxt)>
%else
%if isRSim && StopTime < 0
%assign errTxt = "Stop time must be non-negative number: %<StopTime>"
%<LibReportFatalError(errTxt)>
%endif
%assign stopTime = StopTime
%endif
%endif
%<RTMSet("TFinal", stopTime)>;
%if ::CompiledModel.SolverType == "FixedStep"
%<RTMSet("StepSize", FixedStepOpts.FixedStep)>;
%<RTMSolverSet("FixedStepSize", FixedStepOpts.FixedStep)>;
%endif
%if Solver == "ode14x"
%<RTMSolverSet("SolverExtrapolationOrder", ...
"%<FixedStepOpts.ExtrapolationOrder>")>;
%<RTMSolverSet("SolverNumberNewtonIterations", ...
"%<FixedStepOpts.NumberNewtonIterations>")>;
%createrecord FcnRec{Name "rt_lu"; NumArgs 3}
%addtorecord FcnRec ArgList{Expr "W"; TypeId tSS_DOUBLE; IsPtr 1; IsCplx 0; IsConst 0}
%addtorecord FcnRec ArgList{Expr "nx"; TypeId tSS_INTEGER; IsPtr 0; IsCplx 0; IsConst 0}
%addtorecord FcnRec ArgList{Expr "pivots"; TypeId tSS_INT32; IsPtr 1; IsCplx 0; IsConst 0}
%assign dummy_rt_lu = LibGenFcnCall(FcnRec)
%createrecord FcnRec{Name "rt_ForwardSubstitution"; NumArgs 7}
%addtorecord FcnRec ArgList{Expr "W"; TypeId tSS_DOUBLE; IsPtr 1; IsCplx 0; IsConst 0}
%addtorecord FcnRec ArgList{Expr "Delta"; TypeId tSS_DOUBLE; IsPtr 1; IsCplx 0; IsConst 0}
%addtorecord FcnRec ArgList{Expr "f1"; TypeId tSS_DOUBLE; IsPtr 1; IsCplx 0; IsConst 0}
%addtorecord FcnRec ArgList{Expr "nx"; TypeId tSS_INTEGER; IsPtr 0; IsCplx 0; IsConst 0}
%addtorecord FcnRec ArgList{Expr "1"; TypeId tSS_INTEGER; IsPtr 0; IsCplx 0; IsConst 0}
%addtorecord FcnRec ArgList{Expr "pivots"; TypeId tSS_INT32; IsPtr 1; IsCplx 0; IsConst 0}
%addtorecord FcnRec ArgList{Expr "1"; TypeId tSS_BOOLEAN; IsPtr 0; IsCplx 0; IsConst 0}
%assign dummy_fs = LibGenFcnCall(FcnRec)
%createrecord FcnRec{Name "rt_BackwardSubstitution"; NumArgs 6}
%addtorecord FcnRec ArgList{Expr "W+nx*nx-1"; TypeId tSS_DOUBLE; IsPtr 1; IsCplx 0; IsConst 0}
%addtorecord FcnRec ArgList{Expr "f1+nx-1"; TypeId tSS_DOUBLE; IsPtr 1; IsCplx 0; IsConst 0}
%addtorecord FcnRec ArgList{Expr "Delta"; TypeId tSS_DOUBLE; IsPtr 1; IsCplx 0; IsConst 0}
%addtorecord FcnRec ArgList{Expr "nx"; TypeId tSS_INTEGER; IsPtr 0; IsCplx 0; IsConst 0}
%addtorecord FcnRec ArgList{Expr "1"; TypeId tSS_INTEGER; IsPtr 0; IsCplx 0; IsConst 0}
%addtorecord FcnRec ArgList{Expr "0"; TypeId tSS_BOOLEAN; IsPtr 0; IsCplx 0; IsConst 0}
%assign dummy_bs = LibGenFcnCall(FcnRec)
%endif
%if ::isRAccel
%<SLibDumpServicePortConnectionsInit()>
%<SLibDumpServicePortSelfInit()>
%<SLibDumpServicePortRequestersInit()>
%endif
%assign mdlRefBlks = ISFIELD(::CompiledModel,"ModelReferenceBlocks") ? ...
::CompiledModel.ModelReferenceBlocks : []
%<CallModelrefBlockRegFcns(mdlRefBlks)>
%if MatFileLogging
%<SLibDumpModelRegDataLoggingSetup(TLC_TRUE, TLC_TRUE)>
%endif
%if NumContStates > 0 || NumZCEvents > 0
{
static struct _ssStatesInfo2 statesInfo2;
%<RTMSolverSet("StatesInfo2", "&statesInfo2")>;
}
{
static ssPeriodicStatesInfo periodicStatesInfo;
%<RTMSolverSet("PeriodicStatesInfo", "&periodicStatesInfo")>;
%if NumPeriodicContStates > 0
%assign copyAddr = "%<LibGetPeriodicContStateIndices()>"
%<RTMSet("PeriodicContStateIndices", copyAddr)>;
(void) %<LibGenMemFcnCall("memset", "(void*) %<copyAddr>", "0", "%<NumPeriodicContStates>*sizeof(int_T)")>;
%assign copyAddr = "%<LibGetPeriodicContStateRanges()>"
%<RTMSet("PeriodicContStateRanges", copyAddr)>;
(void) %<LibGenMemFcnCall("memset", "(void*) %<copyAddr>", "0", "%<2*NumPeriodicContStates>*sizeof(real_T)")>;
%endif
}
{
static ssJacobianPerturbationBounds jacobianPerturbationBounds;
%<RTMSolverSet("JacobianPerturbationBounds", "&jacobianPerturbationBounds")>;
}
%endif
%if isRSimWithSolverModule
%<SLibDumpModelRegRSimSetup()>
%endif
%if NumZCEvents > 0 && !LibPrevZCStatesStructIsEmpty()
%<LibDumpModelInitializePrevZCStates(TLC_TRUE, TLC_TRUE)>
%endif
%<SLibDumpModelChecksumReg()>
%<SLibDumpExtModeReg(TLC_TRUE, TLC_TRUE)>
%if UsingMalloc && GenerateGRTWrapper
%<RTMModelMthsSet("mdlInitializeSizes", "MdlInitializeSizes")>;
%<RTMModelMthsSet("mdlInitializeSampleTimes", "MdlInitializeSampleTimes")>;
%<RTMModelMthsSet("mdlStart", "MdlStart")>;
%<RTMModelMthsSet("mdlOutputs", "MdlOutputs")>;
%<RTMModelMthsSet("mdlUpdate", "MdlUpdate")>;
%if NumContStates > 0
%<RTMModelMthsSet("mdlDerivatives", "MdlDerivatives")>;
%<RTMModelMthsSet("mdlProjection", "MdlProjection")>;
%if ModelIsLinearlyImplicit == "yes"
%<RTMModelMthsSet("mdlMassMatrix", "MdlMassMatrix")>;
%<RTMModelMthsSet("mdlForcingFunction", "MdlForcingFunction")>;
%else
%<RTMModelMthsSet("mdlMassMatrix", SLibGetNullDefinitionFromTfl())>;
%<RTMModelMthsSet("mdlForcingFunction", SLibGetNullDefinitionFromTfl())>;
%endif
%else
%<RTMModelMthsSet("mdlDerivatives", SLibGetNullDefinitionFromTfl())>;
%<RTMModelMthsSet("mdlProjection", SLibGetNullDefinitionFromTfl())>;
%<RTMModelMthsSet("mdlMassMatrix", SLibGetNullDefinitionFromTfl())>;
%<RTMModelMthsSet("mdlForcingFunction", SLibGetNullDefinitionFromTfl())>;
%endif
%<RTMModelMthsSet("mdlTerminate", "MdlTerminate")>;
%if GenRTModel
%<RTMModelMthsSet("RTModelPtr", ::tSimStruct)>;
%endif
%endif
%endfunction
%function FcnNeedsToSetRTWSfcnInfo() void
%return (CodeFormat == "S-Function") || GenRTModel
%endfunction
%function FcnSetBlkInfo2(childSS, childIdx) void
%openfile tmpBuffer
{
%if !UsingMalloc || SLibIsERTCodeFormat()
%if !SLibIsERTCodeFormat()
static struct _ssBlkInfo2 _blkInfo2;
struct _ssBlkInfo2 *blkInfo2 = &_blkInfo2;
ssSetBlkInfo2Ptr(%<childSS>, blkInfo2);
%else
%assign nonInlSfcns = "%<RTMGet("NonInlinedSFcns")>"
ssSetBlkInfo2Ptr(%<childSS>, &%<nonInlSfcns>.blkInfo2[%<childIdx>]);
%endif
%else
struct _ssBlkInfo2 *blkInfo2 = ...
(struct _ssBlkInfo2 *) malloc(sizeof(struct _ssBlkInfo2));
%<RTMChkMemAndReturnIfErr("blkInfo2")>;
ssSetBlkInfo2Ptr(%<childSS>, blkInfo2);
%endif
}
%closefile tmpBuffer
%return tmpBuffer
%endfunction
%function FcnSetPortInfo2(childSS, childIdx) void
%openfile tmpBuffer
%if !UsingMalloc
%if !SLibIsERTCodeFormat()
{
static struct _ssPortInfo2 _portInfo2;
struct _ssPortInfo2 *portInfo2 = &_portInfo2;
_ssSetBlkInfo2PortInfo2Ptr(%<childSS>, portInfo2);
}
%else
%assign nonInlSfcns = "%<RTMGet("NonInlinedSFcns")>"
_ssSetBlkInfo2PortInfo2Ptr(%<childSS>, &%<nonInlSfcns>.inputOutputPortInfo2[%<childIdx>]);
%endif
%else
{
struct _ssPortInfo2 *portInfo2 = ...
(struct _ssPortInfo2 *) malloc(sizeof(struct _ssPortInfo2));
%<RTMChkMemAndReturnIfErr("portInfo2")>;
_ssSetBlkInfo2PortInfo2Ptr(%<childSS>, portInfo2);
}
%endif
%closefile tmpBuffer
%return tmpBuffer
%endfunction
%function FcnSetupSFcnRTWInfo() Output
{
%if UsingMalloc && !SLibIsERTCodeFormat()
RTWSfcnInfo *sfcnInfo = (RTWSfcnInfo *) ...
malloc(sizeof(RTWSfcnInfo));
%<RTMChkMemAndReturnIfErr("sfcnInfo")>;
%else
%if SLibIsERTCodeFormat()
RTWSfcnInfo *sfcnInfo = &%<RTMGet("NonInlinedSFcns")>.sfcnInfo;
%else
static RTWSfcnInfo _sfcnInfo;
RTWSfcnInfo *sfcnInfo = &_sfcnInfo;
%endif
%endif
%<RTMSet("RTWSfcnInfo", "sfcnInfo")>;
rtssSetErrorStatusPtr(sfcnInfo, %<GetRTMErrorStatusPtr()>);
rtssSetNumRootSampTimesPtr(sfcnInfo, &%<RTMGet("NumSampleTimes")>);
%foreach idx = NumSampleTimes
%<RTMGet">RTMGet("NonInlinedSFcns")>.taskTimePtrs[%<idx>] = &(%<RTMGet">RTMGet("TPtr")>[%<idx>]);
%endforeach
rtssSetTPtrPtr(sfcnInfo,%<RTMGet("NonInlinedSFcns")>.taskTimePtrs);
rtssSetTStartPtr(sfcnInfo, &%<RTMGet("TStart")>);
%if RTMTFinalIsReqFcn()
rtssSetTFinalPtr(sfcnInfo, &%<RTMGet("TFinal")>);
%endif
rtssSetTimeOfLastOutputPtr(sfcnInfo, ...
&%<RTMGet("TimeOfLastOutput")>);
rtssSetStepSizePtr(sfcnInfo, &%<RTMGet("StepSize")>);
rtssSetStopRequestedPtr(sfcnInfo, &%<RTMGetStopRequested()>);
rtssSetDerivCacheNeedsResetPtr(sfcnInfo, ...
&%<RTMGet("DerivCacheNeedsReset")>);
rtssSetZCCacheNeedsResetPtr(sfcnInfo, ...
&%<RTMGet("ZCCacheNeedsReset")>);
rtssSetContTimeOutputInconsistentWithStateAtMajorStepPtr(sfcnInfo, ...
&%<RTMGet("ContTimeOutputInconsistentWithStateAtMajorStepFlag")>);
rtssSetSampleHitsPtr(sfcnInfo, &%<RTMGet("SampleHitPtr")>);
rtssSetPerTaskSampleHitsPtr(sfcnInfo, ...
&%<RTMGet("PerTaskSampleHitsPtr")>);
rtssSetSimModePtr(sfcnInfo, &%<RTMGet("SimMode")>);
%if SLibIsERTCodeFormat()
rtssSetSolverInfoPtr(sfcnInfo, &%<RTMGet("RTWSolverInfoPtr")>);
%else
rtssSetSolverInfoPtr(sfcnInfo, &%<RTMGet("RTWSolverInfo")>);
%endif
}
%endfunction
%function SLibSetupTimingInfoForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns)
%openfile retBuf
/* timing info */
%assign numSfcnSampleTimes = SIZE(TID, 1)
%if usingStatic
static time_T sfcnPeriod[%<numSfcnSampleTimes>];
static time_T sfcnOffset[%<numSfcnSampleTimes>];
static int_T sfcnTsMap[%<numSfcnSampleTimes>];
%elseif SLibIsERTCodeFormat()
%assign SfcnIdx = "%<nonInlSfcns>.Sfcn%<childIdx>"
time_T *sfcnPeriod = %<SfcnIdx>.sfcnPeriod;
time_T *sfcnOffset = %<SfcnIdx>.sfcnOffset;
int_T *sfcnTsMap = %<SfcnIdx>.sfcnTsMap;
%else
time_T *sfcnPeriod;
time_T *sfcnOffset;
int_T *sfcnTsMap;
sfcnPeriod = (time_T *) ...
malloc(%<numSfcnSampleTimes> * sizeof(time_T));
%<RTMChkMemAndReturnIfErr("sfcnPeriod")>;
sfcnOffset = (time_T *) ...
malloc(%<numSfcnSampleTimes> * sizeof(time_T));
%<RTMChkMemAndReturnIfErr("sfcnOffset")>;
sfcnTsMap = (int_T *) ...
malloc(%<numSfcnSampleTimes> * sizeof(int_T ));
%<RTMChkMemAndReturnIfErr("sfcnTsMap")>;
%endif
(void) %<LibGenMemFcnCall("memset", "(void*)sfcnPeriod", "0", ...
"sizeof(time_T)*%<numSfcnSampleTimes>")>;
(void) %<LibGenMemFcnCall("memset", "(void*)sfcnOffset", "0", ...
"sizeof(time_T)*%<numSfcnSampleTimes>")>;
ssSetSampleTimePtr(%<s>, &sfcnPeriod[0]);
ssSetOffsetTimePtr(%<s>, &sfcnOffset[0]);
%<underScore>ssSetSampleTimeTaskIDPtr(%<s>, sfcnTsMap);
%closefile retBuf
%return retBuf
%endfunction
%function SLibSetupMdlInfoForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns) void
%assign prefix = "/* Set up the mdlInfo pointer *//n"
%assign postfix = ""
%if (CodeFormat == "S-Function")
%assign prefix = prefix + "# ifdef USE_RTMODEL/n"
%assign postfix = "# else/n" + ...
"%<underScore>ssSetMdlInfoPtr(%<s>, %<RTMGet("MdlInfoPtr")>);/n" + ...
"# endif /* USE_RTMODEL *//n"
%else
%if GenRTModel
%if IsModelReferenceForASimstructBasedTarget()
%assign postfix = ...
"%<underScore>ssSetMdlInfoPtr(%<s>, ssGetMdlInfoPtr(%<tMdlRefSfcnS>));/n"
%endif
%else
%assign postfix = ...
"%<underScore>ssSetMdlInfoPtr(%<s>, %<RTMGet("MdlInfoPtr")>);/n"
%endif
%endif
%assign setBlkInfo2Str = ""
%assign setPortInfo2Str = ""
%assign setSfcnInfoStr = ""
%assign setBlkInfo2Str = FcnSetBlkInfo2(s, childIdx)
%assign setPortInfo2Str = FcnSetPortInfo2(s, childIdx)
%if FcnNeedsToSetRTWSfcnInfo()
%assign setSfcnInfoStr = "ssSetRTWSfcnInfo(%<s>, %<RTMGet("RTWSfcnInfo")>);/n"
%endif
%return setBlkInfo2Str + setPortInfo2Str + prefix + ...
setSfcnInfoStr + postfix
%endfunction
%function SLibAllocateStatesInfo2MemForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns)
%openfile retBuf
%assign numContStates = ContStates[0]
%if ParamSettings.FunctionLevel == 2
/* Allocate memory for states auxilliary information */
{
%if usingStatic
static struct _ssStatesInfo2 statesInfo2;
static ssPeriodicStatesInfo periodicStatesInfo;
static ssJacobianPerturbationBounds jacPerturbationBounds;
ssSetStatesInfo2(%<s>, &statesInfo2);
ssSetPeriodicStatesInfo(%<s>, &periodicStatesInfo);
ssSetJacobianPerturbationBounds(%<s>, &jacPerturbationBounds);
%if SolverType == "VariableStep" && numContStates > 0
ssSetAbsTolVector(%<s>, %<RTMGet("AbsTolVector")> + %);
ssSetAbsTolControlVector(%<s>, %<RTMGet("AbsTolControlVector")> + %);
%endif
%elseif SLibIsERTCodeFormat()
ssSetStatesInfo2(%<s>, &%<nonInlSfcns>.statesInfo2[%<childIdx>]);
ssSetPeriodicStatesInfo(%<s>, &%<nonInlSfcns>.periodicStatesInfo[%<childIdx>]);
%else
struct _ssStatesInfo2 *statesInfo2 = ...
(struct _ssStatesInfo2 *) ...
malloc(sizeof(struct _ssStatesInfo2));
ssPeriodicStatesInfo* periodicStatesInfo = (ssPeriodicStatesInfo*) malloc(sizeof(ssPeriodicStatesInfo));
ssJacobianPerturbationBounds *jacPerturbationBounds = (ssJacobianPerturbationBounds*) malloc(sizeof(ssJacobianPerturbationBounds));
%<RTMChkMemAndReturnIfErr("statesInfo2")>;
ssSetStatesInfo2(%<s>, statesInfo2);
%<RTMChkMemAndReturnIfErr("periodicStatesInfo")>;
ssSetPeriodicStatesInfo(%<s>, periodicStatesInfo);
%<RTMChkMemAndReturnIfErr("jacPerturbationBounds")>;
ssSetJacobianPerturbationBounds(%<s>, jacPerturbationBounds);
%if SolverType == "VariableStep" && numContStates > 0
ssSetAbsTolVector(%<s>, %<RTMGet("AbsTolVector")> + %);
ssSetAbsTolControlVector(%<s>, %<RTMGet("AbsTolControlVector")> + %);
%<underScore>ssSetJacobianPerturbationBoundsMinVec(%<s>, %<RTMGet("JacobianPerturbationBoundsMinVec")>);
%<underScore>ssSetJacobianPerturbationBoundsMaxVec(%<s>, %<RTMGet("JacobianPerturbationBoundsMaxVec")>);
%endif
%endif
}
%endif
%closefile retBuf
%return retBuf
%endfunction
%function SLibAllocateMethods2MemForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns)
%openfile retBuf
%if ParamSettings.FunctionLevel == 2
/* Allocate memory of model methods 2 */
{
%if usingStatic
static struct _ssSFcnModelMethods2 methods2;
ssSetModelMethods2(%<s>, &methods2);
%elseif SLibIsERTCodeFormat()
ssSetModelMethods2(%<s>, &%<nonInlSfcns>.methods2[%<childIdx>]);
%else
struct _ssSFcnModelMethods2 *methods2 = ...
(struct _ssSFcnModelMethods2 *) ...
malloc(sizeof(struct _ssSFcnModelMethods2));
%<RTMChkMemAndReturnIfErr("methods2")>;
ssSetModelMethods2(%<s>, methods2);
%endif
}
/* Allocate memory of model methods 3 */
{
%if usingStatic
static struct _ssSFcnModelMethods3 methods3;
ssSetModelMethods3(%<s>, &methods3);
%elseif SLibIsERTCodeFormat()
ssSetModelMethods3(%<s>, &%<nonInlSfcns>.methods3[%<childIdx>]);
%else
struct _ssSFcnModelMethods3 *methods3 = ...
(struct _ssSFcnModelMethods3 *) ...
malloc(sizeof(struct _ssSFcnModelMethods3));
%<RTMChkMemAndReturnIfErr("methods3")>;
ssSetModelMethods3(%<s>, methods3);
%endif
}
/* Allocate memory of model methods 4 */
{
%if usingStatic
static struct _ssSFcnModelMethods4 methods4;
ssSetModelMethods4(%<s>, &methods4);
%elseif SLibIsERTCodeFormat()
ssSetModelMethods4(%<s>, &%<nonInlSfcns>.methods4[%<childIdx>]);
%else
struct _ssSFcnModelMethods4 *methods4 = ...
(struct _ssSFcnModelMethods4 *) ...
malloc(sizeof(struct _ssSFcnModelMethods4));
%<RTMChkMemAndReturnIfErr("methods4")>;
ssSetModelMethods4(%<s>, methods4);
%endif
}
%endif
%closefile retBuf
%return retBuf
%endfunction
%function SLibSetupInputsForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns)
%assign thisBlock = ChildSFunctionList[childIdx]
%openfile retBuf
%if (CodeFormat == "S-Function" && UsingMalloc && ...
ParamSettings.FunctionLevel == 2) || ...
IsModelReferenceSimTarget()
ssSetRegNumInputPortsFcn(%<s>, ...
(_ssRegNumInputPortsFcn)RegNumInputPorts);
ssSetRegNumInputPortsFcnArg(%<s>,%<s>);
%endif
%if NumDataInputPorts > 0
%assign SfcnIdx = "%<nonInlSfcns>.Sfcn%<childIdx>"
/* inputs */
%switch ParamSettings.FunctionLevel
%case 1
%assign uWidth = LibGetRecordWidth(DataInputPort)
%assign inputsContiguous = ...
(ParamSettings.InputContiguous == "yes")
%assign usingUPtrs = (ParamSettings.UsingUPtrs == "yes")
%if usingUPtrs
{
%if usingStatic
static real_T const *sfcnUPtrs[%<uWidth>];
%elseif SLibIsERTCodeFormat()
real_T const **sfcnUPtrs = /
(real_T const **) &%<SfcnIdx>.UPtrs;
%else
real_T const **sfcnUPtrs =
(real_T const **) malloc(%<uWidth> * sizeof(real_T *));
%<RTMChkMemAndReturnIfErr("sfcnUPtrs")>;
%endif
%assign rollVars = ["U"]
%roll idx = RollRegions, lcv = RollThreshold, thisBlock, ...
"Roller", rollVars
%assign lhs = LibGetIndexedElement("sfcnUPtrs", ...
uWidth, lcv, idx)
%<lhs> = %<LibBlockInputSignalAddr(0, "", lcv, idx)>;
%endroll
%<underScore>ssSetUPtrs(%<s>, &sfcnUPtrs[0]);
}
%elseif !inputsContiguous
%assign errTxt = "Level 1 S-function not using uPtrs and " ...
"inputs are not contiguous"
%<LibBlockReportFatalError(thisBlock,errTxt)>
%else
%<underScore>ssSetU(%<s>, (void *)...
%<LibBlockInputSignalAddr(0,"","",0)>);
%endif
%break
%case 2
{
%if usingStatic
static struct _ssPortInputs inputPortInfo[%<NumDataInputPorts>];
_ssSetNumInputPorts(%<s>, %<NumDataInputPorts>);
ssSetPortInfoForInputs(%<s>, &inputPortInfo[0]);
%elseif SLibIsERTCodeFormat()
_ssSetNumInputPorts(%<s>, %<NumDataInputPorts>);
ssSetPortInfoForInputs(%<s>, &%<SfcnIdx>.inputPortInfo[0]);
%else
struct _ssPortInputs *inputPortInfo =
(struct _ssPortInputs *) calloc(%<NumDataInputPorts>, ...
sizeof(struct _ssPortInputs));
%<RTMChkMemAndReturnIfErr("inputPortInfo")>;
_ssSetNumInputPorts(%<s>, %<NumDataInputPorts>);
ssSetPortInfoForInputs(%<s>, &inputPortInfo[0]);
%endif
%if NumDataInputPorts>0
%if usingStatic
{
static struct _ssInPortUnit inputPortUnits[%<NumDataInputPorts>];
_ssSetPortInfo2ForInputUnits(%<s>, &inputPortUnits[0]);
}
%elseif SLibIsERTCodeFormat()
_ssSetPortInfo2ForInputUnits(%<s>, &%<SfcnIdx>.inputPortUnits[0]);
%else
{
struct _ssInPortUnit *inputPortUnits =
(struct _ssInPortUnit *) calloc(%<NumDataInputPorts>, ...
sizeof(struct _ssInPortUnit));
%<RTMChkMemAndReturnIfErr("inputPortUnits")>;
_ssSetPortInfo2ForInputUnits(%<s>, &inputPortUnits[0]);
}
%endif
%endif
%foreach ipIdx = NumDataInputPorts
ssSetInputPortUnit(%<s>, %<ipIdx>, %<LibBlockInputSignalUnitId(ipIdx)>);
%endforeach
%if NumDataInputPorts>0
%if usingStatic
{
static struct _ssInPortCoSimAttribute inputPortCoSimAttribute[%<NumDataInputPorts>];
_ssSetPortInfo2ForInputCoSimAttribute(%<s>, &inputPortCoSimAttribute[0]);
}
%elseif SLibIsERTCodeFormat()
_ssSetPortInfo2ForInputCoSimAttribute(%<s>, &%<SfcnIdx>.inputPortCoSimAttribute[0]);
%else
{
struct _ssInPortCoSimAttribute *inputPortCoSimAttribute =
(struct _ssInPortCoSimAttribute *) calloc(%<NumDataInputPorts>, ...
sizeof(struct _ssInPortCoSimAttribute));
%<RTMChkMemAndReturnIfErr("inputPortCoSimAttribute")>;
_ssSetPortInfo2ForInputCoSimAttribute(%<s>, &inputPortCoSimAttribute[0]);
}
%endif
%endif
%foreach ipIdx = NumDataInputPorts
ssSetInputPortIsContinuousQuantity(%<s>, %<ipIdx>, %<LibBlockInputPortIsContinuousQuantity(ipIdx)>);
%endforeach
%if FcnBlockHasVarDimsInput()
%assign num_vardims_input = FcnBlockNumVarDimsInput()
%if usingStatic
{
static struct _ssInPortVarDims inputPortCurrentDims[%<num_vardims_input>];
_ssSetPortInfo2ForInputs(%<s>, &inputPortCurrentDims[0]);
}
%elseif SLibIsERTCodeFormat()
_ssSetPortInfo2ForInputs(%<s>, &%<SfcnIdx>.inputPortCurrentDims[0]);
%else
{
struct _ssInPortVarDims *inputPortCurrentDims =
(struct _ssInPortVarDims *) calloc(%<num_vardims_input>, ...
sizeof(struct _ssInPortVarDims));
%<RTMChkMemAndReturnIfErr("inputPortCurrentDims")>;
_ssSetPortInfo2ForInputs(%<s>, &inputPortCurrentDims[0]);
}
%endif
%endif
%assign vipIdx = 0
%foreach ipIdx = NumDataInputPorts
/* port %<ipIdx> */
{
%assign ip = DataInputPort[ipIdx]
%assign dtype = SLibGetRecordDataTypeName(ip,"")
%assign width = LibBlockInputSignalWidth(ipIdx)
%assign dims = LibBlockInputSignalDimensions(ipIdx)
%assign nDims = LibBlockInputSignalNumDimensions(ipIdx)
%if ParamSettings.UsingUPtrs[ipIdx] == "yes"
%if usingStatic
static %<dtype> const *sfcnUPtrs[%<width>];
%if %<nDims> >= matrixDimensionThreshhold
static int_T dimensions[%<nDims>];
%endif
%elseif SLibIsERTCodeFormat()
%<dtype> const **sfcnUPtrs = /
(%<dtype> const **) &%<SfcnIdx>.UPtrs%<ipIdx>;
%if nDims >= matrixDimensionThreshhold
int_T *dimensions = (int_T *) &%<SfcnIdx>.iDims%<ipIdx>;
%endif
%else
%if %<nDims> >= matrixDimensionThreshhold
%if CodeFormat == "S-Function"
#if defined(MATLAB_MEX_FILE)
/* If the child S-function defines its port dimensions
* as DYNAMIC_DIMENSION Simlulink will free this memory
* and reallocate it. Therefore it must be allocated
* using utMalloc .
*/
int_T *dimensions = (int_T *) ...
utMalloc(%<nDims> * sizeof(int_T));
#else
int_T *dimensions = (int_T *) ...
malloc(%<nDims> * sizeof(int_T));
#endif
%else
int_T *dimensions = (int_T *) ...
malloc(%<nDims> * sizeof(int_T));
%endif
%endif
%<dtype> const **sfcnUPtrs = (%<dtype> const **)
malloc(%<width> * sizeof(%<dtype> *));
%if %<nDims> >= matrixDimensionThreshhold
%<RTMChkMemAndReturnIfErr("dimensions")>;
%endif
%<RTMChkMemAndReturnIfErr("sfcnUPtrs")>;
%endif
%if CodeFormat == "S-Function"
%foreach sigIdx = width
%assign rec = SLibGetSourceMapInfo(ip, sigIdx)
%if rec.mapSrc == "U"
%assign u = RTMGetIdxed("InputPortSignalPtrs", ...
rec.mapIdx) + "[%<rec.signalOffset>]"
sfcnUPtrs[%<sigIdx>] = (%<dtype> const *) %<u>;
%else
%assign u = ...
LibBlockInputSignalAddr(ipIdx, "", "", sigIdx)
sfcnUPtrs[%<sigIdx>] = (%<dtype> const *) %<u>;
%endif
%endforeach
%else
%assign rollVars = ["u%<ipIdx>"]
%with ip
%assign rollRegion = RollRegions
%endwith
%roll idx = rollRegion, lcv = RollThreshold, ...
thisBlock, "Roller", rollVars
%assign lhs = LibGetIndexedElement("sfcnUPtrs", ...
width,lcv,idx)
%<lhs> = %<LibBlockInputSignalAddr(ipIdx,"",lcv,idx)>;
%endroll
%endif
%<underScore>ssSetInputPortSignalPtrs(%<s>, %<ipIdx>, ...
(InputPtrsType)&sfcnUPtrs[0]);
%else
%if ParamSettings.InputContiguous[ipIdx] == "yes"
%if %<nDims> >= matrixDimensionThreshhold
%if usingStatic
%if %<nDims> >= matrixDimensionThreshhold
static int_T dimensions[%<nDims>];
%endif
%elseif SLibIsERTCodeFormat()
%if nDims >= matrixDimensionThreshhold
int_T *dimensions = /
(int_T *) &%<SfcnIdx>.iDims%<ipIdx>;
%endif
%else
%if CodeFormat == "S-Function"
#if defined(MATLAB_MEX_FILE)
/* If the child S-function defines its port dimensions
* as DYNAMIC_DIMENSION Simlulink will free this memory
* and reallocate it. Therefore it must be allocated
* using utMalloc.
*/
int_T *dimensions = (int_T *) ...
utMalloc(%<nDims> * sizeof(int_T));
#else
int_T *dimensions = (int_T *) ...
malloc(%<nDims> * sizeof(int_T));
#endif
%else
int_T *dimensions = (int_T *) ...
malloc(%<nDims> * sizeof(int_T));
%endif
%<RTMChkMemAndReturnIfErr("dimensions")>;
%endif
%endif
%assign sigAddr = LibBlockInputSignalAddr(ipIdx,"","",0)
ssSetInputPortRequiredContiguous(%<s>, %<ipIdx>, 1);
%<underScore>ssSetInputPortSignal(%<s>, %<ipIdx>, ...
%<sigAddr>);
%else
%assign errTxt = "Level 2 S-function not using " ...
"uPtrs and inputs are not contiguous"
%<LibBlockReportFatalError(thisBlock,errTxt)>
%endif
%endif
%if %<nDims> >= matrixDimensionThreshhold
%if %<nDims> >= matrixDimensionThreshhold
%foreach Idx = nDims
dimensions[%<Idx>] = %;
%endforeach
%endif
_ssSetInputPortDimensionsPtr(%<s>, %<ipIdx>, dimensions);
%endif
_ssSetInputPortNumDimensions(%<s>, %<ipIdx>, %<nDims>);
ssSetInputPortWidth(%<s>, %<ipIdx>, %<width>);
%if LibGetIsInputPortVarDims(ipIdx)
%assign dwork_var = SLibGetCurrentInputPortDimensions(ipIdx, 0)
_ssSetInputPortVariableDimsPtr(%<s>, ...
%<vipIdx>, &%<dwork_var>);
%assign vipIdx = vipIdx + 1
%endif
}
%endforeach
}
%break
%endswitch
%endif
%closefile retBuf
%return retBuf
%endfunction
%function SLibSetupOutputsForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns)
%assign thisBlock = ChildSFunctionList[childIdx]
%openfile retBuf
%if (CodeFormat == "S-Function" && UsingMalloc && ...
ParamSettings.FunctionLevel == 2) || ...
IsModelReferenceSimTarget()
ssSetRegNumOutputPortsFcn(%<s>, ...
(_ssRegNumOutputPortsFcn)RegNumOutputPorts);
ssSetRegNumOutputPortsFcnArg(%<s>,%<s>);
%endif
%if NumDataOutputPorts > 0
%assign SfcnIdx = "%<nonInlSfcns>.Sfcn%<childIdx>"
/* outputs */
%switch ParamSettings.FunctionLevel
%case 1
%assign op = FcnGetOutputPortRecord(0)
%assign idNum = IDNUM(op.SignalSrc[0])
%if idNum[0] == "F"
%<underScore>ssSetY(%<s>, %<SLibGetNullDefinitionFromTfl()>);
%else
%assign dt = LibBlockOutputSignalDataTypeName(0, "")
%<underScore>ssSetY(%<s>, ...
((%<dt> *) %<LibBlockOutputSignalAddr(0,"","",0)>));
%endif
%break
%case 2
{
%if usingStatic
static struct _ssPortOutputs outputPortInfo[%<NumDataOutputPorts>];
ssSetPortInfoForOutputs(%<s>, &outputPortInfo[0]);
%elseif SLibIsERTCodeFormat()
ssSetPortInfoForOutputs(%<s>, &%<SfcnIdx>.outputPortInfo[0]);
%else
struct _ssPortOutputs *outputPortInfo = ...
(struct _ssPortOutputs *)
calloc(%<NumDataOutputPorts>, ...
sizeof(struct _ssPortOutputs));
%<RTMChkMemAndReturnIfErr("outputPortInfo")>;
ssSetPortInfoForOutputs(%<s>, &outputPortInfo[0]);
%endif
_ssSetNumOutputPorts(%<s>, %<NumDataOutputPorts>);
%if NumDataOutputPorts>0
%if usingStatic
{
static struct _ssOutPortUnit outputPortUnits[%<NumDataOutputPorts>];
_ssSetPortInfo2ForOutputUnits(%<s>, &outputPortUnits[0]);
}
%elseif SLibIsERTCodeFormat()
_ssSetPortInfo2ForOutputUnits(%<s>, &%<SfcnIdx>.outputPortUnits[0]);
%else
{
struct _ssOutPortUnit *outputPortUnits =
(struct _ssOutPortUnit *) calloc(%<NumDataOutputPorts>, ...
sizeof(struct _ssOutPortUnit));
%<RTMChkMemAndReturnIfErr("outputPortUnits")>;
_ssSetPortInfo2ForOutputUnits(%<s>, &outputPortUnits[0]);
}
%endif
%endif
%foreach opIdx = NumDataOutputPorts
ssSetOutputPortUnit(%<s>, %<opIdx>, %<LibBlockOutputSignalUnitId(opIdx)>);
%endforeach
%if NumDataOutputPorts>0
%if usingStatic
{
static struct _ssOutPortCoSimAttribute outputPortCoSimAttribute[%<NumDataOutputPorts>];
_ssSetPortInfo2ForOutputCoSimAttribute(%<s>, &outputPortCoSimAttribute[0]);
}
%elseif SLibIsERTCodeFormat()
_ssSetPortInfo2ForOutputCoSimAttribute(%<s>, &%<SfcnIdx>.outputPortCoSimAttribute[0]);
%else
{
struct _ssOutPortCoSimAttribute *outputPortCoSimAttribute =
(struct _ssOutPortCoSimAttribute *) calloc(%<NumDataOutputPorts>, ...
sizeof(struct _ssOutPortCoSimAttribute));
%<RTMChkMemAndReturnIfErr("outputPortCoSimAttribute")>;
_ssSetPortInfo2ForOutputCoSimAttribute(%<s>, &outputPortCoSimAttribute[0]);
}
%endif
%endif
%foreach ipIdx = NumDataOutputPorts
ssSetOutputPortIsContinuousQuantity(%<s>, %<ipIdx>, %<LibBlockOutputPortIsContinuousQuantity(ipIdx)>);
%endforeach
%if FcnBlockHasVarDimsOutput()
%assign num_vardims_output = FcnBlockNumVarDimsOutput()
%if usingStatic
{
static struct _ssOutPortVarDims outputPortCurrentDims[%<num_vardims_output>];
_ssSetPortInfo2ForOutputs(%<s>, &outputPortCurrentDims[0]);
}
%elseif SLibIsERTCodeFormat()
_ssSetPortInfo2ForOutputs(%<s>, &%<SfcnIdx>.outputPortCurrentDims[0]);
%else
{
struct _ssOutPortVarDims* outputPortCurrentDims =
(struct _ssOutPortVarDims *) calloc(%<num_vardims_output>,
sizeof(struct _ssOutPortVarDims));
%<RTMChkMemAndReturnIfErr("outputPortCurrentDims")>;
_ssSetPortInfo2ForOutputs(%<s>, &outputPortCurrentDims[0]);
}
%endif
%endif
%assign vopIdx = 0
%foreach opIdx = NumDataOutputPorts
/* port %<opIdx> */
{
%assign oWidth = LibBlockOutputSignalWidth(opIdx)
%assign oNumDims = LibBlockOutputSignalNumDimensions(opIdx)
%assign oDims = LibBlockOutputSignalDimensions(opIdx)
%if %<oNumDims> >= matrixDimensionThreshhold
%if usingStatic
%if %<oNumDims> >= matrixDimensionThreshhold
static int_T dimensions[%<oNumDims>];
%endif
%elseif SLibIsERTCodeFormat()
%if oNumDims >= matrixDimensionThreshhold
int_T *dimensions = (int_T *) &%<SfcnIdx>.oDims%<opIdx>;
%endif
%else
%if CodeFormat == "S-Function"
#if defined(MATLAB_MEX_FILE)
/* If the child S-function defines its dimensions as
* DYNAMIC_DIMENSION Simlulink will free this memory
* and reallocate it. Therefor it must be allocated
* using utMalloc .
*/
int_T *dimensions = (int_T *) ...
utMalloc(%<oNumDims> * sizeof(int_T));
#else
int_T *dimensions = (int_T *) ...
malloc(%<oNumDims> * sizeof(int_T));
#endif
%else
int_T *dimensions = (int_T *) ...
malloc(%<oNumDims> * sizeof(int_T));
%endif
%endif
%foreach Idx = oNumDims
dimensions[%<Idx>] = %;
%endforeach
_ssSetOutputPortDimensionsPtr(%<s>, %<opIdx>, dimensions);
%endif
_ssSetOutputPortNumDimensions(%<s>, %<opIdx>, %<oNumDims>);
ssSetOutputPortWidth(%<s>, %<opIdx>, %<oWidth>);
%assign op = FcnGetOutputPortRecord(opIdx)
%assign idNum = IDNUM(op.SignalSrc[0])
%if idNum[0] == "F"
%<underScore>ssSetOutputPortSignal(%<s>, %<opIdx>, %<SLibGetNullDefinitionFromTfl()>);
%else
%assign dt = LibBlockOutputSignalDataTypeName(opIdx, "")
%assign yAddr = LibBlockOutputSignalAddr(opIdx, "", "", 0)
%<underScore>ssSetOutputPortSignal(%<s>, ...
%<opIdx>, ((%<dt> *) %<yAddr>));
%endif
%if LibGetIsOutputPortVarDims(opIdx)
%assign dwork_var = SLibGetCurrentOutputPortDimensions(opIdx, 0)
_ssSetOutputPortVariableDimsPtr(%<s>, ...
%<vopIdx>, &%<dwork_var>);
%assign vopIdx = vopIdx + 1
%endif
}
%endforeach
}
%break
%endswitch
%endif
%closefile retBuf
%return retBuf
%endfunction
%function SLibSetupStatesForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns)
%openfile retBuf
%assign numDiscStates = DiscStates[0]
%assign numContStates = ContStates[0]
%assign nStates = numDiscStates + numContStates
%if nStates > 0
%assign SfcnIdx = "%<nonInlSfcns>.Sfcn%<childIdx>"
/* states */
%switch ParamSettings.FunctionLevel
%case 1
%if StatesDiscontiguous == 1
{
%if usingStatic
static real_T sfcnX[%<nStates>];
%elseif SLibIsERTCodeFormat()
real_T *sfcnX = (real_T *) &%<SfcnIdx>.X[0];
%else
real_T *sfcnX = (real_T *) ...
malloc(%<nStates> * sizeof(real_T));
%<RTMChkMemAndReturnIfErr("sfcnX")>;
%endif
(void) %<LibGenMemFcnCall("memset", "(void*)sfcnX", "0", ...
"sizeof(real_T)*%<nStates>")>;
%<underScore>ssSetContStates(%<s>, &sfcnX[0]);
}
%elseif numContStates > 0
%<underScore>ssSetContStates(%<s>, ...
&%<LibBlockContinuousState("", "", 0)>);
%if(ISEQUAL(::CompiledModel.SolverType, "VariableStep"))
%<underScore>ssSetContStateDisabled(%<s>, ...
&%<LibBlockContStateDisabled("", "", 0)>);
{
real_T* minVec = %<"&"+ LibBlockContStatePerturbMin("", "", 0)>;
real_T* maxVec = %<"&"+ LibBlockContStatePerturbMax("", "", 0)>;
%<underScore>ssSetJacobianPerturbationBoundsMinVec(%<s>, minVec);
%<underScore>ssSetJacobianPerturbationBoundsMaxVec(%<s>, maxVec);
}
%endif
%else
%<underScore>ssSetContStates(%<s>, ...
&%<LibBlockDiscreteState("", "", 0)>);
%endif
%break
%case 2
%if numContStates > 0
%<underScore>ssSetContStates(%<s>, ...
&%<LibBlockContinuousState("", "", 0)>);
%if(ISEQUAL(::CompiledModel.SolverType, "VariableStep"))
%<underScore>ssSetContStateDisabled(%<s>, ...
&%<LibBlockContStateDisabled("", "", 0)>);
{
real_T* minVec = %<"&"+ LibBlockContStatePerturbMin("", "", 0)>;
real_T* maxVec = %<"&"+ LibBlockContStatePerturbMax("", "", 0)>;
%<underScore>ssSetJacobianPerturbationBoundsMinVec(%<s>, minVec);
%<underScore>ssSetJacobianPerturbationBoundsMaxVec(%<s>, maxVec);
}
%endif
%endif
%if numDiscStates > 0
%<underScore>ssSetDiscStates(%<s>, ...
(real_T *) &%<LibBlockDiscreteState("", "", 0)>);
%endif
%break
%endswitch
%endif
%closefile retBuf
%return retBuf
%endfunction
%function SLibSetupPathInfoForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns)
%assign thisBlock = ChildSFunctionList[childIdx]
%assign raccelUseMexFile = ...
::isRAccel && ParamSettings.WillBeDynamicallyLoaded == "yes"
%openfile retBuf
/* path info */
%if CodeFormat == "S-Function" || IsModelReferenceSimTarget() || raccelUseMexFile
%<underScore>ssSetModelName(%<s>, ...
"%<thisBlock.ParamSettings.FunctionName>");
%else
%if ISFIELD(thisBlock,"SLName")
%assign sysName = SYSNAME(SLName)
%else
%if BlockCommentType == "BlockSIDComment"
%assign rtwName = FEVAL("coder.internal.convertBlockSIDNameToRTWName", "%<LibGetModelName()>", Name)
%assign sysName = SYSNAME(rtwName)
%else
%assign sysName = SYSNAME(Name)
%endif
%endif
%<underScore>ssSetModelName(%<s>, "%<STRING(sysName[1])>");
%endif
%assign pathName = LibGetFormattedBlockPath(thisBlock)
%<underScore>ssSetPath(%<s>, "%<pathName>");
%if GenRTModel
%if !IsModelReferenceSimTarget()
ssSetRTModel(%<s>,%<GetSimStructExpr(System[GetBaseSystemIdx()], ::tSimStruct)>);
%<underScore>ssSetParentSS(%<s>, %<SLibGetNullDefinitionFromTfl()>);
%<underScore>ssSetRootSS(%<s>, %<s>);
%else
ssSetRTModel(%<s>,%<GetSimStructExpr(System[GetBaseSystemIdx()], ::tSimStruct)>);
%<underScore>ssSetParentSS(%<s>, %<tMdlRefSfcnS>);
%<underScore>ssSetRootSS(%<s>, ssGetRootSS(%<tMdlRefSfcnS>));
%endif
%else
if (ssGetRTModel(%<::tSimStruct>) == %<SLibGetNullDefinitionFromTfl()>) {
%<underScore>ssSetParentSS(%<s>, %<RTMGetModelSS()>);
%<underScore>ssSetRootSS(%<s>, %<RTMGet("RootSS")>);
} else {
ssSetRTModel(%<s>,ssGetRTModel(%<::tSimStruct>));
%<underScore>ssSetParentSS(%<s>, %<SLibGetNullDefinitionFromTfl()>);
%<underScore>ssSetRootSS(%<s>, %<s>);
}
%endif
%if ParamSettings.FunctionLevel == 1
ssSetVersion(%<s>, SIMSTRUCT_VERSION_LEVEL1);
%else
ssSetVersion(%<s>, SIMSTRUCT_VERSION_LEVEL2);
%endif
%closefile retBuf
%return retBuf
%endfunction
%function SLibSetupSfcnParamsForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns)
%openfile retBuf
%assign numArgs = Parameters[0] / 2
%if numArgs > 0
%assign SfcnIdx = "%<nonInlSfcns>.Sfcn%<childIdx>"
%openfile tmpBuffer
%foreach argIdx = numArgs
%assign paramIdx = argIdx + 1
%assign paramName = "P%<paramIdx>Size"
%assign paramAddr = LibBlockParameterAddr(%<paramName>,"","",0)
%<underScore>ssSetSFcnParam(%<s>, %<argIdx>, (mxArray*)%<paramAddr>);
%endforeach
%closefile tmpBuffer
/* parameters */
{
%if usingStatic
static mxArray *sfcnParams[%<numArgs>];
%elseif SLibIsERTCodeFormat()
mxArray **sfcnParams = /
(mxArray **) &%<SfcnIdx>.params;
%else
mxArray **sfcnParams = (mxArray **) malloc(%<numArgs> * sizeof(mxArray *));
%<RTMChkMemAndReturnIfErr("sfcnParams")>;
%endif
%<underScore>ssSetSFcnParamsCount(%<s>, %<numArgs>);
%<underScore>ssSetSFcnParamsPtr(%<s>, &sfcnParams[0]);
%if CodeFormat == "S-Function" || IsModelReferenceSimTarget()
%if LibSFunctionLevel() == "Level2"
#if defined(MATLAB_MEX_FILE)
{
%if usingStatic
static uint_T attribs[%<numArgs>];
%elseif SLibIsERTCodeFormat()
uint_T *attribs = (uint_T *) &%<SfcnIdx>.attribs;
%else
uint_T *attribs;
attribs = (uint_T *) ...
mxCalloc(%<numArgs>, sizeof(uint_T));
mexMakeMemoryPersistent(attribs);
%endif
ssSetSFcnParamAttribsPtr(%<s>, &attribs[0]);
(void) %<LibGenMemFcnCall("memset", "(void *)&attribs[0]", ...
" 0", " %<numArgs> * sizeof(uint_T)")>;
}
#endif
%endif
%<SLibWriteSFunctionGuards("if")>
mxArray *param;
int_T i;
real_T *vals;
%foreach argIdx = numArgs
%assign paramIdx = argIdx + 1
%assign paramVal = "P%<paramIdx>"
%assign prmValue = SLibGetValueFromParamRec(Parameter[argIdx*2], TLC_FALSE)
%assign mSize = CAST("Number", prmValue[0])
%assign nSize = CAST("Number", prmValue[1])
%assign bufferLen = mSize * nSize
%if LibGetRecordIsComplex(Parameter[argIdx*2+1])
%assign nSize = 2*nSize
%endif
%assign data = ...
LibBlockMatrixParameterAddr(%<paramVal>, "", "", ...
0, "", "", 0)
%if SLibGetBlockParameterStorageClass(%<paramVal>) == "Auto_SFCN"
%assign tunableParam = ...
SLibGetBlockParameterIdentifier(%<paramVal>)
%<underScore>ssSetSFcnParam(%<s>, %<argIdx>, /
%<tunableParam>(%<RTMGetModelSS()>));
%else
param = mxCreateDoubleMatrix(%<mSize>,%<nSize>,mxREAL);
mexMakeArrayPersistent(param);
%if mSize*nSize > 0
vals = (real_T *) %<data>;
for (i = 0; i < %<bufferLen>; i++) {
mxGetPr(param)[i] = vals[i];
}
%endif
%<underScore>ssSetSFcnParam(%<s>, %<argIdx>, param);
%endif
%endforeach
%<SLibWriteSFunctionGuards("else")>
%<tmpBuffer>/
%<SLibWriteSFunctionGuards("endif")>
%else
%<tmpBuffer>/
%endif
}
%endif
%closefile retBuf
%return retBuf
%endfunction
%function SLibSetupWorksForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns)
%assign thisBlock = ChildSFunctionList[childIdx]
%assign numRWorks = RWork[0]
%assign numIWorks = IWork[0]
%assign numPWorks = PWork[0]
%assign numDWorks = thisBlock.NumDWork
%assign numModes = ModeVector[0]
%openfile tmpBuffer
%if numRWorks > 0
%<underScore>ssSetRWork(%<s>, (real_T *) ...
&%<LibBlockRWork(RWork, "", "", 0)>);
%endif
%if numIWorks > 0
%<underScore>ssSetIWork(%<s>, (int_T *) ...
&%<LibBlockIWork(IWork, "", "", 0)>);
%endif
%if numPWorks > 0
%<underScore>ssSetPWork(%<s>, (void **) ...
&%<LibBlockPWork(PWork, "", "", 0)>);
%endif
%if numDWorks > 0
{
%assign SfcnIdx = "%<nonInlSfcns>.Sfcn%<childIdx>"
%if usingStatic
static struct _ssDWorkRecord dWorkRecord[%<numDWorks>];
static struct _ssDWorkAuxRecord dWorkAuxRecord[%<numDWorks>];
%elseif SLibIsERTCodeFormat()
struct _ssDWorkRecord *dWorkRecord = /
(struct _ssDWorkRecord *) &%<SfcnIdx>.dWork;
struct _ssDWorkAuxRecord *dWorkAuxRecord = /
(struct _ssDWorkAuxRecord *) &%<SfcnIdx>.dWorkAux;
%else
struct _ssDWorkRecord *dWorkRecord = ...
(struct _ssDWorkRecord *) malloc(%<numDWorks> * sizeof(struct _ssDWorkRecord));
struct _ssDWorkAuxRecord *dWorkAuxRecord = ...
(struct _ssDWorkAuxRecord *) calloc(%<numDWorks>, sizeof(struct _ssDWorkAuxRecord));
%<RTMChkMemAndReturnIfErr("dWorkRecord")>;
%<RTMChkMemAndReturnIfErr("dWorkAuxRecord")>;
%endif
ssSetSFcnDWork(%<s>, dWorkRecord);
ssSetSFcnDWorkAux(%<s>, dWorkAuxRecord);
_ssSetNumDWork(%<s>, %<numDWorks>);
%foreach idx = numDWorks
%assign dwork = DWork[idx]
%assign dtIdCurDWork = LibGetDataTypeIdAliasedThruToFromId(...
LibBlockDWorkDataTypeId(dwork))
%assign dwRec = ::CompiledModel.DWorks.DWork[dwork.FirstRootIdx]
/* %<dwork.Name> */
ssSetDWorkWidth(%<s>, %<idx>, ...
%<LibBlockDWorkWidth(dwork)>);
%if LibIsBuiltInDataType(dtIdCurDWork)
%assign dtEnum = LibGetDataTypeEnumFromId(dtIdCurDWork)
ssSetDWorkDataType(%<s>, %<idx>,%<dtEnum>);
%elseif LibIsHalfDataType(dtIdCurDWork)
DTypeId halfID = ssRegisterDataTypeHalfPrecision(
%<s>,
0 /* 0 means do NOT obey data type override setting for this subsystem */ );
ssSetDWorkDataType( %<s>, %<idx>, halfID );
%else
%assign curDT = FixPt_GetDataTypeFromIndex(dtIdCurDWork)
%if curDT.IsFixedPoint
{
DTypeId dataTypeIdReg =
%if FixPt_DataTypeIsFloat(curDT)
ssRegisterDataTypeFxpScaledDouble(
%else
ssRegisterDataTypeFxpFSlopeFixExpBias(
%endif
%<s>,
%<curDT.IsSigned>,
%<curDT.RequiredBits>,
%<curDT.FracSlope>,
%<curDT.FixedExp>,
%<curDT.Bias>,
0 /* false means do NOT obey data type override setting for this subsystem */ );
ssSetDWorkDataType( %<s>, %<idx>, dataTypeIdReg );
}
%else
%assign dtEnum = LibGetDataTypeEnumFromId(dtIdCurDWork)
%if dtEnum == "SS_POINTER" || dtEnum == "SS_INTEGER"
ssSetDWorkDataType(%<s>, %<idx>,%<dtEnum>);
%elseif LibSFunctionLevel() != "RTWLevel2"
%assign raccelUseMexFile = ...
::isRAccel && ParamSettings.WillBeDynamicallyLoaded == "yes"
%if !raccelUseMexFile
%assign errTxt = "User-defined data type " ...
"%<LibGetDataTypeNameFromId(dtIdCurDWork)> is required " ...
"for DWork %<idx>, but the information needed to define this " ...
"data type is unknown. The generated code that normally " ...
"specifies the data type of this DWork is being omitted. " ...
"If additional custom code does not register this user-define data type " ...
"and set the data type of this DWork, then the generated code " ...
"will be incomplete."
%<LibBlockReportWarning(thisBlock, errTxt)>
%endif
%endif
%endif
%endif
ssSetDWorkComplexSignal(%<s>, %<idx>, ...
%<LibBlockDWorkIsComplex(dwork)>);
%if dwRec.UsedAs == "DSTATE"
ssSetDWorkUsedAsDState(%<s>, %<idx>, 1);
%endif
%<underScore>ssSetDWork(%<s>, %<idx>, ...
%<LibBlockDWorkAddr(dwork, "", "", 0)>);
%endforeach
}
%endif
%if numModes > 0
%<underScore>ssSetModeVector(%<s>, (int_T *) ...
&%<LibBlockMode("", "", 0)>);
%endif
%closefile tmpBuffer
%openfile retBuf
%if !WHITE_SPACE(tmpBuffer)
/* work vectors */
%<tmpBuffer>/
%endif
%closefile retBuf
%return retBuf
%endfunction
%function SLibSetupCallSysForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns)
%openfile retBuf
%if NumSFcnSysOutputCalls > 0
%assign SfcnIdx = "%<nonInlSfcns>.Sfcn%<childIdx>"
/* register function-calls */
{
%assign pZeroWidth = LibBlockOutputSignalWidth(0)
%if usingStatic
static int_T callSysOutputs[%<pZeroWidth>];
static void *callSysArgs1[%<pZeroWidth>];
static int_T callSysArgs2[%<pZeroWidth>];
static SysOutputFcn callSysFcns[%<4*pZeroWidth>];
%elseif SLibIsERTCodeFormat()
int_T *callSysOutputs = (int_T *) &%<SfcnIdx>.callSysOutputs;
void **callSysArgs1 = (void **) &%<SfcnIdx>.callSysArgs1;
int_T *callSysArgs2 = (int_T *) &%<SfcnIdx>.callSysArgs2;
SysOutputFcn *callSysFcns = (SysOutputFcn *) &%<SfcnIdx>.callSysFcns;
%else
int_T *callSysOutputs;
void **callSysArgs1;
int_T *callSysArgs2;
SysOutputFcn *callSysFcns;
callSysOutputs = (int_T *) ...
malloc(%<LibBlockOutputSignalWidth(0)> ...
* sizeof(int_T));
%<RTMChkMemAndReturnIfErr("callSysOutputs")>;
callSysArgs1 = (void **) ...
malloc(%<pZeroWidth> * sizeof(void *));
%<RTMChkMemAndReturnIfErr("callSysArgs1")>;
callSysArgs2 = (int_T *) ...
malloc(%<pZeroWidth> * sizeof(int_T));
%<RTMChkMemAndReturnIfErr("callSysArgs2")>;
callSysFcns = (SysOutputFcn *) ...
malloc(%<4*pZeroWidth> * sizeof(SysOutputFcn));
%<RTMChkMemAndReturnIfErr("callSysFcns")>;
%endif
%assign loopCode = SLibEmitForLoopCounterCode(pZeroWidth, "i")
{
%
% {
callSysOutputs[i] = 0;
callSysFcns[i] = (SysOutputFcn) %<SLibGetNullDefinitionFromTfl()>;
callSysFcns[%<pZeroWidth>+i] = (SysOutputFcn) %<SLibGetNullDefinitionFromTfl()>;
callSysFcns[2*%<pZeroWidth>+i] = (SysOutputFcn) %<SLibGetNullDefinitionFromTfl()>;
%if IsModelReferenceSimTarget()
%assign enableFcnIdx = 1
%assign disableFcnIdx = 2
%else
%assign enableFcnIdx = 2
%assign disableFcnIdx = 3
callSysFcns[3*%<pZeroWidth>+i] = (SysOutputFcn) %<SLibGetNullDefinitionFromTfl()>;
%endif
}
}
%<underScore>ssSetCallSystemOutputPtr(%<s>, &callSysOutputs[0]);
%<underScore>ssSetCallSystemOutputArg1List(%<s>, ...
&callSysArgs1[0]);
%<underScore>ssSetCallSystemOutputArg2List(%<s>, ...
&callSysArgs2[0]);
%<underScore>ssSetCallSystemOutputFcnList(%<s>, ...
&callSysFcns[0]);
%assign portEl = -1
%foreach fcnCallIdx = NumSFcnSysOutputCallDsts
%if portEl == SFcnSystemOutputCall[fcnCallIdx].OutputElement
%continue
%else
%assign portEl = SFcnSystemOutputCall[fcnCallIdx].OutputElement
%endif
%with SFcnSystemOutputCall[fcnCallIdx]
%if STRING(BlockToCall) != "unconnected"
%assign sysIdx = BlockToCall[0]
%assign blkIdx = BlockToCall[1]
%assign ssBlock = ::CompiledModel.System[sysIdx].Block[blkIdx]
%assign ppIf = ssBlock.VariantCondition
%<SLibIfVariantConditionForm(ppIf)>
%assign tidVal = ParamSettings.SampleTimesToSet[0][1]
callSysArgs1[%<OutputElement>] = (void *)%<RTMGetModelSS()>;
callSysArgs2[%<OutputElement>] = %<FcnPortElement>;
%assign fcnCallFNI = LibGetFcnCallFNI(ssBlock,FcnPortElement,tidVal)
%assign fcnInitializeFNI = LibGetFcnSystemResetFNI(ssBlock,FcnPortElement,tidVal)
%assign fcnEnableFNI = LibGetFcnEnableFNI(ssBlock,FcnPortElement,tidVal)
%assign fcnDisableFNI = LibGetFcnDisableFNI(ssBlock,FcnPortElement,tidVal)
%assert fcnCallFNI != ""
callSysFcns[%<OutputElement>] = (SysOutputFcn) %<fcnCallFNI>;
%if !IsModelReferenceSimTarget()
%if fcnInitializeFNI != ""
callSysFcns[%<pZeroWidth>+%<OutputElement>] = (SysOutputFcn) /
%<fcnInitializeFNI>;
%else
callSysFcns[%<pZeroWidth>+%<OutputElement>] = (SysOutputFcn) %<SLibGetNullDefinitionFromTfl()>;
%endif
%endif
%if fcnEnableFNI != ""
callSysFcns[%+%<OutputElement>] = (SysOutputFcn) /
%<fcnEnableFNI>;
%else
callSysFcns[%+%<OutputElement>] = (SysOutputFcn) %<SLibGetNullDefinitionFromTfl()>;
%endif
%if fcnDisableFNI != ""
callSysFcns[%+%<OutputElement>] = (SysOutputFcn) /
%<fcnDisableFNI>;
%else
callSysFcns[%+%<OutputElement>] = (SysOutputFcn) %<SLibGetNullDefinitionFromTfl()>;
%endif
%<SLibEndIfVariantConditionForm(ppIf)>
callSysOutputs[%<OutputElement>] = 1;
%else
/* Unconnected function-call */
callSysArgs1[%<OutputElement>] = (void *)%<SLibGetNullDefinitionFromTfl()>;
callSysArgs2[%<OutputElement>] = 0;
callSysFcns[%<OutputElement>] = (SysOutputFcn) %<SLibGetNullDefinitionFromTfl()>;
callSysFcns[%<pZeroWidth>+%<OutputElement>] = (SysOutputFcn) %<SLibGetNullDefinitionFromTfl()>;
callSysFcns[2*%<pZeroWidth>+%<OutputElement>] = (SysOutputFcn) %<SLibGetNullDefinitionFromTfl()>;
%if !IsModelReferenceSimTarget()
callSysFcns[3*%<pZeroWidth>+%<OutputElement>] = (SysOutputFcn) %<SLibGetNullDefinitionFromTfl()>;
%endif
%endif
%endwith
%endforeach
%undef sysIdx, blkIdx, ssIdx
}
%endif
%closefile retBuf
%return retBuf
%endfunction
%function SLibAdjustStInfoForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns)
%openfile tempBuffer
%foreach idx = SIZE(ParamSettings.SampleTimesToSet, 0)
%assign sfcnTID = ParamSettings.SampleTimesToSet[idx][0]
%assign mdlTID = ParamSettings.SampleTimesToSet[idx][1]
%if mdlTID < 0
%assign period = LibRealNonFinite(inf)
%assign offset = 0
%else
%assign period = ...
CAST("Real",::CompiledModel.SampleTime[mdlTID].PeriodAndOffset[0])
%assign offset = ...
CAST("Real",::CompiledModel.SampleTime[mdlTID].PeriodAndOffset[1])
%endif
ssSetSampleTime(%<s>, %<sfcnTID>, %<period>);
ssSetOffsetTime(%<s>, %<sfcnTID>, %<offset>);
%endforeach
%foreach idx = SIZE(ParamSettings.SampleTimesToSet, 0)
%assign sfcnTID = ParamSettings.SampleTimesToSet[idx][0]
%assign mdlTID = ParamSettings.SampleTimesToSet[idx][1]
%if mdlTID <0
sfcnTsMap[%<sfcnTID>] = %<mdlTID>;
%else
%if IsModelReferenceTarget()
%if (!MdlRefIsConstSampleBlock() || MdlRefHasParameterRate()) && ...
MdlRefDisallowSampleTimeInheritance()
sfcnTsMap[%<sfcnTID>] = mdlref_TID%<mdlTID>;
%else
%assert SIZE(ParamSettings.SampleTimesToSet, 0) == 1
sfcnTsMap[%<sfcnTID>] = 0;
%endif
%elseif CodeFormat == "S-Function" || GenerateErtSFunction
%if LibAsynchronousTriggeredTID(mdlTID)
sfcnTsMap[%<sfcnTID>] = 0;
%assert (SIZE(ParamSettings.SampleTimesToSet, 0) == 1)
%else
sfcnTsMap[%<sfcnTID>] = %<RTMGet("SampleTimeTaskIDPtr")>[%<mdlTID>];
%endif
%else
sfcnTsMap[%<sfcnTID>] = %<mdlTID>;
%endif
%endif
%endforeach
%closefile tempBuffer
%openfile retBuf
%if !WHITE_SPACE(tempBuffer)
/* adjust sample time */
%<tempBuffer>/
%endif
%closefile retBuf
%return retBuf
%endfunction
%function SLibCallChildSfcnInitializationFcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns)
%assign sfuncName = ParamSettings.FunctionName
%assign thisBlock = ChildSFunctionList[childIdx]
%openfile retBuf
/* registration */
%if (CodeFormat == "S-Function" && !usingStatic) || IsModelReferenceSimTarget()
%<SLibWriteSFunctionGuards("if")>
int_T i;
mxArray *plhs[1];
mxArray *prhs[4];
double *pr;
volatile int_T *intS = (int_T *)&%<s>;
int_T addrlen = sizeof(SimStruct *);
int_T m = addrlen/sizeof(int_T) + 1;
prhs[0] = mxCreateDoubleMatrix(0,0,mxREAL);
prhs[1] = mxCreateDoubleMatrix(m,1,mxREAL);
pr = mxGetPr(prhs[1]);
for (i = 0; i < m - 1; i++) {
pr[i] = (double)intS[i];
}
pr[i] = (double)SIMSTRUCT_VERSION_LEVEL2;
prhs[2] = mxCreateDoubleMatrix(0,0,mxREAL);
prhs[3] = mxCreateDoubleMatrix(1,1,mxREAL);
/* Reset port dimensions info functions because the S-function
* and accelerator mex-files explicitly set their dimensions,
* i.e., they are not dynamically sized. For this case, the
* mex-file is responsible for the dimensions info memory
* and Simulink should not free it. This is achieved by
* setting the following two methods to NULL.
*/
ssSetRegInputPortDimensionInfoFcn(%<s>, %<SLibGetNullDefinitionFromTfl()>);
ssSetRegOutputPortDimensionInfoFcn(%<s>, %<SLibGetNullDefinitionFromTfl()>);
/*
* Setup function pointers and call mdlInitializeSizes via
* simulink.c
*/
mexCallMATLAB(1, plhs, 4, prhs, "%<sfuncName>");
mxDestroyArray(plhs[0]);
mxDestroyArray(prhs[0]);
mxDestroyArray(prhs[1]);
mxDestroyArray(prhs[2]);
mxDestroyArray(prhs[3]);
%<SLibWriteSFunctionGuards("else")>
%assign simTargetWillUseSFcnMexFile = ...
IsModelReferenceSimTarget() && ParamSettings.WillBeDynamicallyLoaded == "yes"
%if simTargetWillUseSFcnMexFile
sfcnLoader_callSFcn("%<sfuncName>", "%<thisBlock.TLCBlockSID>", %<s>);
%else
%<sfuncName>(%<s>);
sfcnInitializeSizes(%<s>);
%endif
%<SLibWriteSFunctionGuards("endif")>
%if PortBasedSampleTimes == "no"
sfcnInitializeSampleTimes(%<s>);
%endif
%else
%assign raccelUseMexFile = ...
::isRAccel && ParamSettings.WillBeDynamicallyLoaded == "yes"
%assert !(raccelUseMexFile && ParamSettings.FunctionLevel == 1)
%if raccelUseMexFile
{
raccelLoadSFcnMexFile("%<sfuncName>", "%<thisBlock.TLCBlockSID>", %<s>, %<childIdx>);
if (ssGetErrorStatus(rtS)) {
return rtS;
}
}
%else
%<sfuncName>(%<s>);
%endif
%if !raccelUseMexFile
sfcnInitializeSizes(%<s>);
%endif
%if PortBasedSampleTimes == "no"
sfcnInitializeSampleTimes(%<s>);
%endif
%endif
%closefile retBuf
%return retBuf
%endfunction
%function SLibResetDynSizedFieldsForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns)
%assign thisBlock = ChildSFunctionList[childIdx]
%assign numDiscStates = DiscStates[0]
%assign numContStates = ContStates[0]
%openfile retBuf
%assign dsSize = SIZE(ParamSettings.DynamicallySizedVectors,1)
%if dsSize > 0
/* set compiled values of dynamic vector attributes */
%if ParamSettings.FunctionLevel == 1
%foreach idx = dsSize
%assign dsVar = ParamSettings.DynamicallySizedVectors[idx]
%switch dsVar
%case "U"
%if isRSimWithSolverModule
ssSetNumU(%<s>, %<LibBlockInputSignalWidth(0)>);
%else
ssSetNumInputs(%<s>, %<LibBlockInputSignalWidth(0)>);
%endif
%break
%case "Y"
%if isRSimWithSolverModule
ssSetNumY(%<s>, %<LibBlockOutputSignalWidth(0)>);
%else
ssSetNumOutputs(%<s>, %<LibBlockOutputSignalWidth(0)>);
%endif
%break
%case "Xc"
ssSetNumContStates(%<s>, %<numContStates>);
%break
%case "Xd"
ssSetNumDiscStates(%<s>, %<numDiscStates>);
%break
%case "RWork"
ssSetNumRWork(%<s>, %);
%break
%case "IWork"
ssSetNumIWork(%<s>, %);
%break
%case "PWork"
ssSetNumPWork(%<s>, %);
%break
%case "Modes"
ssSetNumModes(%<s>, %);
%break
%case "NonsampledZCs"
ssSetNumNonsampledZCs(%<s>, %<NumNonsampledZCs>);
%break
%default
%assign errTxt = "No case for dynamically sizing: %<dsVar>"
%<LibReportFatalError(errTxt)>
%endswitch
%endforeach
%else
%foreach idx = dsSize
%assign dsVar = ParamSettings.DynamicallySizedVectors[idx]
%assign idNum = IDNUM(dsVar)
%assign num = idNum[1]
%switch idNum[0]
%case "U"
%assign u = DataInputPort[num]
ssSetInputPortWidth(%<s>, %<num>, %<LibGetRecordWidth(u)>);
%assign dtIdCurInput = LibGetDataTypeIdAliasedThruToFromId(...
SLibGetRecordDataTypeId(u))
%if LibIsBuiltInDataType(dtIdCurInput)
%assign dtEnum = LibGetDataTypeEnumFromId(dtIdCurInput)
ssSetInputPortDataType(%<s>, %<num>, %<dtEnum>);
%elseif LibIsHalfDataType(dtIdCurInput)
DTypeId halfID = ssRegisterDataTypeHalfPrecision(
%<s>,
0 /* 0 means do NOT obey data type override setting for this subsystem */ );
ssSetInputPortDataType( %<s>, %<num>, halfID );
%else
%assign curDT = FixPt_GetDataTypeFromIndex(dtIdCurInput)
%if curDT.IsFixedPoint
{
DTypeId dataTypeIdReg =
%if FixPt_DataTypeIsFloat(curDT)
ssRegisterDataTypeFxpScaledDouble(
%else
ssRegisterDataTypeFxpFSlopeFixExpBias(
%endif
%<s>,
%<curDT.IsSigned>,
%<curDT.RequiredBits>,
%<curDT.FracSlope>,
%<curDT.FixedExp>,
%<curDT.Bias>,
0 /* false means do NOT obey data type override setting for this subsystem */ );
ssSetInputPortDataType(%<s>, %<num>, dataTypeIdReg );
}
%else
%assign dtEnum = LibGetDataTypeEnumFromId(dtIdCurInput)
%if dtEnum == "SS_POINTER" || dtEnum == "SS_INTEGER"
ssSetInputPortDataType(%<s>, %<num>, %<dtEnum>);
%else
%assign raccelUseMexFile = ...
::isRAccel && ParamSettings.WillBeDynamicallyLoaded == "yes"
%if !raccelUseMexFile
%assign errTxt = "User-defined data type " ...
"%<LibGetDataTypeNameFromId(dtIdCurInput)> is required " ...
"for Root Level Input %<num>, but the information needed to define this " ...
"data type in the generated S-Function code format is unknown."
%<LibBlockReportError(thisBlock, errTxt)>
%endif
%endif
%endif
%endif
ssSetInputPortComplexSignal(%<s>, %<num>, ...
%<SLibGetRecordIsComplex(u)>);
ssSetInputPortFrameData(%<s>, %<num>, ...
%<LibBlockInputSignalIsFrameData(num)>);
%if NumDataInputPorts>0
ssSetInputPortUnit(%<s>, %<num>, ...
%<LibBlockInputSignalUnitId(num)>);
%endif
ssSetInputPortIsContinuousQuantity(%<s>, %<num>, ...
%<LibBlockInputPortIsContinuousQuantity(num)>);
%break
%case "Y"
%assign yWidth = LibBlockOutputSignalWidth(num)
%assign op = FcnGetOutputPortRecord(num)
%assign sigRec = SLibGetSourceRecord(op, 0)
ssSetOutputPortWidth(%<s>, %<num>, %<yWidth>);
%if !ISEMPTY(sigRec)
%assign dtIdCurOutput = LibGetDataTypeIdAliasedThruToFromId(...
SLibGetRecordDataTypeId(sigRec))
%if LibIsBuiltInDataType(dtIdCurOutput)
%assign dtEnum = LibGetDataTypeEnumFromId(dtIdCurOutput)
ssSetOutputPortDataType(%<s>, %<num>, %<dtEnum>);
%elseif LibIsHalfDataType(dtIdCurOutput)
DTypeId halfID = ssRegisterDataTypeHalfPrecision(
%<s>,
0 /* 0 means do NOT obey data type override setting for this subsystem */ );
ssSetOutputPortDataType(%<s>, %<num>, halfID);
%else
%assign curDT = FixPt_GetDataTypeFromIndex(dtIdCurOutput)
%if curDT.IsFixedPoint
{
DTypeId dataTypeIdReg =
%if FixPt_DataTypeIsFloat(curDT)
ssRegisterDataTypeFxpScaledDouble(
%else
ssRegisterDataTypeFxpFSlopeFixExpBias(
%endif
%<s>,
%<curDT.IsSigned>,
%<curDT.RequiredBits>,
%<curDT.FracSlope>,
%<curDT.FixedExp>,
%<curDT.Bias>,
0 /* false means do NOT obey data type override setting for this subsystem */ );
ssSetOutputPortDataType(%<s>, %<num>, dataTypeIdReg);
}
%else
%assign dtEnum = LibGetDataTypeEnumFromId(dtIdCurOutput)
%if dtEnum == "SS_POINTER" || dtEnum == "SS_INTEGER"
ssSetOutputPortDataType(%<s>, %<num>,%<dtEnum>);
%else
%assign raccelUseMexFile = ...
::isRAccel && ParamSettings.WillBeDynamicallyLoaded == "yes"
%if !raccelUseMexFile
%assign errTxt = "User-defined data type " ...
"%<LibGetDataTypeNameFromId(dtIdCurOutput)> is required " ...
"for Root Level Output %<num>, but the information needed to define this " ...
"data type in the generated S-Function code format is unknown."
%<LibBlockReportError(thisBlock, errTxt)>
%endif
%endif
%endif
%endif
ssSetOutputPortComplexSignal(%<s>, %<num>, ...
%<SLibGetRecordIsComplex(sigRec)>);
ssSetOutputPortFrameData(%<s>, %<num>, ...
%<LibBlockOutputSignalIsFrameData(num)>);
%if NumDataOutputPorts>0
ssSetOutputPortUnit(%<s>, %<num>, ...
%<LibBlockOutputSignalUnitId(num)>);
%endif
ssSetOutputPortIsContinuousQuantity(%<s>, %<num>, ...
%<LibBlockOutputPortIsContinuousQuantity(num)>);
%endif
%break
%case "Xc"
ssSetNumContStates(%<s>, %<numContStates>);
%break
%case "Xd"
ssSetNumDiscStates(%<s>, %<numDiscStates>);
%break
%case "RWork"
ssSetNumRWork(%<s>, %);
%break
%case "IWork"
ssSetNumIWork(%<s>, %);
%break
%case "PWork"
ssSetNumPWork(%<s>, %);
%break
%case "DWork"
_ssSetNumDWork(%<s>, %<numDWorks>);
%break
%case "D"
%assign dwork = thisBlock.DWork[num]
ssSetDWorkWidth(%<s>, %<num>, ...
%<LibBlockDWorkWidth(dwork)>);
%assign dtIdCurDWork = LibGetDataTypeIdAliasedThruToFromId(...
LibBlockDWorkDataTypeId(dwork))
%if LibIsBuiltInDataType(dtIdCurDWork)
%assign dtEnum = LibGetDataTypeEnumFromId(dtIdCurDWork)
ssSetDWorkDataType(%<s>, %<num>, %<dtEnum>);
%elseif LibIsHalfDataType(dtIdCurDWork)
DTypeId halfID = ssRegisterDataTypeHalfPrecision(
%<s>,
0 /* 0 means do NOT obey data type override setting for this subsystem */ );
ssSetDWorkDataType( %<s>, %<num>, halfID );
%else
%assign curDT = FixPt_GetDataTypeFromIndex(dtIdCurDWork)
%if curDT.IsFixedPoint
{
DTypeId dataTypeIdReg =
%if FixPt_DataTypeIsFloat(curDT)
ssRegisterDataTypeFxpScaledDouble(
%else
ssRegisterDataTypeFxpFSlopeFixExpBias(
%endif
%<s>,
%<curDT.IsSigned>,
%<curDT.RequiredBits>,
%<curDT.FracSlope>,
%<curDT.FixedExp>,
%<curDT.Bias>,
0 /* false means do NOT obey data type override setting for this subsystem */ );
ssSetDWorkDataType(%<s>, %<num>, dataTypeIdReg );
}
%else
%assign dtEnum = LibGetDataTypeEnumFromId(dtIdCurDWork)
%if dtEnum == "SS_POINTER" || dtEnum == "SS_INTEGER"
ssSetDWorkDataType(%<s>, %<num>,%<dtEnum>);
%else
%assign raccelUseMexFile = ...
::isRAccel && ParamSettings.WillBeDynamicallyLoaded == "yes"
%if !raccelUseMexFile
%assign errTxt = "User-defined data type " ...
"%<LibGetDataTypeNameFromId(dtIdCurDWork)> is required " ...
"for DWork %<num>, but the information needed to define this " ...
"data type in the generated S-Function code format is unknown. " ...
"The generated code that normally " ...
"specifies the data type of this DWork is being omitted. " ...
"If additional custom code does not register this user-define data type " ...
"and set the data type of this DWork, then the generated code " ...
"will be incomplete."
%<LibBlockReportWarning(thisBlock, errTxt)>
%endif
%endif
%endif
%endif
ssSetDWorkComplexSignal(%<s>, %<num>, ...
%<LibBlockDWorkIsComplex(dwork)>);
%break
%case "Modes"
ssSetNumModes(%<s>, %);
%break
%case "NonsampledZCs"
ssSetNumNonsampledZCs(%<s>, %<NumNonsampledZCs>);
%break
%default
%assign errTxt = "No case for dynamically sizing: %<dsVar>"
%<LibReportFatalError(errTxt)>
%endswitch
%endforeach
%endif
%endif
%closefile retBuf
%return retBuf
%endfunction
%function SLibUpdatePortConnectivityForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns)
%openfile retBuf
%if ParamSettings.FunctionLevel == 2
/* Update connectivity flags for each port */
%foreach ipIdx = NumDataInputPorts
_ssSetInputPortConnected(%<s>, %<ipIdx>, ...
%<LibBlockInputSignalConnected(ipIdx)>);
%endforeach
%foreach ipIdx = NumDataOutputPorts
_ssSetOutputPortConnected(%<s>, %<ipIdx>, ...
%<LibBlockOutputSignalConnected(ipIdx)>);
%endforeach
%foreach ipIdx = NumDataOutputPorts
_ssSetOutputPortBeingMerged(%<s>, %<ipIdx>, ...
%<LibBlockOutputSignalBeingMerged(ipIdx)>);
%endforeach
/* Update the BufferDstPort flags for each input port */
%foreach ipIdx = NumDataInputPorts
%assign bufDst = LibBlockInputSignalBufferDstPort(ipIdx)
%<underScore>ssSetInputPortBufferDstPort(%<s>, %<ipIdx>, %<bufDst>);
%endforeach
%if PortBasedSampleTimes == "yes"
/* Update port-based sample time attributes */
%foreach ipIdx = NumDataInputPorts
_ssSetInputPortSampleTimeIndex(%<s>, %<ipIdx>, ...
%<LibBlockInputSignalLocalSampleTimeIndex(ipIdx)>);
ssSetInputPortSampleTime(%<s>, %<ipIdx>, ...
%<LibBlockInputSignalSampleTime(ipIdx)>);
ssSetInputPortOffsetTime(%<s>, %<ipIdx>, ...
%<LibBlockInputSignalOffsetTime(ipIdx)>);
%endforeach
%foreach opIdx = NumDataOutputPorts
_ssSetOutputPortSampleTimeIndex(%<s>, %<opIdx>, ...
%<LibBlockOutputSignalLocalSampleTimeIndex(opIdx)>);
ssSetOutputPortSampleTime(%<s>, %<opIdx>, ...
%<LibBlockOutputSignalSampleTime(opIdx)>);
ssSetOutputPortOffsetTime(%<s>, %<opIdx>, ...
%<LibBlockOutputSignalOffsetTime(opIdx)>);
%endforeach
sfcnInitializeSampleTimes(%<s>);
%endif
%endif
%closefile retBuf
%return retBuf
%endfunction
%function SLibInitRegDataTypeFcnToErrFcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns)
%openfile retBuf
%if (CodeFormat == "S-Function" && UsingMalloc && ParamSettings.FunctionLevel == 2) || ...
IsModelReferenceSimTarget()
(%<s>)->regDataType.arg1 = ((void *)(%<s>));
(%<s>)->regDataType.registerFcn = ((OldRegisterDataType)FcnSetErrorStatus);
(%<s>)->regDataType.getSizeFcn = ((GetDataTypeSize)FcnSetErrorStatus);
(%<s>)->regDataType.getZeroFcn = ((GetDataTypeZero)FcnSetErrorStatus);
(%<s>)->regDataType.getNameFcn = ((GetDataTypeName)FcnSetErrorStatus);
(%<s>)->regDataType.getIdFcn = ((GetDataTypeId)FcnSetErrorStatus);
%endif
%closefile retBuf
%return retBuf
%endfunction
%function SLibCacheBranchedSysCalledByNonInlinedSfcn() void
%foreach childIdx = NumChildSFunctions
%assign thisBlock = ChildSFunctionList[childIdx]
%if SLibSfcnHasBranchFcnCall(thisBlock)
%foreach callIdx = thisBlock.NumSFcnSysOutputCalls
%assign recIdx = thisBlock.SFcnSystemOutputCallMappingInfo[callIdx].StartingIdx
%assign nCalledFC = thisBlock.SFcnSystemOutputCallMappingInfo[callIdx].NumOfCalledFC
%if nCalledFC > 1
%assign fcOutPortEl = thisBlock.SFcnSystemOutputCall[recIdx].OutputElement
%assign firstBlkToCall = thisBlock.SFcnSystemOutputCall[recIdx].BlockToCall
%assign callPort = thisBlock.SFcnSystemOutputCall[recIdx].FcnPortIdx
%assert STRING(firstBlkToCall) != "unconnected"
%assign sysIdx = firstBlkToCall[0]
%assign blkIdx = firstBlkToCall[1]
%assign fcnCallBlock = ::CompiledModel.System[sysIdx].Block[blkIdx]
%if fcnCallBlock.Type == "SubSystem"
%with fcnCallBlock
%assert (Type == "SubSystem")
%assign sysIdx = LibBlockParamSetting("Subsystem", "SystemIdx")
%endwith
%assign fcnCallSys = System[sysIdx]
%if !LibIsSystemField(fcnCallSys, "CallerBlkIdx")
%<LibAddToSystem(fcnCallSys, "CallerBlkIdx", thisBlock.BlockIdx)>
%<LibAddToSystem(fcnCallSys, "CallerBlkPortEl", fcOutPortEl)>
%else
%<LibSetSystemField(fcnCallSys, "CallerBlkIdx",[-1 -1 -1])>
%<LibSetSystemField(fcnCallSys, "CallerBlkPortEl",-1)>
%endif
%elseif fcnCallBlock.Type == "ModelReference"
%if !ISFIELD(fcnCallBlock, "CallerBlkInfo")
%assign numInputPorts = fcnCallBlock.NumDataInputPorts
%if ISFIELD(fcnCallBlock.ParamSettings, "ModelEventPortNames")
%assign numInputPorts = numInputPorts + ...
SIZE(fcnCallBlock.ParamSettings.ModelEventPortNames, 1)
%endif
%foreach inputPort = numInputPorts
%addtorecord fcnCallBlock CallerBlkInfo { ...
CallerBlkIdx []; ...
CallerBlkPortEl -1}
%endforeach
%endif
%assign fcnCallBlock.CallerBlkInfo[callPort].CallerBlkIdx = thisBlock.BlockIdx
%assign fcnCallBlock.CallerBlkInfo[callPort].CallerBlkPortEl = fcOutPortEl
%endif
%endif
%endforeach
%endif
%endforeach
%endfunction
%function LibCacheChildSFunctionRegistration(s, modelName) void
%if NumChildSFunctions == 0 && ::CompiledModel.ModelBlocksHaveNonInlinedSfcns == 0
%assign ::CompiledModel.SFunctionRegistration = ""
%return ""
%endif
%assign usingStatic = !UsingMalloc && (!SLibIsERTCodeFormat())
%if CodeFormat == "S-Function" || IsModelReferenceSimTarget()
%assign underScore = "_"
%else
%assign underScore = ""
%endif
%assign baseSysIdx = GetBaseSystemIdx()
%with System[baseSysIdx]
%openfile sfunctionRegBuffer
%if GenRTModel
%if !IsModelReferenceTarget()
%<FcnSetupSFcnRTWInfo()>
%elseif !IsModelReferenceForASimstructBasedTarget() && ...
NumChildSFunctions > 0 && !GenerateClassInterface
%<RTMSet("RTWSfcnInfo", "rt_sfcnInfo")>;
%endif
%endif
%if NumChildSFunctions > 0
%<RTMSet("NumSFunctions", NumChildSFunctions)>;
/* register each child */
{
%assign nonInlSfcns = ""
%if usingStatic
static SimStruct childSFunctions[%<NumChildSFunctions>];
static SimStruct *childSFunctionPtrs[%<NumChildSFunctions>];
(void) %<LibGenMemFcnCall("memset", "(void *)&childSFunctions[0]", ...
"0", "sizeof(childSFunctions)")>;
%if CodeFormat == "S-Function"
%<RTMuSet("SFunctions", "&childSFunctionPtrs[0]")>;
%else
%<RTMSet("SFunctions", "&childSFunctionPtrs[0]")>;
%endif
%elseif SLibIsERTCodeFormat()
%assign nonInlSfcns = "%<RTMGet("NonInlinedSFcns")>"
(void) %<LibGenMemFcnCall("memset", ...
"(void *)&%<nonInlSfcns>.childSFunctions[0]", "0", ...
"%<NumChildSFunctions>*sizeof(SimStruct)")>;
%<RTMSet("SFunctions", "&%<nonInlSfcns>.childSFunctionPtrs[0]")>;
%else
SimStruct *childSFunctions;
SimStruct **childSFunctionPtrs;
childSFunctions = (SimStruct *) ...
malloc(%<NumChildSFunctions> * sizeof(SimStruct));
%<RTMChkMemAndReturnIfErr("childSFunctions")>;
(void) %<LibGenMemFcnCall("memset", "(void *)childSFunctions", "0", ...
"%<NumChildSFunctions>*sizeof(SimStruct)")>;
childSFunctionPtrs = (SimStruct **) ...
malloc(%<NumChildSFunctions> * sizeof(SimStruct *));
%<RTMChkMemAndReturnIfErr("childSFunctionPtrs")>;
%if CodeFormat == "S-Function"
%<RTMuSet("SFunctions", "childSFunctionPtrs")>;
%else
%<RTMSet("SFunctions", "childSFunctionPtrs")>;
%endif
%endif
%if NumChildSFunctions >= RollThreshold
{
int_T i;
for (i = 0; i < %<NumChildSFunctions>; i++) {
%if CodeFormat == "S-Function"
%<RTMuSetIdxed("SFunction", "i", "&childSFunctions[i]")>;
%elseif SLibIsERTCodeFormat()
%<RTMSetIdxed("SFunction", "i", "&%<nonInlSfcns>.childSFunctions[i]")>;
%else
%<RTMSetIdxed("SFunction", "i", "&childSFunctions[i]")>;
%endif
}
}
%elseif NumChildSFunctions >= 1
%foreach childIdx = NumChildSFunctions
%assign childSfunLabel = "childSFunctions[" + "%<childIdx>" + "]"
%assign childSfunAddrLabel = "&%<childSfunLabel>"
%if CodeFormat == "S-Function"
%<RTMuSetIdxed("SFunction", childIdx, childSfunAddrLabel)>;
%elseif SLibIsERTCodeFormat()
%assign childSfunLabel = "&%<nonInlSfcns>." + "%<childSfunLabel>"
%<RTMSetIdxed("SFunction", childIdx, childSfunLabel)>;
%else
%<RTMSetIdxed("SFunction", childIdx, childSfunAddrLabel)>;
%endif
%endforeach
%endif
%foreach childIdx = NumChildSFunctions
%assign thisBlock = ChildSFunctionList[childIdx]
%with thisBlock
%assign sfuncName = ParamSettings.FunctionName
%openfile tmpChildRegBuffer
%<SLibSetupTimingInfoForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns)>
%<SLibSetupMdlInfoForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns) >
%<SLibAllocateMethods2MemForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns) >
%<SLibAllocateStatesInfo2MemForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns) >
%<SLibSetupInputsForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns) >
%<SLibSetupOutputsForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns) >
%<SLibSetupStatesForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns) >
%<SLibSetupPathInfoForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns) >
%<SLibSetupSfcnParamsForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns) >
%<SLibSetupWorksForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns) >
%<SLibSetupCallSysForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns) >
%<SLibInitRegDataTypeFcnToErrFcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns)>
%<SLibCallChildSfcnInitializationFcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns) >
%<SLibAdjustStInfoForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns) >
%<SLibResetDynSizedFieldsForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns) >
%<SLibUpdatePortConnectivityForChildSfcn(s, childIdx, underScore, ...
usingStatic, nonInlSfcns) >
%assign raccelUseMexFile = ...
::isRAccel && ParamSettings.WillBeDynamicallyLoaded == "yes"
%if LibSFunctionLevel() == "RTWLevel2" && !raccelUseMexFile
%assert !IsModelReferenceTarget()
%if !UsingMalloc
%assign funcName = STRING(ParamSettings.FunctionName)
%assign end = SIZE(funcName,1) - 3
%assign origName = ""
%foreach idx = end
%assign origName = origName + funcName[idx]
%endforeach
%assign sidInc = "%<origName>_sfcn_rtw/%<origName>_sid.h"
/* Instance data for generated S-Function: %<origName> */
%if CodeFormat == "S-Function"
{
SimStruct *rts = childS;
#include "%<sidInc>"
}
%else
#include "%<sidInc>"
%endif
%endif
%endif
%closefile tmpChildRegBuffer
%if CodeFormat == "S-Function" && (sfuncName == ::CompiledModel.Name)
%assign errTxt = "/n/nDetected duplicate name '%<sfuncName>' for this generated " ...
"S-function and the noninlined S-function name from block '%<thisBlock.Name>'." ...
" Please choose another name for this generated S-function. "
%<LibReportError(errTxt)>
%endif
%assign varName = "SFcn_%<ParamSettings.FunctionName>_PrototypeCached"
%if !EXISTS("::CompiledModel.%<varName>")
%addtorecord ::CompiledModel %<varName> 1
%openfile fcnPrototype
%assign flag = LibExternInFcnDecls()
%if GenCPP
%assign flag = "extern /"C/""
%endif
%<flag> void %<ParamSettings.FunctionName>(SimStruct *%<s>);
%closefile fcnPrototype
%<LibCacheFunctionPrototype(fcnPrototype)>/
%endif
%assign thisSystem = ::CompiledModel.System[thisBlock.BlockIdx[0]]
%<SLibIfSystemVariantCondition(thisSystem)>
%<SLibIfVariantCondition(thisBlock)>
/* %<TypeLevel> Block: %<modelName>%<"/">%<Name> (%<sfuncName>) */
{
SimStruct *%<s> = %<RTMGetIdxed("SFunction", childIdx)>;
%<tmpChildRegBuffer>/
}
%<SLibEndIfVariantCondition(thisBlock)>
%<SLibEndIfSystemVariantCondition(thisSystem)>
%endwith
%endforeach
}
%endif
%closefile sfunctionRegBuffer
%endwith
%assign ::CompiledModel.SFunctionRegistration = sfunctionRegBuffer
%endfunction
%function LibSFunctionRegistrationIsEmpty() void
%<LibTrapCacheAssert(SFunctionRegistration)>
%return WHITE_SPACE(SFunctionRegistration)
%endfunction
%function LibDumpSFunctionRegistration() Output
%<LibTrapCacheAssert(SFunctionRegistration)>/
%if !WHITE_SPACE(SFunctionRegistration)
/* child S-Function registration */
%<SFunctionRegistration>/
%endif
%endfunction
%function GenStandaloneRegistrationFunction() void
%assign rootFile = GetBaseFileName()
%assign callBuf = ""
%foreach sysIdx = NumSystems
%assign system = System[sysIdx]
%if LibIsSystemField(system, "CachedInitializeDataBody") && ...
!WHITE_SPACE(LibGetSystemField(system, "CachedInitializeDataBody"))
%openfile regBuf
%assign fcnName = system.StandaloneInitializeFcn
%if LibSystemIsInlined(system)
%<SLibGetFcnComment(system,"Initialize")>/
%else
%assign fcnAbstract = SLibGetFcnCommentContents(system,"Initialize")
%assign fcnBlockDescription = SLibGetBlockDescriptionForSS(system,"Initialize")
%assign fcnReturns = "void"
%assign fcnParams = "void"
%createrecord fcnRec {Name fcnName; Returns fcnReturns; Params fcnParams; Abstract fcnAbstract; ...
Category "model"; GeneratedBy "commonreglib.tlc"; Type "Initialize"; ...
GeneratedFor FcnGeneratedFor(system); BlockDescription fcnBlockDescription}
%<SLibDumpFunctionBanner(fcnRec)>
%undef fcnRec
%endif
%<SLibIfSystemVariantCondition(system)>
%<SLibGetFcnMemSecPragmaForSystem(fcnName, "MemSecFuncInitTerm", "Pre", system)>/
%<fcnReturns> %<fcnName>(%<fcnParams>) {
%<LibGetSystemField(system, "CachedInitializeDataBody")>
}
%<SLibGetFcnMemSecPragmaForSystem(fcnName, "MemSecFuncInitTerm", "Post", system)>/
%<SLibEndIfSystemVariantCondition(system)>
%closefile regBuf
%<SLibCacheSystemCodeToFile("sys_fcn_defn", system, regBuf)>
%assign fileBaseName = SLibGetFileNameForSystemCode("mdl_src", system)
%openfile extRegBuf
%<SLibGetFcnMemSecPragmaForSystemOnDecl(fcnName, "MemSecFuncInitTerm", "Pre", system)>/
%<LibExternInFcnDecls()> void %<fcnName>(void);
%<SLibGetFcnMemSecPragmaForSystemOnDecl(fcnName, "MemSecFuncInitTerm", "Post", system)>/
%closefile extRegBuf
%if fileBaseName != rootFile
%<SLibCacheSystemCodeToFile("sys_standalone_reg_fcn_decl", system, extRegBuf)>
%else
%<SLibCacheCodeToFile("mdl_priv_fcn_decl",extRegBuf)>
%endif
%assign callBuf = callBuf + SLibIfSystemVariantCondition(system) + "/n"
%assign callBuf = callBuf + "%<fcnName>();/n"
%assign callBuf = callBuf + SLibEndIfSystemVariantCondition(system) + "/n"
%endif
%endforeach
%if !WHITE_SPACE(callBuf)
%assign callBuf = "/* Initialize subsystem data *//n" + callBuf
%endif
%return callBuf
%endfunction
%function SigSrcLivesInStandaloneSS(sigSrc) void
%assign retVal = TLC_FALSE
%if ((sigSrc[1] != -1) && System[sigSrc[0]].LivesInStandaloneSS[sigSrc[1]])
%assign retVal = TLC_TRUE
%endif
%return retVal
%endfunction
%function StandaloneParentSysIdxOfSigSrc(sigSrc) void
%assign retVal = -1
%if ((sigSrc[1] != -1) && System[sigSrc[0]].LivesInStandaloneSS[sigSrc[1]])
%assign retVal = System[sigSrc[0]].StandaloneParentSysIdx[sigSrc[1]]
%endif
%return retVal
%endfunction
%function StandaloneParentSysIdxOfDataRec(dataRec) void
%assert !ISEMPTY(dataRec.SigSrc)
%return StandaloneParentSysIdxOfSigSrc(SLibGetSystemAndCallSideIndex(dataRec))
%endfunction
%function SLibInitBlockIOHelperOld(ptrBlockIOLabel, startIdx, standaloneSSIdx) Output
%assign withSysIdx = standaloneSSIdx ? GetBaseSystemIdx() : standaloneSSIdx
%assign ::CurrentModuleIdx = System[withSysIdx].CGIRModuleIdx
%assign blkioIsEmpty = ::CompiledModel.DWorkAndBlockIOCombined ? ...
SLibModelDWorkStructIsEmpty() : SLibModelBlockIOStructIsEmpty()
%if !blkioIsEmpty
%assign memsetToZeroNeeded = 0
%openfile csgInitBuffer
%openfile straightInitBuffer
%openfile useLoopVarInitBuffer
%assign baseSystemIdx = GetBaseSystemIdx()
%assign numElemInMemoryChunk = 0
%assign prevSysIdx = -1
%assign prevInstIdx = -1
%assign prevDataTypeId = -1
%assign prevMemsetToZeroSuffice = -1
%assign numOutputsPlusOne = BlockOutputs.NumGlobalBlockOutputs + 1
%assign changeInMemoryChunk = 0
%assign localVoidPointerName = "pVoidBlockIORegion"
%foreach loopIdx = (numOutputsPlusOne - startIdx)
%assign boIdx = loopIdx + startIdx
%if boIdx != BlockOutputs.NumGlobalBlockOutputs && ...
ISEMPTY(BlockOutputs.GlobalBlockOutput[boIdx].SigSrc)
%continue
%endif
%assign fInfo = GetFinalPassAndNextTransitionIndex(boIdx, standaloneSSIdx)
%assign finalPass = fInfo[0]
%assign skipRecord = fInfo[1]
%assign nextStdIdx = fInfo[2]
%assign nextStartIdx = fInfo[3]
%if skipRecord
%continue
%endif
%if !finalPass
%assign bo = BlockOutputs.GlobalBlockOutput[boIdx]
%assign curSysIdx = System[bo.SigSrc[0]].HStructDeclSystemIdx
%assign curInstIdx = bo.SigSrc[1]
%assign curDataTypeId = LibGetDataTypeIdAliasedThruToFromId(LibGetRecordDataTypeId(bo))
%if !ISEMPTY(bo.InitialValue)
%if !FcnSkipDataInitialValueInReg(bo)
%if (bo.Invariant != "yes")
%if SLibRemoveZeroInitForData(bo, bo.InitialValue)
%continue
%endif
%endif
%assign id = SLibGetBlockOutputIdentifierFromRecord(bo,baseSystemIdx)
%selectfile csgInitBuffer
%<FcnInitDataInitialValue(bo, id)>
%endif
%continue
%endif
%if SLibRemoveZeroInitForDataDefault(bo)
%continue
%endif
%assign nterms = LibGetRecordWidth(bo)
%if LibGetRecordIsComplex(bo)
%assign nterms = 2*nterms
%endif
%if ...
(curSysIdx != prevSysIdx ) || ...
(curInstIdx != prevInstIdx ) || ...
(curDataTypeId != prevDataTypeId )
%assign changeInMemoryChunk = 1
%else
%assign changeInMemoryChunk = 0
%endif
%if changeInMemoryChunk
%assign curMemsetToZeroSuffice = FcnMemsetToZeroInitSuffice(curDataTypeId)
%if curMemsetToZeroSuffice
%assign memsetToZeroNeeded = 1
%endif
%endif
%endif
%if changeInMemoryChunk || finalPass
%if ( numElemInMemoryChunk > 0 ) && ...
!prevMemsetToZeroSuffice
%assign prevDataTypeDefaultInitValue = ...
SLibGetDefaultInitialValueFromId(prevDataTypeId)
%assign prevDataTypeName = ...
LibGetDataTypeNameFromId(prevDataTypeId)
%if FcnSuitableForMemset(prevDataTypeDefaultInitValue, prevDataTypeId, "") && ...
FcnPreferMemsetToAssignment(numElemInMemoryChunk, prevDataTypeId)
%selectfile straightInitBuffer
%assign sanitizedInitValue = ...
FcnCastValueForMemsetUse(prevDataTypeId, prevDataTypeDefaultInitValue)
(void) %<LibGenMemFcnCall("memset", prevStartAddr, sanitizedInitValue, ...
"%<numElemInMemoryChunk>*sizeof(%<prevDataTypeName>)")>;
%else
%if numElemInMemoryChunk > 1
%selectfile useLoopVarInitBuffer
%<localVoidPointerName> = (void *)(%<prevStartAddr>);
for (i = 0; i < %<numElemInMemoryChunk>; i++) {
((%<prevDataTypeName>*)%<localVoidPointerName>)[i] = ...
%<prevDataTypeDefaultInitValue>;
}
%else
%selectfile straightInitBuffer
((%<prevDataTypeName>*)%<prevStartAddr>)[0] = ...
%<prevDataTypeDefaultInitValue>;
%endif
%endif
%endif
%if !finalPass
%assign prevSysIdx = curSysIdx
%assign prevInstIdx = curInstIdx
%assign prevDataTypeId = curDataTypeId
%assign prevMemsetToZeroSuffice = curMemsetToZeroSuffice
%assign numElemInMemoryChunk = 0
%if prevMemsetToZeroSuffice
%assign prevStartAddr = "#error do not use address: memset zero sufficient"
%else
%assign prevStartAddr = SLibGetBlockOutputFromRecord(bo,baseSystemIdx)
%endif
%endif
%endif
%if !finalPass
%assign numElemInMemoryChunk = numElemInMemoryChunk + nterms
%endif
%if finalPass
%break
%endif
%endforeach
%closefile csgInitBuffer
%closefile straightInitBuffer
%closefile useLoopVarInitBuffer
%if memsetToZeroNeeded
%if standaloneSSIdx == -1
%assign blockIOType = IsModelReferenceTarget() ? ...
System[NumSystems-2].Interface.tsysBlockIOType : ::tBlockIOType
(void) %<LibGenMemFcnCall("memset", ptrBlockIOLabel, "0", ...
"sizeof(%<blockIOType>)")>;
%<SLibAccessArgHelper(System[baseSystemIdx].Interface.BlockIOArgDef,"","")>
%else
%assign type = System[standaloneSSIdx].Interface.tsysBlockIOType
%assign var = "(void *) &" + System[standaloneSSIdx].Interface.tsysBlockIO
(void) %<LibGenMemFcnCall("memset", var, "0", "sizeof(%<type>)")>;
%endif
%endif
%if !WHITE_SPACE(csgInitBuffer) ...
|| !WHITE_SPACE(straightInitBuffer) ...
|| !WHITE_SPACE(useLoopVarInitBuffer)
{
%if !WHITE_SPACE(useLoopVarInitBuffer)
int_T i;
void *%<localVoidPointerName>;
%<useLoopVarInitBuffer>/
%endif
%<straightInitBuffer>/
%<csgInitBuffer>/
}
%endif
%endif
%assign ::CurrentModuleIdx = -1
%return [%<nextStdIdx>, %<nextStartIdx>]
%endfunction
%function LocalInitDworkVectorOld(stdSSBuf, stdIdx, ...
initCount, contents, initValue, dType, baseAddr, ppIf, ppFi) void
%openfile tmpBuf
%<ppIf>
%if initCount == 1
%<contents> = %<initValue>;
%elseif initCount >= RollThreshold
{
int_T i;
%<dType> *dwork_ptr = (%<dType> *) %<baseAddr>;
for (i = 0; i < %<initCount>; i++) {
dwork_ptr[i] = %<initValue>;
}
}
%else
{
%<dType> *dwork_ptr = (%<dType> *) %<baseAddr>;
%foreach initIdx = initCount
dwork_ptr[%<initIdx>] = %<initValue>;
%endforeach
}
%endif
%<ppFi>
%closefile tmpBuf
%assign stdSSBuf.DWorkBuff[stdIdx].initBuffer = ...
stdSSBuf.DWorkBuff[stdIdx].initBuffer + tmpBuf
%return stdSSBuf
%endfunction
%function SLibInitDWorkOld(stdSSBuf) void
%assign prevDataTypeIdx = -1
%assign prevStdIdx = -1
%assign initCount = 0
%foreach dwIdx = ::CompiledModel.DWorks.NumNonLocalDWorks
%assign dwRec = ::CompiledModel.DWorks.DWork[dwIdx]
%if SLibOmitRecord(dwRec) || dwRec.StorageClass != "Auto"
%continue
%endif
%assign idx = SLibGetSystemAndCallSideIndex(dwRec)
%if SigSrcLivesInStandaloneSS(idx)
%assign baseSystemIdx = StandaloneParentSysIdxOfDataRec(dwRec)
%else
%assign baseSystemIdx = GetBaseSystemIdx()
%endif
%assign stdIdx = System[baseSystemIdx].IndexInStandaloneSubsystemArray
%if SLibRemoveZeroInitForDataDefault(dwRec)
%continue
%endif
%if dwRec.SharedLocalDSMForHasBeenInit
%continue
%endif
%assign nterms = SLibDWorkWidth(dwRec)
%assign isComplex = SLibDWorkIsComplex(dwRec)
%assign vcRecord = SLibGetDataInlineVariantNetConditions(dwRec)
%assign vcRecord = FcnAddSharedDataInitProtection(dwRec, vcRecord)
%assign ifCond = vcRecord.ifCond
%assign ifEndCond = vcRecord.endIfCond
%if prevDataTypeIdx != SLibDWorkDataTypeId(dwRec) || prevStdIdx != stdIdx
%if initCount > 0
%assign stdSSBuf.DWorkBuff[prevStdIdx].haveFloat = 1
%assign dType = LibGetDataTypeNameFromId(prevDataTypeIdx)
%assign defaultInitialValue = SLibGetDefaultInitialValueFromId(prevDataTypeIdx)
%assign stdSSBuf = ...
LocalInitDworkVectorOld(stdSSBuf, prevStdIdx, ...
initCount, contents, defaultInitialValue, dType, baseAddr, ifCond, ifEndCond)
%assign initCount = 0
%endif
%assign prevDataTypeIdx = SLibDWorkDataTypeId(dwRec)
%assign prevStdIdx = stdIdx
%if (LibGetDataTypeIdAliasedThruToFromId(prevDataTypeIdx) == tSS_DOUBLE || ...
LibGetDataTypeIdAliasedThruToFromId(prevDataTypeIdx) == tSS_SINGLE)
%if InitFltsAndDblsToZero
%assign name = FcnGetDWorkIdentifier(dwRec, baseSystemIdx)
%assign dataLayout = SLibGetDataLayout(dwRec)
%assign reim = isComplex ? ".%<tRealPart>" : ""
%assign initCount = isComplex ? nterms * 2 : nterms
%assign contents = "%<name>%%<reim>"
%assign baseAddr = "&%<contents>"
%elseif SLibZeroMemory("DWork")
%assign stdSSBuf.DWorkBuff[stdIdx].needMemset = 1
%endif
%elseif (prevDataTypeIdx>1) && SLibZeroMemory("DWork")
%assign stdSSBuf.DWorkBuff[stdIdx].needMemset = 1
%endif
%else
%if LibGetDataTypeIdAliasedThruToFromId(prevDataTypeIdx) == tSS_DOUBLE ||...
LibGetDataTypeIdAliasedThruToFromId(prevDataTypeIdx) == tSS_SINGLE
%if InitFltsAndDblsToZero
%assign nterms = isComplex ? nterms * 2 : nterms
%assign initCount = initCount + nterms
%elseif SLibZeroMemory("DWork")
%assign stdSSBuf.DWorkBuff[stdIdx].needMemset = 1
%endif
%endif
%endif
%endforeach
%if initCount > 0
%assert(prevStdIdx == stdIdx)
%assign stdSSBuf.DWorkBuff[prevStdIdx].haveFloat= 1
%assign dType = LibGetDataTypeNameFromId(prevDataTypeIdx)
%assign defaultInitialValue = SLibGetDefaultInitialValueFromId(prevDataTypeIdx)
%assign stdSSBuf = ...
LocalInitDworkVectorOld(stdSSBuf,prevStdIdx, ...
initCount, contents, defaultInitialValue, dType, baseAddr, ifCond, ifEndCond)
%endif
%if stdSSBuf.DWorkBuff[0].needMemset
%assert(!IsModelReferenceTarget())
%assign baseSystemIdx = GetBaseSystemIdx()
%<SLibAccessArgHelper(System[baseSystemIdx].Interface.DWorkArgDef,"","")>
%endif
%return stdSSBuf
%endfunction
%function SLibIsSimulinkFunctionArginReused(fcnRec, arginIdx) void
%assign isInout = TLC_FALSE
%foreach inoutIdx = (SIZE(fcnRec.InoutArgs)[1])/2
%if fcnRec.InoutArgs[ inoutIdx * 2 ] == arginIdx
%assign isInout = TLC_TRUE
%break
%endif
%endforeach
%return isInout
%endfunction
%function FcnSlFcnInputArgTypeStrAuto(typeName, argName, fcnRec, argIdx, width, cgTypeIdx, slTypeIdx, isAutosarRteActive)
%if isAutosarRteActive
%assign constPrefix = SLibAutosarGetPtrConstPrefix()
%else
%assign constPrefix = "const"
%endif
%if LibCGTypeIsMatrix(cgTypeIdx) && "1"!=width
%if isAutosarRteActive
%assign arg = "%<constPrefix> %<typeName>* %<argName>"
%assign isPtrType = TLC_TRUE
%else
%assign argName = "%<argName>[%<width>]"
%assign arg = "%<constPrefix> %<typeName> %<argName>"
%assign isPtrType = TLC_FALSE
%endif
%assign isConstData = ISEQUAL(constPrefix,"const")
%elseif LibCGTypeIsStruct(cgTypeIdx) && ...
!LibIsDataTypeMultiWordFixpt(slTypeIdx) && ...
!LibCGTypeIsComplex(cgTypeIdx)
%assign arg = "%<constPrefix> %<typeName> *%<argName>"
%assign isPtrType = TLC_TRUE
%assign isConstData = ISEQUAL(constPrefix,"const")
%else
%assign arg = "%<typeName> %<argName>"
%assign isConstData = TLC_FALSE
%assign isPtrType = TLC_FALSE
%endif
%if SLibAutosarCompilerAbstractionRequired()
%assign retType = SLibAutosarCompilerAbstractionForDataDecl(isConstData, typeName, isPtrType, TLC_FALSE, argName, "DataAutomatic")
%else
%assign retType = arg
%endif
%return retType
%endfunction
%function FcnSlFcnInputArgTypeStr(typeName, argName, fcnRec, argIdx, width, cgTypeIdx, slTypeIdx, isAutosarRteActive)
%assign passByType = fcnRec.ArginPassByType[argIdx]
%if passByType==eSLFARG_PASSBYTYPE.AUTO
%return FcnSlFcnInputArgTypeStrAuto(typeName, argName, fcnRec, argIdx, width, cgTypeIdx, slTypeIdx,isAutosarRteActive)
%else
%assign isaVoidPtr = passByType==eSLFARG_PASSBYTYPE.POINTER_VOID || passByType==eSLFARG_PASSBYTYPE.POINTER_CONST_VOID
%if isaVoidPtr
%assign typeName = "void"
%endif
%assign typeStr = typeName
%assign isArrSizeOne = passByType==eSLFARG_PASSBYTYPE.ARR_SIZEONE || passByType==eSLFARG_PASSBYTYPE.CONST_ARR_SIZEONE
%assign isMatrix = !isaVoidPtr && ...
( isArrSizeOne || (LibCGTypeIsMatrix(cgTypeIdx) && "1"!=width) )
%if isMatrix
%assign typeStr = "%<typeStr> %<argName>[%<width>]"
%assign isPtrType = TLC_FALSE
%else
%switch passByType
%case eSLFARG_PASSBYTYPE.POINTER
%case eSLFARG_PASSBYTYPE.POINTER_VOID
%case eSLFARG_PASSBYTYPE.POINTER_CONST_VOID
%case eSLFARG_PASSBYTYPE.POINTER_CONST_DATA
%assign typeStr = "%<typeStr> *%<argName>"
%assign isPtrType = TLC_TRUE
%break
%case eSLFARG_PASSBYTYPE.CONST_POINTER_CONST_DATA
%assign typeStr = "%<typeStr> * const %<argName>"
%assign isPtrType = TLC_TRUE
%break
%default
%assign typeStr = "%<typeStr> %<argName>"
%assign isPtrType = TLC_FALSE
%endswitch
%endif
%switch passByType
%case eSLFARG_PASSBYTYPE.CONST_DATA
%case eSLFARG_PASSBYTYPE.CONST_ARR_SIZEONE
%case eSLFARG_PASSBYTYPE.POINTER_CONST_DATA
%case eSLFARG_PASSBYTYPE.POINTER_CONST_VOID
%case eSLFARG_PASSBYTYPE.CONST_POINTER_CONST_DATA
%assign typeStr = "const %<typeStr>"
%assign isConstData = TLC_TRUE
%break
%default
%assign isConstData = TLC_FALSE
%endswitch
%if SLibAutosarCompilerAbstractionRequired()
%if isMatrix
%assign argName = "%<argName>[%<width>]"
%endif
%assign retType = SLibAutosarCompilerAbstractionForDataDecl(isConstData, typeName, isPtrType, TLC_FALSE, argName, "DataAutomatic")
%else
%assign retType = typeStr
%endif
%return retType
%endif
%endfunction
%function FcnSlFcnOutputArgTypeStrAuto(typeName, argName, width, cgTypeIdx, isAutosarRteActive)
%assign isMatrix = LibCGTypeIsMatrix(cgTypeIdx) && "1"!=width
%if isMatrix
%if isAutosarRteActive
%assign arg = "%<typeName>* %<argName>"
%assign isPtrType = TLC_TRUE
%else
%assign argName = "%<argName>[%<width>]"
%assign arg = "%<typeName> %<argName>"
%assign isPtrType = TLC_FALSE
%endif
%else
%assign arg = "%<typeName> *%<argName>"
%assign isPtrType = TLC_TRUE
%endif
%if SLibAutosarCompilerAbstractionRequired()
%assign retType = SLibAutosarCompilerAbstractionForDataDecl(TLC_FALSE, typeName, isPtrType, TLC_FALSE, argName, "DataAutomatic")
%else
%assign retType = arg
%endif
%return retType
%endfunction
%function FcnSlFcnOutputArgTypeStr(typeName, argName, fcnRec, argIdx, width, cgTypeIdx, isAutosarRteActive)
%assign passByType = fcnRec.ArgoutPassByType[argIdx]
%if passByType==eSLFARG_PASSBYTYPE.AUTO
%return FcnSlFcnOutputArgTypeStrAuto(typeName, argName, width, cgTypeIdx, isAutosarRteActive)
%else
%assign isaVoidPtr = passByType==eSLFARG_PASSBYTYPE.POINTER_VOID || passByType==eSLFARG_PASSBYTYPE.POINTER_CONST_VOID
%if isaVoidPtr
%assign typeName = "void"
%endif
%assign typeStr = typeName
%assign isArrSizeOne = passByType==eSLFARG_PASSBYTYPE.ARR_SIZEONE
%assign isMatrix = !isaVoidPtr && ...
( isArrSizeOne || (LibCGTypeIsMatrix(cgTypeIdx) && "1"!=width) )
%if isMatrix
%assign typeStr = "%<typeStr> %<argName>[%<width>]"
%assign isPtrType = TLC_FALSE
%else
%switch passByType
%case eSLFARG_PASSBYTYPE.POINTER
%case eSLFARG_PASSBYTYPE.POINTER_VOID
%assign typeStr = "%<typeStr> *%<argName>"
%assign isPtrType = TLC_TRUE
%break
%default
%assign errTxt = "Invalid type specified for output argument '%<argName>' of Simulink Function '%<fcnRec.Name>'"
%<LibReportFatalError(errTxt)>
%endswitch
%endif
%if SLibAutosarCompilerAbstractionRequired()
%if isMatrix
%assign argName = "%<argName>[%<width>]"
%endif
%assign retType = SLibAutosarCompilerAbstractionForDataDecl(TLC_FALSE, typeName, isPtrType, TLC_FALSE, argName, "DataAutomatic")
%else
%assign retType = typeStr
%endif
%return retType
%endif
%endfunction
%function FcnDeclareSimulinkFunctionArg(fcnRec, argType, argIdx, arg, args, sep, isAutosarRteActive, stripAlias) void
%if argType == "I"
%assign cgTypeIdx = fcnRec.ArginCGTypeIdxFlat[argIdx]
%assign slTypeIdx = LibCGTypeToSLType(cgTypeIdx)
%assign argType = stripAlias ? LibAliasedThruCGTypeName(cgTypeIdx) : LibCGTypeName(cgTypeIdx)
%assign width = LibCGTypeSymbolicWidth(cgTypeIdx)
%assign arg = FcnSlFcnInputArgTypeStr(argType, arg, fcnRec, argIdx, width, cgTypeIdx, slTypeIdx, isAutosarRteActive)
%assign args = "%<args>%<sep>%<arg>"
%assign sep = ", "
%else
%assert argType == "O"
%assign cgTypeIdx = fcnRec.ArgoutCGTypeIdxFlat[argIdx]
%assign argType = stripAlias ? LibAliasedThruCGTypeName(cgTypeIdx) : LibCGTypeName(cgTypeIdx)
%assign width = LibCGTypeSymbolicWidth(cgTypeIdx)
%assign arg = FcnSlFcnOutputArgTypeStr(argType, arg, fcnRec, argIdx, width, cgTypeIdx, isAutosarRteActive)
%assign args = "%<args>%<sep>%<arg>"
%assign sep = ", "
%endif
%return args
%endfunction
%function SLibDeclareSimulinkFunction(fcnRec, stripAlias, useSlArgNames) Output
%if SuppressSimulinkFunctionArgumentControl == "yes"
%assign fcnDecl = SLibDeclareSimulinkFunctionIgnoreArgMap(fcnRec, stripAlias)
%else
%assign fcnDecl = SLibDeclareSimulinkFunctionUseArgMap(fcnRec, stripAlias, useSlArgNames)
%endif
%return fcnDecl
%endfunction
%function SLibDeclareSimulinkFunctionIgnoreArgMap(fcnRec, stripAlias) Output
%if ::isRAccel && ...
(((fcnRec.IsCalled == "yes") && (fcnRec.IsCalledInThisModel == "no")) || ...
((fcnRec.IsDefined == "yes") && (fcnRec.IsDefinedInThisModel == "no")))
%return
%endif
%if !SLibSimulinkFunctionNeedsDeclaration(fcnRec)
%return
%endif
%assign args = ""
%assign sep = ""
%assign isAutosarRteActive = TLC_FALSE
%foreach idx = SIZE(fcnRec.ArginCGTypeIdxFlat)[1]
%assign argType = "I"
%assign arg = "argin%<idx>"
%assign args = FcnDeclareSimulinkFunctionArg(fcnRec, argType, idx, arg, args, sep, isAutosarRteActive, stripAlias)
%assign sep = ","
%endforeach
%foreach idx = SIZE(fcnRec.ArgoutCGTypeIdxFlat)[1]
%assign argType = "O"
%assign arg = "argout%<idx>"
%assign args = FcnDeclareSimulinkFunctionArg(fcnRec, argType, idx, arg, args, sep, isAutosarRteActive, stripAlias)
%assign sep = ","
%endforeach
%assign fcnPrototype = "extern void %<fcnRec.CGFunctionName>("
%assign comma = ""
%assign needsContext = (fcnRec.IsMultiInstance == "yes") && !::GenerateClassInterface
%if needsContext
%assign fcnPrototype = fcnPrototype + "%<tSimStructType> * const %<tSimStruct>"
%assign comma = ","
%endif
%if args != ""
%assign fcnPrototype = fcnPrototype + "%<comma>%<args>);//"
%else
%if needsContext
%assign fcnPrototype = fcnPrototype + ");//"
%else
%assign fcnPrototype = fcnPrototype + "void);//"
%endif
%endif
%openfile buffer
%<fcnPrototype>
%closefile buffer
%return buffer
%endfunction
%function SLibDeclareSimulinkFunctionUseArgMap(fcnRec, stripAlias, useSlArgNames) Output
%if !SLibSimulinkFunctionNeedsDeclaration(fcnRec)
%return
%endif
%assign fcnLHS = SLibSimulinkFunctionDeclarationGetLHS(fcnRec)
%assign isAutosarRteActive = TLC_FALSE
%assign fcnRHS = SLibSimulinkFunctionDeclarationGetRHS(fcnRec, isAutosarRteActive, stripAlias, useSlArgNames)
%assign extern = ::GenerateClassInterface ? "" : "extern"
%openfile buffer
%<extern> %<fcnLHS> %<fcnRec.CGFunctionName>(%<fcnRHS>);/
%closefile buffer
%return buffer
%endfunction
%function SLibSimulinkFunctionDeclarationGetRHS(fcnRec, isAutosarRteActive, stripAlias, useSlArgNames)
%assign argIndices = fcnRec.ArgIndices
%assign argNames = fcnRec.ArgNames
%assign numArgs = SIZE(argIndices)[1]
%if numArgs == 0
%assign args = "void"
%else
%assign args = ""
%assign sep = ""
%endif
%if !::GenerateClassInterface && ...
(fcnRec.IsDefinedInThisModel == "yes" && ...
(MultiInstanceERTCode || (IsModelReferenceTarget() && ::CompiledModel.OkToMultiInstanceModelref)))
%assign arg = "%<tSimStructType> * const %<tSimStruct>"
%assign args = "%<arg>%<sep>%<args>"
%assign sep = ", "
%endif
%foreach idx = numArgs
%assign argIdNum = IDNUM(argIndices[idx])
%assign argType = argIdNum[0]
%assign argIdx = argIdNum[1]
%if useSlArgNames
%if argType == "I"
%assign arg = fcnRec.SlArginNames[argIdx]
%else
%assert argType == "O"
%assign arg = fcnRec.SlArgoutNames[argIdx]
%endif
%else
%assign arg = argNames[idx]
%endif
%assign args = FcnDeclareSimulinkFunctionArg(fcnRec, argType, argIdx, arg, args, sep, isAutosarRteActive, stripAlias)
%assign sep = ", "
%endforeach
%return args
%endfunction
%function SLibSimulinkFunctionDeclarationGetLHS(fcnRec)
%assign retIdx = fcnRec.ReturnArgIndex
%if retIdx < 0
%assign retType = "void"
%else
%assign cgTypeIdx = fcnRec.ArgoutCGTypeIdxFlat[retIdx]
%assign retType = LibCGTypeName(cgTypeIdx)
%endif
%if SLibAutosarCompilerAbstractionRequired()
%assign retType = SLibAutosarCompilerAbstractionForFcnDeclRtnType(retType, "FuncCalledByRTE", "")
%endif
%return retType
%endfunction
%function SLibSimulinkFunctionNeedsDeclaration(fcnRec)
%if (fcnRec.IsConstUncalledFunction == "yes" || ...
(fcnRec.IsCalledInThisModel == "no") && ...
(fcnRec.IsDefinedInThisModel == "no")) || ...
ISEMPTY(fcnRec.FullPathToFunction) || ...
(fcnRec.FullPathToFunction[0] != "G" && fcnRec.FullPathToFunction[0] != "P" ) || ...
(fcnRec.IsMultiInstance == "yes")
%assign needsDecalartion = TLC_FALSE
%else
%assign needsDecalartion = TLC_TRUE
%endif
%return needsDecalartion
%endfunction
%function SLibRateGroupedSimulinkFunctionNeedsDeclaration(system, aFcnType, aTID)
%if SLibIsRateGroupedSLFcn(system, aFcnType, aTID)
%foreach fcnIdx = NumSimulinkFunctions
%assign fcn = SimulinkFunction[fcnIdx]
%if fcn.CGFunctionName == SampleTime[aTID].EntryFcnName && ...
SLibSimulinkFunctionNeedsDeclaration(fcn) && ...
!(GenerateClassInterface && fcn.FullPathToFunction != "G") && ...
!IsModelReferenceSimTarget()
%return TLC_TRUE
%endif
%endforeach
%endif
%return TLC_FALSE
%endfunction
%function SLibGetRateGroupedSimulinkFunctionName(system, aFcnType, aTID)
%assign fcnName = ""
%if SLibIsRateGroupedSLFcn(system, aFcnType, aTID)
%foreach fcnIdx = NumSimulinkFunctions
%assign fcn = SimulinkFunction[fcnIdx]
%if fcn.CGFunctionName == SampleTime[aTID].EntryFcnName
%return fcn.Name
%endif
%endforeach
%endif
%return fcnName
%endfunction
%function SLibGetSimulinkFunctionNameInNonExportFcnModel(system)
%assign fcnName = ""
%if LibIsGlobalServer(system) || SLibIsModelScopedServer(system)
%foreach fcnIdx = NumSimulinkFunctions
%assign fcn = SimulinkFunction[fcnIdx]
%if fcn.CGFunctionName == system.Identifier
%return fcn.Name
%endif
%endforeach
%endif
%return fcnName
%endfunction
%function SLibWriteSFunctionGuards(sectionName) Output
%switch sectionName
%case "if"
%assign preprocessorVal = "#if defined(MATLAB_MEX_FILE)"
%assign codeVal = "if(! slIsRapidAcceleratorSimulating())"
%assign startBrace = "{"
%assign stopBrace = ""
%break
%case "else"
%assign preprocessorVal = "#else"
%assign codeVal = "else"
%assign startBrace = "{"
%assign stopBrace = "}"
%break
%case "endif"
%assign preprocessorVal = "#endif"
%assign codeVal = ""
%assign startBrace = ""
%assign stopBrace = "}"
%break
%default
%assert TLC_FALSE
%endswitch
%<stopBrace>
%if IsModelReferenceTarget()
%<codeVal>
%else
%<preprocessorVal>
%endif
%<startBrace>
%endfunction
%function IsConfiguredForConditionalMATFileCode() void
%assign isConditionalLoggingCodeNeeded = TLC_FALSE
%assign dlo = ::CompiledModel.DataLoggingOpts
%if MatFileLogging && FcnIsOutputLoggingEnabled(dlo)
%if ISFIELD(VariantConditions, "CGVCEList")
%assign cgvceList = VariantConditions.CGVCEList
%else
%assign cgvceList = ""
%endif
%assign nOutportBlks = ExternalOutputs.NumExternalOutputs
%foreach idx = nOutportBlks
%assign extOut = ExternalOutputs.ExternalOutput[idx]
%assign sysIdx = extOut.Block[0]
%assign blkIdx = extOut.Block[1]
%assign outportBlock = System[sysIdx].Block[blkIdx]
%if !FcnExtOutLoggable(extOut)
%continue
%endif
%if ISFIELD(extOut, "LocalCGVCEIdx") && (extOut.LocalCGVCEIdx != -1)
%assign variantCondition = cgvceList[extOut.LocalCGVCEIdx]
%else
%continue
%endif
%if ISFIELD(outportBlock, "Inactive")
%continue
%endif
%if !ISEMPTY(variantCondition)
%assign isConditionalLoggingCodeNeeded = TLC_TRUE
%break
%endif
%endforeach
%endif
%return isConditionalLoggingCodeNeeded
%endfunction
%function SLibDeclareExternalSimulinkFunctions() Output
%if !(IsModelReferenceSimTarget() || isRAccel)
%return
%endif
%with ::CompiledModel
%openfile tmpBuf
%foreach fcnIdx = NumSimulinkFunctions
%assign fcnRec = SimulinkFunction[fcnIdx]
%if SLibSimulinkFunctionNeedsDeclaration(fcnRec) && fcnRec.IsRateGrouped == "no"
%<SLibDeclareSimulinkFunction(fcnRec, TLC_FALSE, TLC_FALSE)>
%endif
%endforeach
%closefile tmpBuf
%if !WHITE_SPACE(tmpBuf)
%<SLibCacheCodeToFile("mdl_hdr_userBottom", tmpBuf)>
%endif
%endwith
%endfunction
%function SLibSimulinkFunctionCtx(tType, tArg) void
%if tType == "tSimStruct"
%return RTMGet("MdlRefSfcnS")
%elseif tType == "tFunction"
%return "/"%<tArg>/""
%else
%assign errTxt = "Unknown option tType in SLibSimulinkFunctionCtx"
%<LibReportFatalError(errTxt)>
%endif
%endfunction
%function SLibInitLegacyStorageClassVarGroup(varGroupIdx) void
%openfile returnBuffer
%assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
%foreach elIdx = varGroup.NumVarGroupElements
%assign idnum = IDNUM(SLibVarGroupElementSource(varGroupIdx, elIdx))
%assign recType = idnum[0]
%assign recIdx = idnum[1]
%if SLibIsLocalVariableRecordType(varGroupIdx, elIdx)
%continue
%endif
%if recType == "VG"
%assign subGroupBuff = SLibInitLegacyStorageClassVarGroup(recIdx)
%<subGroupBuff>
%continue
%endif
%assign dataRec = SLibGetDataRecForVarGroupMember(recType, recIdx)
%assign cscDefn = dataRec.CSCDefn
%assign dataInit = SLibGetDataInitForData(cscDefn, dataRec)
%if ((dataInit == "Static" || dataInit == "None") || ...
(ISFIELD(dataRec, "RecordType") && dataRec.RecordType == "ModelParameter" && dataInit == "Auto"))
%continue
%endif
%if !ISEMPTY(SLibDataTypeConstructFcnName(LibGetRecordDataTypeId(dataRec)))
%continue
%endif
%assign dataScope = SLibGetDataScope(dataRec.CSCDefn, dataRec)
%if dataScope == "Imported"
%continue
%endif
%assign isExtOut = (ISFIELD(dataRec, "RecordType") && dataRec.RecordType == "ExternalOutput")
%if isExtOut && (FcnIgnoreExtOutForInit(dataRec) || !FcnInitializeExternalOutput(dataRec))
%continue
%endif
%assign vcRecord = SLibGetDataInlineVariantNetConditions(dataRec)
%assign ifCond = vcRecord.ifCond
%assign ifEndCond = vcRecord.endIfCond
%assign stdSSIdx = -1
%assign sysIdx = -1
%if (ISFIELD(dataRec, "RecordType") && ...
(dataRec.RecordType == "BlockOutput" || dataRec.RecordType == "DWork"))
%assign sysIdx = StandaloneParentSysIdxOfDataRec(dataRec)
%if sysIdx == -1 && dataScope == "File"
%assign sysIdx = FcnGetNonRootFileFunctionOwner(dataRec, sysIdx)
%endif
%endif
%if sysIdx != -1
%assign stdSSIdx = sysIdx
%assign stdSSBuffer = ""
%endif
%openfile initCode
%if isExtOut
%assign sysIdx = dataRec.Block[0]
%assign blkIdx = dataRec.Block[1]
%assign outportBlock = System[sysIdx].Block[blkIdx]
%with outportBlock
%<SLibEmitLibCustomInitCode(dataRec, LibGetRecordSymbolicWidth(dataRec), LibGetRecordIsComplex(dataRec))>
%endwith
%else
%<SLibEmitLibCustomInitCode(dataRec, LibGetRecordSymbolicWidth(dataRec), LibGetRecordIsComplex(dataRec))>
%endif
%closefile initCode
%if !WHITE_SPACE(initCode)
%if stdSSIdx != -1
%openfile tmpBuffer
%endif
%<ifCond>
%<initCode>
%<ifEndCond>
%if stdSSIdx != -1
%closefile tmpBuffer
%assign stdSSBuffer = stdSSBuffer + tmpBuffer
%endif
%endif
%if stdSSIdx != -1 && !WHITE_SPACE(stdSSBuffer)
%<LibAddToSystemField(System[stdSSIdx],"TempInitBuffer",...
stdSSBuffer)>
%endif
%endforeach
%closefile returnBuffer
%<FcnCacheStandaloneSubsyInitFromTempBuffers("/* Storage classes */")>
%return returnBuffer
%endfunction
%function SLibInitBlockIOForVarGroup(varGroupIdx, initBuffers)
%assign retBuffers = initBuffers
%assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
%foreach elIdx = varGroup.NumVarGroupElements
%assign idnum = IDNUM(varGroup.VarGroupElements[elIdx])
%assign recType = idnum[0]
%assign recIdx = idnum[1]
%if recType == "B"
%assign bo = ::CompiledModel.BlockOutputs.GlobalBlockOutput[recIdx]
%assign ret = SLibInitBlockIOForBufferHelper(bo, baseSystemIdx, TLC_TRUE)
%if !bo.InitInStart
%assign retBuffers.buffers[0] = retBuffers.buffers[0] + ret[0]
%assign retBuffers.buffers[1] = retBuffers.buffers[1] + ret[1]
%assign retBuffers.buffers[2] = retBuffers.buffers[2] + ret[2]
%endif
%if ret[3]
%assign retBuffers.buffers[3] = ret[3]
%endif
%if IsModelReferenceSimTarget() || ::isRAccel
%assign boDataTypeId = LibGetRecordDataTypeId(bo)
%assign boWidth = LibGetRecordWidth(bo)
%assign id = SLibGetBlockOutputIdentifierFromRecord(bo, baseSystemIdx)
%openfile stringInitBuffer
%<SlibInitStringData(boDataTypeId, id, boWidth)>
%closefile stringInitBuffer
%assign retBuffers.buffers[1] = retBuffers.buffers[1] + stringInitBuffer
%endif
%elseif recType == "W"
%assign dwRec = ::CompiledModel.DWorks.DWork[recIdx]
%if dwRec.SharedLocalDSMForHasBeenInit
%continue
%endif
%assign idx = SLibGetSystemAndCallSideIndex(dwRec)
%if SigSrcLivesInStandaloneSS(idx)
%assign sysIdxToUse = StandaloneParentSysIdxOfDataRec(dwRec)
%else
%assign sysIdxToUse = GetBaseSystemIdx()
%endif
%assign cross = System[sysIdxToUse].CrossNoArgFcnBound
%assign vcRecord = SLibGetDataInlineVariantNetConditions(dwRec)
%assign vcRecord = FcnAddSharedDataInitProtection(dwRec, vcRecord)
%assign ifCond = vcRecord.ifCond
%assign ifEndCond = vcRecord.endIfCond
%assign stdIdx = System[sysIdxToUse].IndexInStandaloneSubsystemArray
%assign retBuffers.ssBuf = SLibInitDWorkHelper(retBuffers.ssBuf, stdIdx, sysIdxToUse, ...
cross, dwRec, TLC_FALSE, ifCond, ifEndCond)
%elseif recType == "VG"
%assign retBuffers = SLibInitBlockIOForVarGroup(recIdx, retBuffers)
%endif
%endforeach
%return retBuffers
%endfunction
%endif