%%
%%Copyright1994-2019TheMathWorks,Inc.
%%
%%Abstract:Opaqueblocklibrary
 
%include "%<LibGetModelName()>_aux.tlc"
 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%Helperfunctions
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 
%%Function:SLibCG_SE
%%Abstract:
%%Provideasafeexpressionwhenintegratingwithaunknownenvironment.
%%Thisfunctionwilltakeaexpressioninputandaddparenthesesaroundit
%%ifthisexpressionisnotselfcontained,i.e.asymbol,oranexpression
%%containedbyparenthesesalready
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%
%function SLibCG_SE(in) void
  %%
  %switch TYPE(in)
      %%
    %case "String"
      %%
      %assign eRetValNeedsParen = 1
      %%
      %assign retVal = NEEDS_PAREN(in)
      %%
      %if (retVal & eRetValNeedsParen)
        %%
        %return "(%<in>)"
      %endif
      %break
    %case "Unsigned"
      %%
      %break
      %%
    %case "Real"
    %case "Number"
    %case "Real32"
      %%
      %if in < 0
        %return "(%<in>)"
      %endif
      %%
      %break
      %%
    %default
      %<LibReportFatalError("Internal error: unhandled cases")>
  %endswitch
  %return in
  %%
%endfunction
 
%function SLibCG_ReIm(accessStr, reim) void
  %return ISEMPTY(reim) ? "" : accessStr + reim
%endfunction
 
%function SLibCG_ArrayIndexer(ucv, lcv, offset) void
  %assign indexer = SLibGetStructFieldIndexExpr("", ucv, lcv, offset)
  %return indexer == "[]" ? "" : indexer
%endfunction %% SLibCG_ArrayIndexer
 
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%
%function SLibCG_AccessArg(aModuleIdx, aFcnIdx, aArgIdx) void
  %assign thisModule = ::CompiledModel.RTWCGModules.RTWCGModule[aModuleIdx]
  %assign thisFcn = thisModule.Function[aFcnIdx]
  %assert thisFcn.NumArgs > aArgIdx
  %if 2 > thisFcn.ArgAccessed[aArgIdx] %% not already globally accessed
    %if thisModule.AccessesArgsGlobally
      %assign thisFcn.ArgAccessed[aArgIdx] = 2 %% global variable access
    %else
      %assign thisFcn.ArgAccessed[aArgIdx] = 1 %% function argument access
    %endif
  %endif
%endfunction
 
%function SLibCG_GlobalAccessArg(aModuleIdx, aFcnIdx, aArgIdx) void
  %assign fcn = ...
    ::CompiledModel.RTWCGModules.RTWCGModule[aModuleIdx].Function[aFcnIdx]
  %assert fcn.NumArgs > aArgIdx
  %assign fcn.ArgAccessed[aArgIdx] = 2 %% global variable access
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%
%function SLibCG_UndoAccessArg(aModuleIdx, aFcnIdx, aArgIdx) void
  %assign fcn = ...
    ::CompiledModel.RTWCGModules.RTWCGModule[aModuleIdx].Function[aFcnIdx]
  %assert fcn.NumArgs > aArgIdx
  %assign fcn.ArgAccessed[aArgIdx] = 0
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%
%function SLibCG_ArgAccessed(aModuleIdx, aFcnIdx, aArgIdx) void
  %assign fcn = ...
    ::CompiledModel.RTWCGModules.RTWCGModule[aModuleIdx].Function[aFcnIdx]
  %assert fcn.NumArgs > aArgIdx
  %return (0 < fcn.ArgAccessed[aArgIdx])
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%
%function SLibCG_FcnCallArgAccessed(aModuleIdx, aFcnIdx, aCallIdx, aArgIdx) void
  %assign thisFcn = ...
    ::CompiledModel.RTWCGModules.RTWCGModule[aModuleIdx].Function[aFcnIdx]
  %assert thisFcn.NumFcnCalls > aCallIdx
  %assign thisCall = thisFcn.FunctionCall[aCallIdx]
  %assign calleeModIdx = thisCall.CalleeIdx[0]
  %assign calleeFcnIdx = thisCall.CalleeIdx[1]
  %return SLibCG_ArgAccessed(calleeModIdx, calleeFcnIdx, aArgIdx)
%endfunction
 
%function SLibCG_FcnHasRTMArg(aFcnRec) void
  %if aFcnRec.SimStructArgIndex > -1
    %return aFcnRec.ArgAccessed[aFcnRec.SimStructArgIndex] > 0
  %endif
  %return TLC_FALSE
%endfunction
 
%function SLibCG_RTMAccessed() void
  %assign modIdx = ::CurrentModuleIdx
  %assign fcnIdx = ::CurrentFunctionIdx
  %if modIdx > -1 && fcnIdx > -1
    %assign thisMod = ::CompiledModel.RTWCGModules.RTWCGModule[modIdx]
    %assign thisFcn = thisMod.Function[fcnIdx]
    %if thisFcn.SimStructArgIndex > -1
      %return SLibCG_ArgAccessed(modIdx, fcnIdx, thisFcn.SimStructArgIndex)
    %endif
  %endif
  %return TLC_FALSE
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%
%function SLibCG_AccessRTM() void
  %assign modIdx = ::CurrentModuleIdx
  %assign fcnIdx = ::CurrentFunctionIdx
  %if modIdx > -1 && fcnIdx > -1
    %assign thisMod = ::CompiledModel.RTWCGModules.RTWCGModule[modIdx]
    %assign thisFcn = thisMod.Function[fcnIdx]
    %assign thisSystem = ::CompiledModel.System[thisMod.CGSystemIdx]
    %assign skipTracking = ((IsModelReferenceBaseSys(thisSystem) && (IsModelRefScalableBuild() || GenerateClassInterface)) ||...
      (GenerateClassInterface && SLibIsMultiInstanceServer(thisSystem)))
    %if thisFcn.SimStructArgIndex > -1 && !skipTracking
      %<SLibCG_AccessArg(modIdx, fcnIdx, thisFcn.SimStructArgIndex)>
    %endif
  %endif
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%
%function SLibCG_UndoAccessRTM() void
  %assign modIdx = ::CurrentModuleIdx
  %assign fcnIdx = ::CurrentFunctionIdx
  %if modIdx > -1 && fcnIdx > -1
    %assign thisMod = ::CompiledModel.RTWCGModules.RTWCGModule[modIdx]
    %assign thisFcn = thisMod.Function[fcnIdx]
    %if thisFcn.SimStructArgIndex > -1
      %<SLibCG_UndoAccessArg(modIdx, fcnIdx, thisFcn.SimStructArgIndex)>
    %endif
  %endif
%endfunction
 
 
%%Function:SLibCG_GetRTMArgumentName=============================================================
%%Abstract:
%%ReturntheSimStructorRTMargumentnameofthecurrentfunction.
%%
%function SLibCG_GetRTMArgumentName() void
  %assign modIdx = ::CurrentModuleIdx
  %assign fcnIdx = ::CurrentFunctionIdx
  %if modIdx > -1 && fcnIdx > -1
    %assign thisMod = ::CompiledModel.RTWCGModules.RTWCGModule[modIdx]
    %assign thisFcn = thisMod.Function[fcnIdx]
    %if thisFcn.SimStructArgIndex > -1
      %<SLibCG_AccessArg(modIdx, fcnIdx, thisFcn.SimStructArgIndex)>
      %assign argName = thisFcn.ArgNames[thisFcn.SimStructArgIndex]
      %if "/%<::tSimStruct>" == argName || "/%<tSimStruct>" == argName
        %return ::tSimStruct
      %endif
      %return thisFcn.ArgNames[thisFcn.SimStructArgIndex]
    %endif
  %endif
  %return ::tSimStruct
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%
%function SLibCG_AccessFirstArg() void
  %assign modIdx = ::CurrentModuleIdx
  %assign fcnIdx = ::CurrentFunctionIdx
  %if modIdx > -1 && fcnIdx > -1
    %assign thisMod = ::CompiledModel.RTWCGModules.RTWCGModule[modIdx]
    %assign thisFcn = thisMod.Function[fcnIdx]
    %if thisMod.SimplifiedInterface && thisFcn.NumArgs > 0
      %<SLibCG_AccessArg(modIdx, fcnIdx,0)>
    %endif
  %endif
%endfunction
 
%function SLibCG_GetNonInlinedSysIdx(aModule) void
  %return ::CompiledModel.System[aModule.CGSystemIdx].NonInlinedParentSystemIdx
%endfunction
 
%function SLibCG_GetNonInlinedSystem(aModule) void
  %return ::CompiledModel.System[SLibCG_GetNonInlinedSysIdx(aModule)]
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmVariantsRSim.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%
%function SLibCG_AccessFcnTID(aModIdx, aFcnIdx) void
  %assign thisMod = ::CompiledModel.RTWCGModules.RTWCGModule[aModIdx]
  %assign thisFcn = thisMod.Function[aFcnIdx]
  %if thisFcn.TIDArgIndex > -1
    %<SLibCG_AccessArg(aModIdx, aFcnIdx, thisFcn.TIDArgIndex)>
  %elseif thisFcn.FunctionType == "Output"
    %assign thisSystem = SLibCG_GetNonInlinedSystem(thisMod)
    %<SLibSetNeedLocalTIDInSystem(thisSystem, "Output")>
  %elseif thisFcn.FunctionType == "Update"
    %assign thisSystem = SLibCG_GetNonInlinedSystem(thisMod)
    %<SLibSetNeedLocalTIDInSystem(thisSystem, "Update")>
  %endif
%endfunction %% SLibCG_AccessFcnTID
 
%function SLibIsCustomCodeFcnEmpty(system, sysFcnType, tid) void
  %return ...
    WHITE_SPACE(LibGetSystemField(system, sysFcnType + "Header")) && ...
    WHITE_SPACE(LibGetSystemField(system, sysFcnType + "Body")) && ...
    WHITE_SPACE(LibGetSystemField(system, sysFcnType + "Trailer")) && ...
    WHITE_SPACE(LibGetSystemField(system, sysFcnType + "Header" + tid)) && ...
    WHITE_SPACE(LibGetSystemField(system, sysFcnType + "Body" + tid)) && ...
    WHITE_SPACE(LibGetSystemField(system, sysFcnType + "Trailer" + tid))
     
%endfunction
 
%function SLibCustomCodeNeedsTID(system, sysFcnType, tid) void
  %if ::CompiledModel.CustomCodeNeedTID
    %if "Outputs" == sysFcnType
      %return !SLibIsCustomCodeFcnEmpty(system, "Output", "%<tid>")
    %elseif "Update" == sysFcnType
      %return !SLibIsCustomCodeFcnEmpty(system, "Update", "%<tid>")
    %endif
  %endif
  %return TLC_FALSE
%endfunction
   
%function SLibCG_AccessTID() void
  %assign modIdx = ::CurrentModuleIdx
  %assign fcnIdx = ::CurrentFunctionIdx
  %if modIdx > -1 && fcnIdx > -1
    %<SLibCG_AccessFcnTID(modIdx, fcnIdx)>
  %else
    %assign ::CompiledModel.CustomCodeNeedTID = TLC_TRUE
  %endif
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/inlineVariants/ivGeneral/tVariantsAndSubmodels.m
%%
%function SLibCG_AccessCPI() void
  %assign modIdx = ::CurrentModuleIdx
  %assign fcnIdx = ::CurrentFunctionIdx
  %if modIdx > -1 && fcnIdx > -1
    %assign thisMod = ::CompiledModel.RTWCGModules.RTWCGModule[modIdx]
    %assign thisFcn = thisMod.Function[fcnIdx]
    %if thisFcn.CPIArgIndex > -1
      %<SLibCG_AccessArg(modIdx, fcnIdx, thisFcn.CPIArgIndex)>
    %endif
  %endif
%endfunction
 
%function SLibCG_SetFcnProtoType(aModuleIdx, aFcnIdx, aFcnProtoType) void
  %assign fcn = ...
    ::CompiledModel.RTWCGModules.RTWCGModule[aModuleIdx].Function[aFcnIdx]
  %assign fcn.ProtoType = aFcnProtoType
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/inlineVariants/ivGeneral/tVariantsAndSubmodels.m
%%
%function SLibFcnGenBodySysFcn(system,blkFcnName,multiTID) void
  %if blkFcnName == "Outputs"
    %assign ::CompiledModel.GeneratingOutputsCode = 1
  %endif
   
  %if SLibNonEmptyModel()
    %with system
      %assign rootOpaqueBlock = FcnRootOpaqueBlock()
      %assign bodyFcn = FcnGenerateCodeFromModule(rootOpaqueBlock, system, blkFcnName)
    %endwith
  %elseif multiTID
    %%Only Update and Output functions can have multiTID being true
    %assert blkFcnName == "Update" || blkFcnName == "Outputs"
    %assign Multirate_Buffers = []
    %foreach Tid = NumSampleTimes
      %assign Multirate_Buffers = Multirate_Buffers + ""
    %endforeach
  %endif
 
  %%
  %if blkFcnName == "Outputs"
    %assign ::CompiledModel.GeneratingOutputsCode = 0
  %endif
   
  %if SLibNonEmptyModel() && !WHITE_SPACE(bodyFcn)
    %return bodyFcn
  %elseif multiTID
    %return Multirate_Buffers
  %else
    %return ""
  %endif
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tmg1672961.m
%%
%function SLibFcnGenCodeFragmentAccess(aModule, aFcnIdx) void
  %assign sysFcn = ::BlockFcn
  %assign thisFcn = aModule.Function[aFcnIdx]
  %assign thisSystem = ::CompiledModel.System[aModule.CGSystemIdx]
  %assign cTID = thisSystem.CurrentTID
  %assign isRG = SLibSystemFcnPeriodicRateGrouping(thisSystem, sysFcn)
  %with thisSystem.Interface
    %assert SIZE(thisFcn.ArgAccessed, 1) == thisFcn.NumArgs
    %assert SIZE(thisFcn.ArgSource, 1) == thisFcn.NumArgs
    %foreach argIdx=thisFcn.NumArgs
      %if thisFcn.ArgAccessed[argIdx] > 0
        %assign idNum = SLibSafeIDNUM(thisFcn.ArgSource, argIdx)
        %assign argSrc = idNum[0]
        %assign argSrcIdx = idNum[1]
        %switch argSrc
          %case "I" %% canonical input
            %assign canInputRecord = CanonicalInputArgDef[argSrcIdx]
            %<SLibAccessArg(canInputRecord, sysFcn, cTID, isRG)>
            %break
          %case "O" %% canonical output
            %assign canOutputRecord = CanonicalOutputArgDef[argSrcIdx]
            %<SLibAccessArg(canOutputRecord, sysFcn, cTID, isRG)>
            %break
          %case "D" %% canonical dwork
            %assign canDWorkRecord = CanonicalDWorkArgDef[argSrcIdx]
            %<SLibAccessArg(canDWorkRecord, sysFcn, cTID, isRG)>
            %break
          %case "P" %% canonical parameters
            %assign canParamRecord = CanonicalPrmArgDef[argSrcIdx]
            %<SLibAccessArg(canParamRecord, sysFcn, cTID, isRG)>
            %break
          %case "LB" %% block IO
          %case "LCDG"
            %<SLibAccessArg(BlockIOArgDef, sysFcn, cTID, isRG)>
            %break
          %case "LC" %% constat block IO
            %<SLibAccessArg(ConstBlockIOArgDef, sysFcn, cTID, isRG)>
            %break
          %case "LW" %% dwork
            %<SLibAccessArg(DWorkArgDef, sysFcn, cTID, isRG)>
            %break
          %case "LP" %% parameter
          %case "LCP" %% constant parameter
          %case "LPI" %% const parameter with init
            %<SLibAccessArg(ParameterArgDef, sysFcn, cTID, isRG)>
            %break
          %case "LX" %% continues states
            %<SLibAccessArg(ContStatesArgDef, sysFcn, cTID, isRG)>
            %break
          %case "LDX" %% derivatives
            %<SLibAccessArg(ContStatesDerivativeArgDef, sysFcn, cTID, isRG)>
            %break
          %case "LXDI" %% continues state disabled
            %<SLibAccessArg(ContStatesDisabledArgDef, sysFcn, cTID, isRG)>
            %break
          %case "LXAT" %% continues state absolute tolerance
            %<SLibAccessArg(ContStatesAbsoluteToleranceArgDef, sysFcn, cTID, isRG)>
            %break
          %case "LXPTMIN" %% continues state perturbation min
            %<SLibAccessArg(ContStatesPerturbMinArgDef, sysFcn, cTID, isRG)>
            %break
          %case "LXPTMAX" %% continues state perturbation min
            %<SLibAccessArg(ContStatesPerturbMaxArgDef, sysFcn, cTID, isRG)>
            %break
          %case "LZ" %% non-sampled zero crossings
            %<SLibAccessArg(ZCSVArgDef, sysFcn, cTID, isRG)>
            %break
          %case "LZE" %% zero crossing events
            %<SLibAccessArg(ZCEventArgDef, sysFcn, cTID, isRG)>
            %break
          %case "RTM"
            %<SLibAccessArg(RTMArgDef, sysFcn, cTID, isRG)>
            %break
          %case "X"
            %if !ISEMPTY(thisFcn.ArgTypes[argIdx])
                %break
            %endif
          %case "CPI"
          %case "TID"
          %case "U"
          %case "Y"
          %default
            %%START_ASSERT
            %assign errTxt = "Unhandled argument type '%<argSrc>'."
            %<LibBlockReportError([],errTxt)>
            %break
            %%END_ASSERT
        %endswitch
      %endif
    %endforeach
  %endwith
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tmg1672961.m
%%
%function SLibFcnGenCodeFragment(aSystem, aSystemFcnType) void
  %assign retVal = ""
  %if SLibNonEmptyModel()
    %with aSystem
      %assign moduleIdx = aSystem.CGIRModuleIdx
      %assign module = ::CompiledModel.RTWCGModules.RTWCGModule[moduleIdx]
      %if ISFIELD(module, "SystemFunctionTypes") && ...
        ISFIELD(module.SystemFunctionTypes, aSystemFcnType)
 
        %assign opaqueBlock = FcnRootOpaqueBlock()
        %assign prevModuleIdx = ::CurrentModuleIdx
        %assign ::CurrentModuleIdx = moduleIdx
        %assign retVal = ...
          FcnGenerateCodeFromModule(opaqueBlock, aSystem, aSystemFcnType)
        %assign fcnIdx = GETFIELD(module.SystemFunctionTypes, aSystemFcnType)
        %<SLibFcnGenCodeFragmentAccess(module, fcnIdx)>
        %assign ::CurrentModuleIdx = prevModuleIdx
      %endif
    %endwith
  %endif
  %return retVal
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%TopTester:test/toolbox/simulink/blocks/lib_MathOperations/Gain/rtw/tdtgain4.m
%%TopTester:test/toolbox/simulink/blocks/tconcat.m
%%TopTester:test/toolbox/simulink/blocks/lib_Discrete/DiscreteTimeIntegrator/rtw/tdintegrt.m
%%TopTester:test/toolbox/simulink/blocks/lib_LookupTables/LookupTable2D/rtw/tlookup2d.m
%%
%function SLibFcnGenBodyFcnCache(system,sysFcnType,blkFcnName,profCode,multiTID) void
  %assign ::CompiledModel.NeedTID = 0 %% reset NeedTid flag
   
  %%
  %% For S-Function target (right click build), construct root
  %% systemInitialize this way:
  %%
  %% #define MDL_INITIALIZE_CONDITIONS
  %% static void mdlInitializeConditions(SimStruct *S)
  %% {
  %% // so putting common code (initialize) here (before if branch)
  %% // may lead to incorrect code generation
  %% if (ssIsFirstInitCond(S)) {
  %% // systemInitialize function body here
  %% // contains initialize and systemInitialize
  %% } else {
  %% // systemReset function body here
  %% // contains initialize and systemReset
  %% }
  %% }
  %%
  %% S-Function block should have block initialize method instead of
  %% systemInitialize and systemReset.
  %% Thus make root systemInitialize look like above as normal
  %% initialize method, make root systemReset empty since the logic is
  %% absorbed in root initialize method (!ssIsFirstInitCond part).
  %%
  %assign combineInitAndReset = system.Type == "root" && ...
    CodeFormat == "S-Function" && !Accelerator
  %% Adding definitions and declarations for wrapper functions for
  %% the sim-target so that it can call the right simstruct function
  %% SetupRuntimeResources was chosen below to create these only once
  %%
  %% (@todo [rsunkari]):
  %% This will need a better resting place. Needs more discussions with
  %% Matt E and Mike T
  %%
  %if sysFcnType == "SetupRuntimeResources" && IsModelReferenceTarget() && IsModelReferenceForASimstructBasedTarget() && ISFIELD(::CompiledModel, "NumDataTransfers") && ::CompiledModel.NumDataTransfers > 0
  %openfile rtbAccessMethodBuf
  void %<::CompiledModel.Name>_DataTransferWrite(%<::CompiledModel.GlobalScope.tSimStructType>* rtm, uint32_T gblIdx, void* data);
  void %<::CompiledModel.Name>_DataTransferRead(%<::CompiledModel.GlobalScope.tSimStructType>* rtm, uint32_T gblIdx, void* data);
  void %<::CompiledModel.Name>_DataTransferInitBuffers(%<::CompiledModel.GlobalScope.tSimStructType>* rtm, uint32_T gblIdx, void* data);
 
  %closefile rtbAccessMethodBuf
  %<SLibCacheSystemCodeToFile("sys_fcn_decl", system, rtbAccessMethodBuf)>
     
  %openfile rtbAccessMethodFwd
  void %<::CompiledModel.Name>_DataTransferWrite(%<::CompiledModel.GlobalScope.tSimStructType>* rtm, uint32_T gblIdx, void* data) {
    _ssDataTransferWrite(ssGetRootSS(rtm->_mdlRefSfcnS), gblIdx, data);
    }
     
  void %<::CompiledModel.Name>_DataTransferRead(%<::CompiledModel.GlobalScope.tSimStructType>* rtm, uint32_T gblIdx, void* data) {
    _ssDataTransferRead(ssGetRootSS(rtm->_mdlRefSfcnS), gblIdx, data);
    }
     
  void %<::CompiledModel.Name>_DataTransferInitBuffers(%<::CompiledModel.GlobalScope.tSimStructType>* rtm, uint32_T gblIdx, void* data) {
    _ssDataTransferInitBuffers(ssGetRootSS(rtm->_mdlRefSfcnS), gblIdx, data);
    }
  %closefile rtbAccessMethodFwd
  %<SLibCacheSystemCodeToFile("sys_fcn_defn", system, rtbAccessMethodFwd)>
  %endif
   
  %if sysFcnType == "OutputUpdate"
    %assign updateFcn = SLibFcnGenBodySysFcn(system,"Update",TLC_TRUE)
    %assign outputFcn = SLibFcnGenBodySysFcn(system,"Outputs",TLC_TRUE)
  %elseif sysFcnType == "SystemInitialize" && combineInitAndReset
    %%
    %% For now there is no such a use case that SystemInitialize does not
    %% exist while SystemReset exist.
    %% Suppose there is a use case in the future that breaks the above
    %% assumption, then we need to put the logic in systemReset
    %% (if (!ssIsFirstInitCond(S))) and make the root systemReset the new
    %% root initialize.
    %%
    %assert ISFIELD(system,"SystemInitializeFcn")
    %assign systemInitializeFcn = ...
      SLibFcnGenBodySysFcn(system,"SystemInitialize",multiTID)
    %if ISFIELD(system,"SystemResetFcn")
      %assign systemResetFcn = ...
        SLibFcnGenBodySysFcn(system,"SystemReset",multiTID)
    %endif
    %assign systemInitializeLocalVars = LibGetSystemField(system, "CachedSystemInitializeLocalVars")
    %assign systemResetLocalVars = LibGetSystemField(system, "CachedSystemResetLocalVars")
    %if !ISEMPTY(systemInitializeFcn) && !ISEMPTY(systemResetFcn)
      %assign fcnBody = "if (ssIsFirstInitCond(S)) {" + ...
        systemInitializeLocalVars + ...
        systemInitializeFcn + "} else {" + ...
        systemResetLocalVars + ...
        systemResetFcn + "}"
    %elseif !ISEMPTY(systemInitializeFcn)
      %assign fcnBody = "if (ssIsFirstInitCond(S)) {" + ...
        systemInitializeLocalVars + ...
        systemInitializeFcn + "}"
    %elseif !ISEMPTY(systemResetFcn)
      %assign fcnBody = "if (!ssIsFirstInitCond(S)) {" + ...
        systemResetLocalVars + ...
        systemResetFcn + "}"
    %else
      %assign fcnBody = ""
    %endif
    %<LibSetSystemField(system, "CachedSystemInitializeLocalVars", "")>
    %<LibSetSystemField(system, "CachedSystemResetLocalVars", "")>
  %elseif sysFcnType == "SystemReset" && combineInitAndReset
    %%
    %% For now there is no such a use case that SystemInitialize does not
    %% exist while SystemReset exist.
    %% Suppose there is a use case in the future that breaks the above
    %% assumption, then we need to put the logic in systemReset
    %% (if (!ssIsFirstInitCond(S))) and make the root systemReset the new
    %% root initialize.
    %%
    %assign fcnBody = ""
  %else
    %assign fcnBody = SLibFcnGenBodySysFcn(system,blkFcnName,multiTID)
  %endif
 
  %if sysFcnType == "OutputUpdate"
    %<LibSetSystemFieldForTID(system, "Update","Fcn", updateFcn)>
    %<LibSetSystemFieldForTID(system, "Output","Fcn", outputFcn)>
  %elseif multiTID
    %<LibSetSystemFieldForTID(system, sysFcnType,"Fcn", fcnBody)>
  %else
    %assign cacheFieldName = "Cached" + sysFcnType + "Fcn"
    %if TYPE(fcnBody) == "Vector"
      %<LibSetSystemField(system, cacheFieldName, fcnBody[0])>
    %else
    %<LibSetSystemField(system, cacheFieldName, fcnBody)>
  %endif
  %endif
  
  %<FcnCacheLocalVars(system, sysFcnType)>
 
  %if sysFcnType == "OutputUpdate"
    %<FcnSetSystemFcnNeedTIDFlag(system, "Output")>
    %% No matter what, server functions never have a control port index, even if
    %% forced noninline
    %%%assign needCPIInOutputUpdate = ...
    %% FcnDeclareCPIIfNeeded(system, "OutputUpdate") || ...
    %%(LibSystemIsForceNonInline(system) && !LibIsServer(system))
    %%%<LibSetSystemField(system, "NeedCPIInOutputUpdate", needCPIInOutputUpdate)>
  %elseif multiTID
    %<FcnSetSystemFcnNeedTIDFlag(system, sysFcnType)>
  %endif
   
  %if (sysFcnType != "Update" && sysFcnType != "Output") || ...
      !IsModelReferenceBaseSys(system)
    %% For the model reference base system's Update/Output function, we generate
    %% the interface
    %% and prototype in FcnGenBodySysCache. This is because information
    %% from Output may be needed in Update to determine if an
    %% rtModel argument is needed (one reason is the firstInitCond).
    %if ISFIELD(system, sysFcnType + "Fcn")
      %<LibDefineSystemFcn(system, sysFcnType)>
    %endif
  %endif
 
  %if profCode
    %%
    %% generate profiling code
    %%
    %if sysFcnType == "Derivative"
      %assign profFcnName = "Derivatives"
    %else
      %assign profFcnName = sysFcnType
    %endif
    %assign declsProf = SLibGenProfSysDeclare(system, profFcnName)
    %assign profField = "Cached" + sysFcnType + "ProfileDeclsCode"
    %<LibSetSystemField(system, profField, declsProf)>
    %assign startProf = SLibGenProfSysStart(system, profFcnName)
    %assign profField = "Cached" + sysFcnType + "ProfileStartCode"
    %<LibSetSystemField(system, profField, startProf)>
    %assign endProf = SLibGenProfSysEnd(system, profFcnName)
    %assign profField = "Cached" + sysFcnType + "ProfileEndCode"
    %<LibSetSystemField(system, profField, endProf)>
  %endif
   
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/vssSigObj/tVSSSigObj.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortFcnCall3.m
%%
%function SLibFcnGenBodySysFcnEntry(system,sysFcnType,blkFcnName,withOOCC,statusCheckPoint,profCode,multiTID) void
   %assert !multiTID || sysFcnType == "Update" || sysFcnType == "Output" || ...
           sysFcnType == "OutputUpdate" || ...
           SLibContFcnPartitionGrouping(sysFcnType) && SLibPartitionGroupingSystem(system)
          
   %if statusCheckPoint
     %assign msg = "Generate " + sysFcnType + " function"
     %<SLibAddTLCCompileStatsCheckPoint(TLC_TRUE,msg)>
   %endif
    
   %if sysFcnType == "Update" && system.Type == "root"
     %assign ::BlockFcn = "RootUpdate"
   %else
     %assign ::BlockFcn = sysFcnType
   %endif
   %<LibSetGlobalSysFcnsForArgAccess([])>
   %if withOOCC
     %assign ooccField = []
     %if sysFcnType == "OutputUpdate"
       %if ISFIELD(system, "OutputOOCC")
         %if ISFIELD(system, "UpdateOOCC")
           %assign ooccField = system.OutputOOCC
           %foreach idx = SIZE(system.UpdateOOCC,1)
             %assign ooccField = ooccField + system.UpdateOOCC[idx]
           %endforeach
         %else
           %assign ooccField = system.OutputOOCC
         %endif
       %endif
     %else
       %assign ooccFieldName = sysFcnType + "OOCC"
       %if ISFIELD(system, ooccFieldName)
         %assign ooccField = GETFIELD(system, ooccFieldName)
       %endif
     %endif
    
     %if ooccField != []
       %<LibSetGlobalSysFcnsForArgAccess(ooccField)>
     %endif
   %endif
 
   %<SLibFcnGenBodyFcnCache(system,sysFcnType,blkFcnName,profCode,multiTID)>
 
   %assign ::BlockFcn = "Unknown"
   %<LibSetGlobalSysFcnsForArgAccess([])>
     
   %if statusCheckPoint
     %<SLibAddTLCCompileStatsCheckPoint(TLC_FALSE,msg)>
   %endif
%endfunction
 
 
%%Function:SLibInsertSolverResetCode=============================================================
%%ThisfunctionshouldneverbedirectlycalledfromtheTLC
%%codebase.Itissupposedtobecalledbythegeneratedopaqueblock
%%TLCfiles.
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/tmMultiRateAsyncTask_VC1.m
%%
%function SLibInsertAsyncTaskInitializeCode(system) Output
  %assert system.Type == "root"
  %with system
    %% Initialized flags that are used when asynchronous task
    %% read absolute time from base rate
    %foreach idx = LibGetNumAsyncTasks()
      %assign tid = idx + NumRuntimeExportedRates
      %if RTMAbsTimeNeedTransProtection(tid)
        %if SLibConcurrentTasks()
          %<SLibCGIRMutexOp(0,SLibGetTimerSemID(tid))>
        %elseif RTMAbsTimeNeedNoPriorityTrans(tid)
          %% Initialized flags that are used when asynchronous task
          %% read absolute time from base rate
          %<SLibGetDbBufReadBuf(tid)> = 0xFF;
          %<SLibGetDbBufWriteBuf(tid)> = 0xFF;
          %<SLibGetDbBufLastBufWr(tid)> = 0;
        %endif
      %endif
    %endforeach
  %endwith
%endfunction
 
 
%%Function:SLibInsertMdlOutputForProjectionFcn===================================================
%%ThisfunctionshouldneverbedirectlycalledfromtheTLC
%%codebase.Itissupposedtobecalledbythegeneratedopaqueblock
%%TLCfiles.
%function SLibInsertMdlOutputForProjectionFcn(system) Output
  %assert (system.Type == "root") && (ModelHasProjections == "yes") && ...
          (isRSim)
   
  %% If Model registered Projection function, the ODE solvers must call
  %% MdlOutputs before calling MdlProjection. MdlProjection is generated/called
  %% always, but MdlOutputs should only be called if needed.
  %if !isRSimWithSolverModule %% RSim with an ODE solver
    /* Update Outputs before calling Projections */
    MdlOutputs(0);
  %endif
%endfunction
 
 
%%Function:SLibInsertInitPeriodicCStatesFcn
%%Abstract:
%%Thisfunctiongeneratescodethatinitializesavectorofperiodic
%%continuousstateindicesandassociatedranges.
%%ThisfunctionshouldneverbedirectlycalledfromtheTLC
%%codebase.Itissupposedtobecalledbythegeneratedopaqueblock
%%TLCfiles.
%%
%function SLibInsertInitPeriodicCStatesFcn(system) Output
  %assert system.Type == "root"
         
  %assign numPeriodicContStates = %<NumPeriodicContStates>
  %if LibIsDeploymentDiagram() && (numPeriodicContStates > 0)
    %assign numPeriodicContStates = numPeriodicContStates-SLibDeploymentGetNumPeriodicContStates()
  %endif
  %if !SLibIsDeploymentDiagramWithNoTopSolver() && (numPeriodicContStates > 0)
    %if CodeFormat == "S-Function"
      /* InitializeConditions for S-Function periodic continuous states */
      %foreach idx = numPeriodicContStates
        ssSetPeriodicContState(S, %<idx>, %, %, %);
      %endforeach
    %else
      /* InitializeConditions for root-level periodic continuous states */
      {
        %% Handle indices first
        int_T rootPeriodicContStateIndices[%<numPeriodicContStates>] = {/
          %assign comma = ""
          %foreach idx = numPeriodicContStates
            %<comma>%/
            %assign comma = ", "
          %endforeach
        };
        %% Initialize ranges
        %assign npsr = 2*numPeriodicContStates
        real_T rootPeriodicContStateRanges[%<npsr>] = {/
          %assign comma = ""
          %foreach idx = npsr
            %<comma>%/
            %assign comma = ", "
          %endforeach
        };
 
        %% Root-level periodic continuous state indices
        %assign copyAddr = "%<LibGetPeriodicContStateIndices()>"
        %assign copySize = "%<numPeriodicContStates>*sizeof(int_T)"
        (void) %<LibGenMemFcnCall("memcpy", "(void*)%<copyAddr>", "rootPeriodicContStateIndices", copySize)>;
 
        %% Root-level ranges associated with the periodic continuous states
        %assign copyAddr = "%<LibGetPeriodicContStateRanges()>"
        %assign copySize = "%<npsr>*sizeof(real_T)"
        (void) %<LibGenMemFcnCall("memcpy", "(void*)%<copyAddr>", "rootPeriodicContStateRanges", copySize)>;
      }
    %endif %% CodeFormat == "S-Function"
  %endif %% !LibIsDeploymentDiagram() && numPeriodicContStates > 0
%endfunction %% SLibInsertInitPeriodicCStatesFcn
  
 
%%Function:SLibInsertInitSystemMatricesFcn=======================================================
%%Abstract:
%%Thisfunctiongeneratescodethatinitializessystemmatrices.
%%ThisfunctionshouldneverbedirectlycalledfromtheTLC
%%codebase.Itissupposedtobecalledbythegeneratedopaqueblock
%%TLCfiles.
%%
%function SLibInsertInitSystemMatricesFcn(system) Output
  %assert (ModelIsLinearlyImplicit == "yes") && ...
          (!Accelerator) && ...
          (!IsModelReferenceTarget()) && ...
          (system.Type == "root")
         
  %if !SLibIsDeploymentDiagramWithNoTopSolver()
      /* Root-level InitSystemMatrices */
      {
        %assign nx = %<NumContStates>
        %assign nnz = %
        %if LibIsDeploymentDiagram()
          %assign nx = nx-SLibDeploymentGetNumContStates()
          %assign nnz = nnz-SLibDeploymentGetMassMatrixNzMax()
        %endif
        static int_T modelMassMatrixIr[%<nnz>] = {/
          %assign comma = ""
          %foreach idx = nnz
            %<comma>%/
            %assign comma = ", "
          %endforeach
        };
        %assign njc = nx+1
        static int_T modelMassMatrixJc[%<njc>] = {/
          %assign comma = ""
          %foreach idx = njc
            %<comma>%/
            %assign comma = ", "
          %endforeach
        };
        static real_T modelMassMatrixPr[%<nnz>] = {/
          %assign comma = ""
          %foreach idx = nnz
            %<comma>1.0/
            %assign comma = ", "
          %endforeach
        };
         
        %% global Ir
        %assign copyAddr = LibGetMassMatrixGlobalIr()
        %assign copySize = "%<nnz>*sizeof(int_T)"
        (void) %<LibGenMemFcnCall("memcpy", copyAddr, "modelMassMatrixIr", copySize)>;
         
        %% global Jc
        %assign copyAddr = LibGetMassMatrixGlobalJc()
        %assign copySize = "%<njc>*sizeof(int_T)"
        (void) %<LibGenMemFcnCall("memcpy", copyAddr, "modelMassMatrixJc", copySize)>;
         
        %% global Pr
        %assign copyAddr = LibGetMassMatrixGlobalPr()
        %assign copySize = "%<nnz>*sizeof(real_T)"
        (void) %<LibGenMemFcnCall("memcpy", copyAddr, "modelMassMatrixPr", copySize)>;
         
      }
  %endif %% !SLibIsDeploymentDiagramWithNoTopSolver()
   
%endfunction %% SLibInsertInitSystemMatricesFcn
 
 
%%Function:SLibInsertSolverResetCode=============================================================
%%ThisfunctionshouldneverbedirectlycalledfromtheTLC
%%codebase.Itissupposedtobecalledbythegeneratedopaqueblock
%%TLCfiles.
%function SLibInsertSolverResetCode() Output
 
  %if CodeFormat != "S-Function" || Accelerator || ...
        SolverType != "VariableStep"
        %return
  %endif
   
   
  %% Reset solver if needed
  %openfile resetSolverBuffer
    %assign nDU = SolverResetInfo.NumNonContDerivSignals
    %if nDU > 0
      %assign dU = "nonContDerivSigCache_%<LibGetModelName()>_T"
 
      {
    %assign varName = "pNonContDerivSig"
    %<dU> *%<varName> = (%<dU> *)%<RTMGet("LocalNonContDerivSig")>;
    %foreach idx = nDU
      %%
      %assign sigSrc = SolverResetInfo.NonContDerivSignal[idx].SigSrc
      %assign startEl = SolverResetInfo.NonContDerivSignal[idx].StartEl
      %assign regLen = SolverResetInfo.NonContDerivSignal[idx].RegionLen
      %%
      %assign idNum = IDNUM(sigSrc)
      %assert (idNum[0] == "B")
      %if idNum[1] < BlockOutputs.NumGlobalBlockOutputs
        %assign bo = BlockOutputs.GlobalBlockOutput[idNum[1]]
        %assert (LibGetRecordWidth(bo) >= regLen + startEl)
        %assert (bo.Invariant == "no")
        %assert (!LibGetRecordIsComplex(bo))
        %%
             
            %% For NonContDerivSignal inside For Each subsystem, we need to
            %% index each For Each vargroup level by right index
            %if ISFIELD(SolverResetInfo.NonContDerivSignal[idx], "ForEachSSIterIndices")
              %assign ::UseConstantForVarGroupIdx = TLC_TRUE
              %assign ::VarGroupIndexVector = SolverResetInfo.NonContDerivSignal[idx].ForEachSSIterIndices
              %assign ::VarGroupIndexVectorSize = SIZE(::VarGroupIndexVector, 1)
              %assign ::VarGroupIndexVectorIdx = ::VarGroupIndexVectorSize - 1
            %endif
            %assign name = SLibGetBlockOutputIdentifierFromRecord(bo, NumSystems-1)
            %if ISFIELD(SolverResetInfo.NonContDerivSignal[idx], "ForEachSSIterIndices")
              %assign ::UseConstantForVarGroupIdx = TLC_FALSE
              %assign ::VarGroupIndexVectorIdx = ::VarGroupIndexVectorSize - 1
            %endif
      %else
        %assign nExternalOp = BlockOutputs.NumExternalBlockOutputs
        %foreach iExOp = nExternalOp
          %if BlockOutputs.ExternalBlockOutput[iExOp].LogicalSrc == sigSrc
        %assign bo = BlockOutputs.ExternalBlockOutput[iExOp]
        %break
          %endif
        %endforeach
        %assign name = "%<bo.SigLabel>"
      %endif
      %assign opW = (LibGetRecordWidth(bo) == 1) ? "" : "[%<startEl>]"
      %assign addr = "&%<name>%<opW>"
      %assign dType = LibGetDataTypeNameFromId(LibGetRecordDataTypeId(bo))
      %assign sizeInBytes = "%<regLen>*sizeof(%<dType>)"
 
      if (%<LibGenMemFcnCall("memcmp", "%<varName>->cache_%<idx>", ...
        "(char *)%<addr>", sizeInBytes)> != 0) {
        (void) %<LibGenMemFcnCall("memcpy", "%<varName>->cache_%<idx>", ...
          "(char *)%<addr>", sizeInBytes)>;
        ssSetSolverNeedsReset(%<SLibGetSimStruct()>);
      }
    %endforeach
      }
    %endif
  %closefile resetSolverBuffer
   
  %<resetSolverBuffer>
   
%endfunction %% SLibInsertSolverResetCode
 
 
%%Function:SLibSLibGenerateExtModeOutput(system)=================================================
%%Description:
%%GeneratestheExternalModeOutputscodeforanenabled,triggered,or
%%enabled&triggeredsubsystemtoupdatetheextmodeactivedwork.
%%ThisfunctionshouldonlybecalledfromgeneratedTLCfiles.
%%TopTester:test/toolbox/simulink/variants/inlineVariants/simulinkFunction/tVariantSimulinkFunctionAutoInherit.m
%%
%function SLibGenerateExtModeOutput(system) Output
  %if ExtMode != 1
    %return %% do nothing
  %endif
 
  %with system
    %openfile extBuf
    %if Type == "trigger" || Type == "enable_with_trigger" || Type == "enable" || ...
      Type == "function-call" || Type == "action"
      %assign callSites = CallSites
      %assign graphParentSys = ::CompiledModel.System[callSites[0][2]]
      %assign ssBlock = graphParentSys.Block[callSites[0][3]]
      %with ssBlock
        %foreach i = NumDWork
          %assign dwRec = DWork[i]
          %assign dwName = LibBlockDWorkName(dwRec)
          %assign dwIdx = dwRec.FirstRootIdx
          %if dwName == SLibGetNameOfExtModeActiveDWork()
            %assign mode = SLibGetSubsystemActiveVector(dwIdx)
            %<mode> = EXTMODE_SUBSYS_ENABLED;
          %endif
        %endforeach
      %endwith
    %endif
    %closefile extBuf
  %endwith
   
  %if !ISEMPTY(extBuf) && !WHITE_SPACE(extBuf)
    %<extBuf>
  %endif
   
%endfunction %% SLibSLibGenerateExtModeOutput
 
 
%%Function:SLibRSimUpdateExtU===============================================
%%Abstract:
%%Getinportdatafromfile
%%ThisfunctionshouldonlybecalledfromgeneratedTLCfiles.
%%TopTester:test/toolbox/simulink/variants/inlineVariants/simulinkFunction/tVariantSimulinkFunctionAutoInherit.m
%%
%function SLibGetRootInportsFromFile(system, forSystemInitializeFcn) Output
  %assert isRSim && system.Type == "root" && !IsModelReferenceTarget()
 
  %% If this function is called to emit code in SystemInitializeFcn,
  %% do nothing if there is no root inport block with initialize sample time.
  %if forSystemInitializeFcn
    %assign hasInitEventInput = TLC_FALSE
    %foreach idx = ExternalInputs.NumExternalInputs
      %assign extInp = ExternalInputs.ExternalInput[idx]
      %if extInp.ConnectedToInitializeSubsystem == "yes"
        %assign hasInitEventInput = TLC_TRUE
        %break
      %endif
    %endforeach
    %if !hasInitEventInput
      %return
    %endif
  %endif
 
  %with system
  %openfile inportBuf
  %if NumModelInputs > 0
    /* Read data from the mat file of inport block */
    if(gblInportFileName != %<SLibGetNullDefinitionFromTfl()>)
    {
    %assign useTid = !LibIsSingleRateModel()
    %if !useTid || forSystemInitializeFcn
      real_T time = %<LibGetT()>;
    %endif
    %if ::isRAccel
      bool externalInputIsInDatasetFormat = false;
      void *pISigstreamManager = rt_GetISigstreamManager();
      rtwISigstreamManagerGetInputIsInDatasetFormat( ...
        pISigstreamManager, ...
        &externalInputIsInDatasetFormat ...
        );
      if (slIsRapidAcceleratorSimulating() && externalInputIsInDatasetFormat) {
        %assign nulldef = SLibGetNullDefinitionFromTfl()
        %assign dataPath = FEVAL("get_param",LibGetModelName(),"ExternalInput")
        const int maxErrorBufferSize = 16384; %% 16k
        char errMsg[16384];
        bool bSetErrorStatus = false;
        %if useTid
          %foreach idx = ExternalInputs.NumExternalInputs
            %assign extInp = ExternalInputs.ExternalInput[idx]
            %assign blockPath = extInp.BlockName
            %assign tid = extInp.TID
            %assign hasFcnCallInfo = LibIsSystemField(system, "FcnCallInputInfo")
            %% Only get external input data during initialization for root
            %% inport with initialize sample time.
            %if forSystemInitializeFcn && extInp.ConnectedToInitializeSubsystem == "no"
              %continue
            %endif
            
            %% If this is a function call inport, we need to clear the number of
            %% required calls.
            %% TopTester: test/toolbox/simulink/variants/inlineVariants/ivGeneral/tsimfcsys_rapidaccel.m
            %if extInp.FunctionCallInitiator == "yes" && ...
              !SLibExplicitPeriodicInExportFcnDiagram(extInp.TID) && ...
                hasFcnCallInfo
                %assign fcnCallIdx = 0
                %assign fcnCallInfo = LibGetSystemField(system, "FcnCallInputInfo")
 
                %% Lookup which function call info matches this port index
                %foreach idx2 = SIZE(fcnCallInfo.FcnCallInfo,1)
                  %assign info = fcnCallInfo.FcnCallInfo[idx2]
                  %if(info.PortIdx == idx)
                    %assign fcnCallIdx = idx2
                    %break
                  %endif
                %endforeach
                %% Get the dwork ID out of the FcnCallInfo and use it to get the dwork
                %assign dworkIdx = fcnCallInfo.FcnCallInfo[fcnCallIdx].dworkIndex
 
                %assign dwork = ::CompiledModel.DWorks.DWork[dworkIdx]
                %% Obtain the dwork identifier to write the data into
                %assign youtFcn = LibBlockDWork(dwork, "", "", 0)
                %% Initialize the data to zero
                %<youtFcn>= 0U;
            %endif
             
            %% Don't need to check sample hit during initialization.
            %if !forSystemInitializeFcn && tid != -2 && !SLibParameterChangeEventTID(tid)
            if(%<LibIsSampleHit(tid)>) {
 
            %if extInp.FunctionCallInitiator == "yes" && SLibIsExportFcnDiagram() && ...
              SLibExplicitTaskingTID(tid) && LibAsynchronousTriggeredTID(tid)
              int_T asyncTid = %<tid>;
              if (tid == 0) {
                ssRaiseEventUsingRateIndex(rtS, asyncTid);
              }
              if (tid == asyncTid)
            %endif
            %endif %% %if !forSystemInitializeFcn && tid != -2 && !SLibParameterChangeEventTID(tid)
             
            {
              %if !forSystemInitializeFcn
                real_T time = %<LibGetTaskTime(tid)>;
              %endif
               
              if(!rtwISigstreamManagerIsPeriodicFcnCall( ...
                pISigstreamManager, ...
                %<idx>))
 
              {
                int_T sampleHit = 0U;
                bSetErrorStatus = rtwISigstreamManagerInjectDataMultiRate( ...
                  pISigstreamManager, ...
                  %<idx>, ...
                  time, ...
                  %<::CompiledModel.ErrorXMLMode>, ...
                  "%<blockPath>", ...
                  "%<dataPath>", ...
                  &sampleHit, ...
                  errMsg, ...
                  maxErrorBufferSize);
               
                %if extInp.FunctionCallInitiator == "yes"
                  enableFcnCallFlag[%<extInp.TID>] = sampleHit;
                %endif
              }
            }
             
            %% Don't need to check sample hit during initialization.
            %if !forSystemInitializeFcn && tid != -2 && !SLibParameterChangeEventTID(tid)
            }
            %endif
          %endforeach
        %else
          %assign blockPath = ExternalInputs.ExternalInput[0].BlockName
          bSetErrorStatus = rtwISigstreamManagerInjectDataSingleRate( ...
            pISigstreamManager, ...
            time, ...
            %<::CompiledModel.ErrorXMLMode>, ...
            "%<blockPath>", ...
            "%<dataPath>", ...
            errMsg, ...
            maxErrorBufferSize);
        %endif
         
        if (bSetErrorStatus) {
          %<RTMSetErrStat("errMsg")>;
          return;
        }
      }
      else {
    %endif
     
    int_T currTimeIdx;
     
    int_T i;
     
    %%
    %foreach idx = ExternalInputs.NumExternalInputs
      %assign extInp = ExternalInputs.ExternalInput[idx]
      %% Inactive (SVCE false) inports built in raccel will not be present. Hence, skip init'ing them
      %% TopTester: matlab/test/toolbox/simulink/variants/inlineVariants/ivGeneral/tRootIOFcnCall.m -testspec:lvlTwo_mG1377701_ra
      %if ISFIELD(extInp,"Inactive")
        %continue
      %endif
 
      %% Only get external input data during initialization for root
      %% inport with initialize sample time.
      %if forSystemInitializeFcn && extInp.ConnectedToInitializeSubsystem == "no"
        %continue
      %endif
       
      %assign cgTypeIdx = LibGetRecordCGTypeIdx(extInp)
      %assign numDims = LibCGTypeNumDimensions(cgTypeIdx)
      %assign interp = extInp.Interpolation
      %assign fcnCall = extInp.FunctionCallInitiator == "yes"
      %assign hasFcnCallInfo = LibIsSystemField(system, "FcnCallInputInfo")
        
      /*
      * Read in data from mat file for root inport %<LibGetRecordIdentifier(extInp)>
      */
       
      %if fcnCall && !SLibExplicitPeriodicInExportFcnDiagram(extInp.TID)
         
        %% Never want to interp with function call
        %assign interp = TLC_FALSE
         
        %% The following code is placed here to zero out the dwork buffer prior to
        %% the check for sample hit.
         
        %% The main MATLAB process will have populated the FcncallInputInfo
        %% with the dwork ID for the hidden function call block corresponding
        %% to this inport.
        %% TopTester: test/toolbox/simulink/variants/inlineVariants/ivGeneral/tsimfcsys_rapidaccel.m
        %if hasFcnCallInfo
            %% skipping explicit periodic tasks
            %assign fcnCallIdx = 0
            %assign fcnCallInfo = LibGetSystemField(system, "FcnCallInputInfo")
             
            %% Lookup which function call info matches this port index
            %foreach idx2 = SIZE(fcnCallInfo.FcnCallInfo,1)
              %assign info = fcnCallInfo.FcnCallInfo[idx2]
              %if(info.PortIdx == idx)
                %assign fcnCallIdx = idx2
                %break
              %endif
            %endforeach
            %% Get the dwork ID out of the FcnCallInfo and use it to get the dwork
            %assign dworkIdx = fcnCallInfo.FcnCallInfo[fcnCallIdx].dworkIndex
         
            %assign dwork = ::CompiledModel.DWorks.DWork[dworkIdx]
            %% Obtain the dwork identifier to write the data into
            %assign youtFcn = LibBlockDWork(dwork, "", "", 0)
            %% Initialize the data to zero
            %<youtFcn>= 0U;
        %endif
        %% @todo (remove the following code when ExportPeriodicFcnCall is fully on)
        %% this code is handled by periodic rates.
        %% g1337574
        %% Handle the periodic function call case.
        if (gblInportTUtables[%<idx>].isPeriodicFcnCall) {
          %if hasFcnCallInfo
          %if useTid
            %assign tid = extInp.TID
            real_T time = %<LibGetTaskTime(tid)>;
          %endif
            if (rt_IsPeriodicSampleHit(gblInportTUtables, %<idx>, time)) {
                %<youtFcn> = 1;
            }
          %endif
        } else if (gblInportTUtables[%<idx>].nTimePoints > 0) {
      %else
        %if !SLibExplicitPeriodicInExportFcnDiagram(extInp.TID)
          if (gblInportTUtables[%<idx>].nTimePoints > 0) {
          %%
        %else
          if (!gblInportTUtables[%<idx>].isPeriodicFcnCall && gblInportTUtables[%<idx>].nTimePoints > 0) {
        %endif
      %endif
 
      %if useTid && !forSystemInitializeFcn && extInp.TID != -2 && !SLibParameterChangeEventTID(extInp.TID)
        %assign tid = extInp.TID
        if(%<LibIsSampleHit(tid)>)
        {
         
        %if fcnCall && SLibIsExportFcnDiagram() && SLibExplicitTaskingTID(tid) && LibAsynchronousTriggeredTID(tid)
          int_T asyncTid = %<tid>;
            if (tid == 0) {
                ssRaiseEventUsingRateIndex(rtS, asyncTid);
            }
 
            if (tid == asyncTid)
        %endif
      %else
        {
      %endif
        {
         
      %assign dTypeId = LibGetDataTypeIdAliasedThruToFromId(...
        SLibGetRecordDataTypeId(extInp))
      %assign dTypeRec = FixPt_GetDataTypeFromIndex(dTypeId)
      %assign dTypeName = LibGetDataTypeNameFromId(...
        SLibGetRecordDataTypeId(extInp))
      %assign width = LibGetRecordWidth(extInp)
      %%
      %if interp
        %assign dTypeSize = "sizeof("+ dTypeName +")"
      %endif
      %%
      %if useTid && !forSystemInitializeFcn
          real_T time = %<LibGetTaskTime(tid)>;
      %endif
      %%
       
      %if interp
          int k = 1;
          if(gblInportTUtables[%<idx>].nTimePoints == 1) {
            k = 0;
          }
      %endif
 
      %if fcnCall
          currTimeIdx = rt_getTimeIdx(gblInportTUtables[%<idx>].time, time,
                                      gblInportTUtables[%<idx>].nTimePoints,
                                      gblInportTUtables[%<idx>].currTimeIdx,
                                      %<interp>,
                                      1);
          if(currTimeIdx != -7) {
             gblInportTUtables[%<idx>].currTimeIdx = currTimeIdx;
          }
      %else
          currTimeIdx = rt_getTimeIdx(gblInportTUtables[%<idx>].time, time,
                                      gblInportTUtables[%<idx>].nTimePoints,
                                      gblInportTUtables[%<idx>].currTimeIdx,
                                      %<interp>,
                                      0);
          gblInportTUtables[%<idx>].currTimeIdx = currTimeIdx;
      %endif
 
      %%
      %if numDims >= 2
        %assign dataOffset1 = "%<width>" + "*currTimeIdx + i"
        %assign dataOffset2 = width
      %else
        %assign baseLength = "i*gblInportTUtables[%<idx>].nTimePoints +"
        %assign dataOffset1 = baseLength + "currTimeIdx"
        %assign dataOffset2 = "1"
      %endif
       
       
          for (i = 0; i < %<width>; i++) {
         
        %assign yout1 = SLibGetExtUIdentifier(extInp, "i", "%<tRealPart>")
        %assign yout = "&" + yout1
         
        %if interp && !fcnCall
            %<dTypeName>* realPtr1 = (%<dTypeName>*)gblInportTUtables[%<idx>].ur +
            %<dataOffset1>;
            %<dTypeName>* realPtr2 = realPtr1 + %<dataOffset2>*k;
                                 
            (void)rt_Interpolate_Datatype(
              realPtr1,
              realPtr2,
              %<yout>,
              time,
              gblInportTUtables[%<idx>].time[currTimeIdx],
              gblInportTUtables[%<idx>].time[currTimeIdx + k],
              gblInportTUtables[%<idx>].uDataType);
 
          %if LibGetRecordIsComplex(extInp)
             
            %assign yout1 = SLibGetExtUIdentifier(extInp, "i", "%<tImagPart>")
            %assign yout = "&" + yout1
            if (gblInportTUtables[%<idx>].complex == 0) {
              %<yout1> = %<FixPt_GetGroundValueOrNameFromDataTypeRec(dTypeRec, TLC_FALSE)>;
            } else {
              %<dTypeName>* imagPtr1 = (%<dTypeName>*)gblInportTUtables[%<idx>].ui + %<dataOffset1>;
              %<dTypeName>* imagPtr2 = imagPtr1 + %<dataOffset2>*k;
                   
              (void)rt_Interpolate_Datatype(
                imagPtr1,
                imagPtr2,
                %<yout>,
                time,
                gblInportTUtables[%<idx>].time[currTimeIdx],
                gblInportTUtables[%<idx>].time[currTimeIdx + k],
                gblInportTUtables[%<idx>].uDataType);
            }
          %endif
        %elseif !fcnCall
            if(currTimeIdx == -7){
              %<yout1> = %<FixPt_GetGroundValueOrNameFromDataTypeRec(dTypeRec, TLC_FALSE)>;
            %if LibGetRecordIsComplex(extInp)
              %assign youtIm1 = SLibGetExtUIdentifier(extInp, "i", "%<tImagPart>")
              %assign youtIm = "&" + youtIm1
              %<youtIm1> = %<FixPt_GetGroundValueOrNameFromDataTypeRec(dTypeRec, TLC_FALSE)>;
            %endif
            } else {
            %<dTypeName>* realPtr1 = (%<dTypeName>*)gblInportTUtables[%<idx>].ur +
            %<dataOffset1>;
              %<yout1> = *realPtr1;
            %if LibGetRecordIsComplex(extInp)
              %assign yout1 = SLibGetExtUIdentifier(extInp, "i", "%<tImagPart>")
              %assign yout = "&" + yout1
              if (gblInportTUtables[%<idx>].complex == 0){
                %<yout1> = %<FixPt_GetGroundValueOrNameFromDataTypeRec(dTypeRec, TLC_FALSE)>;
              } else {
                %<dTypeName>* imagPtr1 = (%<dTypeName>*)gblInportTUtables[%<idx>].ui + %<dataOffset1>;
                %<yout1> = *imagPtr1;
              }
            %endif
            }
        %elseif fcnCall
            if(currTimeIdx != -7) {
              uint_T* uintPtr1 = (uint_T*)gblInportTUtables[%<idx>].ur + %<dataOffset1>;
              %if !SLibExplicitPeriodicInExportFcnDiagram(extInp.TID)
                  %if hasFcnCallInfo
                    %<youtFcn> = *uintPtr1;
                  %endif
              %else
                enableFcnCallFlag[%<extInp.TID>] = *uintPtr1;
              %endif
            }
            %if SLibExplicitPeriodicInExportFcnDiagram(extInp.TID)
              else {
                enableFcnCallFlag[%<extInp.TID>] = 0U;
            }
            %endif
        %endif
         
            }
          }
        }
      }
  %endforeach
    }
    /* end read inport data from file */
  %if ::isRAccel
    }
  %endif
  %endif %% NumModelInputs > 0
 
  %if ::isRAccel && !forSystemInitializeFcn && ExternalInputs.NumAperiodicPartitions > 0
    /* Read data from the mat file */
    if(gblAperiodicPartitionHitTimes != %<SLibGetNullDefinitionFromTfl()>)
    {
      bool hasAperiodicPartitionHitTimes = false;
      void *pISigstreamManager = rt_GetISigstreamManager();
      rtwISigstreamManagerHasAperiodicPartitionHitTimes( ...
        pISigstreamManager, ...
        &hasAperiodicPartitionHitTimes ...
        );
      if (slIsRapidAcceleratorSimulating() && hasAperiodicPartitionHitTimes) {
        %assign nulldef = SLibGetNullDefinitionFromTfl()
        %assign dataPath = FEVAL("get_param", LibGetModelName(), "ExternalInput")
        const int maxErrorBufferSize = 16384; %% 16k
        char errMsg[16384];
        bool bSetErrorStatus = false;
        %foreach idx = ExternalInputs.NumAperiodicPartitions
          %assign upInfo = ExternalInputs.AperiodicPartitions[idx]
          %assign name = upInfo.Name
          %assign rateIdx = upInfo.RateIdx
           
          %% Don't need to check sample hit during initialization.
          if (%<LibIsSampleHit(0)> && gblAperiodicPartitionSignalIds[%<idx>] >= 0) {
             
            real_T time = %<LibGetTaskTime(0)>;
            bSetErrorStatus = rtwISigstreamManagerInjectDataAperiodicPartitions( ...
              pISigstreamManager, ...
              gblAperiodicPartitionSignalIds[%<idx>], ...
              time, ...
              %<::CompiledModel.ErrorXMLMode>, ...
              "%<name>", ...
              errMsg, ...
              maxErrorBufferSize);
             
            if (gblUconstrainedPartitionNumHits[%<idx>] > 0) {
              ssRaiseEventUsingRateIndexWithRunMultiplicity(...
                rtS, %<rateIdx>, gblUconstrainedPartitionNumHits[%<idx>]);
            }
          }
           
        %endforeach
       
        if (bSetErrorStatus) {
          %<RTMSetErrStat("errMsg")>;
          return;
        }
      }
    }
  %endif %% ExternalInputs.NumAperiodicPartitions > 0
 
%closefile inportBuf
%endwith
 
%if !WHITE_SPACE(inportBuf)
  %assign inportBuf = "/n" + inportBuf
  %<inportBuf>
%endif
 
%endfunction %% SLibGetRootInportsFromFile
 
 
 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%Function:FcnSysVarGroupIndex
%%type:"DWork","BlockIO","ConstBlockIO","Parameter"
%%"ConstParameter","ContStates","ContStatesDisabled"
%%"ContStatesDerivative","ZCSV","ZCEvent"
%%"ExternalInput","ExternalOutput",
%%"MassMatrixOffset""ConstParameterWithInit"
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%TopTester:test/toolbox/simulink/variants/tvss_sim_code_match_g984892.m
%%
%function FcnSysVarGroupIndex(system, type, callSiteIdx) void
  %assign hStructSystem = ::CompiledModel.System[system.HStructDeclSystemIdx]
  %assign varGroupIdx = -1
 
  %if callSiteIdx < 0
    %assign callSiteIdx = 0
  %endif
 
  %assign indexStr = type + "VarGroupIndex"
  %if ISFIELD(hStructSystem, indexStr)
    %assign varGroupIdx = GETFIELD(hStructSystem, indexStr)[callSiteIdx]
  %endif
  %return varGroupIdx
%endfunction
 
%%Function:SLibVarGroupType======================================================================
%%Abstract:
%%ReturnsthestructuredtypeforagivenVarGroupindexandtype(class).
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%TopTester:test/toolbox/simulink/variants/tvss_sim_code_match_g984892.m
%%
%function SLibVarGroupType(varGroupIdx, type) void
  %if varGroupIdx >= 0
    %assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
    %assign vargroupCategory = LibGetVarGroupCategory(varGroupIdx)
    %if 0 == varGroup.PackageAsStruct
      %return ""
    %endif
    %assign cgType = ::CompiledModel.CGTypes.CGType[varGroup.CGTypeIdx]
    %if LibCGTypeIsMatrix(varGroup.CGTypeIdx)
      %assert type == "DWork" || type == "BlockIO" || ...
              type == "ZCEvent" || type == "ZCSV" || ...
              type == "ContStates" || type == "ContStatesDerivative" || ...
              type == "ContStatesDisabled" || type == "ContStatesAbsoluteTolerance" || ...
              type == "ContStatesPerturbMin" || type == "ContStatesPerturbMax" || ...
              vargroupCategory == "HierarchicalCoderData"
      %assign cgTypeIdx = SLibGetBaseTypeForVarGroupUsedAsMatrix(varGroup.CGTypeIdx)
      %assign cgType = ::CompiledModel.CGTypes.CGType[cgTypeIdx]
    %endif
    %return cgType.Name
  %elseif type == "MassMatrixOffset"
    %% TODO: JK For now only -- till we get a proper (VarGroup) solution
    %return tMassMatrixOffset + "_" + system.Identifier
  %endif
   
  %return ""
%endfunction
 
%function VarGroupTypeToRecType(type)
  %switch(type)
      %case "DWork"
        %assign retVal = "W"
        %break
      %case "BlockIO"
        %assign retVal = "B"
        %break
      %case "ConstBlockIO"
        %assign retVal = "C"
        %break
      %case "Parameter"
        %assign retVal = "P"
        %break
      %case "ConstParameter"
        %assign retVal = "CP"
        %break
      %case "ContStates"
        %assign retVal = "X"
        %break
      %case "ContStatesDisabled"
        %assign retVal = "XDI"
        %break
      %case "ContStatesDerivative"
        %assign retVal = "DX"
        %break
      %case "ZCEvent"
        %assign retVal = "Z"
        %break
      %case "ExternalInput"
        %assign retVal = "U"
        %break
      %case "ExternalOutput"
        %assign retVal = "Y"
        %break
      %case "ConstParameterWithInit"
        %assign retVal = "CPI"
        %break
      %default
          %assign retVal = ""
    %endswitch
    %return retVal
%endfunction
 
%%Function:FcnSysVarGroupType
%%type:"DWork","BlockIO","ConstBlockIO","Parameter"
%%"ConstParameter","ContStates","ContStatesDisabled"
%%"ContStatesDerivative","ZCSV","ZCEvent"
%%"ExternalInput","ExternalOutput",
%%"MassMatrixOffset""ConstParameterWithInit"
%%
%function FcnSysVarGroupType(system, type) void
  %assign varGroupIdx = FcnSysVarGroupIndex(system, type, 0)
  %return SLibVarGroupType(varGroupIdx, type)
%endfunction
 
%%Function:FcnSysVarGroupNonreusedName
%%type:"DWork","BlockIO","ConstBlockIO","Parameter"
%%"ConstParameter","ContStates","ContStatesDisabled"
%%"ContStatesDerivative","ZCSV","ZCEvent"
%%"ExternalInput","ExternalOutput",
%%"MassMatrixOffset""ConstParameterWithInit"
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:
%function FcnSysVarGroupNonreusedName(system, type) void
  %assign varGroupIdx = FcnSysVarGroupIndex(system, type, 0)
  %assign retStr = ""
  %if varGroupIdx >= 0
    %assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
    %return varGroup.NonreusedName
  %else
    %return ""
  %endif
%endfunction
 
%%Function:SLibVarGroupName======================================================================
%%Abstract:
%%ReturnstheVarGroupnameforagivenVarGroupindex.
%%
%function SLibVarGroupName(varGroupIdx) void
  %return ::CompiledModel.VarGroups.VarGroup[varGroupIdx].Name
%endfunction
 
%%Function:SLibVarGroupParentIndex===============================================================
%%Abstract:
%%ReturnstheVarGroupparentindexforagivenVarGroupindex.
%%
%function SLibVarGroupParentIndex(varGroupIdx) void
  %return ::CompiledModel.VarGroups.VarGroup[varGroupIdx].ParentVarGroupIdx
%endfunction
 
 
%function SLibCGVarGroupMemberCGTypeIdx(varGroupIdx, memberIdx) void
  %return SLibVarGroupElementType(varGroupIdx, memberIdx)
%endfunction
 
%function SLibCGVarGroupMemberName(varGroupIdx, memberIdx) void
  %return SLibVarGroupElementName(varGroupIdx, memberIdx)
%endfunction
 
%function SLibClearAccessRecord(dataRec) void
  %assign activeFcn = FcnGetActiveFcnForDecl()
  %assign declareInFcnScope = "DeclareIn%<activeFcn>FcnScope"
  %if ISFIELD(dataRec,declareInFcnScope)
    %assign dataRec.%<declareInFcnScope> = 0
  %endif
  %assign dataRec.TID = []
%endfunction
 
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/blocks/tconcat.m
%%TopTester:test/toolbox/simulink/variants/tvss_sim_code_match_g984892.m
%%
%function SLibCGIRSAccessRecord(accSysIdx, dataRec, accTid) void
  %assign activeFcn = FcnGetActiveFcnForDecl()
  %assign declareInFcnScope = "DeclareIn%<activeFcn>FcnScope"
  %if ISFIELD(dataRec,declareInFcnScope)
    %assign dataRec.%<declareInFcnScope> = 1
  %endif
  %if activeFcn == "ModelConstructor"
    %assign numFields = ::CompiledModel.System[baseSystemIdx].Variables.LocalBlockIODef.NumFlatFields
    %assign ::CompiledModel.System[baseSystemIdx].Variables.LocalBlockIODef.NumFlatFields = numFields+1
  %endif
  %if FcnSysModuleIsRateGrouping(System[GetBaseSystemIdx()], "Outputs") && ...
    SLibSystemFcnIsRateGroupType(activeFcn) && accTid >= 0
    %if !ISEQUAL(dataRec.TID, accTid)
      %assign temp = []
      %foreach i = NumSampleTimes
    %assign temp = temp + 0
      %endforeach
 
      %if TYPE(dataRec.TID) == "Vector"
    %foreach i = SIZE(dataRec.TID,1)
      %assign idx = (dataRec.TID[i] > 0) ? dataRec.TID[i] : 0
      %assign temp[idx] = 1
    %endforeach
      %elseif TYPE(dataRec.TID) == "Number"
        %assert dataRec.TID >= 0
        %assign temp[dataRec.TID] = 1
      %endif
      %assign temp[accTid] =1
      %assign dataRec.TID = []
      %foreach i = NumSampleTimes
    %if temp[i] == 1
      %assign dataRec.TID = dataRec.TID + i
    %endif
      %endforeach
    %endif
  %endif
%endfunction
 
%function SLibCGIRAccessLocalVar(varIndex, accTid, initVal) void
  %assign localBO = ::CompiledModel.BlockOutputs.LocalBlockOutput[varIndex]
  %if !WHITE_SPACE(initVal)
    %addtorecord ::CompiledModel.BlockOutputs.LocalBlockOutput[varIndex] initialValue initVal
  %endif
  %assign ownerSysIdx = localBO.SigDeclSysIdx
  %<SLibCGIRSAccessRecord(ownerSysIdx, localBO, accTid)>
%endfunction
 
%function SLibCGIRAccessLocalDWork(varIndex, accTid) void
  %assign localDW = ::CompiledModel.DWorks.DWork[varIndex]
  %assign ownerSysIdx = localDW.SysCsIdx[0]
  %<SLibCGIRSAccessRecord(ownerSysIdx, localDW, accTid)>
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortFcnCall3.m
%%
%function SLibCG_GetInterfaceData(accSysIdx, fcnType, argType)
  %if TLC_FALSE && AccessDataUseRTM(accSysIdx, fcnType)
    %assign fieldName = "RTMArgDef"
  %else
    %assign fieldName = argType + "ArgDef"
  %endif
  %if ISFIELD(System[accSysIdx].Interface, fieldName)
    %assign interfaceData = System[accSysIdx].Interface.%<fieldName>
  %else
    %assign interfaceData = ""
  %endif
  %return interfaceData
%endfunction
 
%%
%%thisfunctionisonlyusedwhenPreTLCBindingisoff.
%%
%function SLibCG_ReplaceSystemFcnArg(aSystem, aVarGroupIdx) void
  %assign varGroupIdx = aVarGroupIdx
  %assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
  %assert aSystem.GeneratingSubFunctions
  %assert aSystem.SystemIdx == varGroup.SysIdx
  %%
  %% Subfunction called by iterator systems get the address of a
  %% BlockIO or DWork array element passed not just the base pointer.
  %%
  %% e.g. subfcn_call(&localBlockIO[iterBlock_idx])
  %%
  %% The array element is accessed by pointer dereference inside
  %% of the sub-function.
  %%
  %% e.g. localBlockIO->someElement
  %%
  %assign argNotAdded = TLC_TRUE
  %foreach replIdx = SIZE(aSystem.ArgumentReplacements, 1)/2
    %assign argIdx = replIdx * 2
    %if aSystem.ArgumentReplacements[argIdx] == varGroup.LocalName
      %assign argNotAdded = TLC_FALSE
      %break
    %endif
  %endforeach
  %%
  %% Registering the array index expression as a replacement for the
  %% passthrough argument, because we are using a simple pointer
  %% dereference inside of a subfunction to access work vector elements.
  %%
  %if argNotAdded
    %assign aSystem.ArgumentReplacements = ...
      aSystem.ArgumentReplacements + varGroup.LocalName
    %assign replacement = "&" + ...
      SLibGetIndexedCGIRVarGroupPathForISSLoopBoundReuse(varGroupIdx, ...
      varGroup.LocalName, varGroup.SysIdx)
    %assign aSystem.ArgumentReplacements = ...
      aSystem.ArgumentReplacements + replacement
  %endif
%endfunction %% SLibCG_ReplaceSystemFcnArg
 
%%TopTester:test/toolbox/simulink/variants/codevariants/tmg1672961.m
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibVarGroupHasParentStruct(aVarGroup) void
  %assign parentVarGroupIdx = aVarGroup.ParentVarGroupIdx
  %if -1 == parentVarGroupIdx
    %return TLC_FALSE
  %endif
  %assign parentVarGroup = ::CompiledModel.VarGroups.VarGroup[parentVarGroupIdx]
  %return 1 == parentVarGroup.PackageAsStruct
%endfunction
 
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibVarGroupIsSelfGroup(aVarGroup) void
    %if ISFIELD(aVarGroup,"CoderDataGroupIndex")
      %assign coderGroupIdx = aVarGroup.CoderDataGroupIndex
      %if coderGroupIdx > -1
        %return ::CompiledModel.CoderDataGroup[coderGroupIdx].IsSelf
      %endif
    %endif
    %return TLC_FALSE
%endfunction
 
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibVarGroupParentIsSelfGroup(aVarGroup) void
  %assign parentVarGroupIdx = aVarGroup.ParentVarGroupIdx
  %if parentVarGroupIdx > -1
    %assign parentVarGroup = ::CompiledModel.VarGroups.VarGroup[parentVarGroupIdx]
    %return SLibVarGroupIsSelfGroup(parentVarGroup)
  %endif
  %return TLC_FALSE
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortFcnCall3.m
%%TopTester:test/toolbox/simulink/variants/tvss_sim_code_match_g984892.m
%%TopTester:test/toolbox/simulink/blocks/CPPCodeGen/tsmlk_core_cpp_coverage.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants6.m
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibCGIRVarGroupPath(aVarGroupIdx, accSysIdx, aCross) void
  %assign varGroupIdx = aVarGroupIdx
  %assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
  %assign vargroupCategory = LibGetVarGroupCategory(varGroupIdx)
  %assign savedAccSysIdx = accSysIdx
  %assign accSysIdx = ::CompiledModel.System[accSysIdx].ReusedParentSystemIdx
  %assign sysIdx = varGroup.SysIdx
  %assign globalAccess = (accSysIdx == (::CompiledModel.NumSystems - 1))
  %assign thisSystem = ::CompiledModel.System[sysIdx]
  %assign isMdlRefSys = IsModelReferenceBaseSys(thisSystem)
  %assign isAccSysMdlRefSys = IsModelReferenceBaseSys(System[accSysIdx])
  %assign isScalableMRSys = isMdlRefSys && IsModelRefScalableBuild()
  %assign isConstBlockIO = varGroup.Category == "ConstBlockIO"
  %assign isMachineData = varGroup.Category == "MachineLocalData"
  %assign isCoderDataGroupData = varGroup.Category == "HierarchicalCoderData"
  %assign group = isCoderDataGroupData ? ::CompiledModel.CoderDataGroup[varGroup.CoderDataGroupIndex] : []
  %assign isInstP = SLibMultiInstance() && ...
    (isCoderDataGroupData ? group.ContainsInstanceSpecificParameter : TLC_FALSE)
  %assign isParameter = varGroup.Category == "Parameter"
  %assign isMdlRefConstBlockIO = isConstBlockIO && isMdlRefSys
  %assign isMdlRefStandAloneCoderGroupData = isCoderDataGroupData && ...
    group.AsStructure == "Standalone" && isMdlRefSys
  %assign isParameterModelRefBase = isParameter && isMdlRefSys
  %assign isMdlRefRegistration = ::BlockFcn == "Registration" && isMdlRefSys
  %assign isERTSFcnTunParams = ::BlockFcn == "Unknown" && isParameter
  %assign isERTMain = ::BlockFcn == "Main"
  %assign isERTSFcnBody = ...
    ::BlockFcn == "SFunctionOutputs" || ::BlockFcn == "SFunctionStart"
  %assign isConstBlockIOAccInMdlRefSys = isConstBlockIO && isAccSysMdlRefSys
  %assign isBlockIO = varGroup.Category == "BlockIO"
  %assign isBlockIOAccInMdlRefSys = isBlockIO && isAccSysMdlRefSys
  %assign isSelfVarGroup = ISFIELD(varGroup,"IsModelSelfCoderGroupVarGroup") && varGroup.IsModelSelfCoderGroupVarGroup
  %assign simpIface = ::CompiledModel.RTWCGModules.RTWCGModule[thisSystem.CGIRModuleIdx].SimplifiedInterface
  %assign forceDerivFromRTM = ...
    (varGroup.Category == "ContStatesDerivative" || varGroup.Category == "ContStatesDisabled") && ...
    (::BlockFcn == "Derivative" || ::BlockFcn == "ForcingFunction")
  %assign rootSysPointer = varGroup.IsPointer ? "->" : "."
 
  %assert !isERTSFcnTunParams || (GenerateErtSFunction == 1)
  %if GenerateClassInterface && isSelfVarGroup
    %% Self is the class object so we dont need to derefference further
    %return ""
  %endif
  %if isERTSFcnTunParams
    %assign rootSysPointer = IOQualifier
  %elseif isERTSFcnBody || isMachineData || isERTMain
    %assign rootSysPointer = "."
  %elseif forceDerivFromRTM
    %assign rootSysPointer = "->"
  %elseif GenerateClassInterface && ...
    (sysIdx == GetBaseSystemIdx())
    %if ISFIELD(::CompiledModel,"InGeneratingGMM") &&...
        ::CompiledModel.InGeneratingGMM
        %if !isConstBlockIO
          %assign rootSysPointer = "->"
        %endif
    %elseif (accSysIdx == GetBaseSystemIdx() || ...
             System[accSysIdx].ReusedParentSystemIdx == GetBaseSystemIdx()) || ...
            SLibReusableSubsystemCppEncapEnabled()
      %assign rootSysPointer = "."
    %else
      %assign rootSysPointer = "->"
    %endif
  %endif
     
  %% Track access if not tuning params in ERT SFcn wrapper, or
  %% const block IO for mdlref although if it is global access for
  %% const block IO for mdlref, then track it in that one case
  %if !isERTSFcnTunParams && !isMachineData &&...
    sysIdx == accSysIdx && ...
    (!isConstBlockIOAccInMdlRefSys || globalAccess) && ...
    (!isParameterModelRefBase || globalAccess)
    %if varGroup.Category == "HierarchicalCoderData"
      %assign fieldName = "CoderDataGroup" + group.Name
    %else
      %assign fieldName = varGroup.Category
    %endif
    %assign interfaceData = SLibCG_GetInterfaceData(accSysIdx,::BlockFcn,fieldName)
    %if TYPE(interfaceData) == "Scope" && !isSelfVarGroup
      %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
    %endif
 
    %% If this is a coder group in the model reference base system, we also need
    %% to track RTM.
    %if isCoderDataGroupData && isMdlRefSys && SLibAccessGroupThroughSelf(group) && !isSelfVarGroup
      %assign interfaceData = ::CompiledModel.System[accSysIdx].Interface.RTMArgDef
      %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
    %endif
  %endif
   
  %% Root system
  %if sysIdx == (NumSystems-1) || ...
    isMdlRefConstBlockIO || ...
    isMdlRefStandAloneCoderGroupData || ...
    (isMdlRefSys && GenerateClassInterface)
    %assign tmpHasSimStructVars = ::CompiledModel.HasSimStructVars
    %assign ::CompiledModel.HasSimStructVars = AccessDataUseRTM(sysIdx,::BlockFcn, aCross)
     
    %if SLibIsMappedSystemInDeploymentDiagram(savedAccSysIdx) && ...
      (varGroup.Category == "ContStatesDerivative" || ...
      varGroup.Category == "ContStatesDisabled" || ...
      varGroup.Category == "ContStates") && ...
      EXISTS(::GlobalCurrentPID) && ...
      EXISTS(::GlobalCurrentTID) && ...
      SLibDeploymentGetTaskIndexForComponent(::GlobalCurrentPID, ::GlobalCurrentTID) >= 0
      %% For deployment diagram, need to pass the task in the argument
      %assign retStr = ...
        SLibDeploymentGet%<varGroup.Category>Struct(savedAccSysIdx,forceDerivFromRTM) + ...
        rootSysPointer
    %elseif isMachineData
      %return varGroup.Name + "."
    %elseif isCoderDataGroupData
      %if group.AsStructure == "None"
        %assign retStr = ""
      %elseif group.IsSelf
        %assign selfVarGroup = ::CompiledModel.VarGroups.VarGroup[SLibGetSelfVarGroupIndex()]
        %assign retStr = selfVarGroup.LocalName + rootSysPointer
      %else
        %if varGroup.IsPointer && ::CompiledModel.HasSimStructVars
          %% If the group is a pointer and we're accessing through RTM, we'll
          %% get a pointer from LibGetCoderDataGroupStruct. Wrap it in parentheses
          %% so we get compilable code
          %assign retStr = "(" + LibGetCoderDataGroupStruct(group) + ")" + rootSysPointer
        %elseif GenerateClassInterface && group.AsStructure == "InParent" && sysIdx == GetBaseSystemIdx()
          %% in this case we know this is a reference
          %assign retStr = varGroup.StructureReferenceName + "->"
        %else
          %assign retStr = LibGetCoderDataGroupStruct(group) + rootSysPointer
        %endif
      %endif
    %elseif isInstP && !GenerateClassInterface
        %return SLibGetCoderDataGroupPointerFromRTM(group, 0) + "->"
    %else
      %if sysIdx == GetBaseSystemIdx() && SLibIsSelfStructured() && SLibVarGroupParentIsSelfGroup(varGroup)
          %% HasSimStructVars should be true if the varGroup is accessed through self
          %assign ::CompiledModel.HasSimStructVars = TLC_TRUE
      %endif
      %assign retStr = LibGet%<varGroup.Category>Struct() + rootSysPointer
    %endif
    %assign ::CompiledModel.HasSimStructVars = tmpHasSimStructVars
    %return retStr
    %% Standalone subsystem
  %elseif !SLibVarGroupHasParentStruct(varGroup)
    %if ISFIELD(varGroup,"IsModelSelfCoderGroupVarGroup") && varGroup.IsModelSelfCoderGroupVarGroup
      %return SLibGetSimStruct() + "->"
    %elseif !ISEMPTY(varGroup.NonreusedName)
      %return varGroup.NonreusedName + "."
    %elseif LibCGTypeIsMatrix(varGroup.CGTypeIdx)
      %return SLibGetIndexedCGIRVarGroupPathForISSNoLoopBoundReuse(varGroupIdx, varGroup.Name, sysIdx, accSysIdx, aCross)
    %else
      %return varGroup.Name + "."
    %endif
  %% Local access; wait until sysIdx is up to a noninlined boundary,
  %% e.g. not inside an inlined variant subsystem
  %elseif sysIdx == accSysIdx && thisSystem.RTWSystemCode == 2
    %assign staticSingleInstance = isScalableMRSys && !varGroup.IsPointer
    %assign accessViaSelf = simpIface && !isParameter
    %% Local access of nonreusable inside reusable
    %if (aCross || staticSingleInstance || isParameterModelRefBase) && ...
      !ISEMPTY(varGroup.NonreusedName) && !accessViaSelf && !(isSelfVarGroup && isMdlRefSys && IsModelReferenceSimTarget())
      %if varGroup.IsPointer
        %assign interfaceData = thisSystem.Interface.%<varGroup.Category>ArgDef
        %<SLibAccessArgHelper(interfaceData, "Global", FcnGetCurrentAccessTid())>
      %endif
 
      %if LibCGTypeIsMatrix(varGroup.CGTypeIdx) && ...
        ISFIELD(thisSystem, "IndexingSigSrc")
        %% If varGroup is matrix and it's an IIS, the subsystem is capable of reuse
        %% for loop bound, and the path should be indexed.
        %return SLibGetIndexedCGIRVarGroupPathForISSLoopBoundReuse(aVarGroupIdx, varGroup.NonreuseName, sysIdx) + "."
      %elseif SLibGetUseRTMcgType() && IsModelReferenceSimTarget() && SLibGetDoesSelfHasCoderDataGroup() && !IsModelRefScalableBuild()
        %if (ISFIELD(varGroup,"CoderDataGroupIndex") && varGroup.CoderDataGroupIndex > -1)
          %assign group = ::CompiledModel.CoderDataGroup[varGroup.CoderDataGroupIndex]
          %assign accessViaSelf = group.AsStructure == "InSelf"
        %else
          %assign parentVG = ::CompiledModel.VarGroups.VarGroup[varGroup.ParentVarGroupIdx]
          %assign accessViaSelf = ISFIELD(parentVG,"CoderDataGroupIndex") && parentVG.CoderDataGroupIndex == SLibGetSelfCoderDataGroupIndex()
        %endif
        %if (accessViaSelf)
        %% Pop up a level
        %return SLibCGIRVarGroupPath(varGroup.ParentVarGroupIdx, accSysIdx,aCross) + ...
          varGroup.Name + "."
      %else
        %return varGroup.NonreusedName + (varGroup.IsPointer ? "->" : ".")
      %endif
      %else
        %return varGroup.NonreusedName + (varGroup.IsPointer ? "->" : ".")
      %endif
       
    %% local access inside reusable subsystem
    %else
      %if LibCGTypeIsMatrix(varGroup.CGTypeIdx) && ...
        ISFIELD(thisSystem, "IndexingSigSrc")
        %% If varGroup is matrix and it's an IIS, the subsystem is
        %% capable of reuse for loop bound, and the path should be indexed.
        %if thisSystem.GeneratingSubFunctions
          %<SLibCG_ReplaceSystemFcnArg(thisSystem, varGroupIdx)>
          %return varGroup.LocalName + "->"
        %else
          %return SLibGetIndexedCGIRVarGroupPathForISSLoopBoundReuse( ...
            aVarGroupIdx, varGroup.LocalName, sysIdx) + "."
        %endif
      %elseif SLibVarGroupHasParentStruct(varGroup) && SLibVarGroupParentIsSelfGroup(varGroup) && ...
        (simpIface || SLibIsSelfInSimTarget() && ::BlockFcn == "Registration") && ...
        !SLibVarGroupIsSelfGroup(varGroup) && !SLibIsFcnSubFunction(thisSystem, ::BlockFcn)
        %% mark reusable self argument as accessed
        %<SLibCG_AccessFirstArg()>
        %% Pop up a level
        %return SLibCGIRVarGroupPath(varGroup.ParentVarGroupIdx, accSysIdx,aCross) + varGroup.Name + "."
      %else
       %return varGroup.LocalName + "->"
      %endif
    %endif
 
  %% parameter is accessed via the root system when from below
  %elseif isParameter && (sysIdx > accSysIdx)
    %return SLibCGIRVarGroupPath(varGroupIdx, NumSystems-1, aCross)
     
  %elseif isMdlRefSys && !isAccSysMdlRefSys
    %assign nonreusedName = FcnSysVarGroupNonreusedName(thisSystem, varGroup.Category)
    %if ISEMPTY(nonreusedName)
      %return ""
    %else
      %return nonreusedName + "."
    %endif
  %% non-local access of reusable subsystem
  %else
     %if LibCGTypeIsMatrix(varGroup.CGTypeIdx)
    %% (DJia) This is a temporary solution
    %% For dwork in Indexing Subsystem, return the last region since
    %% for-iterator subsystem always logging the later iteration
      %return SLibGetIndexedCGIRVarGroupPathForISSNoLoopBoundReuse(varGroupIdx, varGroup.Name, sysIdx, accSysIdx, aCross)
    %elseif (GenerateClassInterface && varGroup.ParentVarGroupIdx == SLibGetSelfVarGroupIndex())
      %if aCross && ((accSysIdx != GetBaseSystemIdx">GetBaseSystemIdx() && System[accSysIdx].ReusedParentSystemIdx != GetBaseSystemIdx">GetBaseSystemIdx()) || ...
        CGMODEL_ACCESS("CGModel.getUseOperatorNewForModelRefRegistration")) && thisSystem.RTWSystemCode == 2
        %% anchoring to local arg from resuable subsystem
        %return varGroup.Name + "->"
      %else
        %return varGroup.Name + "."
      %endif
    %else
      %% Pop up a level
      %return ...
        SLibCGIRVarGroupPath(varGroup.ParentVarGroupIdx, accSysIdx,aCross) + ...
            varGroup.Name + "."
    %endif
  %endif
%endfunction
 
%%Function:SLibCG_GetOptSubStruct================================================================
%%Abstract:
%%Returnsaoptionalsub-structurereference,ifavargroupelementislocated
%%inasubstructure(e.g.bit-field).
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%
%function SLibCG_GetOptSubStruct(varGroupIdx, memberIdx)
  %assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
  %if varGroup.NumSubStructs > 0
    %assign subStructIdx = varGroup.SubStructIndex[memberIdx]
    %if subStructIdx > -1
      %return varGroup.SubStuctNames[subStructIdx] + "."
    %endif
  %endif
  %return ""
%endfunction
 
%%Function:SLibCG_GetVarGroupElementPath=========================================================
%%Abstract:
%%Getstofullpathtoavargoupelement.
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%
%function SLibCG_GetVarGroupElementPath(varGroupIdx, accSysIdx, cross) void
  %assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx[0]]
  %if 0 == varGroup.PackageAsStruct
    %return SLibVarGroupElementName(varGroupIdx[0], varGroupIdx[1])
  %else
    %assign memberElName = FcnSLibCGIRGetVarGroupMemberName(varGroupIdx[0], varGroupIdx[1])
    %assign subStruct = SLibCG_GetOptSubStruct(varGroupIdx[0], varGroupIdx[1])
    %assign varGroupPath = SLibCGIRVarGroupPath(varGroupIdx[0], accSysIdx, cross)
    %return varGroupPath + subStruct + memberElName
  %endif
%endfunction
 
%%Function:SLibCG_GetMultiWordID=================================================================
%%Abstract:
%%Thisfunctionreturnsachunkaccessstringforanygivenchunkindex
%%greaterorequaltozero.
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/tStringSupport.m
%%
%function SLibCG_GetMultiWordID(chunkIdx) void
  %if TYPE(chunkIdx) == "String"
    %return ".chunks[%<chunkIdx>]"
  %endif
  %if chunkIdx >= 0
    %return ".chunks[%<chunkIdx>]"
  %endif
  %return ""
%endfunction %% SLibCG_GetMultiWordID
 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%Functionsforcustomstorageclass
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 
%%Function:BlkFcnCGIRCSCDataHelper===============================================================
%%Abstract:
%%Returnsacustomstorageclassaccessforagivendatarecord
%%TopTester:test/toolbox/simulink/variants/inlineVariants/ivGeneral/tVariantsAndSubmodels.m
%%
%function BlkFcnCGIRCSCDataHelper(record, width, memberStr, lcv, ucv, idx, reim, addr) void
  %assert record.StorageClass == "Custom"
  %assign sigIndexer = ...
    SLibGet1DStructFieldIndexer(width, memberStr, ucv, lcv, idx)
  %if addr
    %assert LibCustomDataIsAddressable(record)
    %return LibCustomData(record,"address",sigIndexer,reim)
  %else
    %return LibCustomData(record,"contents",sigIndexer,reim)
  %endif
%endfunction
 
%%Function:SLibInhibitSlLutMemAccessIdx==========================================================
%%Abstract:
%%ReturnstrueifthegivenrecordbelongstoaSimulink.LookupTableand
%%theaccessstringisinthisformat".lutMemberName[0]...[0]"andif
%%thecontainertypeofthememberwithintheaccessstringisnD.Returns
%%falseotherwise.
%%
%%ThisfunctionisusedwithinFcnCGIRCSCDataHelpertoavoidappending
%%unnecessaryzeroindextoastructelementaccessforwhichthe
%%thereferencetothefirstelementistaken.Forexample,wegetthis
%%intheaccessStrforaLUT:".Table[0][0]".ThenFcnCGIRCSCDataHelper
%%appendsanextra[0]resultingin"&lut.Table[0][0][0]".Seeg1769955
%%fordetails.
%%
%%NoticethatthisisusedasaSimulink.LookupTableexceptionfor18b.
%%Weplantosupportdimensionspreservationforbusesingeneral:
%%g1708616.Whenthisisdoneweneedamoregeneralsolutionforthe
%%problem.
%%
%function SLibInhibitSlLutMemAccessIdx(rec, accessStr) void
  %assign memberName = []
  %if !ISEMPTY(rec) && ISFIELD(rec, "IsLUTObject") && ...
      rec.IsLUTObject && !ISEMPTY(accessStr)
    %% We need to get the "." for member access, the member field name,
    %% and the zero indexing ([0]...[0]) to inhibit the appending of
    %% an additional zero index.
    %assign accessStrTokens = FEVAL("regexp", accessStr, ...
                                    "(/.)([a-zA-Z0-9_])*(//[(///*.*/*//)?0//])*$", ...
                                    "tokens")
    %if SIZE(accessStrTokens, 0) > 0 && SIZE(accessStrTokens, 1) == 3
      %assign memberName = accessStrTokens[0][1]
    %endif
    %if !ISEMPTY(memberName)
      %assign slDataType = ...
         ::CompiledModel.DataTypes.DataType[rec.OriginalDataTypeIdx]
      %foreach currElemIdx = slDataType.NumElements
        %assign currElem = slDataType.Elements[currElemIdx]
        %if currElem.Name == memberName
          %return SLibIsContainerCGTypeND(currElem)
        %endif
      %endforeach
    %endif
  %endif
  %return TLC_FALSE
%endfunction %% SLibInhibitSlLutMemAccessIdx
 
%%Function:FcnCGIRCSCDataHelper==================================================================
%%[in]preventCastForMacroAccess-iftrue,evaluationoftheneedforacastforanimported
%%definewillbeskipped
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmFunctionCallSplitBlock_hidden_VC1.m
%%TopTester:test/toolbox/simulink/variants/tCSCDefine.m
%%
%function FcnCGIRCSCDataHelper(record, preventCastForMacroAccess, width, memberStr, chunkIdx, ucv, indexExpr, addr) void
  %assign tmpVect = SLibGetReimAndIdx(indexExpr)
  %assign reim = tmpVect[0]
  %assign idx = tmpVect[1]
  %assign isIdxZero = (idx == 0)
  %if SLibIsContainerCGTypeND(record) || ...
      SLibInhibitSlLutMemAccessIdx(record, memberStr) || ...
      SLibIsNdIndexingFeatureOn()
    %assign idx = ""
  %endif
     
  %if SLibIsContainerCGTypeND(record) && isIdxZero == TLC_TRUE && ISEMPTY(memberStr)
    %assign recDims = LibGetRecordDimensions(record)
    %assign sigIndexer = ""
    %foreach dimIdx = SIZE(recDims, 1)
      %assign sigIndexer = sigIndexer + "[0]"
    %endforeach
  %else
    %assign sigIndexer = SLibGet1DStructFieldIndexer(width, memberStr, ucv, "", idx)
  %endif
 
  %if chunkIdx >= 0
    %assign errTxt = "Custom storage classes don't support multi-word " ...
      "fix-point operations at this point."
    %<LibReportError(errTxt)>
  %endif
  %if addr
    %if !LibCustomDataIsAddressable(record)
      %assign errTxt = "%<record.RecordType> %<LibGetRecordVarName(record)> " + ...
        "is not addressable because of its custom storage class."
      %<LibReportFatalError(errTxt)>
    %endif
    %return LibCustomData(record,"address",sigIndexer,reim)
  %elseif preventCastForMacroAccess
    %return SLibAccessCustomDataNoMacroCasts(record,"contents",sigIndexer,reim,"")
  %else
    %return LibCustomData(record,"contents",sigIndexer,reim)
  %endif
%endfunction
 
%function FcnCGIRCSCRefDataHelper(record, width, memberStr, chunkIdx, ucv, indexExpr) void
  %assign tmpVect = SLibGetReimAndIdx(indexExpr)
  %assign reim = tmpVect[0]
  %assert ISEMPTY(reim)
     
  %% Determine if param is an array. If it is idx is not empty.
  %assign idx = tmpVect[1]
  %assign sigIndexer = SLibGet1DStructFieldIndexer(width, memberStr, ucv, "", idx)
   
  %if ISEMPTY(sigIndexer)
    %assign retString = FcnCGIRCSCDataHelper(record, TLC_TRUE, width, memberStr, chunkIdx, ucv, indexExpr, TLC_TRUE)
  %else
    %% Pretend to generate a reference to content, then remove the last [0].
    %assign retString = FcnCGIRCSCDataHelper(record, TLC_TRUE, width, memberStr, chunkIdx, ucv, indexExpr, TLC_FALSE)
    %assign tmp = FEVAL("regexp", retString, "(//[0//]$)", "tokens")
    %if !ISEMPTY(tmp)
      %assign retString = FEVAL("regexprep", retString, "//[0//]$", "")
    %endif
  %endif
   
  %return retString
%endfunction
 
%%Function:SLibCGIR_CSCP===========================================
%%Abstract:
%%Returnsacustomstorageclassaccessforagivenparameter
%%
%%[in]preventCastForMacroAccess-iftrue,evaluationoftheneedforacastforanimported
%%definewillbeskipped
%%
%function SLibCGIR_CSCP(paramIdx, preventCastForMacroAccess, width, memberStr, chunkIdx, ucv, indexExpr) void
  %assign param = ::CompiledModel.ModelParameters.Parameter[paramIdx]
  %return FcnCGIRCSCDataHelper(param, preventCastForMacroAccess, width, memberStr, ...
                               chunkIdx, ucv, indexExpr, TLC_FALSE)
%endfunction
 
%function SLibCGIR_CSCPAddr(paramIdx, preventCastForMacroAccess, width, memberStr, chunkIdx, ucv, indexExpr, numDims) void
  %assign param = ::CompiledModel.ModelParameters.Parameter[paramIdx]
  %if !ISFIELD(param,"NumOfDimensions")
      %addtorecord param NumOfDimensions numDims
  %else
      %assign param.NumOfDimensions = numDims
  %endif
  %assign pAddr = FcnCGIRCSCDataHelper(param, preventCastForMacroAccess, width, memberStr, chunkIdx, ucv, indexExpr, TLC_TRUE)
  %return pAddr
%endfunction
 
%function SLibCGB_CSCP(block, paramIdx, width, memberStr, lcv, ucv, sigIdx, reim) void
  %assign param = ::CompiledModel.ModelParameters.Parameter[paramIdx]
  %return BlkFcnCGIRCSCDataHelper(param, width, memberStr, lcv, ucv, sigIdx, reim, TLC_FALSE)
%endfunction
 
%function SLibCGB_CSCPAddr(block, paramIdx, width, memberStr, lcv, ucv, sigIdx, reim) void
  %assign param = ::CompiledModel.ModelParameters.Parameter[paramIdx]
  %if !LibCustomDataIsAddressable(param)
    %<SLibReportErrorWithIdAndArgs("RTW:tlc:CSCParamNotAddressable", ...
      "%<LibGetRecordVarName(param)>")>
  %endif
  %% To complete fix geck 1801427(model argument with array slicing), the result of this function
  %% has to be a pointer type, which means:
  %% for sub-matrix reference expression, prefix with "&"
  %% for other expressions, prefix with "&" ONLY if it is a scalar.
  %% Ideally, BlkFcnCGIRCSCDataHelper should stick to this mental model, but its exposure is too broad
  %% for bug fixing.
  %assign pVal = BlkFcnCGIRCSCDataHelper(param, width, memberStr, lcv, ucv, sigIdx, reim, TLC_FALSE)
  %if width == 1 || SLibIsSubMatrixRef(pVal)
    %return "&" + pVal
  %else
    %return pVal
  %endif
%endfunction
 
%function SLibIsSubMatrixRef(expr) void
  %assign size = SIZE(expr)[1]
  %return (expr[size-1] == "]" || (expr[0]=="(" && expr[size-1]==")" && expr[size-2]=="]"))
%endfunction
 
%%ThisfunctionshoulddoexactlythesameasSLibCGIR_CSCPAddr
%%Howeverattheendconverttheaddresstoanl-valuebeforereturn.
%function SLibCGIR_AUTOSAR_CSCPAddr(paramIdx, preventCastForMacroAccess, width, memberStr, chunkIdx, ...
  ucv, indexExpr) void
   
  %assign tmpVect = SLibGetReimAndIdx(indexExpr)
  %assign reim = tmpVect[0]
  %% AUTOSAR Target does not support complex numbers
  %if !ISEMPTY(reim)
    %<SLibReportErrorWithId("RTW:autosar:noComplexSupport")>
  %endif
   
  %% Determine if param is an array. If it is idx is not empty
  %assign idx = tmpVect[1]
  %assign sigIndexer = SLibGet1DStructFieldIndexer(width, memberStr, ucv, "", idx)
  %if !ISEMPTY(sigIndexer)
    %% Pretend to generate a reference to content. Then remove the last [0].
    %assign param = ::CompiledModel.ModelParameters.Parameter[paramIdx]
    %assign pAddr = FcnCGIRCSCDataHelper(param, TLC_TRUE, width, memberStr, chunkIdx, ...
      ucv, indexExpr, TLC_FALSE)
    %% Remove the [0] at the end
    %assign tmpSignalAddr = FEVAL("regexp", pAddr, ...
      "(//[0//])$", "tokens")
    %if !ISEMPTY(tmpSignalAddr)
      %assign pAddr = FEVAL("regexprep", pAddr, ...
        "//[0//]$", "")
    %endif
    %return pAddr
  %else
    %% If idx is empty then the the CSC must not be an array in this case we
    %% do the same thing as SLibCGIR_CSCPAddr
    %assign param = ::CompiledModel.ModelParameters.Parameter[paramIdx]
    %assign pAddr = FcnCGIRCSCDataHelper(param, TLC_TRUE, width, memberStr, ...
     chunkIdx, ucv, indexExpr, TLC_TRUE)
    %return pAddr
  %endif
%endfunction
 
%%ThisfunctioniscalledfromRTWCGtounpackinstancehandlethatwillbe
%%usedbyareusablesubsystem
%function SLibCG_UnpackInstanceHandleViaRTM(createBinding) void
  %assign recName = "AutosarInstanceHandle"
  %if !EXISTS("AutosarInstanceHandleRTMFieldAdded")
    %% Only need to add this field once
    %assign ::AutosarInstanceHandleRTMFieldAdded = TLC_TRUE
    %assign CONST_QUALIFIER = "CONST"
    %<RTMAddRecSclr(...
      "%<recName>", ...
      "%<FcnGetInstanceHandleName()>", ...
      "", ...
      "VOID_PTR", ...
      CONST_QUALIFIER, ...
      [0,0,0,0], ...
      "TLC_TRUE")>
  %endif
   
  %assign rtmField = RTMGet(recName)
  %<SLibCG_AccessRTM()>
  %assign var = FcnGetMultiInstanceRunnableArgs(createBinding)
  %openfile retBuf
  %if !createBinding
    %<var> = (Rte_Instance)%<rtmField>;
  %else
    %% root system init function where we establish the binding
    %<rtmField> = (const void *)%<var>;
  %endif
  %closefile retBuf
   
  %return retBuf
%endfunction
 
 
%%ThisfunctiontracksCalibrationParametersthatarebeingusedinafunction
%%thatisusedbytheARXMLgenerationprocess.
%function SLibCGIR_AUTOSAR_TrackCalPrm(paramIdx) void
  %assign param = ::CompiledModel.ModelParameters.Parameter[paramIdx]
  %return FcnAddAccessInfoForAutosarCalibrationHelper(param)
%endfunction
 
 
%function SLibCG_CSCDW(dworkIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %return FcnCGIRCSCDataHelper(::CompiledModel.DWorks.DWork[dworkIdx], TLC_FALSE, width, memberStr, chunkIdx, ucv, indexExpr, TLC_FALSE)
%endfunction
 
%function SLibCGB_CSCDW(block, dworkIdx, width, memberStr, lcv, ucv, sigIdx, reim) void
  %assign dwork = ::CompiledModel.DWorks.DWork[dworkIdx]
  %return BlkFcnCGIRCSCDataHelper(dwork, width, memberStr, lcv, ucv, sigIdx, reim, TLC_FALSE)
%endfunction
 
%function SLibCG_CSCDWAddr(dworkIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %return FcnCGIRCSCDataHelper(::CompiledModel.DWorks.DWork[dworkIdx], TLC_TRUE, width, memberStr, chunkIdx, ucv, indexExpr, TLC_TRUE)
%endfunction
 
%function SLibCG_CSCDWRef(dworkIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %return FcnCGIRCSCRefDataHelper(::CompiledModel.DWorks.DWork[dworkIdx], width, memberStr, chunkIdx, ucv, indexExpr)
%endfunction
 
%function SLibCGB_CSCDWAddr(block, dworkIdx, width, memberStr, lcv, ucv, sigIdx, reim) void
  %assign dwork = ::CompiledModel.DWorks.DWork[dworkIdx]
  %if !LibCustomDataIsAddressable(dwork)
    %<SLibReportNonAddressableError("Dwork", block, dwork)>
  %endif
  %return BlkFcnCGIRCSCDataHelper(dwork, width, memberStr, lcv, ucv, sigIdx, reim, TLC_TRUE)
%endfunction
 
%function SLibCG_BOCSC(bufIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %return FcnCGIRCSCDataHelper(::CompiledModel.BlockOutputs.ExternalBlockOutput[bufIdx], TLC_FALSE, width, memberStr, chunkIdx, ucv, indexExpr, TLC_FALSE)
%endfunction
 
%function SLibCG_BOFCSC(bufIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %return FcnCGIRCSCDataHelper(::CompiledModel.BlockOutputs.LocalBlockOutput[bufIdx], TLC_FALSE, width, memberStr, chunkIdx, ucv, indexExpr, TLC_FALSE)
%endfunction
 
%function SLibCG_BOCSC_DefaultMapping(bufIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %assign bo = ::CompiledModel.BlockOutputs.GlobalBlockOutput[bufIdx]
  %assert SLibIsLegacyStorageClassForDataRecord(bo) == TLC_TRUE
  %return FcnCGIRCSCDataHelper(bo, TLC_FALSE, width, memberStr, chunkIdx, ucv, indexExpr, TLC_FALSE)
%endfunction
 
%function SLibCGB_BOCSC(block, bufIdx, width, memberStr, lcv, ucv, sigIdx, reim) void
  %assign bo = ::CompiledModel.BlockOutputs.ExternalBlockOutput[bufIdx]
  %return BlkFcnCGIRCSCDataHelper(bo, width, memberStr, lcv, ucv, sigIdx, reim, TLC_FALSE)
%endfunction
 
%function SLibCGB_BOFCSC(block, bufIdx, width, memberStr, lcv, ucv, sigIdx, reim) void
  %assign bo = ::CompiledModel.BlockOutputs.LocalBlockOutput[bufIdx]
  %return BlkFcnCGIRCSCDataHelper(bo, width, memberStr, lcv, ucv, sigIdx, reim, TLC_FALSE)
%endfunction
 
%function SLibCG_BOCSCAddr(bufIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %return FcnCGIRCSCDataHelper(::CompiledModel.BlockOutputs.ExternalBlockOutput[bufIdx], TLC_TRUE, width, memberStr, chunkIdx, ucv, indexExpr, TLC_TRUE)
%endfunction
 
%function SLibCG_BOCSCRef(bufIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %return FcnCGIRCSCRefDataHelper(::CompiledModel.BlockOutputs.ExternalBlockOutput[bufIdx], width, memberStr, chunkIdx, ucv, indexExpr)
%endfunction
 
%function SLibCG_BOFCSCAddr(bufIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %return FcnCGIRCSCDataHelper(::CompiledModel.BlockOutputs.LocalBlockOutput[bufIdx], TLC_TRUE, width, memberStr, chunkIdx, ucv, indexExpr, TLC_TRUE)
%endfunction
 
%function SLibCG_BOCSCAddr_DefaultMapping(bufIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %assign record = ::CompiledModel.BlockOutputs.GlobalBlockOutput[bufIdx]
  %assert SLibIsLegacyStorageClassForDataRecord(record) == TLC_TRUE
  %return FcnCGIRCSCDataHelper(record, TLC_TRUE, width, memberStr, chunkIdx, ucv, indexExpr, TLC_TRUE)
%endfunction
 
%function SLibCGB_BOCSCAddr(block, bufIdx, width, memberStr, lcv, ucv, sigIdx, reim) void
  %assign bo = ::CompiledModel.BlockOutputs.ExternalBlockOutput[bufIdx]
  %if !LibCustomDataIsAddressable(bo)
    %<SLibReportNonAddressableError("Output", block, bo)>
  %endif
  %return BlkFcnCGIRCSCDataHelper(bo, width, memberStr, lcv, ucv, sigIdx, reim, TLC_TRUE)
%endfunction
 
%function SLibCGB_BOFCSCAddr(block, bufIdx, width, memberStr, lcv, ucv, sigIdx, reim) void
  %assign bo = ::CompiledModel.BlockOutputs.LocalBlockOutput[bufIdx]
  %if !LibCustomDataIsAddressable(bo)
    %<SLibReportNonAddressableError("Output", block, bo)>
  %endif
  %return BlkFcnCGIRCSCDataHelper(bo, width, memberStr, lcv, ucv, sigIdx, reim, TLC_TRUE)
%endfunction
 
%function SLibCG_SetCSCData(record, width, memberStr, chunkIdx, ucv, indexExpr, rhs) void
  %return SLibCG_CSCDataHelper(record, width, memberStr, chunkIdx, ucv, indexExpr, rhs, "set")
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%
%function SLibCG_CSCDataHelper(record, width, memberStr, chunkIdx, ucv, indexExpr, rhs, type) void
  %assert record.StorageClass == "Custom" || SLibIsLegacyStorageClassForDataRecord(record)
  %if chunkIdx >= 0
    %assign errTxt = "Custom storage classes don't support multi-word " ...
      "fix-point operations at this point."
    %<LibReportError(errTxt)>
  %endif
  %if record.CustomStorageClassVersion > 1
    %assign tmpVect = SLibGetReimAndIdx(indexExpr)
    %assign reim = tmpVect[0]
    %assign idx = tmpVect[1]
    %assign sigIndexer = SLibGet1DStructFieldIndexer(width, memberStr, ucv, "", idx)
    %return LibAccessCustomData(record,type,sigIndexer,reim,rhs)
  %else
    %assign lhs = FcnCGIRCSCDataHelper(record, TLC_FALSE, width, memberStr, chunkIdx, ...
      ucv, indexExpr, TLC_FALSE)
    %return lhs + " = " + rhs + ";/n"
  %endif
%endfunction
 
  
%function SLibCG_SetCSCDW(dworkIdx, width, memberStr, chunkIdx, ucv, indexExpr, rhs) void
  %assign record = ::CompiledModel.DWorks.DWork[dworkIdx]
  %return SLibCG_SetCSCData(record, width, memberStr, chunkIdx, ucv, indexExpr, rhs)
%endfunction
  
%function SLibCG_SetBOCSC(bufIdx, width, memberStr, chunkIdx, ucv, indexExpr, rhs) void
  %assign record = ::CompiledModel.BlockOutputs.ExternalBlockOutput[bufIdx]
  %return SLibCG_SetCSCData(record, width, memberStr, chunkIdx, ucv, indexExpr, rhs)
%endfunction
 
%function SLibCG_SetBOFCSC(bufIdx, width, memberStr, chunkIdx, ucv, indexExpr, rhs) void
  %assign record = ::CompiledModel.BlockOutputs.LocalBlockOutput[bufIdx]
  %return SLibCG_SetCSCData(record, width, memberStr, chunkIdx, ucv, indexExpr, rhs)
%endfunction
 
%function SLibCG_SetBOCSC_DefaultMapping(bufIdx, width, memberStr, chunkIdx, ucv, indexExpr, rhs) void
  %assign record = ::CompiledModel.BlockOutputs.GlobalBlockOutput[bufIdx]
  %assert SLibIsLegacyStorageClassForDataRecord(record) == TLC_TRUE
  %return SLibCG_SetCSCData(record, width, memberStr, chunkIdx, ucv, indexExpr, rhs)
%endfunction
 
%function SLibCG_SetEOCSC(bufIdx, width, memberStr, chunkIdx, ucv, indexExpr, rhs) void
  %assign record = ::CompiledModel.ExternalOutputs.ExternalOutput[bufIdx]
  %return SLibCG_SetCSCData(record, width, memberStr, chunkIdx, ucv, indexExpr, rhs)
%endfunction
 
%function SLibCG_InitEICSC(bufIdx, width, memberStr, chunkIdx, ucv, indexExpr, rhs) void
  %assign record = ::CompiledModel.ExternalInputs.ExternalInput[bufIdx]
  %return SLibCG_CSCDataHelper(record, width, memberStr, chunkIdx, ucv, indexExpr, rhs, "initialize")
%endfunction
 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%Functionsfor"simple"andlocalcgVars
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/tStringSupport.m
%%
%function FcnCGIRSimpleCGVarHelper(identifier, isPointer, width, memberStr, chunkIdx, ucv, indexExpr, addr) void
  %assign tmpVect = SLibGetReimAndIdx(indexExpr)
  %assign reim = tmpVect[0]
  %if reim != ""
    %assign reim = "." + reim
  %endif
  %assign idx = tmpVect[1]
  %assign sigIndexer = SLibGet1DStructFieldIndexer(width, memberStr, ucv, "", idx)
  %assign followingId = sigIndexer + reim
  %assign chunk = SLibCG_GetMultiWordID(chunkIdx)
  %% sigIndexer may look like .b.c[3] or [3] or ""
  %% if followingId starts with [, don't add *
  %% if followingId starts with ., add *
  %% if followingId is empty, add * if we want content.
 
  %if ISEMPTY(followingId)
    %if isPointer
      %if !addr
        %return "(*%<identifier>)" + chunk
      %else
        %if ISEMPTY(chunk)
          %return identifier
        %else
          %return "&(*" + identifier + ")" + chunk
        %endif
      %endif
    %endif
  %elseif isPointer
    %assign identifier = "(*" + identifier + ")"
  %endif
   
  %if addr
    %return "&" + identifier + followingId + chunk
  %else
    %return identifier + followingId + chunk
  %endif
%endfunction
 
%function SLibCG_V(identifier, isPointer, width, memberStr, chunkIdx, ucv, indexExpr)
  %return FcnCGIRSimpleCGVarHelper(identifier, isPointer, width, memberStr, chunkIdx, ucv, indexExpr, TLC_FALSE)
%endfunction
 
%function SLibCG_VAddr(identifier, isPointer, width, memberStr, chunkIdx, ucv, indexExpr) void
  %return FcnCGIRSimpleCGVarHelper(identifier, isPointer, width, memberStr, chunkIdx, ucv, indexExpr, TLC_TRUE)
%endfunction
 
%function SLibCG_SetV(identifier, isPointer, width, memberStr, chunkIdx, ucv, indexExpr, rhs) void
  %assign lhs = SLibCG_V(identifier, isPointer, width, memberStr, chunkIdx, ...
    ucv, indexExpr)
  %return lhs + " = " + rhs + ";/n"
%endfunction
 
%function SLibCG_SetASOVAddr(boRecordIdx, accTid, width, memberStr, chunkIdx, ucv, indexExpr, rhs) void
  %assign blkOutputRec = ::CompiledModel.BlockOutputs.LocalBlockOutput[boRecordIdx]
  %assert blkOutputRec.DeclareAsPointer == "yes"
  %assign ownerSysIdx = blkOutputRec.SigDeclSysIdx
  %<SLibCGIRSAccessRecord(ownerSysIdx, blkOutputRec, accTid)>
  %assign blkOutputId = blkOutputRec.Identifier
  %return "%<SLibCG_V(blkOutputId, TLC_FALSE, 1, "", chunkIdx, "", 0)> = %<rhs>;/n"
%endfunction
 
%function SLibCG_SetASOV(boRecordIdx, accTid, width, memberStr, chunkIdx, ucv, indexExpr, rhs) void
  %assign blkOutputRec = ::CompiledModel.BlockOutputs.LocalBlockOutput[boRecordIdx]
  %assert blkOutputRec.DeclareAsPointer == "yes"
  %assign ownerSysIdx = blkOutputRec.SigDeclSysIdx
  %<SLibCGIRSAccessRecord(ownerSysIdx, blkOutputRec, accTid)>
  %assign blkOutputId = blkOutputRec.Identifier
  %assign lhs = SLibCG_V(blkOutputId, TLC_TRUE, width, memberStr, chunkIdx, ...
    ucv, indexExpr)
  %return lhs + " = " + rhs + ";/n"
%endfunction
 
%function SLibCG_ASOV(boRecordIdx, accTid, width, memberStr, chunkIdx, ucv, indexExpr) void
  %assign blkOutputRec = ::CompiledModel.BlockOutputs.LocalBlockOutput[boRecordIdx]
  %assert blkOutputRec.DeclareAsPointer == "yes"
  %assign ownerSysIdx = blkOutputRec.SigDeclSysIdx
  %<SLibCGIRSAccessRecord(ownerSysIdx, blkOutputRec, accTid)>
  %assign blkOutputId = blkOutputRec.Identifier
  %return SLibCG_V(blkOutputId, TLC_TRUE, width, memberStr, chunkIdx, ucv, indexExpr)
%endfunction
 
%function SLibCG_ASOVAddr(boRecordIdx, accTid, width, memberStr, chunkIdx, ucv, indexExpr) void
  %assign blkOutputRec = ::CompiledModel.BlockOutputs.LocalBlockOutput[boRecordIdx]
  %assign ownerSysIdx = blkOutputRec.SigDeclSysIdx
  %<SLibCGIRSAccessRecord(ownerSysIdx, blkOutputRec, accTid)>
  %assert blkOutputRec.DeclareAsPointer == "yes"
  %assign blkOutputId = blkOutputRec.Identifier
  %return SLibCG_VAddr(blkOutputId, TLC_TRUE, width, memberStr, chunkIdx, ucv, indexExpr)
%endfunction
 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%Functionsforcanonicalarguments
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 
%function SLibCGIRArg(argDef, cross, width, memberStr, chunkIdx, ucv, indexExpr, addr, isPointer, iterVar)
  %assign accessTid = FcnGetCurrentAccessTid()
  %if cross
    %assign identifier = argDef.GlobalIdentifier
  %else
    %assign identifier = argDef.Identifier
  %endif
  
  %if iterVar != ""
    %assign identifier = identifier + "[" + iterVar + "]"
  %endif
   
  %if addr
    %return SLibCG_VAddr(identifier, isPointer, width, ...
      memberStr, chunkIdx, ucv, indexExpr)
  %else
    %return SLibCG_V(identifier, isPointer, width, ...
      memberStr, chunkIdx, ucv, indexExpr)
  %endif
%endfunction
 
%function SLibAccessParamAsVariable(aModelParamIdx) void
   %assign ::CompiledModel.ModelParameters.Parameter[aModelParamIdx].WasAccessedAsVariable = 1
%endfunction
 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%Functionsforhierarchicalstructures
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/tStringSupport.m
%%TopTester:test/toolbox/simulink/blocks/lib_SignalAttributes/InitialCondition/rtw/tinitcond.m
%%TopTester:test/toolbox/rtw/targets/AUTOSAR/Variants/inlineVariants/tInlineVariants4.m
%%
%function FcnCGIRParamCGVarHelper(paramIdx, cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr, baseaddr) void
  %with ::CompiledModel.System[accSysIdx]
  %assign opaqueBlock = FcnRootOpaqueBlock()
  %with opaqueBlock
     
  %assign tmpVect = SLibGetReimAndIdx(indexExpr)
  %assign reim = tmpVect[0]
  %assign idx = tmpVect[1]
  %assign sigIndexer = SLibGet1DStructFieldIndexer(width, memberStr, ucv, "", idx)
  %assign mdlParam = ::CompiledModel.ModelParameters.Parameter[paramIdx]
 
  %if SLibIsLegacyStorageClassForDataRecord(mdlParam) == TLC_TRUE
    %return FcnCGIRCSCDataHelper(mdlParam, TLC_FALSE, width, memberStr, chunkIdx, ucv, indexExpr, baseaddr)
  %endif
 
  %assign prmSize = SLibGetSizeOfValueFromParamRec(mdlParam)
  %assign nCols = prmSize[1]
  %assign address = ""
  %assign chunk = SLibCG_GetMultiWordID(chunkIdx)
   
  %assign retString = ""
   
  %if baseaddr || !ISEMPTY(memberStr)
    %assign nRows = prmSize[0]
    %if nRows > 1
      %assert idx == 0
      %assert ucv == ""
      %if (SLibIsContainerCGTypeND(mdlParam) || ...
           SLibIsNdIndexingFeatureOn()) && !ISEMPTY(memberStr)
        %assign sigIndexer = memberStr
      %else
        %if ISEMPTY(memberStr)
          %assert memberStr == ""
          %if (SLibIsContainerCGTypeND(mdlParam) || SLibIsNdIndexingFeatureOn())
              %assign numDims = SIZE(LibGetRecordDimensions(mdlParam),1)
              %assign sigIndexer = LibGetIndexOfFirstElement(numDims)
          %else
             %assign sigIndexer = SLibGet2DArrayIndexer(0,nRows,"","",0,nCols,"","",0)
          %endif
        %endif
      %endif
    %endif
    %assign cast = ""
    %% Cast away volatility if necessary
    %if baseaddr && ...
      (mdlParam.InConstSection || mdlParam.InConstWithInitSection) && ...
      SLibGetGlobalConstantMemorySectionHasVolatile()
      %assign dtypeName = LibGetRecordCompositeDataTypeName(mdlParam)
      %assign cast = "("
      %if (mdlParam.InConstSection)
        %assign cast = cast + "const "
      %endif
      %assign cast = cast + dtypeName + "*)"
    %endif
    %if !ISEMPTY(reim)
      %assign reim = "." + reim
    %endif
    %if ISEMPTY(reim) && ISEMPTY(chunk) && baseaddr
      %assign retString = ...
        cast + FcnAccessModelParameterRef(mdlParam, sigIndexer)
    %else
      %assign optAddr = baseaddr ? "&" : ""
      %assign retString = ...
        cast + optAddr + FcnAccessModelParameter(mdlParam, sigIndexer) + reim + chunk
    %endif
  %else
    %if (ucv != "") && (nCols > 1)
      %assign retString = FcnGenerateNonEmptyUcvParameter(mdlParam, sigIndexer, reim) + chunk
    %elseif InlineParameters != 0 && ...
      mdlParam.TestpointIndex < 0 && ...
      !LibIsDataTypeMultiWordFixpt(mdlParam.OriginalDataTypeIdx)
      %assign value = FcnGenerateInlinedParameter("", mdlParam, sigIndexer, ...
        "", idx, reim)
      %assign retString = "%<value>" + chunk
    %else
       %assign retString = FcnGenerateNonInlinedParameter("", mdlParam, sigIndexer, ...
        "", reim) + chunk
    %endif
  %endif
  %endwith
  %endwith
   
  %return retString
%endfunction
 
%function SLibCGIR_PV(paramIdx, cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %return FcnCGIRParamCGVarHelper(paramIdx, cross, accSysIdx, width, memberStr, ...
    chunkIdx, ucv, indexExpr, TLC_FALSE)
%endfunction
 
%function SLibCGIR_PVAddr(paramIdx, cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %return FcnCGIRParamCGVarHelper(paramIdx, cross, accSysIdx, width, memberStr,...
    chunkIdx, ucv, indexExpr, TLC_TRUE)
%endfunction
 
%%functionFcnCGIRCGVarIdentifier
%%Abstract:ThisfunctionreturnstheCGIRvaridentifier
%%Thisfunctionallowsyoutocontrolselectvalueorreference.
%%Ifyouneedtoreadthevalueofvar,youcanuseFcnCGIRCGVarHelper
%%Ifyouneedtoreadaddressofthevar,youcanuseFcnCGIRCGVarRefHelper
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/tStringSupport.m
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function FcnCGIRCGVarIdentifier(varGroupIdx, memberIdx, cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr, isPointer, getRef) void
  %assign tmpVect = SLibGetReimAndIdx(indexExpr)
  %assign reim = tmpVect[0]
  %if reim != ""
    %assign reim = "." + reim
  %endif
  %assign idx = tmpVect[1]
  %assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
 
  %assign sigIndexer = SLibGet1DStructFieldIndexer(width, memberStr, ucv, "", idx)
  %assign chunk = SLibCG_GetMultiWordID(chunkIdx)
  %if varGroup.PackageAsStruct == 1 && !(GenerateClassInterface && varGroup.IsModelSelfCoderGroupVarGroup)
    %assign memberId = FcnSLibCGIRGetVarGroupMemberName(varGroupIdx, memberIdx)
    %assign varGroupPath = SLibCGIRVarGroupPath(varGroupIdx, accSysIdx,cross)
    %assign subStruct = SLibCG_GetOptSubStruct(varGroupIdx, memberIdx)
    %assign var = varGroupPath + subStruct + memberId
  %else
    %assign var = SLibVarGroupElementName(varGroupIdx, memberIdx)
  %endif
 
  %if isPointer
    %assign var = "(*" + var + ")"
  %endif
  %if getRef
    %if ISEMPTY(reim) && ISEMPTY(chunk) && width > 1 && FEVAL("strcmp",sigIndexer,"[0]")
      %return var
    %else
      %return "&" + var + sigIndexer + reim + chunk
    %endif
  %else
    %return var + sigIndexer + reim + chunk
  %endif
%endfunction
 
%function FcnCGIRCGVarHelper(varGroupIdx, memberIdx, cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr, isPointer) void
  %return FcnCGIRCGVarIdentifier(varGroupIdx, memberIdx, cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr, isPointer, TLC_FALSE)
%endfunction
 
%function FcnCGIRCGVarRefHelper(varGroupIdx, memberIdx, cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr, isPointer) void
  %return FcnCGIRCGVarIdentifier(varGroupIdx, memberIdx, cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr, isPointer, TLC_TRUE)
%endfunction
 
%function SLibCG_VarGroupElement(varGroupIdx, memberIdx, cross, accSysIdx, width, ucv, indexExpr) void
  %return FcnCGIRCGVarHelper(varGroupIdx, memberIdx, cross, accSysIdx, ...
    width, "", -1, ucv, indexExpr, TLC_FALSE)
%endfunction
 
%function SLibCG_CS(csIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr) void
  %assign cs = ::CompiledModel.ContStates.ContState[csIdx]
  %return FcnCGIRCGVarHelper(cs.VarGroupIdx[0], cs.VarGroupIdx[6], cross, ...
    accSysIdx, width, "", chunkIdx, ucv, indexExpr, TLC_FALSE)
%endfunction
 
%function SLibCG_CSAddr(csIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr) void
  %return "&" + SLibCG_CS(csIdx, cross, accSysIdx, width, chunkIdx, ...
    ucv, indexExpr)
%endfunction
 
%function SLibCG_CSD(csIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr) void
  %assign cs = ::CompiledModel.ContStates.ContState[csIdx]
  %return FcnCGIRCGVarHelper(cs.VarGroupIdx[1], cs.VarGroupIdx[6], cross, ...
    accSysIdx, width, "", chunkIdx, ucv, indexExpr, TLC_FALSE)
%endfunction
 
%function SLibCG_CSDAddr(csIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr) void
  %return "&" + SLibCG_CSD(csIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr)
%endfunction
 
 
%function SLibCG_CSDAgg(sysIdx, instIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr) void
  %assign varIdx = ::CompiledModel.System[sysIdx].ContStatesVarGroupIndex[instIdx]
  %assign var = ::CompiledModel.VarGroups.VarGroup[varIdx]
  %assign varGroupIdx = var.ParentVarGroupIdx
  %assign memberIdx = var.MemberIdxInParent
 
  %return FcnCGIRCGVarHelper(varGroupIdx, memberIdx, cross, ...
    accSysIdx, 1, "", chunkIdx, ucv, indexExpr, TLC_FALSE)
%endfunction
 
%function SLibCG_CSDAggAddr(sysIdx, instIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr) void
  %return "&" + SLibCG_CSDAgg(sysIdx, instIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr)
%endfunction
 
%function SLibCG_DRV(csIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr) void
  %assign cs = ::CompiledModel.ContStates.ContState[csIdx]
  %return FcnCGIRCGVarHelper(cs.VarGroupIdx[2], cs.VarGroupIdx[6], cross, ...
    accSysIdx, width, "", chunkIdx, ucv, indexExpr, TLC_FALSE)
%endfunction
 
%function SLibCG_DRVAddr(csIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr) void
  %return "&" + SLibCG_DRV(csIdx, cross, accSysIdx, width, chunkIdx, ...
    ucv, indexExpr)
%endfunction
 
%function SLibCG_CSAbsTol(csIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr) void
  %assign cs = ::CompiledModel.ContStates.ContState[csIdx]
  %return FcnCGIRCGVarHelper(cs.VarGroupIdx[3], cs.VarGroupIdx[6], cross, ...
    accSysIdx, width, "", chunkIdx, ucv, indexExpr, TLC_FALSE)
%endfunction
 
%function SLibCG_CSAbsTolAddr(csIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr) void
  %return "&" + SLibCG_CSAbsTol(csIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr)
%endfunction
 
%function SLibCG_CSPerturbMin(csIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr) void
  %assign cs = ::CompiledModel.ContStates.ContState[csIdx]
  %return FcnCGIRCGVarHelper(cs.VarGroupIdx[4], cs.VarGroupIdx[6], cross, ...
    accSysIdx, width, "", chunkIdx, ucv, indexExpr, TLC_FALSE)
%endfunction
 
%function SLibCG_CSPerturbMinAddr(csIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr) void
  %return "&" + SLibCG_CSPerturbMin(csIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr)
%endfunction
 
 
%function SLibCG_CSPerturbMax(csIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr) void
  %assign cs = ::CompiledModel.ContStates.ContState[csIdx]
  %return FcnCGIRCGVarHelper(cs.VarGroupIdx[5], cs.VarGroupIdx[6], cross, ...
    accSysIdx, width, "", chunkIdx, ucv, indexExpr, TLC_FALSE)
%endfunction
 
%function SLibCG_CSPerturbMaxAddr(csIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr) void
  %return "&" + SLibCG_CSPerturbMax(csIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr)
%endfunction
 
 
%function SLibCG_ZCSV(zcIdx, zcElIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr) void
  %assign zcInfo = ::CompiledModel.ZcRec.BlkZcRec[zcIdx].ZcSignalInfo[zcElIdx]
  %return FcnCGIRCGVarHelper(zcInfo.VarGroupIdx[2], zcInfo.VarGroupIdx[3], ...
    cross, accSysIdx, width, "", chunkIdx, ucv, indexExpr, TLC_FALSE)
%endfunction
 
%function SLibCG_ZCSVAddr(zcIdx, zcElIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr) void
  %return "&" + SLibCG_ZCSV(zcIdx, zcElIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr)
%endfunction
 
%function SLibCG_ZCSVAgg(sysIdx, instIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr) void
  %assign varIdx = ::CompiledModel.System[sysIdx].ZCSVVarGroupIndex[instIdx]
  %assign var = ::CompiledModel.VarGroups.VarGroup[varIdx]
  %assign varGroupIdx = var.ParentVarGroupIdx
  %assign memberIdx = var.MemberIdxInParent
 
  %return FcnCGIRCGVarHelper(varGroupIdx, memberIdx, ...
    cross, accSysIdx, width, "", chunkIdx, ucv, indexExpr, TLC_FALSE)
%endfunction
 
%function SLibCG_ZCSVAggAddr(sysIdx, instIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr) void
  %return "&" + SLibCG_ZCSVAgg(sysIdx, instIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr)
%endfunction
 
%function SLibCG_ZCE(zcIdx, zcElIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr) void
  %assign zcInfo = ::CompiledModel.ZcRec.BlkZcRec[zcIdx].ZcSignalInfo[zcElIdx]
  %if SLibIsLegacyStorageClassForDataRecord(zcInfo)
    %return FcnCGIRCSCDataHelper(zcInfo, TLC_FALSE, width, "", chunkIdx, ucv, indexExpr, TLC_FALSE)
  %else
    %return FcnCGIRCGVarHelper(zcInfo.VarGroupIdx[0], zcInfo.VarGroupIdx[1], ...
      cross, accSysIdx, width, "", chunkIdx, ucv, indexExpr, TLC_FALSE)
  %endif
   
%endfunction
 
%function SLibCG_ZCEAddr(zcIdx, zcElIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr) void
  %return "&" + SLibCG_ZCE(zcIdx, zcElIdx, cross, accSysIdx, width, chunkIdx, ucv, indexExpr)
%endfunction
 
%function SLibCG_DWV(dwIdx, cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %assign dw = ::CompiledModel.DWorks.DWork[dwIdx]
  %if CodeFormat == "S-Function" && !Accelerator
    %return FcnCGIRSFcnCGVarHelper("ssGetDWork", TLC_FALSE, "", ...
      dw.VarGroupIdx[0], dw.VarGroupIdx[1], ...
      width, memberStr, chunkIdx, ucv, indexExpr)
  %else
    %return FcnCGIRCGVarHelper(dw.VarGroupIdx[0], dw.VarGroupIdx[1], ...
      cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr, TLC_FALSE)
  %endif
%endfunction
 
%function SLibCG_DWVAddr(dwIdx, cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %assign dw = ::CompiledModel.DWorks.DWork[dwIdx]
  %if CodeFormat == "S-Function" && !Accelerator
    %return "&" + SLibCG_DWV(dwIdx, cross, accSysIdx, width, memberStr, ...
      chunkIdx, ucv, indexExpr)
  %else
    %if SLibIsLegacyStorageClassForDataRecord(dw) == TLC_TRUE
      %return FcnCGIRCSCDataHelper(dw, TLC_TRUE, width, memberStr, chunkIdx, ucv, indexExpr, TLC_TRUE)
    %endif
    %return FcnCGIRCGVarRefHelper(dw.VarGroupIdx[0], dw.VarGroupIdx[1], ...
      cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr, TLC_FALSE)
  %endif
%endfunction
 
%function SLibCG_SetDWV(dwIdx, cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr, rhs) void
  %assign lhs = SLibCG_DWV(dwIdx, cross, accSysIdx, width, memberStr, ...
    chunkIdx, ucv, indexExpr)
  %return lhs + " = " + rhs + ";/n"
%endfunction
 
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibCGIRDWorkGlobalCGVarBaseAddr(varGroupIdx, memberIdx, cross) void
  %assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
  %assign pureSFcnTarget = CodeFormat == "S-Function" && !Accelerator
  %assign pureSFcnTargetDWork = varGroup.Category == "DWork" && pureSFcnTarget
 
  %assign width = LibCGTypeWidth(SLibVarGroupElementType(varGroupIdx, memberIdx))
 
  %if pureSFcnTargetDWork
    %return "&" + FcnCGIRSFcnCGVarHelper("ssGetDWork", TLC_FALSE, "", ...
      varGroupIdx, memberIdx, width, "", -1, "", "0")
  %else
    %assign accSysIdx = ::CompiledModel.NumSystems - 1
    %assign useCross = isGRTMallocOnERT() || (cross && MultiInstanceERTCode && !GenerateClassInterface)
    %if LibCGTypeIsStdContainer(SLibCGVarGroupMemberCGTypeIdx(varGroupIdx, memberIdx))
      %return "&" + FcnCGIRCGVarHelper(varGroupIdx, memberIdx, useCross, accSysIdx, width, "", -1, "", "0", TLC_FALSE)
    %else
      %return FcnCGIRCGVarRefHelper(varGroupIdx, memberIdx, useCross, accSysIdx, width, "", -1, "", "0", TLC_FALSE)
    %endif
  %endif
%endfunction
 
%function SLibCG_VGE(vgeIdx, cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %assign varGroupIdx = ::CompiledModel.VarGroups.VarGroupVarIdx[vgeIdx]
  %return FcnCGIRCGVarHelper(varGroupIdx[0], varGroupIdx[1], ...
    cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr, TLC_FALSE)
%endfunction
 
%function SLibCG_VGEAddr(vgeIdx, cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %return "&" + SLibCG_VGE(vgeIdx, cross, accSysIdx, width, memberStr, ...
    chunkIdx, ucv, indexExpr)
%endfunction
 
%function SLibCG_SetVGE(vgeIdx, cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr, rhs) void
  %assign lhs = SLibCG_VGE(vgeIdx, cross, accSysIdx, width, memberStr, ...
    chunkIdx, ucv, indexExpr )
  %return lhs + " = " + rhs + ";/n"
%endfunction
 
%function SLibCG_SetVGEAddr(vgeIdx, cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr, rhs) void
  %assign bo = ::CompiledModel.BlockOutputs.GlobalBlockOutput[vgeIdx]
  %assign lhs = FcnCGIRCGVarHelper(bo.VarGroupIdx[0], bo.VarGroupIdx[1], ...
    cross, accSysIdx, 1, memberStr, chunkIdx, ucv, indexExpr, TLC_FALSE)
  %return lhs + " = " + rhs + ";/n"
%endfunction
 
%function SLibCG_BOV(bufIdx, cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %assign bo = ::CompiledModel.BlockOutputs.GlobalBlockOutput[bufIdx]
  %assign isPointer = bo.DeclareAsPointer == "yes"
  %return FcnCGIRCGVarHelper(bo.VarGroupIdx[0], bo.VarGroupIdx[1], ...
    cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr, isPointer)
%endfunction
 
%function SLibCG_BOVAddr(bufIdx, cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %assign bo = ::CompiledModel.BlockOutputs.GlobalBlockOutput[bufIdx]
  %if SLibIsLegacyStorageClassForDataRecord(bo) == TLC_TRUE
    %return FcnCGIRCSCDataHelper(bo, TLC_TRUE, width, memberStr, chunkIdx, ucv, indexExpr, TLC_TRUE)
  %endif
  %return "&" + SLibCG_BOV(bufIdx, cross, accSysIdx, width, memberStr, ...
    chunkIdx, ucv, indexExpr)
%endfunction
 
%function SLibCG_BOVRef(bufIdx, cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %assign tmpVect = SLibGetReimAndIdx(indexExpr)
  %assign reim = tmpVect[0]
  %assert ISEMPTY(reim)
   
  %assign bo = ::CompiledModel.BlockOutputs.GlobalBlockOutput[bufIdx]
  %assign isPointer = bo.DeclareAsPointer == "yes"
   
  %% Determine if signal is an array. If it is idx is not empty.
  %assign idx = tmpVect[1]
  %assign sigIndexer = SLibGet1DStructFieldIndexer(width, memberStr, ucv, "", idx)
   
  %if ISEMPTY(sigIndexer)
    %return "&" + FcnCGIRCGVarHelper(bo.VarGroupIdx[0], bo.VarGroupIdx[1], ...
      cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr, isPointer)
  %else
    %return FcnCGIRCGVarRefHelper(bo.VarGroupIdx[0], bo.VarGroupIdx[1], ...
      cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr, isPointer)
  %endif
%endfunction
 
%function SLibCG_SetBOV(bufIdx, cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr, rhs) void
  %assign lhs = SLibCG_BOV(bufIdx, cross, accSysIdx, width, memberStr, ...
    chunkIdx, ucv, indexExpr )
  %return lhs + " = " + rhs + ";/n"
%endfunction
 
%function SLibCG_SetBOVAddr(bufIdx, cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr, rhs) void
  %assign bo = ::CompiledModel.BlockOutputs.GlobalBlockOutput[bufIdx]
  %assign lhs = FcnCGIRCGVarHelper(bo.VarGroupIdx[0], bo.VarGroupIdx[1], ...
    cross, accSysIdx, 1, memberStr, chunkIdx, ucv, indexExpr, TLC_FALSE)
  %return lhs + " = " + rhs + ";/n"
%endfunction
 
%function SLibCG_CBOV(bufIdx, cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %assign bo = ::CompiledModel.BlockOutputs.ConstBlockOutput[bufIdx]
  %if !GeneratingDeadCode
    %assign bo.RequiredInConstBlockIO = 1
  %endif
  %return FcnCGIRCGVarHelper(bo.VarGroupIdx[0], bo.VarGroupIdx[1], ...
    cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr, TLC_FALSE)
%endfunction
 
%function SLibCG_CBOVAddr(bufIdx, cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %return "&" + SLibCG_CBOV(bufIdx, cross, accSysIdx, width, memberStr, chunkIdx, ucv, ...
    indexExpr)
%endfunction
 
%function SLibCG_SetCBOV(bufIdx, cross, accSysIdx, width, memberStr, chunkIdx, ucv, indexExpr, rhs) void
  %%START_ASSERT
  %assign grSrc = ::CompiledModel.BlockOutputs.ConstBlockOutput[bufIdx].GrSrc
  %assign msg = "Try to set constant block output port of %<SLibGrBlockPath(grSrc)>. " ...
    "This will cause compiler error. Consider putting a 'Signal Specification' block at "...
    "one of the block input port, specify a non-constant sample through the "...
    "'Signal Specification' block"
  %<LibReportFatalError(msg)>
  %%END_ASSERT
%endfunction
 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%Functionswe'dliketoobsoletesincewe'vemovedthedataintoIR
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 
%function SLibCG_P(prmIdx, width, chunkIdx, ucv, indexExpr) void
  %assign chunk = SLibCG_GetMultiWordID(chunkIdx)
  %return LibBlockParameter(Parameter[prmIdx], ucv, "", indexExpr) + chunk
%endfunction
 
%function SLibCG_PBaseAddr(parmIdx, width, chunkIdx, ucv, indexExpr) void
  %assign prmSize = SLibGetSizeOfValueFromParamRec(Parameter[parmIdx])
  %assign nRows = prmSize[0]
  %assign chunk = SLibCG_GetMultiWordID(chunkIdx)
  %if nRows > 1
    %return LibBlockMatrixParameterBaseAddr(Parameter[parmIdx]) + chunk
  %else
    %return LibBlockParameterBaseAddr(Parameter[parmIdx]) + chunk
  %endif
%endfunction
 
%function SLibCG_BIAddr(portIdx, width, memberStr, chunkIdx, ucv, sigIdx) void
  %if ISEMPTY(memberStr)
    %return LibBlockInputSignalAddr(portIdx, ucv, "", sigIdx) + ...
      SLibCG_GetMultiWordID(chunkIdx)
  %else
    %assign busSignal = LibBlockInputSignal(portIdx, "", "", 0)
    %return SLibCG_VAddr(busSignal, TLC_FALSE, width, memberStr, chunkIdx, ucv, sigIdx)
  %endif
%endfunction
 
%function SLibCG_BI(portIdx, width, memberStr, chunkIdx, ucv, sigIdx) void
  %if ISEMPTY(memberStr)
    %return LibBlockInputSignal(portIdx, ucv, "", sigIdx) + ...
      SLibCG_GetMultiWordID(chunkIdx)
  %else
    %assign blkInput = LibBlockInputSignal(portIdx, "", "", 0)
    %return SLibCG_V(blkInput, TLC_FALSE, width, memberStr, chunkIdx, ucv, sigIdx)
  %endif
%endfunction
 
%function SLibCG_SetBO(portIdx, width, memberStr, chunkIdx, ucv, sigIdx, rhs) void
  %if ISEMPTY(memberStr) && chunkIdx < 0
    %return LibBlockAssignOutputSignal(portIdx, ucv, "", sigIdx, rhs)
  %else
    %assign lhs = SLibCG_BO(portIdx, width, memberStr, chunkIdx, ucv, sigIdx)
    %return lhs + " = " + rhs + ";/n"
  %endif
%endfunction
 
%function SLibCG_BO(portIdx, width, memberStr, chunkIdx, ucv, sigIdx) void
  %if LibBlockOutputSignalIsExpr(portIdx)
    %assign srcSys = ::CompiledModel.System[BlockIdx[0]]
    %assign srcBlk = srcSys.Block[BlockIdx[2]]
    %return SLibBlockOutputSignal(srcBlk,srcSys,portIdx,ucv,"",sigIdx,"Signal") + ...
       SLibCG_GetMultiWordID(chunkIdx)
  %elseif ISEMPTY(memberStr)
    %return FcnGetInputOrOutputSignal("output", portIdx, ucv, "", sigIdx) + ...
      SLibCG_GetMultiWordID(chunkIdx)
  %else
    %assign blkOutput = LibBlockOutputSignal(portIdx, "", "", 0)
    %return SLibCG_V(blkOutput, TLC_FALSE, width, memberStr, chunkIdx, ucv, sigIdx)
  %endif
%endfunction %% SLibCG_BO
 
%function SLibCG_BOAddr(portIdx, memberStr, chunkIdx, ucv, sigIdx) void
  %assert !LibBlockOutputSignalIsExpr(portIdx)
  %if ISEMPTY(memberStr)
    %return FcnGetInputOrOutputSignal("outputAddr", portIdx, ucv, "", sigIdx) + ...
      SLibCG_GetMultiWordID(chunkIdx)
  %else
    %assign blockOutput = SLibCG_BO(portIdx, memberStr, chunkIdx, ucv, sigIdx)
    %return "&" + blockOutput
  %endif
%endfunction %% SLibCGIRBlockOutputSignalAddr
 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%FunctionsforwhichwehavenotyetmoveddataintoIR
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 
%%SLibCGIRZCFcn=========================================
%%Generatecalltort_ZCFcn()orrt_I32ZCFcn()
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%
%function SLibCGIRZCFcn(zcDir, pzc, zcSig, dtypeId) void
  %assert(LibIsBuiltInDataType(dtypeId))
 
  %assign FcnName = "rt_zcFcn"
  %assign RTWType = FcnGetMathDataTypeNameFromId(dtypeId)
 
  %if !LibMathFcnExists(FcnName,dtypeId)
    %assign msg = "Database has no function '%<FcnName>' returning '%<RTWType>'"
    %<LibReportFatalError(msg)>
  %endif
   
  %createrecord zcFcnRec {Name FcnName; RetTypeId tSS_INT32; NumArgs 3}
  %addtorecord zcFcnRec ArgList { Expr "zcDir"; TypeId tSS_INT32; IsPtr 0; IsCplx 0; IsConst 1 }
  %addtorecord zcFcnRec ArgList { Expr "pzc"; TypeId tSS_UINT8; IsPtr 0; IsCplx 0; IsConst 1 }
  %addtorecord zcFcnRec ArgList { Expr "zcSig"; TypeId dtypeId; IsPtr 0; IsCplx 0; IsConst 1 }
     
  %assign zcFcnRec.ArgList[0].Expr = zcDir
  %assign zcFcnRec.ArgList[1].Expr = "&%<pzc>"
  %assign zcFcnRec.ArgList[2].Expr = "(%<zcSig>)"
 
  %% This generates a call to either rt_ZCFcn() or rt_I32ZCFcn()
  %% depending on whether dtypeId is real or integer
  %return SLibGenRTLibFcnCallForDataTypeId(zcFcnRec, dtypeId)
 
%endfunction
 
%%SLibCGIRInlineSignFcn=========================================
%%Inlinecodetogetsignofnon_builtindatatypes
%%
 
%function SLibCGIRInlineSignFcn(sigSign,sig, dtypeId) void
  %openfile retBuf
 
  %assert(!LibIsBuiltInDataType(dtypeId))
  %assign signFcn = LibSignTLCFcnName(dtypeId)
   
  %if signFcn == ""
    %assign dataTypeName = LibGetDataTypeNameFromId(dtypeId)
    %assign errTxt = "The data type '%<dataTypeName>' " ...
      "is not supported because it has no Sign function."
    %<LibReportFatalError(errTxt)>
  %endif
   
  %assign status = %<signFcn> (dtypeId, sig, "", sigSign)
  %if status != 1
    %assign msg = "Invalid sign function of customer data type"
    %<LibReportFatalError(msg)>
  %endif
     
  %closefile retBuf
  %return retBuf
%endfunction
 
 
%%SLibCGIRInlineIsPositiveFcn=========================================
%%InlinecodetogetisPositiveofnon_builtindatatypes
%%
 
%function SLibCGIRInlineIsPositiveFcn(sigIsPositive,sig, dtypeId) void
  %openfile retBuf
 
  %assert(!LibIsBuiltInDataType(dtypeId))
  %assign signFcn = LibIsPositiveTLCFcnName(dtypeId)
   
  %if signFcn == ""
    %assign dataTypeName = LibGetDataTypeNameFromId(dtypeId)
    %assign errTxt = "The data type '%<dataTypeName>' " ...
      "is not supported because it has no IsPositive function."
    %<LibReportFatalError(errTxt)>
  %endif
   
  %assign status = %<signFcn> (dtypeId, sig, "", sigIsPositive)
  %if status != 1
    %assign msg = "Invalid isPositive function of customer data type"
    %<LibReportFatalError(msg)>
  %endif
     
  %closefile retBuf
  %return retBuf
%endfunction
 
%%SLibCGIRCustomCastFcn=========================================
%%Inlinecodetogetcastofnon_builtindatatypes
%%
 
%function SLibCGIRCustomCastFcn(outputVar,inputVar,outputDtypeId,inputDtypeId) void
  %openfile retBuf
 
  %assign castFcn = LibConvertBetweenTLCFcnName(inputDtypeId)
   
  %if castFcn == ""
    %assign dataTypeName = LibGetDataTypeNameFromId(inputDtypeId)
    %assign errTxt = "The data type '%<dataTypeName>' " ...
      "is not supported because it has no CustomCast function."
    %<LibReportFatalError(errTxt)>
  %endif
   
  %assign status = %<castFcn> (outputDtypeId, inputDtypeId, inputVar, "", outputVar)
  %if status != 1
    %assign msg = "Invalid cast function of customer data type"
    %<LibReportFatalError(msg)>
  %endif
     
  %closefile retBuf
  %return retBuf
%endfunction
 
%function SLibCG_EOAddr(port, width, memberStr, chunkIdx, ucv, indexExpr) void
  %return FcnCGIRExtOutputHelper(port, width, memberStr, chunkIdx, ucv, indexExpr, TLC_TRUE)
%endfunction
   
%function SLibCG_EO(port, width, memberStr, chunkIdx, ucv, indexExpr) void
  %return FcnCGIRExtOutputHelper(port, width, memberStr, chunkIdx, ucv, indexExpr, TLC_FALSE)
%endfunction
 
%function SLibCG_TrackEO(port) void
  %assign extOut = ::CompiledModel.ExternalOutputs.ExternalOutput[port]
  %<SLibAccessArgHelper(extOut,"",System[SystemIdx].CurrentTID)>
%endfunction
 
%function FcnCGIRExtOutputHelper(port, width, memberStr, chunkIdx, ucv, indexExpr, addr) void
  %% SLibCG_EO and SLibCG_EOAddr should not be called in a reusable subsystem
   
  %assert SystemIdx == NumSystems-1 || RTWSystemCode != 2
  %assert !IsModelReferenceSimTarget() && !IsModelReferenceRTWTarget()
  %assign extOut = ::CompiledModel.ExternalOutputs.ExternalOutput[port]
   %if SLibIsLegacyStorageClassForDataRecord(extOut) == TLC_TRUE
    %return FcnCGIRCSCDataHelper(extOut, TLC_FALSE, width, memberStr, chunkIdx, ucv, indexExpr, addr)
  %endif
  %assign varGroupIdx = extOut.VarGroupIdx[0]
  %assign memberIdx = extOut.VarGroupIdx[1]
  %assign portVarName = FcnSLibCGIRGetVarGroupMemberName(varGroupIdx, memberIdx)
  %assign currentTID = System[SystemIdx].CurrentTID
  %assign isPointer = TLC_FALSE
 
  %if CodeFormat == "S-Function" %% && !Accelerator
    %assign sfcnExtOut = FcnCGIRSFcnCGVarHelper("ssGetOutputPortSignal",...
      TLC_FALSE, "", varGroupIdx, memberIdx, ...
      width, memberStr, chunkIdx, ucv, indexExpr)
    %if addr
      %return "&%<sfcnExtOut>"
    %else
      %return sfcnExtOut
    %endif
  %endif
  %<SLibAccessArgHelper(extOut,"",currentTID)>
  %assert UsingMalloc
 
  %% set tmpHasSimStructVars so that access extern outport through rtM.
  %% when system is not reusable. For GRTMalloc target, root system
  %% is reuable system. All other subsystem must be non-resuable system to get here.
  %% see assertion at the beginning of this function.
  %assign tmpHasSimStructVars = ::CompiledModel.HasSimStructVars
  %assign ::CompiledModel.HasSimStructVars = AccessDataUseRTM(SystemIdx,::BlockFcn, TLC_FALSE)
  %assign cross = System[SystemIdx].CrossNoArgFcnBound
  %assign identifier = "%<SLibGetExternalOutputStruct(TLC_TRUE,TLC_TRUE,cross)>%<YQualifier>%<portVarName>"
  %assign ::CompiledModel.HasSimStructVars = tmpHasSimStructVars
  %<SLibAccessArgHelper(extOut,"",currentTID)>
 
  %return FcnCGIRSimpleCGVarHelper(identifier, isPointer, width, memberStr, chunkIdx, ucv, indexExpr, addr)
%endfunction
 
%%TopTester:test/toolbox/simulink/blocks/lib_Discrete/DiscreteTimeIntegrator/rtw/tdintegrt.m
%%
%function FcnCGIRSFcnCGVarHelper(macro, isPointer, qualifier,...
  varGroupIdx, memberIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %assign sysIdx = ::CompiledModel.VarGroups.VarGroup[varGroupIdx].SysIdx
  %<SLibAccessArgHelper(::CompiledModel.System[sysIdx].Interface.RTMArgDef,"",...
    ::CompiledModel.System[sysIdx].CurrentTID)>
 
  %assign cgTypeIdx = SLibCGVarGroupMemberCGTypeIdx(varGroupIdx, memberIdx)
  %assign isComplex = LibCGTypeIsComplex(cgTypeIdx)
 
  %assign tmpVect = SLibGetReimAndIdx(indexExpr)
  %assign reim = tmpVect[0]
  %assign idx = tmpVect[1]
 
  %assign sigIndexer = SLibGet1DStructFieldIndexer(width, memberStr, ucv, "", idx)
  %if sigIndexer == ""
    %assign sigIndexer = "[0]"
  %endif
   
  %%
  %% functions like ssGetInputPortSignalPtrs return a void*, need to cast to
  %% the portVar type first. The portVar type is given by cgTypeIdx
  %%
  %if qualifier != ""
    %assign qualifier = qualifier + " "
  %endif
  %assign deref = isPointer ? "**" : "*"
  %assign cast = qualifier + LibCGTypeName(cgTypeIdx) + " " + deref
 
  %% all followings are possible
  %% 1. ((NumericType*)ssGet())[i] (isPointer is false)
  %% 2. *((NumericType**)ssGet())[i] (isPointer is true)
  %% 3. (*(BusType*)ssGet()).a.b[i] (bus, isPointer is false)
  %% 4. (**(BusType**)ssGet()).a.b[i] (bus, isPointer is true)
  %% 5. ((BusType*)ssGet())[0].a.b[i] (array of bus, isPointer is false)
  %% 6. (*(BusType**)ssGet())[0].a.b[i] (array of bus, isPointer is true)
  %assign elSrc = IDNUM(SLibVarGroupElementSource(varGroupIdx, memberIdx))
  %assign srcIdx = elSrc[1]
  %if "W" == elSrc[0] %% accounting for dworks eliminated in IR
    %assign srcIdx = ::CompiledModel.DWorks.DWorkRecordIndices[elSrc[1]]
  %endif
  %assert -1 < srcIdx
  %assign ssGet = "%<macro>(%<SLibGetSimStruct()>, %<srcIdx>)"
  %if ISEMPTY(memberStr)
    %if !isPointer
      %% case 1
      %assign retSignal = "((%<cast>)%<ssGet>)%<sigIndexer>"
    %else
      %% case 2
      %assign retSignal = "(*((%<cast>)%<ssGet>)%<sigIndexer>)"
    %endif
  %else
    %% case 3, 4, 5, 6
    %assign arrayOfStructs = LibCGTypeIsArrayOfStructs(cgTypeIdx)
    %assign deref = arrayOfStructs ? "" : "*"
    %assign deref = isPointer ? deref + "*" : deref
    %assign retSignal = "(%<deref>(%<cast>)%<ssGet>)%<sigIndexer>"
  %endif
   
  %if reim != ""
    %assign retSignal = "%<retSignal>.%<reim>"
  %endif
 
  %return retSignal + SLibCG_GetMultiWordID(chunkIdx)
%endfunction
 
%%
%%thisfunctionisnotunifiedwithFcnCGIRSFcnCGVarHelper
%%because:
%%-wearepassingportIdxratherthanvargroupmemberidx
%%-ssGetCurrentInputPortDimensionstakes3argumentswhile
%%ssGetInputPortSignaltakes2arguments.
%%
%function FcnCGIRSFcnSizeVarHelper(macro, isPointer, qualifier,...
  cgTypeIdx, portIdx, width, memberStr, ucv, indexExpr) void
  %assign isComplex = LibCGTypeIsComplex(cgTypeIdx)
 
  %assign tmpVect = SLibGetReimAndIdx(indexExpr)
  %assign reim = tmpVect[0]
  %assign idx = tmpVect[1]
 
  %assign sigIndexer = SLibGet1DStructFieldIndexer(width, memberStr, ucv, "", idx)
  %if sigIndexer == ""
    %assign sigIndexer = "[0]"
  %endif
     
  %%
  %% functions like ssGetInputPortSignalPtrs return a void*, need to cast to
  %% the portVar type first. The portVar type is given by cgTypeIdx
  %%
  %if qualifier != ""
    %assign qualifier = qualifier + " "
  %endif
  %assign deref = isPointer ? "**" : "*"
  %assign cast = qualifier + LibCGTypeName(cgTypeIdx) + " " + deref
 
  %% if the I/O port is not structure type, it is always accessed as an array(contiguous or non-contiguous)
  %% and sigIndexer is always present.
  %% if the I/O port is a structure type, it is accessed as a structure(of course contiguous).
  %if ISEMPTY(memberStr)
    %assign retSignal = "((%<cast>)&%<macro>(%<SLibGetSimStruct()>, %<portIdx>, 0))%<sigIndexer>"
  %else
    %assign retSignal = "(%<deref>((%<cast>)&%<macro>(%<SLibGetSimStruct()>, %<portIdx>, 0)))%<sigIndexer>"
    %assign isPointer = TLC_FALSE
  %endif
 
  %if isPointer
      %assign retSignal = "(*(%<retSignal>))"
  %endif
  %if reim != ""
    %assign retSignal = "%<retSignal>.%<reim>"
  %endif
 
  %return retSignal
%endfunction
 
%function FcnGetFcnDataForPort(fcnData, portType, portNum) void
  %foreach idx = fcnData.NumArgSpecData
    %assign spec = fcnData.ArgSpecData[idx]
    %if spec.SLObjectType != portType
      %continue
    %endif
    %if spec.PortNum == portNum
      %return spec
    %endif
  %endforeach
  %<LibReportFatalError("should not be here")>
%endfunction
    
 
%%Function:FcnCG_DSMHelper=======================================================================
%%Abstract:
%%ThisfunctionisahelperfunctionforaccessingaglobalDSM
%%whenusingthemodelreferencesimtarget
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants6.m
%%
%function FcnCG_DSMHelper(dworkIdx, dsmIdx, width, memberStr, chunkIdx, ucv, indexExpr, addr) void
  %assign record = ::CompiledModel.DWorks.DWork[dworkIdx]
  %assign tmpVect = SLibGetReimAndIdx(indexExpr)
  %assign reim = tmpVect[0]
  %if reim != ""
    %assign reim = "." + reim
  %endif
  %assign idx = tmpVect[1]
  %assign sigIndexer = SLibGet1DStructFieldIndexer(width, memberStr, ucv, "", idx)
  %assign chunk = SLibCG_GetMultiWordID(chunkIdx)
  %assign dtName = SLibGetRecordContainerTypeName(record)
  %assign dsmPtr = "((" + dtName + "*) " + ...
    ::CompiledModel.Name + "_DSM[" + "%<dsmIdx>" + "])"
  %if ISEMPTY(sigIndexer)
    %assign dsmVal = "(*" + dsmPtr + ")" + reim + chunk
  %else
    %if ISEMPTY(memberStr)
      %assign dsmVal = dsmPtr + sigIndexer + reim + chunk
    %else
      %assert(LibDataTypeIsBus(LibGetRecordDataTypeId(record)))
      %if sigIndexer[0] == "["
        %assign dsmVal = dsmPtr + sigIndexer + reim + chunk
      %else
        %assign dsmVal = "(*" + dsmPtr + ")" + sigIndexer + reim + chunk
      %endif
    %endif
  %endif
   
  %if addr
    %return "&(" + dsmVal + ")"
  %else
    %return dsmVal
  %endif
%endfunction
 
%%Function:SLibCG_DSM============================================================================
%%Abstract:
%%ThisfunctionreadsfromaglobalDSMwhenusingthemodelreference
%%simtarget
%function SLibCG_DSM(dworkIdx, dsmIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %return FcnCG_DSMHelper(dworkIdx, dsmIdx, width, memberStr, chunkIdx, ucv, indexExpr, TLC_FALSE)
%endfunction
 
%%Function:SLibCG_DSMAddr========================================================================
%%Abstract:
%%ThisfunctionreadsfromaglobalDSMwhenusingthemodelreference
%%simtarget
%function SLibCG_DSMAddr(dworkIdx, dsmIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %return FcnCG_DSMHelper(dworkIdx, dsmIdx, width, memberStr, chunkIdx, ucv, indexExpr, TLC_TRUE)
%endfunction
 
%%Function:SLibCG_SetDSM=========================================================================
%%Abstract:
%%ThisfunctionwritestoaglobalDSMwhenusingthemodelreference
%%simtarget
%function SLibCG_SetDSM(dworkIdx, dsmIdx, width, memberStr, chunkIdx, ucv, indexExpr, rhs) void
  %return SLibCG_DSM(dworkIdx, dsmIdx, width, memberStr, chunkIdx, ucv, indexExpr) + " = " + rhs + ";"
%endfunction
 
%%Function:SLibCG_EI=============================================================================
%%Abstract:
%%Thisfunctiondumpoutsthevariableforthegivenexternal
%%inportblockwithautostorageclass
%%
%function SLibCG_EI(port, width, memberStr, chunkIdx, ucv, indexExpr) void
  %return FcnCGIRExtInputHelper(port, width, memberStr, chunkIdx, ucv, indexExpr, TLC_FALSE)
%endfunction
 
%function SLibCG_EIAddr(port, width, memberStr, chunkIdx, ucv, indexExpr) void
  %return FcnCGIRExtInputHelper(port, width, memberStr, chunkIdx, ucv, indexExpr, TLC_TRUE)
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackrootinportaccess.
%function SLibCG_TrackEI(port) void
  %assign extInp = ::CompiledModel.ExternalInputs.ExternalInput[port]
  %<SLibAccessArgHelper(extInp,"",System[SystemIdx].CurrentTID)>
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackglobalRTMaccess.
%function SLibCG_TrackGlobalRTMArg(accSysIdx) void
  %if !::GenRTModel
    %return
  %endif
   
  %assign blkSysIdx = System[accSysIdx].ReusedParentSystemIdx
  %assign interface = System[blkSysIdx].Interface
  %assign rtmArg = interface.RTMArgDef
  %<SLibAccessArgHelper(rtmArg,"Global", FcnGetCurrentAccessTid())>
  %<SLibAccessArgHelper(rtmArg,"", FcnGetCurrentAccessTid())>
%endfunction
 
%%Function:SLibCG_TrackGroundVariable============================================================
%%Abstract:TrackingstatementtotrackIRgroundvariable
%%ThiswillpreventredefinitionfromTLCaswellasallowTLCtoemitthe
%%externdeclarationofthegroundvariableifneeded
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tMdlRefWithFcnOnDataAsVSSChoice.m
%%
%function SLibCG_TrackGroundVariable(dataTypeId) void
  %assign dtRec = ::CompiledModel.DataTypes.DataType[dataTypeId]
 
  %if (!ISFIELD(dtRec, "GroundReqInMemory"))
    %addtorecord dtRec GroundReqInMemory TLC_TRUE
  %else
    %assign dtRec.GroundReqInMemory = TLC_TRUE
  %endif
   
  %if (!ISFIELD(dtRec, "GroundAlreadyDefined"))
    %addtorecord dtRec GroundAlreadyDefined TLC_TRUE
  %else
    %assign dtRec.GroundAlreadyDefined = TLC_TRUE
  %endif
%endfunction %% SLibCG_TrackGroundVariable
 
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackdworkaccess.
%function SLibCG_TrackDW(accSysIdx) void
  %assign interfaceData = SLibCG_GetInterfaceData(accSysIdx, ::BlockFcn, "DWork")
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackdworksthat
%%areaccessedcrossnoargfunctionboundary.
%function SLibCG_TrackGlobalDW(accSysIdx) void
  %assign interfaceData = SLibCG_GetInterfaceData(accSysIdx, ::BlockFcn, "DWork")
  %<SLibAccessArgHelper(interfaceData,"Global", FcnGetCurrentAccessTid())>
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackblockIOaccess.
%function SLibCG_TrackBlockIO(accSysIdx) void
  %assign interfaceData = SLibCG_GetInterfaceData(accSysIdx, ::BlockFcn, "BlockIO")
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackblockIOthat
%%areaccessedcrossnoargfunctionboundary.
%function SLibCG_TrackGlobalBlockIO(accSysIdx) void
  %assign interfaceData = SLibCG_GetInterfaceData(accSysIdx, ::BlockFcn, "BlockIO")
  %<SLibAccessArgHelper(interfaceData,"Global", FcnGetCurrentAccessTid())>
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackcoderdatagroupaccess.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibCG_TrackCoderDataGroup(accSysIdx, codeGroupIdx) void
  %assign group = ::CompiledModel.CoderDataGroup[codeGroupIdx]
  %assign groupToken = "CoderDataGroup" + group.Name
  %assign fieldName = "Has" + groupToken + "Arg"
  System[accSysIdx].%<fieldName> = TLC_TRUE
  %assign interfaceData = SLibCG_GetInterfaceData(accSysIdx, ::BlockFcn, groupToken)
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
 
  %% If this is the model reference base system, we access the arg through
  %% RTM if InSelf or InParent
  %if IsModelReferenceBaseSys(System[accSysIdx]) && SLibAccessGroupThroughSelf(group)
    %assign interfaceData = System[accSysIdx].Interface.RTMArgDef
    %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
  %endif
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackblockIOthat
%%areaccessedcrossnoargfunctionboundary.
%function SLibCG_TrackGlobalCoderDataGroup(accSysIdx, codeGroupIdx) void
  %assign group = ::CompiledModel.CoderDataGroup[codeGroupIdx]
  %assign groupToken = "CoderDataGroup" + group.Name
  %assign interfaceData = SLibCG_GetInterfaceData(accSysIdx, ::BlockFcn, groupToken)
  %<SLibAccessArgHelper(interfaceData,"Global", FcnGetCurrentAccessTid())>
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
 
  %% If this is the model reference base system, we access the arg through
  %% RTM.
  %if IsModelReferenceBaseSys(System[accSysIdx])
    %assign interfaceData = System[accSysIdx].Interface.RTMArgDef
    %<SLibAccessArgHelper(interfaceData,"Global", FcnGetCurrentAccessTid())>
    %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
  %endif
 
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackconstantblockIOaccess.
%function SLibCG_TrackConstBlockIO(accSysIdx) void
  %assign interfaceData = System[accSysIdx].Interface.ConstBlockIOArgDef
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackconstantblockIOthat
%%areaccessedcrossnoargfunctionboundary.
%function SLibCG_TrackGlobalConstBlockIO(accSysIdx) void
  %assign interfaceData = System[accSysIdx].Interface.ConstBlockIOArgDef
  %<SLibAccessArgHelper(interfaceData,"Global", FcnGetCurrentAccessTid())>
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackparameteraccess.
%function SLibCG_TrackParam(accSysIdx) void
  %assign interfaceData = SLibCG_GetInterfaceData(accSysIdx, ::BlockFcn, "Parameter")
  %if ISFIELD(::CompiledModel.System[accSysIdx], "ParameterVarGroupIndex") || ...
    interfaceData.PassthroughSystemIdx != -1
    %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
  %endif
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackparameterthat
%%areaccessedcrossnoargfunctionboundary.
%function SLibCG_TrackGlobalParam(accSysIdx) void
  %assign interfaceData = SLibCG_GetInterfaceData(accSysIdx, ::BlockFcn, "Parameter")
  %<SLibAccessArgHelper(interfaceData,"Global", FcnGetCurrentAccessTid())>
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackcontinuesstatesaccess.
%function SLibCG_TrackContStates(accSysIdx) void
  %assign interfaceData = System[accSysIdx].Interface.ContStatesArgDef
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackcontinuesstatesthat
%%areaccessedcrossnoargfunctionboundary.
%function SLibCG_TrackGlobalContStates(accSysIdx) void
  %assign interfaceData = System[accSysIdx].Interface.ContStatesArgDef
  %<SLibAccessArgHelper(interfaceData,"Global", FcnGetCurrentAccessTid())>
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackcontinuesstates
%%derivativeaccess.
%function SLibCG_TrackContStatesDerivative(accSysIdx) void
  %assign interfaceData = System[accSysIdx].Interface.ContStatesDerivativeArgDef
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackcontinuesstates
%%derivativethatareaccessedcrossnoargfunctionboundary.
%function SLibCG_TrackGlobalContStatesDerivative(accSysIdx) void
  %assign interfaceData = System[accSysIdx].Interface.ContStatesDerivativeArgDef
  %<SLibAccessArgHelper(interfaceData,"Global", FcnGetCurrentAccessTid())>
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackcontinuesstates
%%disableaccess.
%function SLibCG_TrackContStatesDisabled(accSysIdx) void
  %assign interfaceData = System[accSysIdx].Interface.ContStatesDisabledArgDef
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackcontinuesstates
%%disablethatareaccessedcrossnoargfunctionboundary.
%function SLibCG_TrackGlobalContStatesDisabled(accSysIdx) void
  %assign interfaceData = System[accSysIdx].Interface.ContStatesDisabledArgDef
  %<SLibAccessArgHelper(interfaceData,"Global", FcnGetCurrentAccessTid())>
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackcontinuesstates
%%absolutetolerance
%function SLibCG_TrackContStatesAbsoluteTolerance(accSysIdx) void
  %assign interfaceData = System[accSysIdx].Interface.ContStatesAbsoluteToleranceArgDef
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackcontinuesstates
%%absolutetolerancethatareaccessedcrossnoargfunctionboundary.
%function SLibCG_TrackGlobalContStatesAbsoluteTolerance(accSysIdx) void
  %assign interfaceData = System[accSysIdx].Interface.ContStatesAbsoluteToleranceArgDef
  %<SLibAccessArgHelper(interfaceData,"Global", FcnGetCurrentAccessTid())>
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackcontinuesstates
%%perturbmin
%function SLibCG_TrackContStatesPerturbMin(accSysIdx) void
  %assign interfaceData = System[accSysIdx].Interface.ContStatesPerturbMinArgDef
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackcontinuesstates
%%perturbminthatareaccessedcrossnoargfunctionboundary.
%function SLibCG_TrackGlobalContStatesPerturbMin(accSysIdx) void
  %assign interfaceData = System[accSysIdx].Interface.ContStatesPerturbMinArgDef
  %<SLibAccessArgHelper(interfaceData,"Global", FcnGetCurrentAccessTid())>
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackcontinuesstates
%%perturbmax
%function SLibCG_TrackContStatesPerturbMax(accSysIdx) void
  %assign interfaceData = System[accSysIdx].Interface.ContStatesPerturbMaxArgDef
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackcontinuesstates
%%perturbmaxthatareaccessedcrossnoargfunctionboundary.
%function SLibCG_TrackGlobalContStatesPerturbMax(accSysIdx) void
  %assign interfaceData = System[accSysIdx].Interface.ContStatesPerturbMaxArgDef
  %<SLibAccessArgHelper(interfaceData,"Global", FcnGetCurrentAccessTid())>
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
%endfunction
 
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackzerocrossingsignal
%%valuesaccess.
%function SLibCG_TrackZCSV(accSysIdx) void
  %assign interfaceData = System[accSysIdx].Interface.ZCSVArgDef
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackzerocrossingsignal
%%valuesthatareaccessedcrossnoargfunctionboundary.
%function SLibCG_TrackGlobalZCSV(accSysIdx) void
  %assign interfaceData = System[accSysIdx].Interface.ZCSVArgDef
  %<SLibAccessArgHelper(interfaceData,"Global", FcnGetCurrentAccessTid())>
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackzerocrossingevent
%%access.
%function SLibCG_TrackZCEvent(accSysIdx) void
  %assign interfaceData = System[accSysIdx].Interface.ZCEventArgDef
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
%endfunction
 
%%CGIRgeneratedTLCfilecallsthisfunctiontotrackzerocrossingevents
%%thatareaccessedcrossnoargfunctionboundary.
%function SLibCG_TrackGlobalZCEvent(accSysIdx) void
  %assign interfaceData = System[accSysIdx].Interface.ZCEventArgDef
  %<SLibAccessArgHelper(interfaceData,"Global", FcnGetCurrentAccessTid())>
  %<SLibAccessArgHelper(interfaceData,"", FcnGetCurrentAccessTid())>
%endfunction
 
 
%function SLibCG_TrackIArg(accSysIdx, argIdx, cross, tid) void
  %assign blkSysIdx = System[accSysIdx].ReusedParentSystemIdx
  %assign interface = System[blkSysIdx].Interface
  %assign canInputArg = interface.CanonicalInputArgDef[argIdx]
  %<LibAccessArgTID(canInputArg, tid)>
  %if cross
     %<LibAccessGlobalArgTID(canInputArg, tid)>
  %endif
%endfunction
 
%function SLibCG_TrackOArg(accSysIdx, argIdx, cross, tid) void
  %assign blkSysIdx = System[accSysIdx].ReusedParentSystemIdx
  %assign interface = System[blkSysIdx].Interface
  %assign canOutputArg = interface.CanonicalOutputArgDef[argIdx]
  %<LibAccessArgTID(canOutputArg, tid)>
  %if cross
     %<LibAccessGlobalArgTID(canOutputArg, tid)>
  %endif
%endfunction
 
%function SLibCG_TrackPArg(accSysIdx, argIdx, cross, tid) void
  %assign blkSysIdx = System[accSysIdx].ReusedParentSystemIdx
  %assign interface = System[blkSysIdx].Interface
  %assign canPrmArg = interface.CanonicalPrmArgDef[argIdx]
  %<LibAccessArgTID(canPrmArg, tid)>
  %if cross
     %<LibAccessGlobalArgTID(canPrmArg, tid)>
  %endif
%endfunction
 
%function SLibCG_TrackDwArg(accSysIdx, argIdx, cross, tid) void
  %assign blkSysIdx = System[accSysIdx].ReusedParentSystemIdx
  %assign interface = System[blkSysIdx].Interface
  %assign canDworkArg = interface.CanonicalDWorkArgDef[argIdx]
  %<LibAccessArgTID(canDworkArg, tid)>
  %if cross
     %<LibAccessGlobalArgTID(canDworkArg, tid)>
  %endif
%endfunction
 
%function SLibGetDWorkStructPtr() void
  %return SLibGetDWorkPointerFromRTM(TLC_TRUE)
%endfunction
 
%function SLibGetBlockIOStructPtr() void
  %return SLibGetBlockIOPointerFromRTM(TLC_TRUE)
%endfunction
 
%function SLibGetCoderDataGroupStructPtr(groupIdx) void
  %assign group = ::CompiledModel.CoderDataGroup[groupIdx]
  %return SLibGetCoderDataGroupPointerFromRTM(group, 0)
%endfunction
 
%function SLibGetConstBlockIOStructPtr() void
  %return SLibGetConstBlockIOPointerFromRTM()
%endfunction
 
%function SLibGetParamStructPtr() void
  %return SLibGetParamPointerFromRTM(TLC_TRUE)
%endfunction
 
%function SLibGetContStatesStructPtr() void
  %return SLibGetContStatesPointerFromRTM(TLC_TRUE)
%endfunction
 
%function SLibGetContStatesDerivativeStructPtr() void
  %return SLibGetContStateDerivativesStructFromRTM()
%endfunction
 
%function SLibGetContStatesDisabledStructPtr() void
  %return SLibGetContStateDisabledStructFromRTM()
%endfunction
 
%function SLibGetContStatesAbsoluteToleranceStructPtr() void
  %return SLibGetContStatesAbsoluteToleranceStructFromRTM()
%endfunction
 
%function SLibGetContStatesPerturbMinStructPtr() void
  %return SLibGetContStatesPerturbMinStructFromRTM()
%endfunction
 
%function SLibGetContStatesPerturbMaxStructPtr() void
  %return SLibGetContStatesPerturbMaxStructFromRTM()
%endfunction
 
%function SLibGetPreviousZCStructPtr() void
  %return SLibGetPreviousZCStructFromRTM(TLC_TRUE)
%endfunction
 
%function SLibGetZCSignalValueStrucPtr() void
  %return SLibGetZCSignalValueStructFromRTM(TLC_TRUE)
%endfunction %% SLibGetZCSignalValueStructPtr
 
%function FcnCGIRExtInputHelper(port, width, memberStr, chunkIdx, ucv, indexExpr, addr) void
  %% SLibCG_EI and SLibCG_EIAddr should not be called in a reusable subsystem
  %assert SystemIdx == NumSystems-1 || RTWSystemCode != 2
  %assign extInp = ::CompiledModel.ExternalInputs.ExternalInput[port]
  %assert extInp.StorageClass == "Auto"
   
  %if SLibIsLegacyStorageClassForDataRecord(extInp) == TLC_TRUE
    %return FcnCGIRCSCDataHelper(extInp, TLC_FALSE, width, memberStr, chunkIdx, ucv, indexExpr, addr)
  %endif
   
  %assign varGroupIdx = extInp.VarGroupIdx[0]
  %assign memberIdx = extInp.VarGroupIdx[1]
     
  %if CodeFormat == "S-Function" && !Accelerator
    %if ISFIELD(extInp, "HasVarDims")
      %assign sfcnInput = FcnCGIRSFcnCGVarHelper("ssGetInputPortSignal", ...
        TLC_FALSE, "const", varGroupIdx, memberIdx, ...
        width, memberStr, chunkIdx, ucv, indexExpr)
    %else
      %assign sfcnInput = FcnCGIRSFcnCGVarHelper("ssGetInputPortSignalPtrs",...
        TLC_TRUE, "const", varGroupIdx, memberIdx, ...
        width, memberStr, chunkIdx, ucv, indexExpr)
    %endif
    %if addr
      %return "&" + sfcnInput + SLibCG_GetMultiWordID(chunkIdx)
    %else
      %return sfcnInput + SLibCG_GetMultiWordID(chunkIdx)
    %endif
  %endif
 
  %<SLibAccessArgHelper(extInp,"",System[SystemIdx].CurrentTID)>
    
  %assert Accelerator || UsingMalloc
 
  %assign cross = ::CompiledModel.System[SystemIdx].CrossNoArgFcnBound
  %assign portVarName = FcnSLibCGIRGetVarGroupMemberName(varGroupIdx, memberIdx)
  %assign identifier = ...
    "%<SLibGetExternalInputStruct(TLC_TRUE,TLC_TRUE,cross)>%<UQualifier>%<portVarName>"
  %assign isPointer = PassExtInpByRef(extInp)
  %return FcnCGIRSimpleCGVarHelper(identifier, isPointer, width, memberStr, chunkIdx, ucv, indexExpr, addr)
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/tvss_sim_code_match_g984892.m
%%
%function FcnSLibCGIRGetVarGroupMemberName(aVarGroupIdx, aMemberIdx) void
  %if SLibVarGroupIsStruct(aVarGroupIdx)
    %assign cgTypeIdx = SLibVarGroupCGTypeIdx(aVarGroupIdx)
    %return LibCGTypeMemberName(cgTypeIdx, aMemberIdx)
  %else
    %return SLibVarGroupElementName(aVarGroupIdx, aMemberIdx)
  %endif
%endfunction
 
%%Function:SLibCG_EI_CSC=========================================================================
%%Abstract:
%%Thisfunctiondumpoutsthevariableforthegivenexternal
%%inportblockwithcustomstorageclass
%%
%function SLibCG_EI_CSC(port, width, memberStr, chunkIdx, ucv, indexExpr) void
  %return FcnCGIRExtInputCSCHelper(port, width, memberStr, chunkIdx, ucv, indexExpr, TLC_FALSE)
%endfunction
 
%function SLibCGB_EI_CSC(block, port, width, memberStr, lcv, ucv, sigIdx, reim) void
  %assign extIn = ::CompiledModel.ExternalInputs.ExternalInput[port]
  %return BlkFcnCGIRCSCDataHelper(extIn, width, memberStr, lcv, ucv, sigIdx, reim, TLC_FALSE)
%endfunction
 
%function SLibCG_EI_CSCAddr(port, width, memberStr, chunkIdx, ucv, indexExpr) void
  %return FcnCGIRExtInputCSCHelper(port, width, memberStr, chunkIdx, ucv, indexExpr, TLC_TRUE)
%endfunction
 
%function SLibCGB_EI_CSCAddr(block, port, width, memberStr, lcv, ucv, sigIdx, reim) void
  %assign extIn = ::CompiledModel.ExternalInputs.ExternalInput[port]
  %if !LibCustomDataIsAddressable(extIn)
    %<SLibReportNonAddressableError("Input", block, extIn)>
  %endif
  %return BlkFcnCGIRCSCDataHelper(extIn, width, memberStr, lcv, ucv, sigIdx, reim, TLC_TRUE)
%endfunction
 
%function FcnCGIRExtInputCSCHelper(port, width, memberStr, chunkIdx, ucv, indexExpr, addr) void
  %assign extIn = ::CompiledModel.ExternalInputs.ExternalInput[port]
  %assert extIn.StorageClass == "Custom" || (SLibIsLegacyStorageClassForDataRecord(extIn) == TLC_TRUE)
  %return FcnCGIRCSCDataHelper(extIn, TLC_FALSE, width, memberStr, chunkIdx, ucv, indexExpr, addr)
%endfunction
 
%%Function:SLibCG_EO_CSC=========================================================================
%%Abstract:
%%Thisfunctiondumpoutsthevariableforthegivenexternal
%%outportblockwithcustomstorageclass
%%
%function SLibCG_EO_CSC(port, width, memberStr, chunkIdx, ucv, indexExpr) void
  %return FcnCGIRExtOutputCSCHelper(port, width, memberStr, chunkIdx, ucv, indexExpr, TLC_FALSE)
%endfunction
 
%function SLibCGB_EO_CSC(block, port, width, memberStr, lcv, ucv, sigIdx, reim) void
  %assign extOut = ::CompiledModel.ExternalOutputs.ExternalOutput[port]
  %return BlkFcnCGIRCSCDataHelper(extOut, width, memberStr, lcv, ucv, sigIdx, reim, TLC_FALSE)
%endfunction
 
%function SLibCG_EO_CSCAddr(port, width, memberStr, chunkIdx, ucv, indexExpr) void
  %return FcnCGIRExtOutputCSCHelper(port, width, memberStr, chunkIdx, ucv, indexExpr, TLC_TRUE)
%endfunction
 
%function SLibCGB_EO_CSCAddr(block, port, width, memberStr, lcv, ucv, sigIdx, reim) void
  %assign extOut = ::CompiledModel.ExternalOutputs.ExternalOutput[port]
  %if !LibCustomDataIsAddressable(extOut)
    %<SLibReportNonAddressableError("Output", block, extOut)>
  %endif
  %return BlkFcnCGIRCSCDataHelper(extOut, width, memberStr, lcv, ucv, sigIdx, reim, TLC_TRUE)
%endfunction
 
%function FcnCGIRExtOutputCSCHelper(port, width, memberStr, chunkIdx, ucv, indexExpr, addr) void
  %assign extOut = ::CompiledModel.ExternalOutputs.ExternalOutput[port]
  %assert extOut.StorageClass == "Custom" || (SLibIsLegacyStorageClassForDataRecord(extOut) == TLC_TRUE)
  %return FcnCGIRCSCDataHelper(extOut, TLC_FALSE, width, memberStr, chunkIdx, ucv, indexExpr, addr)
%endfunction
 
%%Function:SLibCG_Grnd===========================================================================
%%Abstract:
%%Thisfunctionreturnsthegroundvalueforagivendatatype.
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/tStringSupport.m
%%
%function SLibCG_Grnd(isComplex, dataTypeID, width, memberStr, chunkIdx, ucv, indexExpr) void
  %if LibDataTypeIsBus(dataTypeID)
    %<SLibSetDataTypeGroundReqInMemory(dataTypeID)>
    %assign grndVar = SLibGetDtGroundName(dataTypeID, TLC_FALSE, "")
    %return SLibCG_V(grndVar, TLC_FALSE, width, memberStr, chunkIdx, ucv, indexExpr)
  %endif
 
  %assign tmpVect = SLibGetReimAndIdx(indexExpr)
  %assign reim = tmpVect[0]
  %assign sigIdx = tmpVect[1]
  %assert sigIdx == 0
  %return "%<FcnGetGroundSignalValue(dataTypeID, isComplex, reim)>" + ...
    SLibCG_GetMultiWordID(chunkIdx)
%endfunction
 
%%Function:SLibCG_GrndAddr=======================================================================
%%Abstract:
%%Thisfunctionreturnstheaddresstoagroundvaluedforagivendatatype.
%%TopTester:test/toolbox/simulink/blocks/lib_Sources/Ground/rtw/tStringSupport.m
%%
%function SLibCG_GrndAddr(isComplex, dataTypeID, width, memberStr, chunkIdx, ucv, indexExpr) void
  %if LibDataTypeIsBus(dataTypeID)
    %<SLibSetDataTypeGroundReqInMemory(dataTypeID)>
    %assign grndVar = SLibGetDtGroundName(dataTypeID, TLC_FALSE, "")
    %return SLibCG_VAddr(grndVar, TLC_FALSE, width, memberStr, chunkIdx, ucv, indexExpr)
  %endif
  %assign tmpVect = SLibGetReimAndIdx(indexExpr)
  %assign reim = tmpVect[0]
  %assign sigIdx = tmpVect[1]
  %assert sigIdx == 0
  %if chunkIdx >= 0
    %%
    %% Returns &MultiWordGround.chunk[chunkIdx]
    %%
    %return "&" + FcnGetGroundSignalValue(dataTypeID, isComplex, reim) + ...
      SLibCG_GetMultiWordID(chunkIdx)
  %else
    %return FcnGetGroundSignalAddr(dataTypeID, isComplex, reim)
  %endif
%endfunction
 
 
%%Function:CGInputExpr===========================================================================
%%Abstract:
%%Thisfunctionreturnsaexpressionoraddressexpressbasedon
%%signaltype.
%%TopTester:test/toolbox/simulink/blocks/tconcat.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%
%function CGInputExpr(sigType, sysIdx, blkIdx, pIdx, chunkIdx, ucv, idxExpr) void
  %if sigType == "Signal"
    %assign outputType = "output"
  %else
    %assert sigType == "SignalAddr"
    %assign outputType = "outputAddr"
  %endif
  %assign srcSys = ::CompiledModel.System[sysIdx]
  %assign srcBlk = srcSys.Block[blkIdx]
  %if chunkIdx >= 0
    %assign errTxt = "Blocks output ports of mult-word fixpoint type " ...
      "should not output expressions"
    %<LibReportError(errTxt)>
  %endif
  %with srcSys %% switch system context if needed
    %assign portObj = srcBlk.DataOutputPort[pIdx]
    %with srcBlk
      %assign isOutputPortSignalExpr = LibBlockOutputSignalIsExpr(pIdx)
    %endwith
    %if isOutputPortSignalExpr == 1
      %assign cast = ""
      %with srcBlk
        %assign isScalar = (LibBlockOutputSignalSymbolicWidth(pIdx) == "1")
      %endwith
      %% only apply casts on scalar signal's value.
      %if isScalar && (sigType == "Signal")
        %assign cast = LibOutputExprCast(srcBlk, pIdx)
      %endif
      %assign retSignal = ...
        SLibBlockOutputSignal(srcBlk, srcSys, pIdx, ucv, "", idxExpr, sigType)
      %if cast != ""
        %assign retSignal = "(%<cast>%<retSignal>)"
      %endif
      %assign retSignal = SLibProcessSafeExpression(srcBlk.Name, retSignal, 1)
      %assign sigRec = SLibGetSourceRecord(portObj, 0)
      %<SLibClearAccessRecord(sigRec)>
    %else
      %with srcBlk
      %assign retSignal = ...
        FcnGetInputOrOutputSignal(outputType, pIdx, ucv, "", idxExpr)
      %endwith
    %endif
  %endwith
  %return retSignal
%endfunction
 
%%Function:SLibCG_Expr===========================================================================
%%Abstract:
%%ThisfunctionreturnstheoutputexpressionforagivenblockinRTW.
%%TopTester:test/toolbox/simulink/blocks/tconcat.m
%%
%function SLibCG_Expr(sysIdx, blkIdx, portIdx, width, strEl, chunkIdx, ucv, sigIdx) void
  %assign prevGeneratingOutputsCode = ::CompiledModel.GeneratingOutputsCode
  %assign ::CompiledModel.GeneratingOutputsCode = 1
  %if ISEMPTY(strEl)
    %assign expr = CGInputExpr("Signal", sysIdx, blkIdx, portIdx, chunkIdx, ucv,sigIdx)
  %else
    %assign expr = CGInputExpr("Signal", sysIdx, blkIdx, portIdx, chunkIdx, "",0)
    %assign expr = SLibCG_V(expr, TLC_FALSE, width, strEl, chunkIdx, ucv, sigIdx)
  %endif
  %assign ::CompiledModel.GeneratingOutputsCode = prevGeneratingOutputsCode
  %return expr
%endfunction
 
%%Function:SLibCG_ExprAddr=======================================================================
%%Abstract:
%%ErrorcondtionforTLCbasedexpressionfolding.
%%
%function SLibCG_ExprAddr(sysIdx, blkIdx, pIdx, width, strEl, chunkIdx, ucv, sigIdx) void
  %if ISEMPTY(strEl)
    %return CGInputExpr("SignalAddr", sysIdx, blkIdx, pIdx, chunkIdx, ucv,sigIdx)
  %else
    %assign expr = CGInputExpr("SignalAddr", sysIdx, blkIdx, pIdx, chunkIdx,"",0)
    %return SLibCG_VAddr(expr, TLC_FALSE, width, strEl, chunkIdx, ucv, sigIdx)
  %endif
%endfunction
 
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%
%function SLibCGExprOutputFcn(blkFcn, sysIdx, blkIdx, portIdx, modIdx, fcnIdx, exprIdx) void
  %assign prevGeneratingOutputsCode = ::CompiledModel.GeneratingOutputsCode
  %assign ::CompiledModel.GeneratingOutputsCode = 1
  %assign indexExpr = SLibBlockOutputExprIdx(sysIdx, blkIdx, portIdx, exprIdx)
  %assign expr = CGInputExpr("Signal", sysIdx, blkIdx, portIdx, -1, indexExpr, 0)
  %assign ::CompiledModel.GeneratingOutputsCode = prevGeneratingOutputsCode
  %return expr
%endfunction
 
%%
%%TLCfunctionusedtogeneratecodethatgetrootinportsize.
%%ItisusedforS-functiontargetsincludingAcceleratormode
%%
%%dwIdxisthedworkindexforrootinportdimsize
%%widthisthewidthoftheinportsizevar,i.e.thenumberofdimensions
%%oftherootinport.
%%
%function SLibGetInportSize(portIdxOrDWIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %% SLibGetInportSize should not be called in a reusable subsystem
  %assert SystemIdx == NumSystems-1 || RTWSystemCode != 2
  %if CodeFormat == "S-Function" && !Accelerator
    %% generate function calls to access SimStruct data
    %% for generated S-Function targets.
    %%
    %assign portIdx = portIdxOrDWIdx
    %assign extInp = ::CompiledModel.ExternalInputs.ExternalInput[portIdx]
     
    %if ISFIELD(extInp,"SizeVarGroupIdx")
      %assign cgTypeIdx = SLibCGVarGroupMemberCGTypeIdx(...
            extInp.SizeVarGroupIdx[0], ...
            extInp.SizeVarGroupIdx[1])
    %elseif ISFIELD(extInp,"DimSizeDWork")
      %assign sizeCGType = LibGetRecordCGTypeIdx(::CompiledModel.DWorks.DWork[extInp.DimSizeDWork])
    %endif
     
    %assign sfcnInputSize = FcnCGIRSFcnSizeVarHelper("ssGetCurrentInputPortDimensions", ...
      TLC_FALSE, "const", ...
      cgTypeIdx, portIdx, width, memberStr, ucv, indexExpr)
    %return sfcnInputSize
  %elseif Accelerator
    %assert CodeFormat == "S-Function"
    %assign dwIdx = portIdxOrDWIdx
    %assign dw = ::CompiledModel.DWorks.DWork[dwIdx]
 
    %assign isPointer = TLC_FALSE %% root inport cannot be pointer
    %assign varGroupIdx = dw.VarGroupIdx[0]
    %assign memberIdx = dw.VarGroupIdx[1]
     
    %assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
    %assign portVarName = FcnSLibCGIRGetVarGroupMemberName(varGroup, memberIdx)
    %assign identifier = "((%<::tDWorkType> *) ssGetRootDWork(S))->%<portVarName>"
    %return FcnCGIRSimpleCGVarHelper(identifier, ...
      isPointer, width, memberStr, chunkIdx, ucv, indexExpr, TLC_FALSE)
  %else
    %% generate access to members of the flat
    %% ExternalInputSizeVarGroup.
    %% cannot use SLibCGIRVarGroupPath because it tracks arguments.
    %%
    %assign portIdx = portIdxOrDWIdx
    %assign extInp = ::CompiledModel.ExternalInputs.ExternalInput[portIdx]
    %assign isPointer = TLC_FALSE %% root outport cannot be pointer
    
    %if ISFIELD(extInp,"SizeVarGroupIdx")
        %assign varGroupIdx = extInp.SizeVarGroupIdx[0]
        %assign memberIdx = extInp.SizeVarGroupIdx[1]
        %assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
        %assign portVarName = FcnSLibCGIRGetVarGroupMemberName(varGroupIdx, memberIdx)
        %assign identifier = varGroup.Name + "." + portVarName
    %elseif ISFIELD(extInp,"DimSizeDWork")
        %assign dWrec = ::CompiledModel.DWorks.DWork[extInp.DimSizeDWork]
        %assign identifier = dWrec.Identifier
    %endif
 
    %return FcnCGIRSimpleCGVarHelper(identifier, ...
        isPointer, width, memberStr, chunkIdx, ucv, indexExpr, TLC_FALSE)
  %endif
%endfunction
 
%%
%%TLCfunctionusedtogeneratecodethatsetrootoutportsize.
%%ItisusedforS-functiontargetonly.
%%
%%widthisthewidthoftheoutportsizevar,i.e.thenumberofdimensions
%%oftherootoutport.
%%TopTester:test/toolbox/simulink/variants/inlineVariants/ivGeneral/tIVfcnCall_neg.m
%%
%function SLibGetOutportSize(portIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %% SLibGetOutportSize should not be called in a reusable subsystem
  %assert SystemIdx == NumSystems-1 || RTWSystemCode != 2
  %assign extOutp = ::CompiledModel.ExternalOutputs.ExternalOutput[portIdx]
 
  %if CodeFormat == "S-Function" && !Accelerator
    %% generate function calls to access SimStruct data
    %% for generated S-Function targets.
    %assign cgTypeIdx = SLibCGVarGroupMemberCGTypeIdx(...
    extOutp.SizeVarGroupIdx[0], ...
    extOutp.SizeVarGroupIdx[1])
    %assign sfcnOutputSize = FcnCGIRSFcnSizeVarHelper("ssGetCurrentOutputPortDimensionsAndRecordIndex", ...
      TLC_FALSE, "", ...
      cgTypeIdx, portIdx, width, memberStr, ucv, indexExpr)
    %return sfcnOutputSize
  %elseif MultiInstanceERTCode
    %% External output size var is still in the DWork VarGroup.
    %% need to clean it up. (Hongbo)
    %assign varGroupIdx = extOutp.SizeVarGroupIdx[0]
    %assign memberIdx = extOutp.SizeVarGroupIdx[1]
    %return FcnCGIRCGVarHelper(varGroupIdx, memberIdx, TLC_FALSE, ...
      System[SystemIdx].HStructDeclSystemIdx, ...
      width, memberStr, chunkIdx, ucv, indexExpr, TLC_FALSE)
  %else
    %% generate access to members of the flat
    %% ExternalOutputSizeVarGroup.
    %% cannot use SLibCGIRVarGroupPath because it tracks arguments.
    %%
    %assign isPointer = TLC_FALSE %% root outport cannot be pointer
    %assign varGroupIdx = extOutp.SizeVarGroupIdx[0]
    %assign memberIdx = extOutp.SizeVarGroupIdx[1]
    %assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
    %assign portVarName = FcnSLibCGIRGetVarGroupMemberName(varGroupIdx, memberIdx)
    %assign identifier = varGroup.Name + "." + portVarName
    %return FcnCGIRSimpleCGVarHelper(identifier, ...
      isPointer, width, memberStr, chunkIdx, ucv, indexExpr, TLC_FALSE)
  %endif
%endfunction
 
%%
%%TLCfunctionusedtopassrootinportsizetoareusable
%%function.
%%dwIdxisthedworkindexforrootinportdimsize
%%
%function SLibGetInportSizeAddr(portIdxOrDWIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %% SLibGetInportSize should not be called in a reusable subsystem
  %assign sfcnInputSize = SLibGetInportSize(portIdxOrDWIdx, width, memberStr, chunkIdx, ucv, indexExpr)
  %return "&" + sfcnInputSize
%endfunction
 
%function SLibGetOutportSizeAddr(portIdx, width, memberStr, chunkIdx, ucv, indexExpr) void
  %assign outportSize = SLibGetOutportSize(portIdx, width, memberStr, chunkIdx, ucv, indexExpr)
  %return "&" + outportSize
%endfunction
 
%function SLibCGIRGetLoopVarName(sysIdx) void
  %return SLibCGIRGetIteratorName(sysIdx)
%endfunction
 
%%Function:SLibCGIRZeroOutDerivativesForSystem===================================================
%%Abstract:
%%Thisfunctioncallsafunctiontozerooutthederivativesforagiven
%%system.
%%TopTester:test/toolbox/simulink/blocks/tconcat.m
%%
%function SLibCGIRZeroOutDerivativesForSystem(sysIdx, ssBlkSysIdx, ssBlkIdx) Output
  %assign system = ::CompiledModel.System[sysIdx]
  %assign ssSystem = ::CompiledModel.System[ssBlkSysIdx]
  %assign ssBlock = ssSystem.Block[ssBlkIdx]
  %%
  %if ISFIELD(ssBlock, "ParamSettings")
    %with ssBlock
      %assign cStates = LibBlockParamSetting("", "SystemContStates")
    %endwith
  %else
    %with ssBlock
      %assign cStates = LibBlockParamSetting("Subsystem", "SystemContStates")
    %endwith
  %endif
  %%
  %assign ncStates = cStates[0]
  %%
  %if ncStates == 0
    %return
  %elseif ncStates > 1
    %assign needDxAndI = 1
  %else
    %assign needDxAndI = 0
  %endif
  %%
  %openfile tmpZero
  %assign ::PartialIndexing = TLC_TRUE
  %assign ::PartialIdxBoundarySysystemIndex = sysIdx
  %<SLibZeroOutDerivativesForSystem(ssBlock, system)>/
  %assign ::PartialIdxBoundarySysystemIndex = -1
  %assign ::PartialIndexing = TLC_FALSE
  %closefile tmpZero
  %%
  %if tmpZero != ""
    %if needDxAndI
      {
        real_T *dx;
        int_T i;
    %endif
        %<tmpZero>/
    %if needDxAndI
      }
    %endif
  %endif
%endfunction
 
%%Function:SLibCGIRZeroOutZeroCrossingsForSystem=================================================
%%Abstract:
%%Zerooutthezerocrossingsforagivensubsystem.
%%
%function SLibCGIRZeroOutZeroCrossingsForSystem(sysIdx, ssBlkSysIdx, ssBlkIdx) Output
  %assign system = ::CompiledModel.System[sysIdx]
  %assign ssSystem = ::CompiledModel.System[ssBlkSysIdx]
  %assign ssBlock = ssSystem.Block[ssBlkIdx]
  %%
  %if ISFIELD(ssBlock, "ParamSettings")
    %assign numNonsampledZCs = ssBlock.ParamSettings.NumNonsampledZCs
  %else
    %assign numNonsampledZCs = ssBlock.SubsystemParamSettings.NumNonsampledZCs
  %endif
  %%
  %%
  %if numNonsampledZCs > 0
    {
      %assign ::PartialIndexing = TLC_TRUE
      %assign ::PartialIdxBoundarySysystemIndex = sysIdx
      %<SLibZeroOutZcSignalsForSystem(ssBlock, system)>
      %assign ::PartialIdxBoundarySysystemIndex = -1
      %assign ::PartialIndexing = TLC_FALSE
    }
  %endif
%endfunction
 
 
%function SLibCGIRInitGlobalIOForBlock(sigsrc, ownerSysIdx) Output
  %assign csgInitBuffer = "" %% for invariant, or signal object InitialValue
  %assign straightInitBuffer = ""
  %assign useLoopVarInitBuffer = ""
  %assign memsetToZeroNeeded = 0
   
  %%
  %assign bo = BlockOutputs.GlobalBlockOutput[sigsrc]
  %assert bo.InitInStart
  %assign sys = System[ownerSysIdx]
  %assign ret = SLibInitBlockIOForBufferHelper(bo, sys.NonInlinedParentSystemIdx, TLC_FALSE)
  %assign csgInitBuffer = ret[0]
  %assign straightInitBuffer = ret[1]
  %assign useLoopVarInitBuffer = ret[2]
   
  %% Memset on all block io buffer will be handled by SLibInitBlockIOHelper
   
  %if !WHITE_SPACE(csgInitBuffer) ...
    || !WHITE_SPACE(straightInitBuffer) ...
    || !WHITE_SPACE(useLoopVarInitBuffer)
    %% SLibGetBlockOutputFromRecord above took care of LibAccessArg
    {
      %if !WHITE_SPACE(useLoopVarInitBuffer)
        %<LibCGTypeName(::CompiledModel.CGTypes.IndexType)> i;
        %<useLoopVarInitBuffer>/
      %endif
      %<straightInitBuffer>/
      %<csgInitBuffer>/
    }
  %endif
%endfunction
 
%function SLibCGIRInitDWorkForBlock(sigsrc, ownerSysIdx) Output
  %assign dwRec = ::CompiledModel.DWorks.DWork[sigsrc]
  %if SLibOmitRecord(dwRec)
    %return
  %endif
  %assign stdSSBuf = CacheStandaloneSystemDWorkInfo()
  %assign idx = SLibGetSystemAndCallSideIndex(dwRec)
  %if SigSrcLivesInStandaloneSS(idx)
    %assign baseSystemIdx = StandaloneParentSysIdxOfDataRec(dwRec)
  %else
    %assign baseSystemIdx = GetBaseSystemIdx()
  %endif
  %assign stdIdx = System[baseSystemIdx].IndexInStandaloneSubsystemArray
 
  %assign sys = System[ownerSysIdx]
  %if ForceBlockIOInitOptimize
    %assign oldInitBuf = SLibInitDWorkOldHelper(stdSSBuf, stdIdx, -1, -1, 0, "", "", sys.NonInlinedParentSystemIdx, dwRec, TLC_TRUE, "", "")
    %assign stdSSBuf = oldInitBuf[0]
  %else
    %assign cross = System[NonInlinedParentSystemIdx].CrossNoArgFcnBound
    %assign stdSSBuf = SLibInitDWorkHelper(stdSSBuf, stdIdx, sys.NonInlinedParentSystemIdx, cross, dwRec, TLC_TRUE, "", "")
  %endif
   
  %if !WHITE_SPACE(stdSSBuf.DWorkBuff[0].initBuffer)
    %
  %endif
%endfunction
 
%%Function:SLibCGIRSetSolverNeedsReset===========================================================
%%Abstract:
%%Thisfunctionoutputscodetoresetthesolverifneedbe.
%%
%function SLibCGIRSetSolverNeedsReset() Output
  %<RTMSetSolverNeedsReset()>;
%endfunction
 
 
%%Function:SLibCGIRIsModeReferenceForASimstructBasedTarget=======================================
%%Abstract:
%%TRUEifModelReferenceforaSimstructtarget
%%
%function SLibCGIRIsModeReferenceForASimstructBasedTarget() void
  %if IsModelReferenceForASimstructBasedTarget()
    %assign res = "true"
  %else
    %assign res = "false"
  %endif
  %return res
%endfunction
 
%%Function:SLibCGIRGetSolverAssertCheck==========================================================
%%Abstract:
%%TRUEiftheSolverischecking/assertingthestates/derivatives
%%
%function SLibCGIRGetSolverAssertCheck() void
  %if IsModelReferenceForASimstructBasedTarget()
    %assign simS = RTMGet("MdlRefSfcnS")
    %assign res = "_ssGetSolverAssertCheck(%<simS>)"
  %elseif IsSimstructBasedTarget()
    %assign mdlinfo = RTMGet("MdlInfoPtr")
    %assign res = "(%<mdlinfo>->mdlFlags.solverAssertCheck == 1U)"
  %else
    %assign res = "false"
  %endif
  %return res
%endfunction
  
%%Function:SLibCGIRGetSolverFoundZcEvents========================================================
%%Abstract:
%%TRUEiftheSolverhasfoundaZeroCrossingevent
%%
%function SLibCGIRGetSolverFoundZcEvents() void
  %if (::CompiledModel.SolverType == "FixedStep")
    %assign res = "false"
  %elseif IsModelReferenceForASimstructBasedTarget()
    %assign simS = RTMGet("MdlRefSfcnS")
    %assign res = "%<LibIsMajorTimeStep()> && ssGetSolverFoundContZcEvents(%<simS>)"
  %else
    %assign solverinfo = RTMGetSolverInfo()
    %assign res = "%<LibIsMajorTimeStep()> && %<solverinfo>->foundContZcEvents"
  %endif
  %return res
%endfunction
 
%%Function:SLibCGIRHasCompiledModelPropertyValue=================================================
%%Abstract:
%%TRUEifthe::CompiledModelhasthespecifiedpropertysettothevalue
%%
%function SLibCGIRHasCompiledModelPropertyValue(property,value) void
  %if ISFIELD(::CompiledModel, property) && ...
    (GETFIELD(::CompiledModel, property) == value)
    %return "true"
  %else
    %return "false"
  %endif
%endfunction
 
%%Function:SLibCGIRGetCompiledModelPropertyValue=================================================
%%Abstract:
%%Getthevalueofthe::CompiledModelproperty(orthedefault)
%%
%function SLibCGIRGetCompiledModelPropertyValue(property,default) void
  %if ISFIELD(::CompiledModel, property)
    %return GETFIELD(::CompiledModel, property)
  %else
    %return default
  %endif
%endfunction
 
%%Function:SLibCGIRGetFixedStepSolverPropertyValue===============================================
%%Abstract:
%%Getthepropertyusedwithfixedstepsolver(orthedefault)
%%
%function SLibCGIRGetFixStepSolverPropertyValue(property,default) void
  %if ISFIELD(::CompiledModel,"FixedStepOpts")
    %return GETFIELD(::CompiledModel.FixedStepOpts, property)
  %else
    %return default
  %endif
%endfunction
 
%%Function:SLibCGIRGetVarStepSolverPropertyValue=================================================
%%Abstract:
%%Getthepropertyusedwithvariablestepsolver(orthedefault)
%%
%function SLibCGIRGetVarStepSolverPropertyValue(property,default) void
  %if ISFIELD(::CompiledModel,"VariableStepOpts")
    %return GETFIELD(::CompiledModel.VariableStepOpts, property)
  %else
    %return default
  %endif
%endfunction
 
%%Function:SLibCGIRSkipSystem====================================================================
%%Abstract:
%%Thisfunctionsetaflagtoskipcodegenerationforagivensystemandits
%%childsystems.
%%
%%Notethatweonlyskipthissystemanditschildrenifthesystemis
%%inlined.Ifitisreused,otherinstancesmayneedtobegenerated
%%andwe'dgetwronganswersifwedidnot.Ifthe
%%systemisfunctiontheusermaywanttohaveitgeneratedanyway.
%%
%function SLibCGIRSkipSystem(sysIdx) void
   %if LibSystemIsInlined(::CompiledModel.System[sysIdx])
    %assign ::CompiledModel.System[sysIdx].DeletedInIR = TLC_TRUE
    %with ::CompiledModel.System[sysIdx]
      %foreach idx=NumChildSystems
        %<SLibCGIRSkipSystem(ChildSystems[idx][0])>
      %endforeach
    %endwith
  %endif
%endfunction
 
%%Function:SLibCGIRDumpSystemUserCode============================================================
%%Abstract:
%%Thisfunctiondumpestheusercodeforagivensystemindex,
%%blockfunctionandlocationinformation.Locationcanbe"header","body"
%%and"trailer".
%%TopTester:test/toolbox/simulink/variants/vssSigObj/tVSSSigObj.m
%%
%function SLibCGIRDumpSystemUserCode(sysIdx, blockFcn, location) Output
  %assign ss = ::CompiledModel.System[sysIdx]
  %assign prevTID = ss.CurrentTID
  %assign ss.CurrentTID = CurrentTID
  %assign buff = ""
  %%
  %%
  %openfile buff
  %<LibDumpSystemUserCodeNoCheck(ss, blockFcn, location)>
  %closefile buff
  %%
  %if location == "Header"
    %if !LibSystemUserCodeIsEmpty(ss,blockFcn,"Header")
      %% has possible variable declaration
      {
    %endif
  %endif
  %<buff>/
  %if location == "Trailer"
    %if !LibSystemUserCodeIsEmpty(ss,blockFcn,"Header")
      %% has possible variable declaration
      }
    %endif
  %endif
  %assign ss.CurrentTID = prevTID
  
%endfunction
 
%%Function:SLibCGIRDumpSystemUserCodeForCriticalSection==========================================
%%Abstract:
%%WrapperaroundSLibCGIRDumpSystemUserCodeforCriticalSection
%%
%function SLibCGIRDumpSystemUserCodeForCriticalSection(sysIdx, blockFcn, location) Output
   %<SLibCGIRDumpSystemUserCode(sysIdx, blockFcn, location)>
%endfunction
 
%%Function:SLibCGIRDumpSystemProfCode============================================================
%%Abstract:
%%Thisfunctiondumpstheprofilecodeforagivensystemindex,
%%lockfunctionandlocationinformation.
%%
%%Locationcanbe:
%%
%%"Declare","Start","End","Terminate"
%%
%function SLibCGIRDumpSystemProfCode(sysIdx, blockFcn, location) Output
  %assign ss = ::CompiledModel.System[sysIdx]
 
  %if blockFcn == "Terminate"
    %<SLibGenProfSysTerminate(ss)>
  %else
    %if location == "Declare"
      %<SLibGenProfSysDeclare(ss, blockFcn)>
    %elseif location == "Start"
      %<SLibGenProfSysStart(ss, blockFcn)>
    %elseif location == "End"
      %<SLibGenProfSysEnd(ss, blockFcn)>
    %else
      %assign msg = "Invalid profile code location: '%<location>'"
      %<LibReportFatalError(msg)>
    %endif
  %endif
%endfunction
 
%%Function:SLibCGIRGetIteratorName===============================================================
%%Abstract:
%%Getthenameoftheiterator.Eitheritwassetbeforebytheiterator
%%subsystemorit'sconstructedviaTLCcodeandweneedtocalltheold
%%function.
%function SLibCGIRGetIteratorName(sysIdx) void
  %if ISFIELD(::CompiledModel.System[sysIdx], "IteratorName")
    %return ::CompiledModel.System[sysIdx].IteratorName
  %else
    %assign loopSuffix = ::CompiledModel.System[sysIdx].SysName
    %return "iter%<loopSuffix>"
  %endif
%endfunction
 
%%Function:SLibCGIRSetIteratorName===============================================================
%%Abstract:
%%Setthenameoftheiterator.
%function SLibCGIRSetIteratorName(sysIdx, iterName) void
  %if !ISFIELD(::CompiledModel.System[sysIdx], "IteratorName")
    %addtorecord ::CompiledModel.System[sysIdx] IteratorName iterName
  %endif
%endfunction
 
%%Function:SLibCGIREmptyFcn======================================================================
%%Abstract:
%%AnemptyfunctionusedtokeepCGIRfromoptimizingcodewithsideeffect
%%
%function SLibCGIREmptyFcn() void
  %return ""
%endfunction
 
%%Function:SLibCGIRIteratorContainer=============================================================
%%Abstract:
%%AnemptyfunctionusedtokeepCGIRfromdeadcodeeliminatinginteratorvariables
%%we'reinterestedin.
%function SLibCGIRIteratorContainer(unused1, unused2) void
  %return ""
%endfunction
 
 
%%Function:SLibCGIRSetStatesDisabled=============================================================
%%Description:
%%Generatecodetoresetconstinuousstate.Thisfunctioniscalled
%%byenablesubsysteminvariablestepsolvermodel.
%%TopTester:test/toolbox/simulink/variants/tMdlrefToVSS.m
%%
%function SLibCGIRSetStatesDisabled(ssBlkSysIdx, ssBlkIdx, value) Output
  %assign ssBlock = ::CompiledModel.System[ssBlkSysIdx].Block[ssBlkIdx]
  %assign system = ::CompiledModel.System[ssBlock.CallSiteInfo.SystemIdx]
  %assign ::PartialIndexing = TLC_TRUE
  %assign ::PartialIdxBoundarySysystemIndex = ssBlock.CallSiteInfo.SystemIdx
  %<SLibSetStatesDisabled(ssBlock,system,value)>
  %assign ::PartialIdxBoundarySysystemIndex = -1
  %assign ::PartialIndexing = TLC_FALSE
%endfunction
 
%%Function:SLibCGIRSetStatesDisabledForMassMatrix================================================
%%Description:
%%Generatecodetoset/clearstatedisabled.Usedinlinearlyimplicit
%%modelstoproperlyindicatetheeye()portionofthemassmatrix.
%%
%function SLibCGIRSetStatesDisabledForMassMatrix(ssBlkSysIdx, ssBlkIdx, value) Output
  %assign ssSystem = ::CompiledModel.System[ssBlkSysIdx]
  %assign ssBlock = ssSystem.Block[ssBlkIdx]
  %assign ::PartialIndexing = TLC_TRUE
  %assign ::PartialIdxBoundarySysystemIndex = ssBlock.CallSiteInfo.SystemIdx
  %<SLibSetStatesDisabled(ssBlock,ssSystem,value)>
  %assign ::PartialIdxBoundarySysystemIndex = -1
  %assign ::PartialIndexing = TLC_FALSE
%endfunction
 
 
%%Function:SLibCGIRModelrefCacheVarStepSolverResetCode===========================================
%%Description:
%%Generatecodetoresetconstinuousstateformodelreference.
%%
%function SLibCGIRModelrefCacheVarStepSolverResetCode(sysIdx) Output
  %assign system = ::CompiledModel.System[sysIdx]
  %assert IsModelReferenceBaseSys(system)
  %assert ::CompiledModel.SolverType == "VariableStep"
  %if IsModelReferenceForASimstructBasedTarget()
    %<ModelrefCacheVarStepSolverResetCode(system)>
  %endif
%endfunction
 
%function SLibListInitializer(moduleIdx,sysFcnType,initType,argExprs) void
  %% initType:
  %% 0: service ports that need to be initialized before modelref's are intialized
  %% 1: modelrefs
  %% 2: service ports that need to be initalized after modelref's are intialized
  %% (currently, this will error out if dynamically allocating mdlrefs). If
  %% not doing dynamic allocation, order is controlled by SLCGCppClassCodeConstructor
  %% 3: model data
   
  %if ISEMPTY(argExprs)
    %return
  %endif
   
  %assign sysFcnTypeName = SLibCGIRGetFcnTypeName(%<sysFcnType>)
  %assign module = ::CompiledModel.RTWCGModules.RTWCGModule[%<moduleIdx>]
  %assign system = ::CompiledModel.System[module.CGSystemIdx]
  %if CGMODEL_ACCESS("CGModel.getUseOperatorNewForModelRefRegistration") && initType==1
    %% for dynamic initialization
    %if !LibIsSystemField(system,"CachedModelRefConstructors")
      %<LibAddToSystem(system, "CachedModelRefConstructors", argExprs)>
    %endif
    %return
  %endif
  %assign oldListInitializerContents = LibIsSystemField(system,"CachedListInitializer") ? LibGetSystemField(system, "CachedListInitializer") : ""
  %assign comma = ""
  %if !WHITE_SPACE(oldListInitializerContents)
    %assign comma = ","
  %else
    %assign oldListInitializerContents = ":/n"
  %endif
  %openfile listInitializer
%<oldListInitializerContents>/
  %foreach idx = SIZE(argExprs,1)
    %if !WHITE_SPACE(argExprs)
      %<comma>% /
 
      %assign comma = ","
    %endif
  %endforeach
  %closefile listInitializer
  %if !LibIsSystemField(system,"CachedListInitializer")
    %<LibAddToSystem(system, "CachedListInitializer", listInitializer)>
  %else
    %<LibSetSystemField(system, "CachedListInitializer", listInitializer)>
  %endif
%endfunction
 
%function SLibIsMessageServiceProvider(system)
  %assign svcBuff = GET_FILE_REP_SCRATCH_BUFFER_CONTENTS("MessageServiceBuff")
  %return !ISEMPTY(svcBuff)
%endfunction
 
%%Function:SLibCGIRGetFcnTypeName================================================================
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortFcnCall4.m
%%TopTester:test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmg1078041_VC1.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants9.m
%%TopTester:test/toolbox/simulink/variants/CondExecutedVSS/tContPortGecks.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tcodevariants3.m
%%TopTester:test/toolbox/simulink/variants/codevariants/tvss_code_variants.m
%%
%function SLibCGIRGetFcnTypeName(sysFcnType)
   
  %switch(sysFcnType)
      %% The index should match SystemFcnEnum
      %case 0
        %return "Start"
      %case 1
        %return "VirtualOutportStart"
      %case 2
        %return "SetupRuntimeResources"
      %case 3
        %return "Initialize"
      %case 4
        %return "SystemInitialize"
      %case 5
        %return "SystemReset"
      %case 6
        %return "Output"
      %case 7
        %return "Update"
      %case 8
        %return "Derivative"
      %case 9
        %return "Projection"
      %case 10
        %return "ForcingFunction"
      %case 11
        %return "MassMatrix"
      %case 12
        %return "ZeroCrossing"
      %case 13
        %return "Enable"
      %case 14
        %return "Disable"
      %case 15
        %return "FinalizeDims"
      %case 16
        %return "SetDims"
      %case 17
        %return "CleanupRuntimeResources"
      %case 18
        %return "Terminate"
      %case 19
        %return "ModelInitialize"
      %case 20
        %return "ModelPrevZCStateInit"
      %case 21
        %return "ModelExternalOutputInit"
      %case 22
        %return "ModelExternalInputInit"
      %case 23
        %return "ModelInitializeSizes"
      %case 24
        %return "ModelConstructor"
      %case 25
        %return "ConstCode"
      %case 26
        %return "OpaqueTypeConstruct"
      %case 27
        %return "OpaqueTypeDestruct"
      %case 28
        %return "OpaqueTypeDestructForMemset"
      %case 29
        %return "DeadCode"
      %default
        %% always assert
        %assert TLC_FALSE
    %endswitch
%endfunction
 
%%Function:SLibCG_SystemFcnArgAccessed===========================================================
%%Abstract:
%%Returnstrueifagivensystemfunctionargumenthasbeenaccessed.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibCG_SystemFcnArgAccessed(fcnName, sysIdx, argIdx) void
  %assign thisSystem = ::CompiledModel.System[sysIdx]
  %if thisSystem.IsRateGroupedSLFcn && !Accelerator
    %assign thisSystem = ::CompiledModel.System[NumSystems-1]
  %endif
  %assign modIdx = thisSystem.CGIRModuleIdx
  %assign ownerModule = ::CompiledModel.RTWCGModules.RTWCGModule[modIdx]
  %assert ISFIELD(ownerModule.SystemFunctions, fcnName)
  %assign fcnIdx = ownerModule.SystemFunctions.%<fcnName>
  %assign fcn = ownerModule.Function[fcnIdx]
  %return fcn.ArgAccessed[argIdx] > 0
%endfunction %% SLibCG_SystemFcnArgAccessed
 
%%Function====================================================================
%%Description:
%%generatefcncallstatement.
%%TopTester:test/toolbox/rtw/targets/ert/tcodevariants.m
%%
%function SLibCGIRGenReusableSysCall(fcnName, canIO, sysIdx, csIdx, ...
  sysFcnType, tid, parentFcnType, accSysIdx) void
  %assign retBuf = ""
  %assign fcnTypeName = SLibCGIRGetFcnTypeName(sysFcnType)
  %assign parentFcnTypeName = SLibCGIRGetFcnTypeName(parentFcnType)
  %assign ss = ::CompiledModel.System[sysIdx]
  %assign cs = ss.CallSites[csIdx]
  %assign dataGrBlk = System[cs[2]].Block[cs[3]]
  %assert dataGrBlk.Type == "SubSystem"
  %assign parentSys = ::CompiledModel.System[cs[0]]
  %assign prevTID = ss.CurrentTID
  %assign ss.CurrentTID = tid
 
  /% %assign tmpTid = SLibSystemTidUsedByRateGroup(ss,fcnTypeName) %/
  /% %if !LibSystemFcnIsEmptyHelper(ss, fcnTypeName, tmpTid) %/
    /% %if SLibSystemFcnIsRateGroupType(fcnTypeName) %/
    /% %assign ss.CurrentTID = tmpTid %/
    /% %endif %/
    %if fcnTypeName == "Output" && !ISFIELD(ss,"OutputFcn") && ...
      !(ISFIELD(ss,"OutputCalledInUpdate") && ...
      ss.OutputCalledInUpdate == "yes")
      %assign fcnTypeName = "OutputUpdate"
    %endif
    %openfile tmpBuf
    %closefile tmpBuf
    %assign retBuf = retBuf + tmpBuf
    %if LibSystemIsInlined(ss)
      %assign buffer = SLibGetBody%<fcnTypeName>FcnCache(ss)
      %openfile tmpBuf
      %if dataGrBlk.PreprocessorConditionsInIR == 1
        %assign needsBlockComment = ...
          SimulinkBlockComments && NEEDS_COMMENT(buffer)
        %<WriteBlockComments(dataGrBlk, needsBlockComment)>
      %endif
      %<buffer>/
      %closefile tmpBuf
      %assign retBuf = retBuf + tmpBuf
    %elseif SLibNeedHandleParallelForEachSS(ss, fcnTypeName)
      %openfile tmpBuf
      %<SLibGenParallelAccelForEachSS(sysIdx, sysFcnType)>
      %closefile tmpBuf
      %assign retBuf = retBuf + tmpBuf
    %else
      %assign fcnInfo = SLibGetFcnInfoForFcnName(ss, fcnName)
      %if ISEMPTY(fcnInfo)
        %assign fcnInfo = LibGetFcnInfo(ss, fcnTypeName, tid)
      %endif
      %%assert !ISEMPTY(fcnInfo)
      %openfile tmpBuf
      %<LibGenSubsystemFcnCall(canIO, fcnInfo, SystemIdx, sysIdx, csIdx)>/
      %closefile tmpBuf
      %assign retBuf = retBuf + tmpBuf
    %endif
    %if sysFcnType != parentFcnType
      %openfile tmpBuf
      %assign accessSysIdx = System[SystemIdx].HStructDeclSystemIdx
      %copyrecord origInterface System[accessSysIdx].Interface
      %assign parentTid = ...
        SLibSystemFcnPeriodicRateGrouping(parentSys, parentFcnTypeName) ? tid : ""
      %<SLibCopyArgAccessedFlags(SystemIdx, fcnTypeName, parentFcnTypeName, parentTid, TLC_FALSE)>
      %assign System[accessSysIdx].Interface = origInterface
      %closefile tmpBuf
      %assign retBuf = retBuf + tmpBuf
    %endif
    %openfile tmpBuf
    %closefile tmpBuf
    /% %endif %/
     %assign retBuf = retBuf + tmpBuf
     %assign ss.CurrentTID = prevTID
     %return retBuf
%endfunction
 
%%Function:HandleNonReusedWithinReused===========================================================
%%Abstract:
%%Accessglobalvariablesthatareusedbynon-reusablefunctionto
%%accessmodelreferenceIO.
%%
%function HandleNonReusedWithinReused(aModuleIdx, aFcnIdx, aSystem, aFcnType) void
  %if LibIsServer(aSystem) || ...
    SLibIsServiceFcn(aSystem, aFcnType, aSystem.CurrentTID)
    %return
  %endif
  %if aModuleIdx > -1 && aFcnIdx > -1 ...
    && !LibSystemIsRoot(aSystem) ...
    && !IsModelReferenceBaseSys(aSystem)
    %assign reusedParent = ::CompiledModel.System[aSystem.ReusedParentSystemIdx]
    %assign isScalableMRSys = ...
      IsModelReferenceBaseSys(reusedParent) && IsModelRefScalableBuild()
    %if isScalableMRSys && TLC_TRUE == reusedParent.ContainsNonreusedFcn
      %assign thisModule = ::CompiledModel.RTWCGModules.RTWCGModule[aModuleIdx]
      %assign thisFcn = thisModule.Function[aFcnIdx]
      %<SLibAccessMdlRefGlobals(thisFcn)>
    %endif
  %endif
%endfunction %% HandleNonReusedWithinReused
 
%%Function:OpaqueTLCBlockFcn=====================================================================
%%Abstract:
%%InlinestheblockcodegeneratedbyitsTLCimplementation.Thisfunction
%%willbecalledbytheautogeneratedopaqueblockTLCcodeforblockthat
%%don'tsupportCGIR.
%%
%function OpaqueTLCBlockFcn(blkFcn, sysIdx, blkIdx, modIdx, fcnIdx, blkFcnIdx) void
  %assign buff = ""
  %assign isOutputs = (blkFcn == "Outputs")
  %assign prevGenOutputs = ::CompiledModel.GeneratingOutputsCode
  %assign prevBlockFcnIdx = ::CurrentBlockFcnIdx
  %assign prevModuleIdx = ::CurrentModuleIdx
  %assign prevFunctionIdx = ::CurrentFunctionIdx
  %assign prevRollThreshold = ::CompiledModel.RollThreshold
  %assign ::CurrentBlockFcnIdx = blkFcnIdx
  %assert ::CurrentModuleIdx == modIdx
  %assign ::CurrentModuleIdx = modIdx
  %assert ::CurrentFunctionIdx == fcnIdx
  %assign ::CurrentFunctionIdx = fcnIdx
  %assign ::CompiledModel.GeneratingOutputsCode = isOutputs
  %assign tmpTid = CurrentTID
  %with ::CompiledModel
    %assign system = ::CompiledModel.System[sysIdx]
    %assign prevTID = system.CurrentTID
    %assign system.CurrentTID = tmpTid
    %with system
      %assign block = system.Block[blkIdx]
      %assert block.Type != "Opaque"
      %assert block.BlockIdx[0] == sysIdx
      %assert block.BlockIdx[2] == blkIdx
      %if isOutputs
        %assign block.OutputBlockFcnIdx = blkFcnIdx
      %endif
      %if 1 == block.HasSymbolicDims
        %assign ::CompiledModel.RollThreshold = 0
      %endif
      %with block
        %if isOutputs
          %if !LibBlockAllOutputSignalsAreExpr()
            %assign buff = ...
              generateNonExprOutput(block, system, "", 0, TLC_FALSE)
          %endif
        %else
          %openfile buff
          %<GENERATE(block, blkFcn, system)> /
          %closefile buff
          %if WHITE_SPACE(buff)
            %assign buff = ""
          %elseif SimulinkBlockComments && NEEDS_COMMENT(buff) && !(::CompiledModel.TagTlcBlocks)
            %% get block start comments
            %assign startComment = "/* " + blkFcn + " for " + ...
              SLibBlkType(block) + ": '" + SLibBlkName(block) + "'"
            %if (writePolySpaceStartComments(block))
              %assign pSpaceStartComment = FcnGetPolySpaceStartComments(block)
              %assign startComment = startComment + "/n" + pSpaceStartComment + "/n"
            %endif
            %assign startComment = startComment + " */"
 
            %% get block end comments
            %assign endComment = ""
            %if (writePolySpaceEndComments(block))
              %assign pSpaceEndComment = FcnGetPolySpaceEndComments(block)
              %assign endComment = "/" + pSpaceEndComment + " *//n"
            %endif
            %assign buff = startComment + buff + endComment
          %endif
        %endif
      %endwith %% block
    %endwith %% system
    %assign system.CurrentTID = prevTID
  %endwith %% ::CompiledModel
  %assign ::CompiledModel.RollThreshold = prevRollThreshold
  %assign ::CompiledModel.GeneratingOutputsCode = prevGenOutputs
  %assign ::CurrentModuleIdx = prevModuleIdx
  %assign ::CurrentFunctionIdx = prevFunctionIdx
  %assign ::CurrentBlockFcnIdx = prevBlockFcnIdx
  %return buff
%endfunction
 
%function OpaqueTLCBlockFcnForTID(blkFcn, sysIdx, blkIdx, tid, ...
  modIdx, fcnIdx, blkFcnIdx) void
  %assign buff = ""
  %assign isOutputs = (blkFcn == "Outputs")
  %assign prevGenOutputs = ::CompiledModel.GeneratingOutputsCode
  %assign ::CompiledModel.GeneratingOutputsCode = isOutputs
  %assign prevBlockFcnIdx = ::CurrentBlockFcnIdx
  %assign prevModuleIdx = ::CurrentModuleIdx
  %assign prevFunctionIdx = ::CurrentFunctionIdx
  %assign prevRollThreshold = ::CompiledModel.RollThreshold
  %assign ::CurrentBlockFcnIdx = blkFcnIdx
  %assert ::CurrentModuleIdx == modIdx
  %assign ::CurrentModuleIdx = modIdx
  %assert ::CurrentFunctionIdx == fcnIdx
  %assign ::CurrentFunctionIdx = fcnIdx
  %assert (isOutputs || blkFcn == "Update")
  %assign tmpTid = CurrentTID
  %with ::CompiledModel
    %assign tid01Eq = ISEQUAL(SolverType, "FixedStep") && FixedStepOpts.TID01EQ
    %assign system = ::CompiledModel.System[sysIdx]
    %assign prevTID = system.CurrentTID
    %assign system.CurrentTID = tmpTid
    %with system
      %assign block = system.Block[blkIdx]
      %assert block.Type != "Opaque"
      %assert block.BlockIdx[0] == sysIdx
      %assert block.BlockIdx[2] == blkIdx
      %if isOutputs
        %assign block.OutputBlockFcnIdx = blkFcnIdx
      %endif
      %if 1 == block.HasSymbolicDims
        %assign ::CompiledModel.RollThreshold = 0
      %endif
      %with block
        %assign isSFcn = (block.Type == "S-Function")
        %assign nonInlinedSFcn = isSFcn && block.SFunctionType != "TLC"
        %if nonInlinedSFcn || !SLibBlockFcnRateGrouping(block, blkFcn)
          %if SLibNonInlinedModelWideEventTID(tmpTid) && ...
            !LibBlockFunctionExists(block, blkFcn + "ForTID")
            %% If the tid-less version exists but the tid'd version
            %% does not, report an error.
            %if LibBlockFunctionExists(block, blkFcn)
              %<SLibReportErrorWithIdAndArgs("RTW:tlc:ConstantNeedsOutputsForTID", "%<block.Name>")>
            %endif
 
          %elseif !tid01Eq || tmpTid != 1 || !ISFIELD(block, "HasTid0Code")
            %openfile buff
             
            %<GENERATE(block, blkFcn, system)> /
            %closefile buff
            %if WHITE_SPACE(buff)
              %assign buff = ""
            %else
              %if SLibBlkHasMultirateCode(block) && !nonInlinedSFcn && ...
                !FcnBlkIsAsyncTopSfcn(block)
                %assign warnTxt = ...
                  "Code of update function for multirate "...
                  "block '%<Name>' is guarded by sample hit checks "...
                  "rather than being rate grouped. This will generate "...
                  "the same code for all rates used by the block, "...
                  "possibly generating dead code. To avoid dead "...
                  "code, you must update the TLC file for the block."
                %<LibReportWarning(warnTxt)>
                %assign warnTxt = ...
                  "/* Because the %<blkFcn> function of multirate block /n"...
                  " %<Name> is not rate grouped, /n"...
                  " the following code might contain unreachable blocks of code. /n"...
                  " To avoid this, you must update your block TLC file. */"
                %assign buff = warnTxt + buff
              %endif
            %endif
            %if tmpTid == 0 && !ISFIELD(block, "HasTid0Code")
              %addtorecord block HasTid0Code TLC_TRUE
            %endif
          %endif
           
        %else
          %assign sfcnName = isSFcn ? ParamSettings.FunctionName : ""
          %if isOutputs
            %if !LibBlockAllOutputSignalsAreExpr()
              %assign buff = ...
                generateNonExprOutput(block, system, sfcnName, tid, TLC_TRUE)
            %endif
          %else
            %openfile buff
             
            %if isSFcn
              %<GENERATE_TYPE(block, "UpdateForTID", sfcnName, system, tid)> /
            %else
              %<GENERATE(block, "UpdateForTID", system, tid)> /
            %endif
            %closefile buff
            %if WHITE_SPACE(buff)
              %assign buff = ""
            %endif
          %endif
        %endif
      %endwith %% block
    %endwith %% system
    %assign system.CurrentTID = prevTID
  %endwith %% ::CompiledModel
  %assign ::CompiledModel.RollThreshold = prevRollThreshold
  %assign ::CompiledModel.GeneratingOutputsCode = prevGenOutputs
  %assign ::CurrentModuleIdx = prevModuleIdx
  %assign ::CurrentFunctionIdx = prevFunctionIdx
  %assign ::CurrentBlockFcnIdx = prevBlockFcnIdx
  %return buff
%endfunction
 
%function OpaqueTLCBlockFcnForMdlRefTID(blkFcn, sysIdx, blkIdx, tid, modIdx, fcnIdx, blkFcnIdx) void
   %return OpaqueTLCBlockFcnForTID(blkFcn, sysIdx, blkIdx, tid, modIdx, fcnIdx, blkFcnIdx)
%endfunction
 
%function OpaqueTLCBlockFcnForMdlRef(blkFcn, sysIdx, blkIdx, modIdx, fcnIdx, blkFcnIdx) void
   %return OpaqueTLCBlockFcn(blkFcn, sysIdx, blkIdx, modIdx, fcnIdx, blkFcnIdx)
%endfunction
 
 
%function OpaqueTLCBlockFcnForSetDims(blkFcn, sysIdx, blkIdx, oidx, ridx, ...
  moduleIdx, fcnIdx, blkFcnIdx) void
  %assign buff = ""
  %assign prevBlockFcnIdx = ::CurrentBlockFcnIdx
  %assign prevModuleIdx = ::CurrentModuleIdx
  %assign prevFunctionIdx = ::CurrentFunctionIdx
  %assign ::CurrentBlockFcnIdx = blkFcnIdx
  %assert ::CurrentModuleIdx == moduleIdx
  %assign ::CurrentModuleIdx = moduleIdx
  %assert ::CurrentFunctionIdx == fcnIdx
  %assign ::CurrentFunctionIdx = fcnIdx
  %with ::CompiledModel
    %assign system = System[sysIdx]
    %with system
      %assign block = Block[blkIdx]
      %assert block.Type != "Opaque"
      %assert block.BlockIdx[0] == sysIdx
      %assert block.BlockIdx[2] == blkIdx
      %with block
        %openfile buff
        %<GENERATE(block, blkFcn, system, oidx, ridx)> /
        %closefile buff
        %if WHITE_SPACE(buff)
          %assign buff = ""
        %endif
      %endwith %% block
    %endwith %% system
  %endwith %% ::CompiledModel
  %assign ::CurrentModuleIdx = prevModuleIdx
  %assign ::CurrentFunctionIdx = prevFunctionIdx
  %assign ::CurrentBlockFcnIdx = prevBlockFcnIdx
  %return buff
%endfunction
 
%function SLibCG_DumpSSCode(openComment, ssBody, closeComment) void
  %if WHITE_SPACE(ssBody)
    %return ""
  %else
    %if TYPE(ssBody) == "String"
      %return openComment + ssBody + closeComment
    %else
      %return openComment + "%<ssBody>" + closeComment
    %endif
  %endif
%endfunction
 
%function SLibOpaqueDumpSystemSSVars(sysIdx, blkFcn) Output
  %<LibDumpSystemSSVars(::CompiledModel.System[sysIdx],blkFcn)>/
%endfunction
   
%function FcnRootOpaqueBlock() void
  %assign rootSystem = ::CompiledModel.System[::CompiledModel.NumSystems-1]
  %assign rootOpaqueBlock = rootSystem.Block[rootSystem.NumBlocks-1]
  %return rootOpaqueBlock
%endfunction
 
%%FunctionFcnSysModuleIsRateGrouping(system,sysFcnType)==================
%%Abstract:
%%Returntrueifthesystemmodulegeneratesrategroupingcode.
%%Ifamodulegeneratesrategroupingcode,baseTidOfTasksiswrittenout.
%%Thisisaarrayforallbasetidforeachtaskinthemodule.
%%
%function FcnSysModuleIsRateGrouping(system, sysFcnType)
  %if SLibSystemFcnIsRateGroupType(sysFcnType)
    %assign moduleIdx = system.CGIRModuleIdx
    %assign moduleRec = ::CompiledModel.RTWCGModules.RTWCGModule[moduleIdx]
    %return moduleRec.RateGrouping
  %else
    %return TLC_FALSE
  %endif
%endfunction
 
%%FunctionFcnSysModuleIsPeriodicRateGrouping(system,sysFcnType)===========
%%Abstract:
%%Returntrueifthesystemmodulegeneratesrategroupingcodefor
%%thesynchronousrates
%%
%function FcnSysModuleIsPeriodicRateGrouping(system, sysFcnType)
  %if SLibSystemFcnIsRateGroupType(sysFcnType)
    %assign moduleIdx = system.CGIRModuleIdx
    %assign moduleRec = ::CompiledModel.RTWCGModules.RTWCGModule[moduleIdx]
    %return moduleRec.PeriodicRateGrouping
  %else
    %return TLC_FALSE
  %endif
%endfunction
 
%%FunctionFcnSysModuleBaseTidOfTasks(system)===========================
%%Abstract:
%%ReturnthebaseTidOfTasksofthesystemmodule
%%
%function FcnSysModuleBaseTidOfTasks(system)
  %assign moduleIdx = system.CGIRModuleIdx
  %assign moduleRec = ::CompiledModel.RTWCGModules.RTWCGModule[moduleIdx]
  %return %<moduleRec.RTWFcnConst.baseTidOfTasks>
%endfunction
 
%function RTWCGBlockExecuteAsyncEntryFcn(callIdx, tidVal)
 %% %if ::CompiledModel.SampleTime[tidVal].IsVirtualTs == "yes"
 %% %return ""
 %% %endif
  %if CodeFormat == "S-Function"
    %assign simStr = SLibGetSimStruct()
    %assign retStr = "%<::CompiledModel.Name>_ASYNC%<tidVal>(%<simStr>, %<callIdx>,%<LibTID()>);"
    %assign protoType = "void %<::CompiledModel.Name>_ASYNC%<tidVal>(%<::tSimStructType>* %<simStr>, int %<::tControlPortIdx>, int %<::tTID>)"
  %else
    %assign retStr = "%<::CompiledModel.Name>_ASYNC%<tidVal>(%<callIdx>);"
    %assign protoType = "void %<::CompiledModel.Name>_ASYNC%<tidVal>(int %<::tControlPortIdx>)"
  %endif
  %if !ISFIELD(SampleTime[tidVal], "TaskEntryFcnProtoType")
    %addtorecord SampleTime[tidVal] TaskEntryFcnProtoType protoType
  %endif
  %assert SampleTime[tidVal].TaskEntryFcnProtoType == protoType
  %return retStr
%endfunction
 
%%Function:SLibGetAsyncSysCodeForTaskTopBlk======================================================
%%Abstract:
%%Gobacktothes-functioninitiatingthisasynctaskand
%%callalldownstreamfunction-callsubsystemsandModelblocks.
%function SLibGetAsyncSysCodeForTaskTopBlk(taskTopBlk, tid, blockType, sysIdx) void
  %% It is more robust Async sys code
  %% to call async code from fcn-call initiator. Need find out
  %% the callIdx conresponding to this subsystem.
  %openfile retBuf
  %if !ISFIELD(SampleTime[tid], "DumpedAsyncOutputCode")
    %assign foundExpCalledFC = TLC_FALSE
    %% Go over each output function-call signal
    %foreach callIdx = taskTopBlk.NumSFcnSysOutputCalls
      %% Jump out of for-loop if expected called block has been found
      %if foundExpCalledFC
        %break
      %endif
       
      %assign startingIdx = taskTopBlk.SFcnSystemOutputCallMappingInfo[callIdx].StartingIdx
      %assign nCalledFC = taskTopBlk.SFcnSystemOutputCallMappingInfo[callIdx].NumOfCalledFC
       
      %foreach fcIdx = nCalledFC
        %assign recIdx = startingIdx + fcIdx
         
        %% Get the first block called by the element
        %assign fcnCallBlkIdx = taskTopBlk.SFcnSystemOutputCall[recIdx].BlockToCall
        %if ISEQUAL(fcnCallBlkIdx, "unconnected")
          %continue
        %endif
        %assign fcnCallBlk = System[fcnCallBlkIdx[0]].Block[fcnCallBlkIdx[1]]
        %assign fcnCallPort = taskTopBlk.SFcnSystemOutputCall[recIdx].FcnPortIdx
         
        %% For a fcn-call subsystem, we only need the systemIdx to determine if
        %% this is the right subsystem, but for a Model block, we need the full
        %% System, Block and Port indexes.
        %assign makeCall = TLC_FALSE
        %if (fcnCallBlk.Type == blockType)
          %switch blockType
            %case "SubSystem"
              %assert SIZE(sysIdx,1) == 1
              %assign makeCall = (sysIdx == fcnCallBlk.CallSiteInfo.SystemIdx)
              %break
               
            %case "ModelReference"
              %% For model reference, sysIdx will have this form:
              %%
              %% [%<sysIdx>, %<blkIdx>, %<portIdx>]
              %%
              %% See SLibCallModelBlockFcnCallInput in modelrefutil.tlc
              %assert SIZE(sysIdx,1) == 3
              %assign makeCall = (sysIdx[0] == fcnCallBlkIdx[0]) && ...
                (sysIdx[1] == fcnCallBlkIdx[1]) && (sysIdx[2] == fcnCallPort)
              %break
               
            %default
              %assert 0
              %break
          %endswitch
        %endif
        %if makeCall
          %<LibBlockExecuteFcnCall(taskTopBlk, callIdx)>/
          %assign foundExpCalledFC = TLC_TRUE %% found expected called block
          %break
        %endif
      %endforeach %% foreach fcIdx = nCalledFC
    %endforeach %% foreach callIdx = taskTopBlk.NumSFcnSysOutputCalls
    %addtorecord SampleTime[tid] DumpedAsyncOutputCode TLC_TRUE
  %endif
  %closefile retBuf
  %return retBuf
%endfunction
   
%%Function:OpaqueTLCBlockGetAsyncSysCode=========================================================
%%Abstract:
%%Thisfunctioniscalledbytheasyncsfcnblock.Thefunction
%%getsasyncodeforcalledasyncsubsystem.
%%
%function OpaqueTLCBlockGetAsyncSysCode(aFcnName, aArgVec, aSysIdx, aFcnType, tid) void
  %assert LibAsynchronousTriggeredTID(tid)
  %assign taskTopBlk = FcnGetTaskTopSfcnBlock(tid)
  %assign thisSystem = ::CompiledModel.System[aSysIdx]
  %assign sysTid = LibGetSubsystemTID(thisSystem, TLC_TRUE)
  %assign fcnTypeName = SLibCGIRGetFcnTypeName(aFcnType)
  %openfile retBuf
  %if (fcnTypeName == "Output") && tid == sysTid && !WHITE_SPACE(taskTopBlk)
    %<SLibGetAsyncSysCodeForTaskTopBlk(taskTopBlk, tid, "SubSystem", aSysIdx)>
  %else
    %if LibSystemIsInlined(thisSystem)
      %assign fieldname = "Cached%<fcnTypeName>%<tid>Fcn"
      %if ISFIELD(thisSystem.InstanceCache, fieldname)
        %<LibGetSystemField(thisSystem, fieldname)>
      %endif
    %elseif FcnIsForcedInlinedForAsync(thisSystem,tid)
      %assign fieldname = "Cached%<fcnTypeName>%<tid>Fcn"
      %if ISFIELD(thisSystem.InstanceCache, fieldname)
        %openfile localVar
        %<LibGetSystemLocalVars(thisSystem,fcnTypeName,tid)>
        %<SLibGetFcnLocalVars(thisSystem,fcnTypeName,tid)>
        %closefile localVar
        %if !WHITE_SPACE(localVar)
          {
             %<localVar>
            %<LibGetSystemField(thisSystem, fieldname)>
          }
        %else
          %<LibGetSystemField(thisSystem, fieldname)>
        %endif
      %endif
    %else
      %if !LibSystemFcnIsEmptyHelper(thisSystem, fcnTypeName, tid)
        %assign modIdx = thisSystem.CGIRModuleIdx
        %assign thisModule = ::CompiledModel.RTWCGModules.RTWCGModule[modIdx]
        %if ISFIELD(thisModule, "SystemFunctions") && ...
          ISFIELD(thisModule.SystemFunctions, aFcnName)
          %assign fcnIndex = GETFIELD(thisModule.SystemFunctions, aFcnName)
          %assign thisFcn = thisModule.Function[fcnIndex]
          %foreach argIdx=thisFcn.NumArgs
            %assign idNum = SLibSafeIDNUM(thisFcn.ArgSource, argIdx)
            %assign argSrc = idNum[0]
            %if "CPI" == argSrc
              %assign aArgVec[argIdx] = ::tControlPortIdx
              %break
            %endif
          %endforeach
        %endif
        %assign fcnInfo = LibGetFcnInfo(thisSystem, fcnTypeName, tid)
        %assign addArgs = ""
        %if fcnInfo.Name == aFcnName
          %assign addArgs = FcnGetAdditionalArgs(aFcnName, aArgVec, ...
            fcnTypeName, aSysIdx, ::CompiledModel.NumSystems-1, 0, TLC_FALSE, TLC_FALSE)
        %endif
        %if !WHITE_SPACE(fcnInfo.CommonArgs) && !WHITE_SPACE(addArgs)
          %assign addArgs = ", " + addArgs
        %endif
        %<fcnInfo.Name>(%<fcnInfo.CommonArgs>%<addArgs>);
      %endif
    %endif
  %endif
  %closefile retBuf
   
  %return retBuf
%endfunction
 
%%GivenafcntypeusedinRTWFcnConst,findthecorresponding
%%BlockFcnvalue.
%function SLibGetBlockFcnForFcnType(fcnType)
 
  %switch fcnType
    %case "InitializeConditions"
      %return "Initialize"
      %%break
    %case "Outputs"
      %return "Output"
      %%break
    %case "Derivatives"
      %return "Derivative"
      %%break
    %case "ZeroCrossings"
      %return "ZeroCrossing"
      %%break
    %default
      %return fcnType
  %endswitch
 
%endfunction
 
%%FunctionFcnGenerateCodeFromModule==========================
%%Abstract:
%%
%function FcnGenerateCodeFromModule(block, system, fcnType) Output
  %if SLibSystemFcnIsRateGroupType(fcnType)
    %assign MultiTask_CodeBuffers = []
    %assign tmp_CodeBuffers = []
    %assign tmp_tid2Code = []
    %if SLibPartitionGroupingSystem(system)
      %assign numOfTasks = SLibGetNumPartitions()
    %else
      %assign numOfTasks = NumSampleTimes
    %endif
    %foreach idx = numOfTasks
      %assign MultiTask_CodeBuffers = MultiTask_CodeBuffers + ""
      %assign tmp_CodeBuffers = tmp_CodeBuffers + ""
      %assign tmp_tid2Code = tmp_tid2Code + ""
    %endforeach
    %assign moduleIdx = system.CGIRModuleIdx
    %assign moduleRec = ::CompiledModel.RTWCGModules.RTWCGModule[moduleIdx]
    %%Mark the accessed variables
    %assign accessTid = FcnGetCurrentAccessTid()
     
    %if FcnSysModuleIsRateGrouping(system, fcnType)
      %assign baseTidOfTasks = FcnSysModuleBaseTidOfTasks(system)
       
      %assign numTids = SIZE(baseTidOfTasks,1)
      %assign hasExportFcn = TLC_FALSE
      %foreach i = numTids
        %assign tid = baseTidOfTasks[i]
        %if TYPE(tid) == "Number" && tid > 0
        %assign hasNonEmptyEntryFcnName = ISFIELD(::CompiledModel.SampleTime[tid],"EntryFcnName") && ...
          !ISEMPTY(::CompiledModel.SampleTime[tid].EntryFcnName)
        %if hasNonEmptyEntryFcnName
          %assign hasExportFcn = TLC_TRUE
          %break
        %endif
        %endif
      %endforeach
      %% For partition grouping, currently deployment diagram is the only use case
      %if SLibPartitionGroupingSystem(system) && SLibSystemFcnPeriodicRateGrouping(system,fcnType)
        %assign bufIdx = 0
        %assign tidIsProcessed = []
        %foreach i = NumSampleTimes
          %assign tidIsProcessed = tidIsProcessed + TLC_FALSE
        %endforeach
         
        %% In order to make the code caching compatible for both rate grouping
        %% and partition grouping, the code should be extracted and buffered in
        %% the following order:
        %% TID 0 PID 0
        %% ...
        %% TID 0 PID n
        %% ...
        %% TID m PID 0
        %% ...
        %% TID m PID n
        %% First, we extract the code following the tid order buffered in
        %% baseTidOfTasks, which may not have the tid in increasing order.
        %% For each tid in baseTidOfTasks, we extract the code for all the
        %% pid that the corresponding partitions have the same tid.
        %% We use a map tmp_tid2code to map the buffer index to tid, so we
        %% can assemble all the codes to the order illustrated above
        %foreach i = numTids
          %if hasExportFcn
            %assign tid = baseTidOfTasks[numTids-i-1]
          %else
            %assign tid = baseTidOfTasks[i]
          %endif
          %if TYPE(tid) != "Number" || tid < 0 || tidIsProcessed[tid]
            %continue
          %endif
          %assign pidVec = SLibGetPidFromTid(tid)
          %foreach idx = SIZE(pidVec, 1)
            %assign tmp_CodeBuffers[bufIdx] = ...
              FcnGenRateGroupedCodeFromModule(block, system, fcnType, tid, pidVec[idx])
            %assign tmp_tid2Code[bufIdx] = tid
            %assign bufIdx = bufIdx + 1
          %endforeach
          %assign tidIsProcessed[tid] = TLC_TRUE
        %endforeach
       
        %assign bufIdx = 0
        %foreach tid = NumSampleTimes
          %assign hasCodeForTid = TLC_FALSE
          %foreach i = numTids
            %if baseTidOfTasks[i] == tid
              %assign hasCodeForTid = TLC_TRUE
              %break
            %endif
          %endforeach
          %if !hasCodeForTid
            %continue
          %endif
          %foreach i = SIZE(tmp_tid2Code, 1)
            %if tmp_tid2Code[i] == tid
              %assign MultiTask_CodeBuffers[bufIdx] = tmp_CodeBuffers[i]
              %assign bufIdx = bufIdx + 1
            %endif
          %endforeach
        %endforeach
      %else
        %foreach i = numTids
          %if hasExportFcn
            %% Loop over TIDs backwards for export fcn diagrams to get
            %% SLibSetModelRefCacheAsyncFcnCallInputInfo called before SLibGetRootInportsFromFile
            %% SLibGetRootInportsFromFile is called when processing TID 0 and
            %% SLibSetModelRefCacheAsyncFcnCallInputInfo is called when processing other TIDs
            %assign tid = baseTidOfTasks[numTids-i-1]
          %else
            %assign tid = baseTidOfTasks[i]
          %endif
          %assign bufIdx = ...
            (SLibSystemFcnPeriodicRateGrouping(system,fcnType) || ...
            LibAsynchronousTriggeredTID(tid)) ? tid : 0
          %assign MultiTask_CodeBuffers[bufIdx] = ...
            FcnGenRateGroupedCodeFromModule(block, system, fcnType, tid, "")
          %% Update function for explicit partitioning
          %if tid == 0 && ...
            (isRSim || Accelerator) && ...
            system.Type == "root" && fcnType == "Update"
            %openfile mdlUpdateBuf
            %% for each explictTasking TID, add a call to explicit task update
            %% functions, wrapped with TsHit
            %foreach t_idx = SIZE(baseTidOfTasks,1)
              %assign tid_num = baseTidOfTasks[t_idx]
              %assign callTidFcn = TLC_FALSE
              %assign fcnInfo = SLibSystemFcnInfoRecord(system, "Update")
              %assign fcnName = ""
              %if SLibIsExplicitPartitioningTID(tid_num)
                %if !SLibIsExplicitPartitioningSystemFcn("Update", tid_num)
                  %continue
                %endif
                %assign callTidFcn = TLC_TRUE
                %assign fcnName = SLibExplicitPartitioningSystemFcnName(fcnInfo.Name, tid_num)
              %elseif SLibIsPeriodicRateGrouping() && tid_num > 0 && ...
                SLibIsRuntimeExportedSystemFcn("Update", tid_num)
                %assign callTidFcn = TLC_TRUE
                %assign fcnName = SLibAppendTIDToSystemFcnName(fcnInfo.Name, tid_num)
              %endif
              %if callTidFcn
                %assign passThroughArgs = "void"
                %if !ISEMPTY(fcnInfo.CommonArgs)
                  %assign passThroughArgs = fcnInfo.CommonArgs
                %endif
                %assign args = "(" + passThroughArgs + ");"
                %assign stmts = fcnName + args
                if(%<LibIsSampleHit(tid_num)>) {
                  %<stmts>
                }
              %endif
            %endforeach
            %closefile mdlUpdateBuf
            %assign MultiTask_CodeBuffers[bufIdx] = MultiTask_CodeBuffers[bufIdx] + mdlUpdateBuf
          %endif
          %%
          %if tid == 0 && ...
            (isRSim || Accelerator) && ...
            system.Type == "root" && fcnType == "Outputs"
            %% we will construct the MdlOutput for
            %% export function with periodic rates
            %% see feat. ExportPeriodicFcnCall
            %openfile mdlOutputBuf
            %% for each explictTasking TID, wrap with TsHit
            %foreach t_idx = SIZE(baseTidOfTasks,1)
              %assign tid_num = baseTidOfTasks[t_idx]
              %assign callTidFcn = TLC_FALSE
              %assign fcnInfo = SLibSystemFcnInfoRecord(system, "Output")
              %assign fcnName = ""
              %if SLibExplicitTaskingTID(tid_num) && ...
                  !LibAsynchronousTriggeredTID(tid_num) && ...
                  SampleTime[tid_num].IsUnionTs != "yes"
                %assign fcnName = SampleTime[tid_num].TaskName
                %if SLibIsExplicitPartitioningTID(tid_num)
                  %if !SLibIsExplicitPartitioningSystemFcn("Outputs", tid_num)
                    %continue
                  %endif
                  %assign fcnName = SLibExplicitPartitioningSystemFcnName(fcnInfo.Name, tid_num)
                %endif
                %assign callTidFcn = TLC_TRUE
              %elseif SLibIsPeriodicRateGrouping() && tid_num > 0 && ...
                SLibIsRuntimeExportedSystemFcn("Outputs", tid_num)
                %assign callTidFcn = TLC_TRUE
                %assign fcnName = SLibAppendTIDToSystemFcnName(fcnInfo.Name, tid_num)
              %endif
              %if callTidFcn
                %assign passThroughArgs = "void"
                %if !ISEMPTY(fcnInfo.CommonArgs)
                  %assign passThroughArgs = fcnInfo.CommonArgs
                %endif
                %assign args = "(" + passThroughArgs + ");"
                %assign stmts = fcnName + args
                %if isRSim && SLibExplicitTaskingTID(tid_num)
                  if(%<LibIsSampleHit(tid_num)> && enableFcnCallFlag[%<tid_num>]) {
                %else
                    if(%<LibIsSampleHit(tid_num)>) {
                %endif
                    %<stmts>
                  }
              %endif
            %endforeach
            %closefile mdlOutputBuf
            %assign MultiTask_CodeBuffers[bufIdx] = MultiTask_CodeBuffers[bufIdx] + mdlOutputBuf
          %endif
          %%
          %% cache the correct prototype in header
          %assign hasNonEmptyTaskName = TYPE(tid) == "Number" && tid >= 0 && ...
            ISFIELD(SampleTime[tid],"TaskName") && !ISEMPTY(SampleTime[tid].TaskName)
          %assign hasNonEmptyEntryFcnName = TYPE(tid) == "Number" && tid >= 0 && ...
            ISFIELD(SampleTime[tid],"EntryFcnName") && !ISEMPTY(SampleTime[tid].EntryFcnName)
          %assign accelAndHasNonEmptyEntryFcnName = hasNonEmptyEntryFcnName && (Accelerator||::isRAccel) && SampleTime[tid].IsUnionTs != "yes"
          %assign accelRateGroupedTid = (Accelerator||::isRAccel) && ...
            SLibIsPeriodicRateGrouping() && TYPE(tid) == "Number" && tid > 0 && ...
            !SLibIsExportFcnDiagram() && tid < NumRuntimeExportedRates
          %if system.Type == "root" && fcnType == "Outputs" && ...
            ((SLibExplicitTaskingTID(tid) && ...
             (accelAndHasNonEmptyEntryFcnName)) || accelRateGroupedTid)
            %assign addExportDefs = TLC_FALSE
            %assign fcnInfo = SLibSystemFcnInfoRecord(system, "Output")
            %if SLibExplicitTaskingTID(tid) && ...
              (((SampleTime[tid].TaskName == fcnInfo.Name) || hasNonEmptyEntryFcnName) && ...
              !ISEMPTY(fcnInfo.FcnPrototype) && !SLibAutosarActive() && ...
              !SLibModelWideEventTID(tid))
                %assign addExportDefs = TLC_TRUE
            %elseif accelRateGroupedTid && !ISEMPTY(fcnInfo.FcnPrototype)
              %assign addExportDefs = TLC_TRUE
            %endif
            %if addExportDefs
              %% Reusable export function diagram will be cached after the output function arguments
              %% are determined.
              %if !SLibIsReusableExportFcn() && !GenerateClassInterface
                %openfile entryPointBuf
                 
                /* Exported entry point function */
                %<SLibGetFcnMemSecPragmaForSystemOnDecl(fcnInfo.Name, "MemSecFuncExecute", "Pre", system)>/
                %<LibExternInFcnDecls()>%<fcnInfo.FcnPrototype>;
                %<SLibGetFcnMemSecPragmaForSystemOnDecl(fcnInfo.Name, "MemSecFuncExecute", "Post", system)>/
                   
                %closefile entryPointBuf
                %<SLibCacheSystemCodeToFile("sys_fcn_decl", system, entryPointBuf)>
              %endif
            %endif
          %endif
          %if system.Type == "root" && fcnType == "Update" && accelRateGroupedTid
            %assign addExportDefs = TLC_FALSE
            %assign fcnInfo = SLibSystemFcnInfoRecord(system, "Update")
            %if accelRateGroupedTid && !ISEMPTY(fcnInfo.FcnPrototype)
              %assign addExportDefs = TLC_TRUE
            %endif
            %if addExportDefs
              %openfile entryPointBuf
               
              /* Exported entry point functions */
              %if !GenerateClassInterface
                %<SLibGetFcnMemSecPragmaForSystemOnDecl(fcnInfo.Name, "MemSecFuncExecute", "Pre", system)>/
              %endif
              %<LibExternInFcnDecls()>%<fcnInfo.FcnPrototype>;
              %if !GenerateClassInterface
                %<SLibGetFcnMemSecPragmaForSystemOnDecl(fcnInfo.Name, "MemSecFuncExecute", "Post", system)>/
              %endif
                 
              %closefile entryPointBuf
              %<SLibCacheSystemCodeToFile("sys_fcn_decl", system, entryPointBuf)>
            %endif
          %endif
        %endforeach
      %endif
    %else
      %assign bufIdx = FcnGetSubsystemCodeBufTID(system)
      %assign MultiTask_CodeBuffers[bufIdx] = ...
        FcnGenRateGroupedCodeFromModule(block, system, fcnType, "", "")
    %endif
    %assign tid01Eq = ISEQUAL(SolverType, "FixedStep") && FixedStepOpts.TID01EQ
    %if tid01Eq && !SLibPartitionGroupingSystem(system)
      %assign localFcnType = (fcnType == "Outputs") ? "Output" : fcnType
      %%
      %if LibIsSystemField(system, "Cached%<localFcnType>0LocalVars")
        %%
        %% combine buffer for tid0 and tid1
        %%
        %assert WHITE_SPACE(MultiTask_CodeBuffers[0]) || ...
          WHITE_SPACE(MultiTask_CodeBuffers[1])
        %%
        %assign localsForTID0 = ...
          LibGetSystemField(system, "Cached%<localFcnType>0LocalVars")
        %assign localsForTID1 = ...
          LibGetSystemField(system, "Cached%<localFcnType>1LocalVars")
        %<LibSetSystemField(system, "Cached%<localFcnType>1LocalVars", "")>
        %assert ISEMPTY(localsForTID0) || ISEMPTY(localsForTID1)
        %if ISEMPTY(localsForTID0)
          %<LibSetSystemField(system, "Cached%<localFcnType>0LocalVars", ...
            localsForTID1)>
        %endif
      %endif
      %assign MultiTask_CodeBuffers[0] = ...
        MultiTask_CodeBuffers[0] + MultiTask_CodeBuffers[1]
      %assign MultiTask_CodeBuffers[1] = ""
    %endif
    %return MultiTask_CodeBuffers
  %else
    %return FcnGenRateGroupedCodeFromModule(block, system, fcnType, "", "")
  %endif
%endfunction
 
%function RTWFcnHasArgTid(fcnRec)
  %return ISFIELD(fcnRec, "HasTidArg") && fcnRec.HasTidArg
%endfunction
 
%function RTWFcnHasArgCpi(fcnRec)
  %return ISFIELD(fcnRec, "HasCpiArg") && fcnRec.HasCpiArg
%endfunction
 
%function SLibCGGenSystemFcn(system)
  %if LibSystemIsReusedFcn(system) || ...
    system.SystemIdx == NumSystems-1 ||...
      IsModelReferenceBaseSys(system)
    %% LibSystemIsReusedFcn(system) : call site code is generate in TLC
    %% root system does not have call site code
    %% mdlRef base system generates call site call in TLC
    %% do nothing when call site code is generate in TLC.
    %% TLC tracks usage of tid.
    %return TLC_FALSE
  %else
    %return TLC_TRUE
  %endif
%endfunction
   
 
%%Currentlyparitiongroupingisasubsetofrategrouping,sowereuseand
%%extendthetlcinfrastructuretosupportpartitiongrouping
%function FcnGenRateGroupedCodeFromModule(block, system, fcnType, tid, pid) Output
  %assign retBuf = ""
  %assign genRateGroupedCode = (TYPE(tid) == "Number")
  %assign moduleIdx = system.CGIRModuleIdx
  %assign moduleRec = ::CompiledModel.RTWCGModules.RTWCGModule[moduleIdx]
  %if moduleRec.CGSystemIdx == system.SystemIdx
    %assign ::activeSysIdx = system.SystemIdx
    %assign fcnConst = "%<fcnType>_Function"
    %if genRateGroupedCode
      %if TYPE(pid) == "Number"
        %assign fcnConst = "%<fcnConst>TID%<tid>PID%<pid>"
      %else
      %assign fcnConst = "%<fcnConst>TID%<tid>"
      %endif
      %assign system.CurrentTID = tid
    %elseif LibIsSingleRateSystem(system)
      %assign system.CurrentTID = LibGetSubsystemTID(system,TLC_TRUE)
    %else
      %% If we are not generating rate grouped code, it doesn't really
      %% matter what the tid is, but we need to pass something as an
      %% empty string will cause us to drop arguments when calling
      %% S-functions and possibly other bad stuff
      %assign tmpTid = LibGetSubsystemTID(system,TLC_FALSE)
      %assign system.CurrentTID = tmpTid[0]
    %endif
     
    %%
    %openfile retBuf
    %if ISFIELD(moduleRec.RTWFcnConst, fcnConst)
      %assign functionRec = moduleRec.RTWFcnConst.%<fcnConst>
      %assign genType = "Module%<moduleIdx>::%<fcnType>"
      %assign filePath = functionRec.TLCFileName
      %generatefile "%<genType>" "%<filePath>"
      %openfile tmpBuf
      %assign prevModIdx = ::CurrentModuleIdx
      %assert -1 == ::CurrentFunctionIdx
      %assign prevFcnIdx = ::CurrentFunctionIdx
      %assert ::CurrentModuleIdx == moduleIdx
      %assign ::CurrentModuleIdx = moduleIdx
      %if genRateGroupedCode
        %assign ::CurrentFunctionIdx = TYPE(pid) == "Number" ? ...
          GETFIELD(moduleRec.SystemFunctionTypes, fcnType + "_TID%<tid>PID%<pid>") : ...
          GETFIELD(moduleRec.SystemFunctionTypes, fcnType + "_TID%<tid>")
        %if SLibCustomCodeNeedsTID(system, fcnType, tid)
          %<SLibCG_AccessFcnTID(::CurrentModuleIdx, ::CurrentFunctionIdx)>
        %endif
        %if TYPE(pid) == "Number"
          %<GENERATE_TYPE(block, fcnType + "ForPID", filePath, system, tid, pid)>
        %else
          %<GENERATE_TYPE(block, fcnType + "ForTID", filePath, system, tid)>
        %endif
      %else
        %if ISFIELD(moduleRec, "SystemFunctionTypes")
        %assign ::CurrentFunctionIdx = ...
          GETFIELD(moduleRec.SystemFunctionTypes, fcnType)
        %if SLibCustomCodeNeedsTID(system, fcnType, tid)
          %<SLibCG_AccessFcnTID(::CurrentModuleIdx, ::CurrentFunctionIdx)>
        %endif
        %<GENERATE_TYPE(block, fcnType, filePath, system)>
        %endif
      %endif
      %closefile tmpBuf
      %%
      %<HandleNonReusedWithinReused(::CurrentModuleIdx, ::CurrentFunctionIdx, ...
        system, fcnType)>
      %%
      %if (NumContStates > 0 || isGRTMallocOnERT()) && ...
        system.Type == "root" && fcnType == "Outputs" &&...
        (!genRateGroupedCode || ISEQUAL(tid,0))
        %<SLibAccessArgHelper(system.Interface.RTMArgDef,"",tid)>
      %endif
      %if SLibCGGenSystemFcn(system)
        %if RTWFcnHasArgCpi(functionRec)
          %% IR code need cpi. Info TLC that tid is required.
          %%
          %% Since tid can always hard code for rate grouped code
          %% RTWFcn should need has tid arg if it is rate grouping.
          %<LibNeedCPI(system)>
        %endif
        %if RTWFcnHasArgTid(functionRec)
          %% Since tid can always hard code for rate grouped code
          %% RTWFcn should not have tid arg if it is rate grouping.
        %elseif FcnSysAccessedTID() && SLibSystemFcnTypeMayUseTid(fcnType)
          %assign ::CompiledModel.NeedTID = TLC_FALSE %% reset NeedTid flag
          %% code that is not in IR needs tid. Add local tid variable.
          %<SLibSetNeedLocalTIDInSystem(system, fcnType)>
        %endif
      %endif
      %assign genTimeManagementCode = TLC_FALSE
      %if FcnSubsystemIsAsycnTopSS(system)
        %assign sysTid = LibGetSubsystemTID(system, TLC_TRUE)
        %% Start and Terminate do NOT generate time management code
        %% g1360318
        %assign genTimeManagementCode = !SLibAsyncSampleTimeGeneratesTimeManagementCode(sysTid) && ...
          fcnType != "Start" && fcnType != "Terminate" && fcnType != "SetupRuntimeResources" && ...
          fcnType != "CleanupRuntimeResources"
      %elseif (system.Type == "root")
        %assign sysTid = tid
        %assign genTimeManagementCode = LibAsynchronousTriggeredTID(sysTid) && ...
          SLibAsyncSampleTimeGeneratesTimeManagementCode(sysTid)
      %elseif SLibIsExplicitTaskingExportFcnRateGrouping("Output", tid)
        %% Async doesn't use global time engine. Currently,
        %% TimeBridge doesn't support async yet. If an async need
        %% absolute time in a model block, the async must run
        %% periodically, so that async can use local timer.
        %assign sysTid = tid
        %assign genTimeManagementCode = TLC_TRUE
      %endif
      %if genTimeManagementCode
        %<FcnGenerateTimeManagementForAsyncTs(fcnType, sysTid,"top")>
        %<tmpBuf>
        %<FcnGenerateTimeManagementForAsyncTs(fcnType, sysTid,"bottom")>
      %else
        %<tmpBuf>
      %endif
      %assign rtmArgSys = ::CompiledModel.System[::CompiledModel.System[::CompiledModel.RTWCGModules.RTWCGModule[0].CGSystemIdx].NonInlinedParentSystemIdx]
      %if (IsModelReferenceBaseSys(rtmArgSys) && (IsModelRefScalableBuild() || GenerateClassInterface)) ||...
        (GenerateClassInterface && SLibIsMultiInstanceServer(rtmArgSys))
        %<SLibCG_UndoAccessRTM()> %% unset RTM tracking if it is accessed globally or from class scope. This avoids an extra argument in prototype
      %endif
      %if genRateGroupedCode
        %if TYPE(pid) == "Number"
          %assign unused = GENERATE_TYPE(block, fcnType + "FcnProtoTypeForPID", ...
            filePath, system, tid, pid)
        %else
        %assign unused = GENERATE_TYPE(block, fcnType + "FcnProtoTypeForTID", ...
          filePath, system,tid)
        %endif
      %else
        %assign unused = GENERATE_TYPE(block, fcnType + "FcnProtoType", ...
          filePath, system)
      %endif
      %assign unused = UNLOAD_GENERATE_TYPE(block, filePath)
      %assign ::CurrentModuleIdx = prevModIdx
      %assign ::CurrentFunctionIdx = prevFcnIdx
    %endif
    %closefile retBuf
  %endif
  %return retBuf
   
%endfunction
 
%%Function:SLibCGSysFcnIsEmptyForTid=============================================================
%%Abstract:
%%RTWCGcallsthisfunctionbeforegenerate
%%callsitecodeforasubsystemfunction.Whenfunctionsreturnstrue,function
%%bodyisemptyandiselimiatedinTLC.Nocallsitecodeshouldbegenerated.
%%
%function SLibCGSysFcnIsEmptyForTid(system, fcn, callerTid)
  
  %if SLibSystemFcnPeriodicRateGrouping(system, fcn)
    %assign calleeTid = LibGetSubsystemTID(system,TLC_FALSE)
    %if TYPE(calleeTid) != "Vector" && LibAsynchronousTriggeredTID(calleeTid)
      %assign tid = calleeTid
    %else
      %assign tid = callerTid
    %endif
    %assign isEmpty = LibSystemFcnIsEmptyHelper(system, fcn, tid)
  %else
    %assign tmpTid = SLibSystemTidUsedByRateGroup(system, fcn)
    %if !ISEMPTY(tmpTid)
      %assign isEmpty = LibSystemFcnIsEmptyHelper(system, fcn, tmpTid)
    %else
      %assign isEmpty = LibSystemFcnIsEmpty(system, fcn)
    %endif
  %endif
   
  %return isEmpty
%endfunction
 
%%Function:SLibInsertUtility=====================================================================
%%Abstract:
%%RegistersautilityfunctiontobeprocessedbytheTLCprogram.
%%
%function SLibInsertUtility(fcnName) void
  %assert !ISFIELD(::CompiledModel.SharedFunctions, fcnName)
  %addtorecord ::CompiledModel.SharedFunctions %<fcnName> 1
  %<SETFIELD(FixPtUtils, fcnName, 1)>
%endfunction
 
%%Function:SLibLookupUtility=====================================================================
%%Abstract:
%%ReturnsTLC_TRUEforautilityfunctionnamethathasbeenprocressedby
%%theTLCprogramalreadyandTLC_FALSEotherwise.
%%
%function SLibLookupUtility(fcnName) void
  %if ISFIELD(FixPtUtils, fcnName)
    %%
    %% Return true since the shared function has already been registered as
    %% a fix-point utility before.
    %%
    %if !ISFIELD(::CompiledModel.SharedFunctions, fcnName)
      %<SLibInsertUtility(fcnName)>
    %endif
    %return TLC_TRUE
  %else
    %%
    %% The utility function will be handled as a regular shared function,
    %% if it is not a fixpoint utility function that has been registered
    %% already.
    %%
    %if ISFIELD(::CompiledModel.SharedFunctions, fcnName)
      %return TLC_TRUE
    %else
      %return TLC_FALSE
    %endif
  %endif
%endfunction
 
%%Function:SLibLookupUtilityDecl=================================================================
%%Abstract:
%%ReturnsTLC_TRUEforautilityfunctiondeclarationthathasbeen
%%registeredwiththeTLCprogramalreadyandTLC_FALSEotherwise.
%%
%function SLibLookupUtilityDecl(fcnName) void
  %return ISFIELD(::CompiledModel.SharedFunctionDecls, fcnName)
%endfunction
 
%%Function:SLibInsertUtilityDecl=================================================================
%%Abstract:
%%RegistersautilityfunctiondeclarationwiththeTLCprogram.
%%
%function SLibInsertUtilityDecl(fcnName) void
  %assert !ISFIELD(::CompiledModel.SharedFunctionDecls, fcnName)
  %addtorecord ::CompiledModel.SharedFunctionDecls %<fcnName> 1
%endfunction
 
%%FunctionSLibBeginDSMVariant================================================
%function SLibBeginDSMVariant(dwIdx) Output
  %assign dw = ::CompiledModel.DWorks.DWork[dwIdx]
  %assign condition = dw.DSMVariantCondition
  %if !ISEMPTY(condition)
    #if %<condition>
  %endif
%endfunction
 
%%FunctionSLibEndDSMVariant================================================
%function SLibEndDSMVariant(dwIdx) Output
  %assign dw = ::CompiledModel.DWorks.DWork[dwIdx]
  %assign condition = dw.DSMVariantCondition
  %if !ISEMPTY(condition)
    #endif /* %<condition> */
  %endif
%endfunction
 
%%FunctionSLibStartMdlRefGlobalDSM===========================================
%%Abstract:
%%GeneratecodetoinitializeaglobalDSMforthecaseofmdlrefsim
%function SLibStartMdlRefGlobalDSM(DataStoreName, DataStoreDataType, ModelIndex, DWorkIdx, SharedLocalDSMInfo) void
  %assign simS = RTMGet("MdlRefSfcnS")
  %assign dsmVar = "%<::CompiledModel.Name>_DSM[%<ModelIndex>]"
 
  %openfile buffer
 
  if (slIsRapidAcceleratorSimulating()) {
    %assign dworkRec = ::CompiledModel.DWorks.DWork[DWorkIdx]
    %if dworkRec.GlobalDSM
      %<dsmVar> = &(%<DataStoreName>);
    %else
      %assign baseSystemIdx = GetBaseSystemIdx()
      %assign dsmValue = FcnGetDWorkIdentifier(dworkRec, baseSystemIdx)
      %assign dsmAddress = "&(" + dsmValue + ")"
      %<dsmVar> = %<dsmAddress>;
    %endif
  } else {
    ssGetSFcnGlobalDataStoreNameAddrIdx(%<simS>, "%<DataStoreName>", ...
      "%<DataStoreDataType>", &(%<dsmVar>),...
      &(%<::CompiledModel.Name>_DSMIdx[%<ModelIndex>]), "%<SharedLocalDSMInfo>");
  }
 
  %closefile buffer
  %return buffer
%endfunction
 
%%FunctionSLibRegisterDSMAccess======================================
%%Abstract:
%%GeneratecodetoregisteraccessingaDSM
%function SLibRegisterDSMAccess(simS, dsmIdx, readWrite, blockPath, idx, idxWidth) Output
  %assign accessIdx = idx
  %if ISEMPTY(idx)
    %if idxWidth == 0
      ss%<readWrite>DataStoreWithPath(%<simS>, ...
        %<dsmIdx>, ...
        "%<blockPath>", ...
        NULL);
    %else
      ss%<readWrite>DataStoreRegionWithPath(%<simS>, ...
        %<dsmIdx>, ...
        "%<blockPath>", ...
        NULL, ...
        NULL);
    %endif
  %else
      ss%<readWrite>DataStoreElementWithPath(%<simS>, ...
        %<dsmIdx>, ...
        "%<blockPath>", ...
        NULL, ...
        %<accessIdx>);
  %endif
%endfunction
 
%%FunctionSLibRegisterReadLocalDSM======================================
%%Abstract:
%%GeneratecodetoregisterreadingalocalDSM
%function SLibRegisterReadLocalDSM(dataStoreSource, blockPath, idx, idxWidth) Output
  %assert Accelerator
  %assign simS = "S"
  %assign dsmIdx = dataStoreSource
  %<SLibCG_AccessRTM()>
  %<SLibRegisterDSMAccess(simS, dsmIdx, "ReadFrom", blockPath, idx, idxWidth)>
%endfunction
 
%%FunctionSLibRegisterWriteLocalDSM=====================================
%%Abstract:
%%GeneratecodetoregisterwritingtoalocalDSM
%function SLibRegisterWriteLocalDSM(dataStoreSource, blockPath, idx, idxWidth) Output
  %assert Accelerator
  %assign simS = "S"
  %assign dsmIdx = dataStoreSource
  %<SLibCG_AccessRTM()>
  %<SLibRegisterDSMAccess(simS, dsmIdx, "WriteTo", blockPath, idx, idxWidth)>
%endfunction
 
%%FunctionSLibRegisterReadGlobalDSM======================================
%%Abstract:
%%GeneratecodetoregisterreadingaglobalDSM
%function SLibRegisterReadGlobalDSM(dataStoreSource, blockPath, idx, idxWidth) Output
  %if Accelerator
    %<SLibCG_AccessRTM()>
    %assign simS = "S"
    %assign dsmIdx = dataStoreSource
  %else
    %assign simS = RTMGet("MdlRefSfcnS")
    %assign dsmIdx = "%<::CompiledModel.Name>_DSMIdx[%<dataStoreSource>]"
  %endif
  %<SLibRegisterDSMAccess(simS, dsmIdx, "ReadFrom", blockPath, idx, idxWidth)>
%endfunction
 
%%FunctionSLibRegisterWriteGlobalDSM=====================================
%%Abstract:
%%GeneratecodetoregisterwritingtoaglobalDSM
%function SLibRegisterWriteGlobalDSM(dataStoreSource, blockPath, idx, idxWidth) Output
  %if Accelerator
    %<SLibCG_AccessRTM()>
    %assign simS = "S"
    %assign dsmIdx = dataStoreSource
  %else
    %assign simS = RTMGet("MdlRefSfcnS")
    %assign dsmIdx = "%<::CompiledModel.Name>_DSMIdx[%<dataStoreSource>]"
  %endif
  %<SLibRegisterDSMAccess(simS, dsmIdx, "WriteTo", blockPath, idx, idxWidth)>
%endfunction
 
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%%FunctionshandleVarGroupandcgType%%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
 
%%FunctionSLibGetDataRecForVarGroupMember====================================
%%Abstract:
%%Returntherecordassociatedwiththedata
%%ofamemberinvargroup.
%%
%%+root
%%|data
%%|----+subSysNode1
%%||data1
%%||---+reusableSys11
%%||data11
%%||---+subsystem12
%%|data12
%%|----+reusableSysNode2
%%|data21
%%|----+subSysNode3
%%data31
%%
%%Theorderofdatainvargroupsissordedbyhstructureasfollowing
%%data
%%data1
%%data12
%%data31
%%NestStrcutForreusableSys11
%%NestStrcutForreusableSys2
%%
%%Dwork,blockIOandConstBlkIOusethesameorder.
%%
%%ContStates,ContStatesDisabled,ContStatesDerivativeand
%%ZCEvent,ZCSignalusedifferentorder,whichis:
%%data
%%data1
%%NestStrcutForreusableSys11
%%data12
%%NestStrcutForreusableSys2
%%data31
%%
%%Sincevargroupdoesn'tsupportthisorderingyet.Wecan'tuse
%%vargrouptogeneratedefforthesedatas.
%%RTWCGshouldcreatevargroupusingaboveorderfor
%%ContStates,ContStatesDisabled,ContStatesDerivativeand
%%ZCEvent,ZCSignal.byu
%%
%function SLibGetDataRecForVarGroupMember(recType, recIdx) void
  %assert recIdx >= 0
  %switch recType
    %case "W"
    %case "LDW"
      %return DWorks.DWork[recIdx]
      %%break
    %case "P"
      %return ModelParameters.Parameter[recIdx]
    %case "ZE"
      %assign blkIdx = ::ZcRecMap[recIdx * 2]
      %assign sigIdx = ::ZcRecMap[recIdx * 2 + 1]
      %return ZcRec.BlkZcRec[blkIdx].ZcSignalInfo[sigIdx]
    %case "B"
      %return BlockOutputs.GlobalBlockOutput[recIdx]
      %%break
    %case "C"
      %return BlockOutputs.ConstBlockOutput[recIdx]
      %%break
    %case "L"
      %return BlockOutputs.LocalBlockOutput[recIdx]
      %%break
    %case "U"
      %return ExternalInputs.ExternalInput[recIdx]
    %case "Y"
      %return ExternalOutputs.ExternalOutput[recIdx]
    %case "S" %% StackVar
    %case "UB" %% UnusedBits
    %case "VG" %% VarGroup
    %case "PD" %% padd element
    %default
      %% self/rtM vargroup references can trigger this
  %endswitch
  %return ""
%endfunction
 
%%FunctionSLibGetCommentForVarGroupMember====================================
%%Abstract:
%%Returnthecommentassociatedwiththedataofamemberinvargroup.
%%
%function SLibGetCommentForVarGroupMember(recType, recIdx) void
  %assert recIdx >= 0
  %assign comment = ""
  %switch recType
    %case "P"
      %assign prm = ::CompiledModel.ModelParameters.Parameter[recIdx]
      %assign comment = SLibGenModelPrmDefnComment(prm)
      %if !WHITE_SPACE(comment)
        %assign comment = "/* " + comment + " */"
      %endif
  %endswitch
  %return comment
%endfunction
 
%function SLibVarGroupTypeNameForRecordType(recType) void
  %switch recType
    %case "W"
      %return "DWork"
      %%break
    %case "B"
      %return "BlockIO"
      %%break
    %case "C"
      %return "ConstBlockIO"
      %%break
    %case "P"
      %return "Parameter"
      %%break
    %case "ZE"
      %return "ZCEvent"
      %%break
    %case "U"
    %case "Y"
      %return "RootIO"
    %case "S" %% StackVar
    %case "UB" %% UnusedBits
    %case "VG" %% VarGroup
    %case "PD" %% padd element
    %case "L" %% local block output converted to global
    %case "LDW" %% local scratch dwork converted to global
      %break
    %default
      %% self/rtM vargroup references can end up here
  %endswitch
  %return ""
%endfunction
 
%function SLibGetTypeNameFromCGType(cgTypeIdx) void
  %assign cgType = ::CompiledModel.CGTypes.CGType[cgTypeIdx]
  %assign typeName = ""
  %if LibCGTypeIsOpaqueStruct(cgTypeIdx)
    %assign typeTag = LibCGTypeTag(cgTypeIdx)
    %assert !WHITE_SPACE(typeTag)
    %assign typeName = "struct " + typeTag
  %elseif ISFIELD(cgType, "Name")
    %assign typeName = cgType.Name
  %elseif LibCGTypeIsStdContainer(cgTypeIdx)
    %assign typeName = LibCGTypeStdContainerName(cgTypeIdx)
  %else
    %assign typeName = SLibGetTypeNameFromCGType(LibCGTypeBaseIndex(cgTypeIdx))
    %if LibCGTypeIsPointer(cgTypeIdx)
      %assign typeName = typeName + "*"
    %elseif LibCGTypeIsReference(cgTypeIdx)
      %assign typeName = typeName + "&"
    %elseif LibCGTypeIsString(cgTypeIdx)
      %assign typeName = "char*"
    %endif
  %endif
  %return typeName
%endfunction
 
%function SLibGetDataDefFromCGType(cgTypeIdx, dataName, bitFieldWidth, comment,matrixRefAsBasePointer) void
  %% This function returns a buffer string with the definition of
  %% the given data object.
  %% For example: "int32_T Constant_Value[2][3]; /*comment*/"
 
  %assign cgType = ::CompiledModel.CGTypes.CGType[cgTypeIdx]
  %if (SLibAutosarActive() && MultiInstanceERTCode)
    %assign typeName = SLibGetTypeNameForMultiInstanceAUTOSAR(cgTypeIdx)
  %else
    %assign typeName = SLibGetTypeNameFromCGType(cgTypeIdx)
  %endif
  %assign symbolicDims = LibCGTypeSymbolicVectorDims(cgTypeIdx)
   
   %if (ISEQUAL(typeName,"CAN_MESSAGE_STANDARD") || ISEQUAL(typeName,"CAN_MESSAGE_EXTENDED") || ISEQUAL(typeName,"CAN_MESSAGE"))
    %assign typeName = "CAN_DATATYPE"
  %endif
   
  %if (ISEQUAL(typeName,"SCP_RX") || ISEQUAL(typeName,"SCP_TX"))
    %assign typeName = "SCP_FRAME"
  %endif
 
  %assign retBuf = ""
  %if ISEMPTY(comment)
    %assign c_comment = ""
  %elseif comment[0] == " "
    %assign c_comment = "/*" + comment + " */"
  %else
    %assign c_comment = "/* " + comment + " */"
  %endif
   
  %if EXISTS(cgType.Name)
    %assign cgTypeNamespace = SLibGetNameSpaceForDataDef(cgType.Name)
  %else
    %assign cgTypeNamespace = []
  %endif
  %assign namespaceStr = ""
  %if !ISEMPTY(cgTypeNamespace)
    %assign namespaceStr = "%<cgTypeNamespace>::"
  %endif
  %openfile retBuf
  %if symbolicDims == ""
    %assign optBitField = bitFieldWidth > 0 ? ":%<bitFieldWidth>" : ""
    %<namespaceStr>%<typeName> %<dataName>%<optBitField>; %<c_comment>
  %elseif matrixRefAsBasePointer
    %<namespaceStr>%<typeName> *%<dataName>; %<c_comment>
  %else
    %assert bitFieldWidth == 0
    %<namespaceStr>%<typeName> %<dataName>%<symbolicDims>; %<c_comment>
  %endif
  %closefile retBuf
  %return retBuf
%endfunction
 
%%Function:SLibGetVarGroupTypeDef================================================================
%%Abstract:
%%Returnsthestructuredtypedefinitionforagivenvargroup.
%%
%function SLibGetVarGroupTypeDef(aVarGroup)
  %return SLibGetStructTypeDef(aVarGroup.CGTypeIdx)
%endfunction
 
%function SLibGetSystemVarGroupDataDef(aSysIdx,aVarGroup)
  %assign cgType = ::CompiledModel.CGTypes.CGType[aVarGroup.CGTypeIdx]
  %assign defns = SLibGetSystemDataDefUsingVarGroup(aSysIdx,aVarGroup.Category, TLC_FALSE)
  %openfile tmpBuffer
  typedef struct {
    %/
  } %<cgType.Name>;
  %closefile tmpBuffer
  %return tmpBuffer
%endfunction
 
%%Function:SLibGetStructTypeDef==================================================================
%%Abstract:
%%ReturnsthestructuredtypedefinitionforagivenCGTypeIdx.Theinput
%%CGTypeIdxmustrepresentastructCGType.
%%
%function SLibGetStructTypeDef(aCgTypeIdx)
  %assign cgType = ::CompiledModel.CGTypes.CGType[aCgTypeIdx]
  %assert LibCGTypeIsStruct(aCgTypeIdx)
  %openfile tmpBuffer
  %assign define = "_" + FEVAL("upper", cgType.Name) + "_"
  typedef struct {
    %foreach mIdx = LibCGTypeNumMembers(aCgTypeIdx)
      %<SLibGetDataDefFromCGType(LibCGTypeMemberCGTypeIdx(aCgTypeIdx, mIdx), ...
        LibCGTypeMemberName(aCgTypeIdx, mIdx), 0, "",TLC_FALSE)>
    %endforeach
  } %<cgType.Name>;
  %closefile tmpBuffer
  %return tmpBuffer
%endfunction
 
%function SLibGetNameSpaceForDataDef(cgTypeName) void
  %assign namespaceStr = []
  %assign mdlRefBlks = ISFIELD(::CompiledModel,"ModelReferenceBlocks") ? ...
    ::CompiledModel.ModelReferenceBlocks : []
   
  %if !ISEMPTY(mdlRefBlks)
    %foreach rowIdx = SIZE(mdlRefBlks,0)
      %assign mdlRefInfo = mdlRefBlks[rowIdx]
      %assign mSysIdx = mdlRefInfo[0]
      %assign bIdx = mdlRefInfo[1]
 
      %if !System[mSysIdx].Block[bIdx].MdlRefIsCPPClassGenMode
         %continue
      %endif
       
      %assign blkInterface = GetModelrefInterface(System[mSysIdx].Block[bIdx])
       
      %assign mdlClassPtrName = blkInterface.FPC.ModelClassName
      %if CGMODEL_ACCESS("CGModel.getUseOperatorNewForModelRefRegistration") != 0
         %assign mdlClassPtrName = mdlClassPtrName + "_ptr"
      %endif
         
      %if EXISTS(blkInterface.FPC.ClassNamespace) && (mdlClassPtrName == cgTypeName)
        %assign namespaceStr = blkInterface.FPC.ClassNamespace
        %break
       %endif
    %endforeach
  %endif
 
  %return namespaceStr
%endfunction
 
%function SLibNeedGenDataDefFromVarGroup(aVarGroupElement, aSysIdx) void
  %assign retVal = [TLC_FALSE, TLC_FALSE, ""]
  %assign hasDataArg = TLC_FALSE
  %assign needGenDataDefFromVarGroup = TLC_FALSE
  %assign mayRequireDataRecGenDef = TLC_TRUE
  %assign dataDefFromRec = ""
  %assign idnum = IDNUM(aVarGroupElement)
  %assign recType = idnum[0]
  %assign recIdx = idnum[1]
  %assert recType != "VG" %% not a vargroup
  %assign dataRec = SLibGetDataRecForVarGroupMember(recType, recIdx)
   
  %switch recType
    %case "P"
      %assign needGenDataDefFromVarGroup = ...
        !SLibOmitRecord(dataRec) && (SLibGetWidthOfValueFromParamRec(dataRec) > 0)
      %break
    %case "B"
      %assign needGenDataDefFromVarGroup = !dataRec.RequiredInBlockIO[0] == 0
      %break
    %case "ZE"
      %% For accelerator mode, we can't skip events because
      %% Simulink allocates events for all zc's. The memory layout
      %% must match.
      %assign needGenDataDefFromVarGroup = dataRec.NeedsEvent || Accelerator
      %assign mayRequireDataRecGenDef = TLC_FALSE
      %break
    %case "C"
      %assign needGenDataDefFromVarGroup = ...
        ::CompiledModel.PadderActive || dataRec.RequiredInConstBlockIO
      %assign mayRequireDataRecGenDef = TLC_FALSE
      %break
    %case "W"
      %if !ISFIELD(dataRec, "IsRemovedInIR") || !dataRec.IsRemovedInIR == 1
        %if dataRec.SigSrc[0] >= 0 && dataRec.SigSrc[2] >= 0 %% not virtual
          %assign needGenDataDefFromVarGroup = ...
            dataRec.StorageClass == "Auto" && ...
            !SLibOmitRecord(dataRec) && ...
            !FcnIsDWorkFromMdlBlockInCppClassGenMode(dataRec)
        %elseif ISFIELD(::CompiledModel.System[aSysIdx], "Block")
          %assign needGenDataDefFromVarGroup = TLC_TRUE
        %else
          %% special handling for the case where a root inport
          %% expects undefined signal
          %assign needGenDataDefFromVarGroup = TLC_FALSE
        %endif
      %endif
      %break
    %case "L"
    %case "LDW"
    %case "S"
    %case "PD"
    %case "PCDG"
      %assign needGenDataDefFromVarGroup = TLC_TRUE
      %assign mayRequireDataRecGenDef = TLC_FALSE
      %break
    %case "U"
      %assign extIn = ::CompiledModel.ExternalInputs.ExternalInput[recIdx]
      %% Skip inactive root inputs
      %if (ISFIELD(extIn, "Inactive"))
        %assign needGenDataDefFromVarGroup = TLC_FALSE
      %else
        %assign needGenDataDefFromVarGroup = TLC_TRUE
      %endif
      %assign mayRequireDataRecGenDef = TLC_FALSE
      %break
    %case "Y"
      %assign extOut = ::CompiledModel.ExternalOutputs.ExternalOutput[recIdx]
      %% Skip inactive root outputs
      %if (ISFIELD(extOut, "Inactive"))
        %assign needGenDataDefFromVarGroup = TLC_FALSE
      %else
      %assign needGenDataDefFromVarGroup = TLC_TRUE
      %endif
      %assign mayRequireDataRecGenDef = TLC_FALSE
      %break
    %case "UB"
      %assign needGenDataDefFromVarGroup = TLC_TRUE
      %assign mayRequireDataRecGenDef = TLC_FALSE
      %break
    %default
      %break
  %endswitch
  %if needGenDataDefFromVarGroup && mayRequireDataRecGenDef
    %assign recTypeName = SLibVarGroupTypeNameForRecordType(recType)
    %assign dataDefFromRec = ...
      FcnGen%<recTypeName>DefNotHandledInVarGroup(dataRec)
    %if !WHITE_SPACE(dataDefFromRec)
      %assign needGenDataDefFromVarGroup = TLC_FALSE
      %assign hasDataArg = TLC_TRUE
      %openfile tmpBuf
      %% traceability to model element category
      %assign elemCategory = SLibGetModelElemCategory(aVarGroupElement)
      %assign elemCategoryTraceMarker= ""
      %if elemCategory != ""
        %assign traceMarker = SLibAddTrace("ModelElemCategory", "%<elemCategory>")
        %<SLibTraceBegin(traceMarker)>
      %endif
      %<dataDefFromRec>
      %<SLibTraceEnd(traceMarker)>
      %closefile tmpBuf
      %assign dataDefFromRec = tmpBuf
    %endif
  %endif
  %assign retVal[0] = needGenDataDefFromVarGroup
  %assign retVal[1] = hasDataArg
  %assign retVal[2] = dataDefFromRec
  %return retVal
%endfunction
 
%function SLibGetModelElemCategoryForDWork(aDWorkRec) void
  %if aDWorkRec.GlobalDSM == 1
    %return "GlobalDataStores"
  %endif
 
  %if aDWorkRec.SharedLocalDSM == 1
    %return "SharedLocalDataStores"
  %endif
   
  %% GlobalDSM ==0 && SharedLocalDSM == 0
  %return "InternalData"
%endfunction
 
%function SLibGetModelElemCategoryForParam(aParamRec) void
  %if aParamRec.Tunable == "no"
    %return "Constants"
  %else
    %if aParamRec.IsGlobal == 1
      %return "GlobalParameters"
    %elseif aParamRec.InstanceSpecific == 1
      %return "InstanceSpecificParameters"
    %elseif aParamRec.IsPublic == 1 || ConfigSet.DefaultParameterBehavior == "Tunable"
      %return "LocalParameters"
    %else
      %return "Parameters"
    %endif
  %endif
%endfunction
 
%function SLibGetModelElemCategory(aVarGroupElement) void
  %assign idnum = IDNUM(aVarGroupElement)
  %assign recType = idnum[0]
  %assign recIdx = idnum[1]
  %switch recType
      %case "U"
        %return "Inports"
        %break
      %case "Y"
        %return "Outports"
        %break
      %case "W"
        %assign dwRec = DWorks.DWork[recIdx]
        %return SLibGetModelElemCategoryForDWork(dwRec)
        %break
      %case "P"
      %case "CP"
        %assign paramRec = ModelParameters.Parameter[recIdx]
        %return SLibGetModelElemCategoryForParam(paramRec)
        %break
      %case "B"
      %case "ZE"
        %return "InternalData"
      %case "C"
        %return "Constants"
      %default
        %return SLibVarGroupTypeNameForRecordType(recType)
    %endswitch
%endfunction
 
%function SLibGetModelElemCategoryForIndividualMapping(aDataRec)
  %if ISFIELD(aDataRec, "DrivesModelRefRootOutport") && aDataRec.DrivesModelRefRootOutport == "yes"
    %return "Outports"
  %elseif aDataRec.RecordType == "ExternalInput"
    %return "Inports"
  %elseif aDataRec.RecordType == "ExternalOutput"
    %return "Outports"
  %elseif aDataRec.RecordType == "DWork"
    %if aDataRec.IsDataStoreMemory == 1
      %return "DataStores"
    %else
      %return "States"
    %endif
  %elseif aDataRec.RecordType == "BlockOutput"
    %return "Signals"
  %elseif aDataRec.RecordType == "ModelParameter"
    %return "Parameters"
  %else
    %assert(TLC_FALSE)
  %endif
%endfunction
 
%function SLibGetSystemDataDefUsingVarGroup(aSysIdx, aVarGroupType, explicitInstPDataDef) void
  %assign res = ["", 0, 0, "", []] %% the third element is the struct alignment
                                 %% the fourth element is the data definition of instance specific parameter
                                 %% the fifth element is array of var groups data init
  %assign sys = ::CompiledModel.System[aSysIdx]
  %assign varGroupIdx = FcnSysVarGroupIndex(sys, aVarGroupType, 0)
  %assign argType = aVarGroupType == "Parameter" ? "Parameters" : aVarGroupType
  %assign numFields = 0
  %if varGroupIdx >= 0
    %assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
    %if 0 == varGroup.PackageAsStruct
      %return res
    %endif
    %assign cgType = ::CompiledModel.CGTypes.CGType[varGroup.CGTypeIdx]
    %assign cgTypeIdx = varGroup.CGTypeIdx
 
    %% The following two variables are used to control the names of items in
    %% the code to prevent empty structure types in the case of code variants
    %assign hasElement = varGroup.HasElement
    %assign dummyElementName = "_rt_unused"
     
    %if LibCGTypeIsMatrix(cgTypeIdx)
      %assign cgTypeIdx = LibCGTypeBaseIndex(cgTypeIdx)
      %assign cgType = ::CompiledModel.CGTypes.CGType[cgTypeIdx]
    %endif
     
    %assert LibCGTypeIsStruct(cgTypeIdx)
    %assert LibCGTypeNumMembers(cgTypeIdx) == varGroup.NumVarGroupElements
    %if varGroup.IsOpaque
      %assign res[1] = ""
      %assign res[1] = 1
      %assign res[2] = 0
    %else
      %openfile tmpBuf
 
      %assign hasDataArg = TLC_FALSE
      %assign hasUnconditionalElement = TLC_FALSE
      %assign hasUnconditionalElementSubStruct = TLC_FALSE
      %assign prevSubStructIdx = -1
 
      %assign isModelSelfVarGroup = (varGroupIdx == SLibGetSelfVarGroupIndex())
      %if isModelSelfVarGroup && SLibCanInlineRTMIntoSelf()
        %if ISFIELD(::CompiledModel, "RTMTypeFields")
          %assign legacyRTMFields = ::CompiledModel.RTMTypeFields
          %<legacyRTMFields>
        %endif
      %endif
      %openfile dataDefBodyBuf
      %foreach mIdx = LibCGTypeNumMembers(cgTypeIdx)
        %assign varGroupElement = varGroup.VarGroupElements[mIdx]
        %assign idnum = IDNUM(varGroupElement)
        %assign subStructIdx = varGroup.NumSubStructs > 0 ? ...
          varGroup.SubStructIndex[mIdx] : -1
        %assign recType = idnum[0]
        %assign recIdx = idnum[1]
        %assign dataRec = ""
        %assign PreprocessorCond_start = ""
        %assign PreprocessorCond_end = ""
          %assign ifCond = ""
        %assign ifEndCond = ""
        %assign curSubStructConds = SLibVariantConditionRecord()
        %assign prevSubStructConds = SLibVariantConditionRecord()
        %assign dataDefFromRec = ""
        %assign typeQualifier = ""
        %assign bitFieldWidth = 0
        %assign needGenDataDefFromVarGroup = TLC_FALSE
        %assign openOrCloseSubStruct = ""
        %assign openOrCloseSubStructFlag = TLC_FALSE
        %assign isPromotedFromLocal = TLC_FALSE
        %if recType != "VG" %% not a vargroup
          %assign dataRec = SLibGetDataRecForVarGroupMember(recType, recIdx)
          %assign needDefOrArg = SLibNeedGenDataDefFromVarGroup(varGroupElement, aSysIdx)
          %assign needGenDataDefFromVarGroup = needDefOrArg[0]
          %assign hasDataArg = needDefOrArg[1]
          %assign dataDefFromRec = needDefOrArg[2]
          %%inline variant condition for global DWork and BlockIO
          %if CGMODEL_ACCESS("CGModel.InlineVariantGlobalData") > 0
            %assign ifCond = SLibIfVariantCondition(dataRec)
            %assign ifEndCond = SLibEndIfVariantCondition(dataRec)
          %else
            %assign ifCond = ""
            %assign ifEndCond = ""
          %endif
 
          %switch recType
            %case "P"
            %case "B"
            %case "ZE"
              %break
            %case "C"
              %assign typeQualifier = dataRec.DoNotConstify ? "" : "const"
              %break
            %case "W"
              %if !ISFIELD(dataRec, "IsRemovedInIR") || !dataRec.IsRemovedInIR == 1
                %if dataRec.SigSrc[0] >= 0 && dataRec.SigSrc[2] >= 0 %% not virtual
                  %assign ownerBlk = ...
                    ::CompiledModel.System[dataRec.SigSrc[0]].Block[dataRec.SigSrc[2]]
                %elseif ISFIELD(sys, "Block")
                  %assign dataRec.SigSrc[0] = aSysIdx
                %endif
              %endif
              %break
            %case "L"
            %case "LDW"
              %assign isPromotedFromLocal = TLC_TRUE
            %case "S"
               %assign stackVarVariantCond = varGroup.VariantConditions[mIdx]
               %assign ifCond = SLibIfVariantConditionForm(stackVarVariantCond)
               %assign ifEndCond = SLibEndIfVariantConditionForm(stackVarVariantCond)
            %case "PD"
            %case "PCDG"
            %case "U"
              %break
            %case "Y"
              %% For external outputs, we need to grab the block to get the variant condition
              %assign extOut = ExternalOutputs.ExternalOutput[recIdx]
              %%Get Block from the External Output record
              %assign extOutSysIdx = extOut.Block[0]
              %assign extOutBlkIdx = extOut.Block[1]
              %assign extOutBlk = ::CompiledModel.System[extOutSysIdx].Block[extOutBlkIdx]
              %assign ifCond = SLibIfVariantCondition(extOutBlk)
              %assign ifEndCond = SLibEndIfVariantCondition(extOutBlk)
              %break
            %case "UB"
              %assign bitFieldWidth = recIdx
              %break
            %default
              %if ISEMPTY(dataRec) && SLibGetUseRTMcgType()
                %assign matrixRefAsBasePointer = recType == "O" || recType == "I"
                %assign memberName = LibCGTypeMemberName(cgTypeIdx, mIdx)
                %assign selfField = SLibGetDataDefFromCGType(LibCGTypeMemberCGTypeIdx(cgTypeIdx, mIdx), ...
                  memberName, 0, "",matrixRefAsBasePointer)
                %if recType == "RCDG"
                  %assign selfFieldCoderGroupIndex = SLibGetCoderGroupIndexFromSelfElementIndex(mIdx)
                  %assign childCoderGroup = ::CompiledModel.CoderDataGroup[recIdx]
                  %assign childVarGroupIdx = FcnSysVarGroupIndex(sys, "CoderDataGroup" +childCoderGroup.Name, 0)
                  %assign childVarGroup = ::CompiledModel.VarGroups.VarGroup[childVarGroupIdx]
                  %if (LibCGTypeIsMatrix(childVarGroup.CGTypeIdx))
                    %assign memberName = "(*" + memberName + ")"
                    %assign selfField = SLibGetDataDefFromCGType(childVarGroup.CGTypeIdx,memberName, 0, "",TLC_FALSE)
                  %endif
                  %if(selfFieldCoderGroupIndex > -1)
                    %assign selfFieldCoderGroup = ::CompiledModel.CoderDataGroup[selfFieldCoderGroupIndex]
                    %assign typeQualifier = SLibTypeQualifierForGroup(selfFieldCoderGroup)
                    %assign selfField = typeQualifier + " " + selfField
                  %endif
                  %if childCoderGroup.ContainsInstanceSpecificParameter && explicitInstPDataDef
                    %assign comment = "/* %<childCoderGroup.Identification> *//n"
                    %assign res[3] = comment + selfField
                    %assign selfField = ""
                  %endif
                %elseif recType == "RVG"
                  %assign childVarGroup = ::CompiledModel.VarGroups.VarGroup[recIdx]
                  %if (LibCGTypeIsMatrix(childVarGroup.CGTypeIdx))
                    %assign memberName = "(*" + memberName + ")"
                    %assign selfField = SLibGetDataDefFromCGType(childVarGroup.CGTypeIdx,memberName, 0, "",TLC_FALSE)
                  %endif
                %elseif recType == "I"
                  %assign baseSys = ::CompiledModel.System[GetBaseSystemIdx()]
                  %assign canInput = sys.Interface.CanonicalInputArgDef[recIdx]
                  %assign typeQualifier = "const"
                  %assign selfField = typeQualifier + " " + selfField
                %elseif recType == "DUM" %% Dummy field
                  %assert varGroup.IsModelSelfCoderGroupVarGroup
                  %assign selfField = ""
                %endif
 
                %<selfField>/
                %assign hasUnconditionalElement = TLC_TRUE
                %if subStructIdx != -1
                  %assign hasUnconditionalElementSubStruct = TLC_TRUE
                %endif
                %assign numFields = numFields + 1
                %continue
              %endif
          %endswitch
          %if ISEMPTY(dataRec)
            %assign comment = ""
            %if recType == "PCDG"
              %assign group = FcnGetCoderGroupForVarGroup(varGroup)
              %assign childDataGroup = FcnGetChildDataGroup(group, recIdx)
              %assert childDataGroup.AsStructure == "InParent"
              %assign mdlrefBlock = ::CompiledModel.ModelReferenceBlocks[childDataGroup.CompiledModelBlockIndex]
              %assign grBlkIndex = [ %, % ]
              %assign comment = "%<SLibGrBlockCommentName(grBlkIndex)>"
            %endif
          %else
            %switch recType
              %case "P"
                %assign comment = SLibGenModelPrmDefnComment(dataRec)
                %break
              %default
                %assign comment = SLibReferencedBy(dataRec)
                %break
            %endswitch
          %endif
 
        %else %% recType == "VG" - is a vargroup
          %assign isSelfGroup = SLibIsSelfCoderGroupVarGroup(varGroupIdx)
          %assign subVarGroup = ::CompiledModel.VarGroups.VarGroup[recIdx]
          %if isSelfGroup
            %if subVarGroup.Category == "ZCEvent"
              %if ::CompiledModel.NumZCEvents == 0
                %continue
              %endif
              %assign subCGTypeIdx = subVarGroup.CGTypeIdx
              %assign needEvent = TLC_FALSE
              %foreach subIdx = LibCGTypeNumMembers(subCGTypeIdx)
                %assign subIDNum = IDNUM(subVarGroup.VarGroupElements[subIdx])
                %assign subDataRec = SLibGetDataRecForVarGroupMember(subIDNum[0],subIDNum[1])
                %if subIDNum[0] == "VG" || subDataRec.NeedsEvent
                  %assign needEvent = TLC_TRUE
                  %break
                %endif
              %endforeach
              %if !needEvent
                %continue
              %endif
            %endif
            %if GenerateClassInterface && subVarGroup.Category == "DWork" && subVarGroup.NumVarGroupElements == 1
              %% check if dwork is empty since it can contain a ficticious dwork from a model ref block
              %assign subIDNum = IDNUM(subVarGroup.VarGroupElements[0])
              %assign subDataRec = SLibGetDataRecForVarGroupMember(subIDNum[0],subIDNum[1])
              %assign isDwRec = (subIDNum[0] == "W" || subIDNum[0] == "LDW")
              %if isDwRec && FcnIsDWorkFromMdlBlockInCppClassGenMode(subDataRec)
                %continue
              %endif
            %endif
            %% if self vargroup we take data definition directly from cgType
            %assign selfFieldName = LibCGTypeMemberName(cgTypeIdx, mIdx)
            %assign selfField = SLibGetDataDefFromCGType(LibCGTypeMemberCGTypeIdx(cgTypeIdx, mIdx), ...
              selfFieldName, 0, "",TLC_FALSE)
            %if SLibGetDoesSelfHasCoderDataGroup() && aSysIdx == GetBaseSystemIdx() && SLibIsSelfCoderGroupField(mIdx)
              %assign selfFieldCoderGroupIndex = SLibGetCoderGroupIndexFromSelfElementIndex(mIdx)
              %if (selfFieldCoderGroupIndex > -1)
                %assign selfFieldCoderGroup = ::CompiledModel.CoderDataGroup[selfFieldCoderGroupIndex]
                %assign typeQualifier = SLibTypeQualifierForGroup(selfFieldCoderGroup)
                %assign selfField = typeQualifier + " " + selfField
              %endif
            %endif
             
            %assign res[4] = res[4] + "%<selfFieldName>()"
 
            %openfile selfFieldBuffer
            %<selfField>/
            %closefile selfFieldBuffer
          %endif
 
          %if subVarGroup.Category == "HierarchicalCoderData"
            %assign group = FcnGetCoderGroupForVarGroup(subVarGroup)
            %% Fix the subArgType. For example, the argType corresponds to
            %% the parent group, like the self group, and then subArgType
            %% corresponds to this group, which is nestled inside self.
            %assign subArgType = "CoderDataGroup" + group.Name
          %else
            %assign subArgType = argType
          %endif
          %if subVarGroup.SysIdx == rootSystem.SystemIdx
            %assign comment = ""
            %if !ISFIELD(rootSystem,"Has"+subArgType+"Arg")
              %addtorecord rootSystem Has%<subArgType>Arg TLC_TRUE
            %endif
            %assign needGenDataDefFromVarGroup = ...
              !rootSystem.StandaloneSubsystem && (rootSystem.Has%<subArgType>Arg)
          %else
            %assign cs = ...
              ::CompiledModel.System[subVarGroup.SysIdx].CallSites[subVarGroup.InstanceIdx]
            %assign dataGrBlk = ::CompiledModel.System[cs[2]].Block[cs[3]]
            %assert dataGrBlk.Type == "SubSystem"
            %assign dataGrSysIdx = dataGrBlk.CallSiteInfo.SystemIdx
            %if InlineParameters == 1 && (aVarGroupType == "Parameter")
              %assign vcRecord = SLibGetInlineSystemRelativeConditionFromVarGroup(subVarGroup)
              %if !ISEMPTY(vcRecord) && vcRecord.hasConds
                  %assign PreprocessorCond_start = vcRecord.ifCond
                  %assign PreprocessorCond_end = vcRecord.endIfCond
              %endif
              %assign comment = SLibGetCallSitesComment(dataGrSysIdx)
            %else
              %% Use relative conditions to guard varGroup records. Do not use instance conditions or other
              %% variants of the net instance condition as this will not work with reuse systems
              %% TopTester: test/toolbox/simulink/variants/tVariantGecks8.m -testspec:TestPoint_mReuseHierInInlineSSWithIVVSS
              %% TopTester: test/toolbox/simulink/variants/codevariants/tSameDataWithAndWithoutIV.m
              %if isSelfGroup
                %assign vcRecord = ""
                %assign vcRecord1 = SLibGetInlineSystemRelativeConditionFromVarGroup(subVarGroup)
                %assign PreprocessorCond_start = vcRecord1.ifCond
                %assign PreprocessorCond_end = vcRecord1.endIfCond
              %else
              %assign vcRecord = SLibGetInlineSystemRelativeConditionFromVarGroup(subVarGroup)
              %endif
              %if !ISEMPTY(vcRecord) && vcRecord.hasConds
                %assign ifCond = vcRecord.ifCond
                %assign ifEndCond = vcRecord.endIfCond
                %% this vargroup represents a new sub-struct
                %if subStructIdx != -1
                  %assign curSubStructConds = vcRecord
                %endif
              %endif
              %assign comment = LibGetChildSystemStructCommentName(aSysIdx, dataGrBlk)
            %endif
            %assign dataGrSys = ::CompiledModel.System[dataGrSysIdx]
            %if !ISFIELD(dataGrSys,"Has"+subArgType+"Arg")
              %addtorecord dataGrSys Has%<subArgType>Arg TLC_TRUE
            %endif
            %assign needGenDataDefFromVarGroup = ...
              !dataGrSys.StandaloneSubsystem && (dataGrSys.Has%<subArgType>Arg)
          %endif
        %endif
 
        %%
        %%
        %% handling sub-structures
        %%
        %% If we have Variants data due to variant subsystems or Inline Variants
        %% we need to ensure that Dwork corresponding to substructures are written
        %% such a way that it shouldn't messup with closing or opening of substructures.
        %% TopTester: test/toolbox/simulink/tVariantGecks.m -testspec:g1404201
        %openfile subStructBuffer
 
        %if prevSubStructIdx != subStructIdx
        %% In case we are at sub struct boundaries, prepare for the transition.
        %%
        %% | prevSubStructIdx != subStructIdx |
        %% |-----------------------+-----------------|
        %% If we 1) start a new sub struct | -1 | >=0 |
        %% |-----------------------+-----------------|
        %% 2) switch to another one | >=0 | >=0 |
        %% |-----------------------+-----------------|
        %% 3) finish the last one | >=0 | -1 |
        %%
           
          %if prevSubStructIdx != -1
          %% cases 2) or 3), we need to close the previous sub struct
 
            %assign openOrCloseSubStruct = ""
 
            %% TopTester: test/toolbox/simulink/variants/inlineVariants/variantSource/systemtests/tmg1396738_VC1.m -testspec:testGeneratedCodeForInactiveVariants
            %if !hasUnconditionalElementSubStruct
                %assign openOrCloseSubStruct = openOrCloseSubStruct + ...
                                              "#ifndef %<hasElementSubStruct>/n" + ...
                                              "char %<dummyElementName>;/n" + ...
                                              "#endif/n"
            %endif
 
            %% Construct the closing brace and the field name of the substruct
            %assign openOrCloseSubStruct = openOrCloseSubStruct + "} %;"
            %assign openOrCloseSubStructFlag = TLC_TRUE
          %endif
           
          %if subStructIdx != -1
          %% cases 1) or 2), we need to open the next sub struct
 
            %assign hasUnconditionalElement = hasUnconditionalElement || !curSubStructConds.hasConds
            %assign hasUnconditionalElementSubStruct = TLC_FALSE %%reset
            %% add #if for this struct
            %if curSubStructConds.hasConds
              %assign openOrCloseSubStruct = openOrCloseSubStruct + curSubStructConds.ifCond
              %assign prevSubStructConds = curSubStructConds
              %assign curSubStructConds = SLibVariantConditionRecord()
            %endif
 
            %% Cnstruct the opening brace
            %assign openOrCloseSubStruct = openOrCloseSubStruct + "/n" + "struct {"
            %assign openOrCloseSubStructFlag = TLC_TRUE
 
            %assign hasUnconditionalElementSubStruct = TLC_FALSE %%reset
            %assign hasElementSubStruct = "%<hasElement>_%<subStructIdx>"
            %% the SubStruct will always be there; until we start guarding the struct itself
            %assign hasUnconditionalElement = TLC_TRUE
          %endif
 
          %% Update the next previous
          %assign prevSubStructIdx = subStructIdx
        %endif
 
        %assign ifCondEmitted = TLC_FALSE
     
        %if recType == "VG" && isSelfGroup
          %if !GenerateClassInterface && subVarGroup.Category == "DWork" && subVarGroup.NumVarGroupElements == 1
            %% check if dwork is empty since it can contain a ficticious dwork from a model ref block
            %assign subIDNum = IDNUM(subVarGroup.VarGroupElements[0])
            %assign subDataRec = SLibGetDataRecForVarGroupMember(subIDNum[0],subIDNum[1])
            %assign isDwRec = (subIDNum[0] == "W" || subIDNum[0] == "LDW")
            %if isDwRec && SLibOmitRecord(subDataRec)
              %assign selfFieldBuffer = ""
            %endif
          %endif
          %<selfFieldBuffer>
          %assign hasUnconditionalElement = TLC_TRUE
          %assign hasDataArg = TLC_TRUE
        %elseif needGenDataDefFromVarGroup
          %% We need to see if all data members should be grouped. Some
          %% with types like 'fcn_call' for e.g. should not be grouped.
          %if(SLibEmitRecordInCoderDataGroupStruct(LibCGTypeMemberCGTypeIdx(cgTypeIdx, mIdx)))
            %% Emit if condition if we are emitting an element
            %<ifCond>
            %assign ifCondEmitted = TLC_TRUE
            %assign align=""
            %assign alignment = varGroup.Alignment
            %if LibCGTypeMemberAlignment(cgTypeIdx, mIdx) > alignment
              %assign alignment = LibCGTypeMemberAlignment(cgTypeIdx, mIdx)
            %endif
           
            %if alignment > 0 && fieldAlign %% if aligning field is supported
              %assign align = SLibGetAlignmentSyntax(::CompiledModel.Name, LibCGTypeMemberName(cgTypeIdx, mIdx), ...
                typeQualifier, alignment, "DATA_ALIGNMENT_STRUCT_FIELD")
            %else
              %if alignment > res[2] %% propagate to struct alignment if aligning field is not supported
                %assign res[2] = alignment
              %endif
            %endif
             
            %% Decide if we need "volatile" qualifier or not for critical section on rate transition
            %% dWork
              %assign volatileQualifier = ""
            %if !ISEMPTY(dataRec) && ISFIELD(dataRec, "IsDataTransferVolatileDWork")...
               && (dataRec.IsDataTransferVolatileDWork == 1)
                %assign volatileQualifier = "volatile"
            %endif
 
            %% traceability to model element category
            %assign elemCategory = SLibGetModelElemCategory(varGroupElement)
            %assign elemCategoryTraceMarker= ""
            %if elemCategory != ""
              %assign elemCategoryTraceMarker= SLibAddTrace("ModelElemCategory", "%<elemCategory>")
              %<SLibTraceBegin(elemCategoryTraceMarker)>
            %endif
            %assign blockTraceMarker = ""
            %if comment != ""
              %assign blockTraceMarker = SLibAddBlockTrace(comment)
              %<SLibTraceBegin(blockTraceMarker)>
            %endif
            %if isPromotedFromLocal && ::CompiledModel.SLCI == "on"
              %assign comment = comment + " (local-to-global)"
            %endif
            %<align> %<typeQualifier> %<volatileQualifier> %<SLibGetDataDefFromCGType(...
              LibCGTypeMemberCGTypeIdx(cgTypeIdx, mIdx), LibCGTypeMemberName(cgTypeIdx, mIdx), bitFieldWidth, comment,TLC_FALSE)>
             
            %<SLibTraceEnd(blockTraceMarker)>
            %<SLibTraceEnd(elemCategoryTraceMarker)>
            %assign hasDataArg = TLC_TRUE
          %endif
        %else
          %% Emit if condition if we are emitting an element. There may be cases in which the data definition
          %% is empty (e.g. inactive root I/O). In this case, don't emit if condition.
          %if !ISEMPTY(dataDefFromRec)
            %<ifCond>
            %assign ifCondEmitted = TLC_TRUE
          %endif
          %<dataDefFromRec>
        %endif
        %closefile subStructBuffer
        %%
         
        %% Open or close a substruct
        %if openOrCloseSubStructFlag == TLC_TRUE
          %% generate dummy element if substruct can become empty
          %<openOrCloseSubStruct>
          %assign openOrCloseSubStructFlag = TLC_FALSE
        %endif
 
        %if !WHITE_SPACE(subStructBuffer)
          %assign varGroup.IndexOfLastNonEmptyMember = mIdx
          %% PreprocessorCond_start/end are empty except for variants
          %% TopTester: test/toolbox/simulink/variants/inlineVariants/variantSource/codeGen/tg1713829.m
          %if recType == "VG" && varGroup.Category == "HierarchicalCoderData" && !isSelfGroup && ...
            (!ifCondEmitted || !needGenDataDefFromVarGroup)
            %assign subVarGroup = ::CompiledModel.VarGroups.VarGroup[recIdx]
            %assign vcRecordToCheck = SLibGetInlineSystemRelativeConditionFromVarGroup(subVarGroup)
            %if !ISEMPTY(vcRecordToCheck)
              %if vcRecordToCheck.hasConds
                %assign ifCond = vcRecordToCheck.ifCond
                %assign ifEndCond = vcRecordToCheck.endIfCond
                %<ifCond>
                %assign ifCondEmitted = TLC_TRUE
              %endif
            %endif
          %endif
          %<PreprocessorCond_start>
          %<subStructBuffer>
           
          %if (ISEMPTY(PreprocessorCond_start) && ISEMPTY(ifCond))
            %if (subStructIdx == -1) %%for the top level struct
              %assign hasUnconditionalElement = TLC_TRUE
            %else %%for the SubStruct
              %assign hasUnconditionalElementSubStruct = TLC_TRUE
            %endif
          %else
            %if (subStructIdx == -1) %%for the top level struct
              #define %<hasElement>
            %else %%for the substruct
              #define %<hasElementSubStruct>
            %endif
          %endif
          %<PreprocessorCond_end>
        %if ifCondEmitted
          %<ifEndCond>
        %endif
     
        %endif
        %%
        %if hasDataArg
          %if !ISFIELD(sys,"Has"+argType+"Arg")
            %addtorecord sys Has%<argType>Arg TLC_TRUE
          %endif
          %if !sys.Has%<argType>Arg
            %assign sys.Has%<argType>Arg = TLC_TRUE
            %% For model reference, we igore anything set in the root system
            %if !(IsModelReferenceTarget() && (NumSystems-1 == aSysIdx))
              %assign ::CompiledModel.Has%<argType>Arg = TLC_TRUE
            %endif
          %endif
          %assign numFields = numFields + 1
        %endif
      %endforeach
      %closefile dataDefBodyBuf
      %if !ISEMPTY(dataDefBodyBuf) && !WHITE_SPACE(dataDefBodyBuf)
        %assign storageClassTraceMarker = SLibAddTrace("StorageClass", "%<SLibGetVarGroupStorageClass(varGroup)>")
        %<SLibTraceBegin(storageClassTraceMarker)>
        %<dataDefBodyBuf>
        %<SLibTraceEnd(storageClassTraceMarker)>
      %endif
      %%
      %% Closing a possibly unclosed sub-structure: a subStruct
      %% whose last element happens to be the last element of the
      %% parent struct.
      %%
      %if prevSubStructIdx != -1
        %if hasUnconditionalElementSubStruct == TLC_FALSE && openOrCloseSubStructFlag == TLC_FALSE
            #ifndef %<hasElementSubStruct>
            char %<dummyElementName>;
            #endif
        %endif
        } %;
      %endif
       
      %if numFields > 0
        %if GetBaseSystemIdx() == aSysIdx && ...
          SLibGetDoesSelfHasCoderDataGroup()
          %assign selfCoderDataGroupIndex = SLibGetSelfCoderDataGroupIndex()
          %assign selfCoderDataGroup = ::CompiledModel.CoderDataGroup[selfCoderDataGroupIndex]
          %assign coderDataGroupToken = "CoderDataGroup" + selfCoderDataGroup.Name
          %if (aVarGroupType == coderDataGroupToken)
            %assign hasUnconditionalElement = TLC_TRUE
            %if !SLibCanInlineRTMIntoSelf() && !::CompiledModel.EmptyRealTimeObject && !SLibSynthesizedRTM()
              %assign legacyRTMTypeName = ::CompiledModel.GlobalScope.tSimStructType
              %assign legacyRTMField = legacyRTMTypeName + "* " + SLibGetRTMPointerVariableNameInsideSelfStructure() + ";"
              %<legacyRTMField>
            %endif
          %endif
        %elseif (aVarGroupType == "Self")
          %assign hasUnconditionalElement = TLC_TRUE
        %endif
      %endif
 
      %if !hasUnconditionalElement && !ISEMPTY(hasElement)
        #ifndef %<hasElement>
        char %<dummyElementName>;
        #endif
      %endif
 
      %closefile tmpBuf
      %assign res[0] = tmpBuf
      %assign res[1] = numFields
      %assign res[2] = LibCGTypeStructAlignment(cgTypeIdx)
    %endif
 
    %% Propagate IndexOfLastNonEmptyMember to all instances
    %assign category = varGroup.Category
    %if category == "HierarchicalCoderData"
      %assign group = FcnGetCoderGroupForVarGroup(varGroup)
      %assign indexFieldName = "CoderDataGroup" + group.Name + "VarGroupIndex"
    %else
      %assign indexFieldName = category + "VarGroupIndex"
    %endif
    %assign varGroupIndices = GETFIELD(sys, indexFieldName)
    %foreach idx = SIZE(varGroupIndices, 1) - 1
      %assign sibling = ::CompiledModel.VarGroups.VarGroup[varGroupIndices[idx + 1]]
      %assign sibling.IndexOfLastNonEmptyMember = varGroup.IndexOfLastNonEmptyMember
    %endforeach
   
  %endif
  %<LibSetFieldSet(sys, "Has" + aVarGroupType + "Arg")>
  %return res
%endfunction
 
%%Function:FcnAddModelRefHeaderForCoderGroup
%%Abstract:
%%Helpertoaddrequiredmodelreferenceheaderfiles
%function FcnAddModelRefHeaderForCoderGroup(mdlRefBlock,opFile,systemIdx,BlkIndex) void
  %assign ModelRefBlock = System[systemIdx].Block[BlkIndex]
  %assign modelRefHeaderFile = ModelRefBlock.ParamSettings.ReferencedModelName+".h"
  %assign fileName = LibGetModelFileAttribute(opFile.Index,"NameWithoutExtension")
  %assign modelHeaderFileName = LibGetMdlPubHdrBaseName()
  %openfile modelRefHeaderFileBuf
  #include "%<modelRefHeaderFile>"
  %closefile modelRefHeaderFileBuf
   
  %% Include the modelRefHeaderFile for any other file other than
  %% the top model header file. This is because the top model header file
  %% always pound includes the reference model headers.
  %if modelHeaderFileName != fileName
    %<SLibSetModelFileAttribute(opFile,"Includes",modelRefHeaderFileBuf)>
  %endif
%endfunction
 
%%Function:FcnAddDependentHeaderForCoderGroup
%%Abstract:
%%Helpertoadddependentheaderfile
%function FcnAddDependentHeaderForCoderGroup(opFile,headerFile) void
  %assign fileName = LibGetSourceFileAttribute(opFile.Index,"Name")
  %if !CGMODEL_ACCESS("FileRepository.getIsFileAlreadyIncluded", headerFile, fileName)
    %openfile headerFileBuf
    #include "%<headerFile>"
    %closefile headerFileBuf
    %<SLibSetModelFileAttribute(opFile,"Includes",headerFileBuf)>
  %endif
%endfunction
 
%%Function:FcnAddDependentHeaderForCoderGroup
%%Abstract:
%%Helpertoadddependentheaderfile
%function FcnAddDependentHeaderForCoderGroupWithQuotes(opFile,headerFile) void
  %assign oldIncludes = LibGetModelFileAttribute(opFile.Index,"Includes")
  %assign fileName = LibGetSourceFileAttribute(opFile.Index,"Name")
  %openfile headerFileBuf
  #include %<headerFile>
  %closefile headerFileBuf
  %if ISEMPTY(FEVAL("strfind",oldIncludes,headerFile)) ...
    && headerFile != fileName
    %<SLibSetModelFileAttribute(opFile,"Includes",headerFileBuf)>
  %endif
%endfunction
 
%%Function:FcnAddTypeDependenciesForCoderGroup
%%Abstract:
%%HelpertoaddAliasandmultiwordTypedependenciestocodergroupheaderfile
%function FcnAddTypeDependenciesForCoderGroup(dataRec, ownerFileSystemHeader, opFile) void
  %assign cgTypeIdx = LibGetRecordCGTypeIdx(dataRec)
  %assign slTypeIdx = LibCGTypeToSLType(cgTypeIdx)
  %if slTypeIdx <= ::CompiledModel.DataTypes.NumDataTypes && slTypeIdx >= 0
    %assign dt = ::CompiledModel.DataTypes.DataType[slTypeIdx]
    %if ISFIELD(dt, "HeaderFile")
      %assign childHeaderFile = dt.HeaderFile
      %if childHeaderFile != ownerFileSystemHeader && !ISEMPTY(childHeaderFile)
        %<FcnAddDependentHeaderForCoderGroupWithQuotes(opFile,childHeaderFile)>
      %endif
    %endif
    %if LibIsHalfDataType(slTypeIdx)
      %assign halfIncludeFile = "/"" + SLibCoderHalfTypeHdrFilename() + "/""
      %<FcnAddDependentHeaderForCoderGroupWithQuotes(opFile, halfIncludeFile)>
    %endif
    %if LibIsDataTypeMultiWordFixpt(slTypeIdx)
      %assign includeFile = "/"" + SLibCoderMultiwordTypesFilename() + "/""
      %<FcnAddDependentHeaderForCoderGroupWithQuotes(opFile, includeFile)>
    %endif
  %endif
%endfunction
 
%function SLibGetFileNameWithoutExtension(headerFileName) void
  %assign headerFileNameWithoutExtension = ""
  %assign headerLength = SIZE(headerFileName)
  %foreach idx = headerLength[1]
    %if headerFileName[idx] == "."
      %break
    %endif
    %assign headerFileNameWithoutExtension = "%<headerFileNameWithoutExtension>%"
  %endforeach
  %return headerFileNameWithoutExtension
%endfunction
 
%function SLibAddCoderGroupHeaderFilePoundIncludes(sysIdx, coderDataGroupIdx) void
  %assign varGroupIdx = SLibGetVarGroupIdxForCoderGroup(sysIdx, coderDataGroupIdx)
   
  %if varGroupIdx < 0
    %return
  %endif
 
  %assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
  %assign coderGroup = ::CompiledModel.CoderDataGroup[coderDataGroupIdx]
  
  %assign system = ::CompiledModel.System[sysIdx]
   
  %if coderGroup.IsSelf && SLibIsSystemTypesModelClassNamespace(system)
    %% don't include if it's self group generated in model class
    %return
  %endif
 
    %assign headerFile = varGroup.CoderDataGroupHeaderFile
    %assign fHeaderFile = SLibGetFileNameWithoutExtension(headerFile)
    %openfile sysheader
    #include "%<headerFile>"
    %closefile sysheader
 
    %assign ownerFileSystem = ::CompiledModel.System[system.FileNameOwnerIdx]
    %assign systemIncludes = LibGetSystemField(ownerFileSystem, "SystemIncludes")
     
    %assign modelHeaderFileName = LibGetMdlPubHdrBaseName()
    %assign modelNameHeader = modelHeaderFileName + ".h"
    %assign modelTypesHeader = LibGetMdlTypesHdrBaseName() + ".h"
    %assign modelPrivateHeader = LibGetMdlPrvHdrBaseName() + ".h"
    %assign systemPrivateHeader = ownerFileSystem.SystemHeaderFileName + "_private.h"
 
    %assign isGlobalServerHeader = (headerFile == systemPrivateHeader && ...
                                    LibIsGlobalServer(ownerFileSystem))
     
    %if ISEMPTY(FEVAL("strfind", systemIncludes, headerFile)) && ...
        (headerFile != modelNameHeader) && ...
        (headerFile != modelTypesHeader) && ...
        (headerFile != modelPrivateHeader) && ...
        (fHeaderFile != ownerFileSystem.SystemHeaderFileName) && ...
        !isGlobalServerHeader
        %<LibAddToSystemField(ownerFileSystem,"SystemIncludes",sysheader)>
    %endif
%endfunction
 
%%Function:LibCacheSystemCoderDataGroupStructDef_Impl
%%Abstract:
%%HelperforLibCacheSystemCoderDataGroupStructDefs
%function LibCacheSystemCoderDataGroupStructDef_Impl(sysIdx, coderDataGroupIdx, dataGroupStructDefForTesting, emitSelfTypeDef) void
  %assign group = ::CompiledModel.CoderDataGroup[coderDataGroupIdx]
 
  %% It's possible that we may try to emit type definitions for legacy CSC's
  %% if they are on variants subsystems. Just retun for legacy CSC groups.
  %if group.IsLegacyStorageClass
    %return
  %endif
 
  %assign modelHeaderFileName = LibGetMdlPubHdrBaseName()
  %assign modelNameHeader = modelHeaderFileName + ".h"
  %assign modelTypesHeader = LibGetMdlTypesHdrBaseName() + ".h"
  %assign opFile = ""
  %assign baseSystem = ::CompiledModel.System[GetBaseSystemIdx()]
  %assign system = ::CompiledModel.System[sysIdx]
  %assign ownerFileSystem = ::CompiledModel.System[system.FileNameOwnerIdx]
  %assign varGroupIdx = SLibGetVarGroupIdxForCoderGroup(sysIdx, coderDataGroupIdx)
  %assign packageAsStruct = TLC_TRUE
  %assign isModelClassNamespace = group.IsSelf && SLibIsSystemTypesModelClassNamespace(system)
  %if varGroupIdx != -1
    %assign varGroup = ::CompiledModel.VarGroups.VarGroup[varGroupIdx]
    %assign packageAsStruct = varGroup.PackageAsStruct
    %assign groupIsImported = SLibCoderDataGroupIsImported(group)
    %assign structTypeDefIsImported = SLibStructTypeDefScopeIsImported(group)
    %assign groupIsOpaque = SLibCoderDataGroupIsOpaque(group)
    %assign headerFile = varGroup.CoderDataGroupHeaderFile
    %assign fHeaderFile = SLibGetFileNameWithoutExtension(headerFile)
 
    %% If it's not imported and we're packaging it as a structure and it's not self group
    %% generated in model class, create the file for the typedef
    %if !structTypeDefIsImported && !isModelClassNamespace
      %assign opFile = SLibAddModelFile("SystemHeader", "Simulink",fHeaderFile)
      %<SLibSetModelFileAttribute(opFile, "Group", "data")>
      %assign ownerFileSystemHeader = ownerFileSystem.SystemHeaderFileName+".h"
 
      %% Add rtwtypes.h based on file packaging format
      %if headerFile != modelNameHeader
        %<SLibSetModelFileAttribute(opFile, "RequiredIncludes", "rtwtypes.h")>
      %endif
       
      %% Add header file for each dependency
      %foreach vgElementId = varGroup.NumVarGroupElements
        %assign vgElement = varGroup.VarGroupElements[vgElementId]
        %assign idNumElement = IDNUM(vgElement)
        %assign recType = idNumElement[0]
        %assign recIdx = idNumElement[1]
        %switch recType
          %case "VG"
            %assign depVarGroup = ::CompiledModel.VarGroups.VarGroup[recIdx]
            %if ISFIELD(depVarGroup, "CoderDataGroupHeaderFile")
              %assign depHeaderFile = depVarGroup.CoderDataGroupHeaderFile
               
              %% Special case: If we're dumping this typedef into parent system's header file,
              %% make sure it's not already included by the parent system
              %assign alreadyIncludedBySystems = TLC_FALSE
              %if headerFile == ownerFileSystemHeader
                %% Check the child VarGroup header to see if its the same
                %% as the child VarGroup system's header file
                %assign depSystem = ::CompiledModel.System[depVarGroup.SysIdx]
                %assign depFileOwnerSystem = ::CompiledModel.System[depSystem.FileNameOwnerIdx]
                %assign depFileSystemHeader = depFileOwnerSystem.SystemHeaderFileName + ".h"
 
                %if depFileSystemHeader == depHeaderFile
                  %assign alreadyIncludedBySystems = TLC_TRUE
                %endif
              %endif
 
              %if (depHeaderFile != ownerFileSystemHeader) && !alreadyIncludedBySystems
                %<FcnAddDependentHeaderForCoderGroup(opFile,depHeaderFile)>
              %endif
            %endif
          %break
          %case "PCDG"
            %assign group = FcnGetCoderGroupForVarGroup(varGroup)
            %assign childDataGroup = FcnGetChildDataGroup(group, recIdx)
            %assign mdlRefBlock = ::CompiledModel.ModelReferenceBlocks[childDataGroup.CompiledModelBlockIndex]
            %assign systemIdx = mdlRefBlock[0]
            %assign blkIndex = mdlRefBlock[1]
            %<FcnAddModelRefHeaderForCoderGroup(mdlRefBlock,opFile,systemIdx,blkIndex)>
          %break
          %case "W"
            %assign dataRec = SLibGetDataRecForVarGroupMember(recType, recIdx)
            %<FcnAddTypeDependenciesForCoderGroup(dataRec, ownerFileSystemHeader, opFile)>
            %assign systemIdx = dataRec.SigSrc[0]
            %assign blkIndex = dataRec.SigSrc[2]
            %assign refBlock = System[systemIdx].Block[blkIndex]
            %if refBlock.Type == "ModelReference"
              %<FcnAddModelRefHeaderForCoderGroup(refBlock,opFile,systemIdx,blkIndex)>
            %endif
          %break
          %case "RCDG"
            %assign childCoderGroup = ::CompiledModel.CoderDataGroup[recIdx]
            %if !childCoderGroup.IsOpaque
            %assign childVarGroupIdx = FcnSysVarGroupIndex(System[sysIdx], "CoderDataGroup" +childCoderGroup.Name, 0)
            %assign childVarGroup = ::CompiledModel.VarGroups.VarGroup[childVarGroupIdx]
            %assign childHeaderFile = childVarGroup.CoderDataGroupHeaderFile
            %if childHeaderFile != ownerFileSystemHeader
              %<FcnAddDependentHeaderForCoderGroup(opFile,childHeaderFile)>
            %endif
            %endif
          %break
          %case "B"
          %case "U"
          %case "Y"
          %case "P"
            %assign dataRec = SLibGetDataRecForVarGroupMember(recType, recIdx)
            %<FcnAddTypeDependenciesForCoderGroup(dataRec, ownerFileSystemHeader, opFile)>
          %break
          %case "ZE"
            %<FcnAddDependentHeaderForCoderGroup(opFile,"zero_crossing_types.h")>
          %break
        %endswitch
      %endforeach
       
      %% Add modelTypesHeader based on file packaging format
      %if headerFile != modelNameHeader
        %if ::CompiledModel.ConfigSet.ERTFilePackagingFormat == "Modular"
          %<SLibSetModelFileAttribute(opFile, "RequiredIncludes", modelTypesHeader)>
        %endif
      %endif
    %endif
  %endif
 
  %% Still call SLibGetSystemDataDefUsingVarGroup()
  %% to trigger side effects but don't actually cache the code
  %if SLibStructTypeDefScopeIsImported(group) && ...
      !::CompiledModel.GenerateImportedDataGroupsTypes
    %return
  %endif
  %% Supress structure definition for base system if AsStructure = None
  %if !packageAsStruct
    %return
  %endif
  %assign groupDef = ""
  %assign groupName = group.Name
  %assign groupToken = "CoderDataGroup" + groupName
  %if group.IsSelf && sysIdx == GetBaseSystemIdx() && SLibCanInlineRTMIntoSelf()
    %assign identifier = tSimStructType
  %else
    %assign identifier = FcnSysVarGroupType(System[sysIdx], groupToken)
  %endif
  %if SLibCoderDataGroupIsOpaque(group)
    %assign identifierTag = identifier + "_tag"
  %elseif SLibIsSynthesizedRTM(group) && SLibCoderGroupPackageAsStruct(group) && ...
    (sysIdx == GetBaseSystemIdx())
    %assign identifierTag = ::tSimStructTypeTag
    %assign identifier = "" %% For synthesized base self, we typedef in model_types
  %else
    %assign identifierTag = ""
  %endif
  %assign sysInfo = GetSystemNameForComments(System[sysIdx])
 
  %assign groupBuff = SLibGetSystemDataDefUsingVarGroup(sysIdx, groupToken, TLC_FALSE)
   
  %openfile comment
  %if SLibIsSelfCoderGroup(sysIdx, coderDataGroupIdx)
    /* Self %<group.Identification>, for %<sysInfo> */
  %else
    /* %<group.Identification>, for %<sysInfo> */
  %endif
  %closefile comment
 
  %if (sysIdx == (NumSystems-1))
    %assign field = groupToken + "StructDefn"
    %addtorecord ::CompiledModel %<field> WHITE_SPACE(groupBuff[0])?"":"Nonempty"
    %if SLibAutosarActive()
      %assign identifierTag = ""
    %endif
  %endif
  %if groupBuff[1] > 0 %% number of elements
    %openfile groupDef
     
    %assign nonInlSysIdx = System[sysIdx].NonInlinedParentSystemIdx
    %if !LibSystemIsReusedLibraryFcn(System[nonInlSysIdx]) && ...
      %<SLibAllocatesCoderDataGroup(group)>
      %<GetHideChildDefineSymbol("ifndef")>/
    %endif
    %if !(SLibIsSelfCoderGroup(sysIdx, coderDataGroupIdx) && !emitSelfTypeDef)
      %<comment>/
      %% The coder groups elements themselves are guarded. No outer guarding is needed
      %% TopTester :test/toolbox/simulink/variants/inlineVariants/variantSource/codeGen/tCodeGenVsSimGecks.m -testspec:mg1623720
      %%<SLibIfSystemVariantCondition(System[sysIdx])>
      %<SLibDumpStructDefWithAlignment(identifierTag, identifier, groupBuff[2], groupBuff[0])>
      %%<SLibEndIfSystemVariantCondition(System[sysIdx])>
    %endif
    %if !LibSystemIsReusedLibraryFcn(System[nonInlSysIdx]) && ...
      %<SLibAllocatesCoderDataGroup(group)>
      %<GetHideChildDefineSymbol("endif")>/
    %endif
    %closefile groupDef
     
    %if SLibStructTypeDefScopeIsImported(::CompiledModel.CoderDataGroup[coderDataGroupIdx]) ...
        && ::CompiledModel.GenerateImportedDataGroupsTypes
      %% create a test file for the typedef
      %assign ownerInfo = ...
          FEVAL("rtw.connectivity.Utils.getMDXOwnerInfo", ::CompiledModel.Name)
 
      %% if this group has an MDXOwner dump the typedef in the
      %% LibEmitSystemGroupStructDefsForTesting buffer. We will emit them
      %% later in the test/Model_GroupTypes.h file
      %if ownerInfo.HasMDXOwner
        %selectfile dataGroupStructDefForTesting
        %<groupDef>
      %else
        %% else if this group does not have an owner so we will emit the
        %% typedefs in the test/"group.headerfile" file
        %assign headerName = varGroup.CoderDataGroupHeaderFile
        %assign file = FEVAL("rtw.connectivity.Utils.createStubFolderAndGetFilePaths", ...
          ::CompiledModel.Name, IsModelReferenceRTWTarget(), headerName)
        %openfile stub = file.RelativePath, "a"
        %<groupDef>
        %closefile stub
      %endif
    %else
      %% dump the typedefs in the exported file
      %if isModelClassNamespace
        %<SLibCacheCPPEncapModelData("Typedefs", groupDef)>
      %else
        %<SLibSetModelFileAttribute(opFile, "Typedefs", groupDef)>
      %endif
    %endif
  %endif
%endfunction
 
%%Function:LibCacheSystemCoderDataGroupStructDef=================================================
%%Abstract:
%%Cachesthedefinitionofthesystemstructureforacoderdatagroup
%%
%function LibCacheSystemCoderDataGroupStructDefs(sysIdx) void
  %if !SLibSystemHasOwnDataScope(System[sysIdx])
    %return
  %endif
  %if ::CompiledModel.NumCoderDataGroups == 0
    %return
  %endif
     
  %openfile dataGroupStructDefForTesting
   
  %assign collectiveDefs = ""
  %assign slfCoderGrpIdxs = []
  %% Make sure that the value of the GenerateImportedDataGroupsTypes
  %% feature is compatible with the current SystemTargetFile
  %if (::CompiledModel.GenerateImportedDataGroupsTypes && (::CompiledModel.ConfigSet.SystemTargetFile != "mdx.tlc"))
    %<SLibReportErrorWithId("PIL:pil:UnsupportedSTFGenGroupsTypes")>
  %endif
  %foreach coderDataGroupIdx = ::CompiledModel.NumCoderDataGroups
    %<SLibAddCoderGroupHeaderFilePoundIncludes(sysIdx, coderDataGroupIdx)>
    %% The type definition for Self must go last; that is why we skip
    %% Self at this point if we encounter it.
    %if SLibGetSelfCoderDataGroupIndex() == coderDataGroupIdx && (GetBaseSystemIdx() > sysIdx)
      %continue
    %endif
    %<LibCacheSystemCoderDataGroupStructDef_Impl(sysIdx, coderDataGroupIdx, dataGroupStructDefForTesting, TLC_FALSE)>
  %endforeach
  %closefile dataGroupStructDefForTesting
 
  %% Dump dataGroupStructDefForTesting if needed
  %if !SLibIsSelfUserDefinedAndStructured()
    %% Emit now since there is no self
    %<LibEmitSystemGroupStructDefsForTesting(dataGroupStructDefForTesting)>
  %elseif !ISEMPTY(dataGroupStructDefForTesting) && !WHITE_SPACE(dataGroupStructDefForTesting)
    %% Emit later since we will have a Self typedef that hasn't been finalized yet; we will emit
    %% at that point. See code around LibCacheSystemCoderDataGroupStructDef_Impl in formatwide.tlc.
    %<LibAddToCompiledModel("CoderGroupStructDefinitionsForTesting", dataGroupStructDefForTesting)>
  %endif
   
  %assign groupToken = "sys_data_CoderDataGroup_typedef"
  %<SLibCacheSystemCodeToFile(groupToken, System[sysIdx], collectiveDefs)>
%endfunction %% LibCacheSystemCoderDataGroupStructDefs
 
 
%%Function:LibEmitSystemGroupStructDefsForTesting================================================
%%Abstract:
%%Createsthe'test'folderanddumpsthetypedeclarationsforthe
%%CoderDataGroupsin"buffer"
%%
%function LibEmitSystemGroupStructDefsForTesting(buffer) void
   
  %if SLibNeedGroupTypesForTesting() && IsModelReferenceTarget()
    %assign ownerInfo = FEVAL("rtw.connectivity.Utils.getMDXOwnerInfo",::CompiledModel.Name)
    %assign isModelRefRTWTarget = IsModelReferenceRTWTarget()
    %% check if we need to include model_types.h
    %if ::CompiledModel.ConfigSet.ERTFilePackagingFormat == "Modular"
      %assign modelTypesHeader = ::CompiledModel.Name+"_types.h"
      %assign modelTypesHFile = FEVAL("rtw.connectivity.Utils.getFilePaths", ...
        modelTypesHeader, ::CompiledModel.Name, isModelRefRTWTarget)
      %assign modelTypesHFileRelName = modelTypesHFile.RelativePathToSlprj
    %else
      %assign modelTypesHFileRelName = []
    %endif
    %% check if we need to include model_access_functions.h
    %% need g1435529
    %%if !ISEMPTY(::CompiledModel.AccessFunctionTestHFileName)
    %if TLC_FALSE
      %assign accessFcnHFile = FEVAL("rtw.connectivity.Utils.getFilePaths", ...
        ::CompiledModel.AccessFunctionTestHFileName, ::CompiledModel.Name, isModelRefRTWTarget)
      %assign accessFcnHFileRelName = accessFcnHFile.RelativePathToSlprjStub
    %else
      %assign accessFcnHFileRelName = []
    %endif
 
    %if !WHITE_SPACE(buffer) && ownerInfo.HasMDXOwner
      %% this system has a MDXOwner, we have to generate a stub header
      %assign headerFileName = ownerInfo.StubHeaderFileName
      %assign file = FEVAL("rtw.connectivity.Utils.createStubFolderAndGetFilePaths", ...
        ::CompiledModel.Name, isModelRefRTWTarget, headerFileName)
 
      %assign headerTag = "RTW_HEADER_" + headerFileName + "_h_"
      %openfile stub = file.RelativePath + ".h"
#ifndef %<headerTag>
#define %<headerTag>
      %assign tgtType = "RTW"
      %assign refModelsIncludes = FEVAL("rtw.connectivity.Utils.includeReferencedModelsHeaders", ::CompiledModel.Name, tgtType)
      %if !ISEMPTY(refModelsIncludes)
%<refModelsIncludes>
      %endif
      %if !ISEMPTY(accessFcnHFileRelName)
#include "%<accessFcnHFileRelName>"
      %endif
      %if !ISEMPTY(modelTypesHFileRelName)
#include "%<modelTypesHFileRelName>"
      %endif
%<buffer>
 
#endif /* %<headerTag> */
      %closefile stub
      %% we also need to add the path to the owner (FC) 'test' folder to build this ref model
      %assign addOwnerTestPath = TLC_TRUE
      %if !FEVAL("rtw.connectivity.Utils.addHeaderFileToBuildInfo",...
        ::CompiledModel.Name,file.AbsolutePath, addOwnerTestPath)
        %<SLibReportErrorWithId("RTW:tlc:TestGroupTypesModifyBuildInfo")>
      %endif
      %% indent with c_beautyfier
      %<SLibIndentFile(file.AbsolutePath + ".h", ::CompiledModel.Name)>
    %else
      %% the correct header has been generated, we need just to post process it
      %% this will also add the path to model_ref/'test' to build info
      %matlab feval("rtw.connectivity.Utils.postProcessSystemHeadersWithNoOwner",...
        ::CompiledModel.Name, accessFcnHFileRelName, modelTypesHFileRelName)
    %endif
  %endif
%endfunction %% LibEmitSystemGroupStructDefsForTesting
 
 
%%FunctionSLibCGIRMutexOp====================================================
%%Abstract:
%%Thisdummyfunctionisanexamplefortargetauthortowritetheirown
%%LibGenTargetSpecificMutex.
%%MutextOpTypeisthetypeofoperationformutualexclusion(e.g.mutex):
%%0:Createorinitializemutualexclusion.
%%1:Lock
%%2:Unlock
%%3:Destroymutualexclusion
%%
%%mutexDWisavoidpointer.ThisisablockDWorkusedto
%%savemutualexclusionpointerorID.
%%
%function SLibCGIRMutexOp(MutexOpType, mutexDW)
  %if TargetRegistMutexOp && SLibConcurrentTasks()
      %return SLibGenPlatformSpecificMutexThruTFLLookup(MutexOpType, mutexDW)
    %else
    %if ::CompiledModel.ConcurrentTasks == "yes"
      %if !LibIsModelReferenceSimTarget() && !Accelerator && !::isRAccel
        %assign warnTxt = "Generating example Mutex code for illustration purpose only. "...
          "To support data transfer for concurrent tasks, target must include "...
          "'TargetRegisterMutexOp = 1' in target system file and "...
          "provide tlc file to generate target specific mutex implementation code"
        %<LibReportWarning(warnTxt)>
      %endif
      %assign ::CompiledModel.ConcurrentTasks = "dummy"
    %endif
    %return SLibCGIRDummyMutex(MutexOpType, mutexDW)
  %endif
%endfunction
 
 
%function SLibCGIRDummyMutex(MutexOpType,mutexDW)
  %switch (MutexOpType)
    %case 0
      %return " /* %<mutexDW> = semBCreate(SEM_Q_PRIORITY, SEM_EMPTY); */ /n"
    %case 1
      %return"/* semTake(%<mutexDW>, WAIT_FOREVER) */ /n"
    %case 2
      %return "/* semGive(%<mutexDW>) */ /n"
    %case 3
      %return "/* semDelete(%<mutexDW>) */ /n"
    %default
      %return " error out /n"
  %endswitch
%endfunction
 
%%FunctionSLibCGIRSynchroOp==================================================
%%Abstract:
%%Thisdummyfunctionisanexamplefortargetauthortowritetheirown
%%LibGenTargetSpecificSynchro.
%%SynchroOpTypeisthetypeofoperationforsynchronization:
%%0:Createorinitializesynchronizationoperation(e.g.semaphore)
%%1:Waitforsynchronization
%%2:Sendsynchronizationrequest
%%3:Destroysynchronizationoperation.
%%
%%synchroDWisavoidpointer.ThisisablockDWorkusedtosavethe
%%synchronizationpointerorID.
%%
%%initValisanintegerusedtospecifytheinitialvalueofthesemaphore.
%%
%function SLibCGIRSynchroOp(SynchroOpType, synchroDW, initVal) void
  %if TargetRegistSynchroOp && SLibConcurrentTasks()
      %% START_ASSERT
      %assign msg = "TLC TFL solution is not supported for Synchronous Semaphore mode"
      %<LibReportFatalError(msg)>
      %% END_ASSERT
    %else
    %if ::CompiledModel.ConcurrentTasks == "yes"
      %if !LibIsModelReferenceSimTarget()
        %assign warnTxt = "Generating example Semaphore code for illustration purpose only. "...
          "To support data transfer for concurrent tasks, target must include "...
          "'TargetRegisterSynchroOp = 1' in target system file and "...
          "provide tlc file to generate target specific semaphore implementation code"
        %<LibReportWarning(warnTxt)>
      %endif
      %assign ::CompiledModel.ConcurrentTasks = "dummy"
    %endif
    %return SLibCGIRDummySynchro(SynchroOpType,synchroDW, initVal)
  %endif
%endfunction
 
%function SLibCGIRDummySynchro(SynchroOpType, synchroDW, initVal) void
  %switch (SynchroOpType)
    %case 0
      %return " /* %<synchroDW> = semBCreate(SEM_Q_PRIORITY, SEM_EMPTY); */ /n"
    %case 1
      %return"/* semTake(%<synchroDW>, WAIT_FOREVER) */ /n"
    %case 2
      %return "/* semGive(%<synchroDW>) */ /n"
    %case 3
      %return "/* semDelete(%<synchroDW>) */ /n"
    %default
      %return " error out /n"
  %endswitch
%endfunction
 
 
%function SLibCGIRIsSampleHit(tid, compIdx) void
  %if !LibIsDeploymentDiagram() || ...
    !SLibIsMappedSystemInDeploymentDiagram(System[compIdx].NonInlinedParentSystemIdx)
    %return LibIsSampleHit(tid)
  %else
    %return SLibDeploymentIsSampleHit(tid, compIdx)
  %endif
%endfunction
 
   
%function SLibCreateRecordForMutex(key)
  %createrecord FcnRec {Name key; NumArgs 1; NumDWorkArgs 1}
  %addtorecord FcnRec ArgList {Expr ""; TypeId tSS_VOID; IsPtr 0; IsCplx 0; IsConst 0}
  %addtorecord FcnRec DWorkArgList {Expr ""; TypeId tSS_VOID; IsPtr 1; IsDoublePtr 0; IsCplx 0; IsConst 0}
  %return FcnRec
%endfunction %% SLibCreateRecord
 
 
%function SLibGenPlatformSpecificMutexThruTFLLookup(MutexOpType, mutexDW)
  %% create record to query TFL
  %switch(MutexOpType)
    %case 0
      %assign key = "RTW_MUTEX_INIT"
      %break
    %case 1
      %assign key = "RTW_MUTEX_LOCK"
      %break
    %case 2
      %assign key = "RTW_MUTEX_UNLOCK"
      %break
    %case 3
      %assign key = "RTW_MUTEX_DESTROY"
      %break
    %default
      %return " error out /n"
      %%break
  %endswitch
   
  %assign FcnRec = SLibCreateRecordForMutex(key)
  %assign FcnRec.DWorkArgList.Expr = mutexDW
 
  %assign FcnInfo = SLibGenFcnCallInfo(FcnRec)
  %assign callExpr = "%<FcnInfo.Expr>; /n"
  %return callExpr
 
%endfunction %% SLibGenPlatformSpecificMutexThruTFLLookup
 
 
%function SLibCallMdlOutputsParameterSampleTime() Output
  %assign paramChangeTid = SLibTidOfParameterChangeEvent()
  %if paramChangeTid != -1
    MdlOutputsParameterSampleTime(%<paramChangeTid>);
  %endif
%endfunction
 
 
/% LocalWords: DWork ZCSV ZC GMM SLib rhs Iter Concat Addr zc pzc YQualifier
 %/
/% LocalWords: deref ret reim UQualifier Expr iter ASYNC Proto Async Cpi DSM
 %/
/% LocalWords: UB DATATYPE SCP
 %/