Main Content

Block Replacement for Code Optimization

You can configure the code generator to replace the default C/C++ code generated for a Simulink® block with custom implementation code, such as a library optimized for your target hardware. Customize how and when the code generator replaces the code for Simulink blocks by developing a code replacement library that includes block replacement entries.

How Block Replacement Works

To replace generated code for a block, you create a code replacement library that contains block replacement entries. Each entry defines the conceptual representation of a block and maps it to the implementation code that you want to use to replace the code generated for that block. When the code generator encounters a block that matches the conceptual representation in a block replacement entry, instead of generating the default code for the block, it generates calls to the implementation code that you specify in the entry. The code generator also generates code needed for packaging, initializing, and updating data associated with the implementation. If a block matches multiple block replacement entries in a table, the code generator uses the entry with the higher priority, which you specify when you create the entry. The highest priority is 0 and the lowest priority is 100.

Code replacement for blocks does not change the simulation behavior of the blocks for which you replace the code.

Conceptual Information for Matching Blocks

In a block replacement entry, the conceptual representation describes the blocks for which you want to replace the default generated code with your implementation code. The code generator uses conceptual information to match blocks for code replacement. The conceptual representation of a block includes these parts:

  • Block key

  • Inputs and outputs

  • Block property settings

  • Block parameter arguments

For more information about conceptual information that you can specify for a block replacement entry, see RTW.TflBlockEntry.

Block Key

The block key indicates the type of block that the block replacement entry matches. For example, DiscreteFir is the key for the Discrete FIR filter block.

To find the key for a block, determine the value of the BlockType property for the block. For example, use get_param at the command line and specify the path to the block:

get_param("myModel/Discrete FIR Filter","BlockType")
For the Discrete FIR Filter block, this command returns the block type 'DiscreteFir'. Use this block type as the block key.

If this command returns 'S-Function' as the block type, you must use the MaskType value as the key for the block instead of the block type. Determine the mask type by calling:

get_param("myModel/Biquad Filter","MaskType")

Specify the block key as the Key property of the RTW.TflBlockEntry object.

Block keys for supported blocks are listed in Blocks You Can Replace.

Inputs and Outputs

Specify the data types of the block inputs and outputs by adding conceptual arguments to the block replacement entry. Create an argument handle and add the argument to the entry for each input and output of the block that you want to replace. For an example, see Define the Conceptual Representation.

Block Property Settings

Use block property setting criteria to control the code replacement process so that the code generator matches only blocks that support your implementation code. You can specify settings for the block replacement entry to match, including block dialog properties and block algorithm properties. For example, when your implementation code uses a specific rounding mode, configure the entry to match only blocks that use the same rounding mode. Specify these settings by creating RTW.BlockProperty objects and adding them to the entry. For an example, see Define the Conceptual Representation.

Some blocks have required properties that you must specify in the block replacement entry. For a list of the required properties, see Blocks You Can Replace.

Block Parameter Arguments

When your implementation code uses block parameter values as arguments, or uses derived parameters that depend on block parameter values, you must specify those block parameters as block parameter arguments in the conceptual representation for the block replacement entry. A block parameter argument specifies the data type that the block parameter value must match for code replacement to occur. This specification prevents the code generator from replacing code from a block that uses a data type that is not compatible with the implementation code. Specifying the block parameter argument also enables you to specify the parameter as an argument for an implementation function. For example, if your implementation code for a Discrete FIR filter block uses the value of the Coefficients parameter, you must add that parameter as a block parameter argument. For more information on using block parameter arguments, see Use Derived Data in Replacement Code Implementations.

Implementation Information for Replacing Block Code

In a block replacement entry, the implementation information describes the custom code that you want the generated code to call instead of the default code for the block. You can specify this information about your custom implementation code:

  • Implementation functions that are called by the system functions generated from the block

  • Derived parameters that store values calculated from block inputs, outputs, and other block parameters

  • Arguments used by the replacement functions, including:

    • Derived parameter arguments

    • DWork arguments that are accessible to implementation functions

    • Arguments to use in-place as buffers for both inputs and outputs

Implementation Functions

When you replace the code generated from a block, you can specify which implementation function is called by each system function. You can specify implementation functions for these system functions:

  • initialize — the <model>_initialize function

  • output — the system function containing the output code, which is either the <model>_step function or the <model>_output function, depending on the setting of Single output/update function

  • update — the system function containing the update code, which is either the <model>_step function or the <model>_update function, depending on the setting of Single output/update function

  • terminate — the <model>_terminate function

For each implementation function, you specify properties of the function and arguments for the function signature by using a RTW.CImplementation object. Add the implementation object to the block replacement entry by using the addImplementation method.

outImplementation = RTW.CImplementation;
outImplementation.Name = 'MyDiscreteFIR_out';
argIn = getTflArgFromString(hTable,'u1','single*');
addArgument(outImplementation,argIn);
addImplementation(hEntry,'output', outImplementation);

For more information, see Define the Implementation Representation.

Derived Parameters for Implementation Functions

Some custom implementations that you can use for code replacement require data derived from the block inputs, outputs, and block parameters. For example, an implementation function could require the dimensions of the input data. Input dimensions are not stored as a block parameter but can be computed from the input data. For block code replacement, define this computed data as a derived parameter. For an example that shows how to use derived parameters, see Use Derived Data in Replacement Code Implementations.

DWork Arguments for Implementation Functions

If your implementation function requires states, global data, or other data that is typically generated in a DWork vector, you must create custom DWork vector arguments. Implementation functions can access the DWork vectors that you specify for a block replacement entry. For an example, see Define the Implementation Representation.

Arguments for In-Place Use

If your implementation function uses a buffer for both input and output data storage, configure the buffer by specifying the buffer as an in-place argument. For either the input or output argument, set the property ArgumentForInPlaceUse to the name of the other argument that shares the buffer. Use in-place arguments for only input and output arguments. Do not use in-place arguments for derived parameters or DWork vector arguments.

Blocks You Can Replace

This table shows the blocks you can replace, the key for each block, block parameter settings that you can specify, and valid block parameter arguments for each block. The table also indicates which block parameter settings and block parameter arguments you are required to set in a block replacement entry for each block. For fixed-point implementations for supported blocks, you must also specify the required data type parameters.

BlockKeyBlock ParametersBlock Parameter ArgumentsData Type Block Parameters for Fixed-Point Implementations
Discrete FIR FilterDiscreteFir

Required parameters:

  • Coefficient source (CoefSource)

  • Filter structure (FilterStructure)

  • Input processing (InputProcessing)

  • Coefficients (Coefficients)

  • Initial states (InitialStates)

Required parameters:

  • Tap sum (TapSumDataTypeStr)

  • Coefficients (CoefDataTypeStr)

  • Product output (ProductDataTypeStr)

  • Accumulator (AccumDataTypeStr)

  • State (StateDataTypeStr)

  • Output (OutDataTypeStr)

  • Lock data type settings against changes by the fixed-point tools (LockScale)

  • Integer rounding mode (RndMeth)

  • Saturate on integer overflow (SaturateOnIntegerOverflow)

Optional parameters:

  • Coefficients (Coefficients)

  • Initial states (InitialStates)

  • Show enable port (ShowEnablePort)

  • External reset (ExternalReset)

  • Sample time (SampleTime)

Not supported — do not specify these parameters:

  • Coefficients minimum (CoeffMin)

  • Coefficients maximum (CoeffMax)

  • Output minimum (OutMin)

  • Output maximum (OutMax)

Biquad Filter (DSP System Toolbox)Biquad Filter

Required parameters:

  • Coefficient source (FilterSource)

  • Filter structure (IIRFiltStruct)

  • Input processing (InputProcessing)

  • SOS Matrix (Mx6) (BiQuadCoeffs)

  • Initial conditions (IC)

  • Initial conditions on zeros side (ICnum)

  • Initial conditions on poles side (ICden)

  • Scale values (ScaleValue)

Required parameters:

  • Rounding mode (RoundingMode)

  • Saturate on integer overflow (OverflowMode)

  • Coefficients (firstCoeffMode)

  • Product output (prodOutputMode)

  • Accumulator (accumMode)

  • States (memoryMode)

  • Output (outputMode)

  • Section input (stageInputMode)

  • Section output (stageOutputMode)

  • Multiplicand (multiplicandMode)

  • Lock data type settings against changes by the fixed-point tools (LockScale)

Optional parameters:

  • SOS Matrix (Mx6) (BiQuadCoeffs)

  • Scale values (ScaleValues)

  • Initial conditions (IC)

  • Initial conditions on zeros side (ICnum)

  • Initial conditions on poles side (ICden)

  • Scale values mode (ScaleValueMode)

  • Action when the a0 values of the SOS matrix are not one (a0Flag)

  • Optimize unity scale values (OptimizeUnityScaleValues)

FFT (DSP System Toolbox)FFT

Required parameters:

  • FFT implementation (FFTImplementation)

  • Output in bit-reversed order (BitRevOrder)

  • Divide output by FFT length (Normalize)

  • Inherit FFT length from input dimensions (InheritFFTLength)

  • FFT length (FFTLength) — Required if InheritFFTLength is off

  • Wrap input data when FFT length is shorter than input length (WrapInput) — Required if InheritFFTLength is off

NoneFixed-point implementations are not supported.
IFFT (DSP System Toolbox)IFFT

Required parameters:

  • FFT implementation (FFTImplementation)

  • Input is in bit-reversed order (BitRevOrder)

  • Input is conjugate symmetric (cs_in)

  • Divide output by FFT length (Normalize)

  • Inherit FFT length from input dimensions (InheritFFTLength)

  • FFT length (FFTLength) — Required if InheritFFTLength is off

  • Wrap input data when FFT length is shorter than input length (WrapInput) — Required if InheritFFTLength is off

NoneFixed-point implementations are not supported.
FIR Decimation (DSP System Toolbox)FIR Decimation

Required parameters:

  • Coefficient source (FilterSource) — Must be set to dialog parameters, input port, or auto

  • Decimation factor (D)

  • FIR filter coefficients (h) — Required if FilterSource is dialog parameters

  • Filter structure (FiltStruct)

  • Input processing (InputProcessing)

  • Rate options (framing)

  • Output buffer initial conditions (OutputBufInitCond) — Required if framing is allow multirate processing

  • Allow arbitrary frame length for fixed-size input signals (AllowArbitraryInputLength) — Required if framing is enforce single-rate processing

  • Decimation factor (D)

  • FIR filter coefficients (h) — Required if FilterSource is dialog parameters

Fixed-point implementations are not supported.
FIR Interpolation (DSP System Toolbox)FIR Interpolation

Required parameters:

  • Coefficient source (FilterSource) — Must be set to dialog parameters, input port, or auto

  • Interpolation factor (L)

  • FIR filter coefficients (h) — Required if FilterSource is dialog parameters

  • Input processing (InputProcessing)

  • Rate options (framing)

  • Output buffer initial conditions (OutputBufInitCond) — Required if framing is allow multirate processing

  • Interpolation factor (L)

  • FIR filter coefficients (h) — Required if FilterSource is dialog parameters

Fixed-point implementations are not supported.

Limitations

  • Multirate blocks and blocks inside subsystems that require multiple rates do not support block replacement. This includes FIR Interpolation and FIR Decimation blocks that have Rate options set to Allow multirate processing or Input processing set to Elements as channels (sample based).

  • For fixed-point data types, which you create by calling fixdt, you must specify the scaling.

See Also

| |

Related Topics