MATLAB Examples

Eliminate Dead Code Paths in Generated Code

This example shows how the code generator eliminates dead (that is, unused) code paths from generated code. This optimization increases execution speed and conserves ROM and RAM consumption.

Contents

Example

In the model rtwdemo_deadpathElim, the signal leaving the Sum block divides into two separate code paths. The top path is not a dead code path. If the user disables the Assertion block, the bottom path becomes a dead code path.

model = 'rtwdemo_deadpathElim';
open_system(model);

Generate Code with an Enabled Assertion Block

  1. For the Assertion block, open the block parameters dialog box.
  2. Select the Enable assertion box. Alternatively, use the command-line API to enable the Assertion block.
set_param([model '/Assert1'], 'Enabled', 'on');

Create a temporary folder for the build and inspection process.

currentDir = pwd;
[~,cgDir] = rtwdemodir();

Build the model.

rtwbuild(model)
### Starting build procedure for model: rtwdemo_deadpathElim
### Successful completion of build procedure for model: rtwdemo_deadpathElim

Because the Assertion block is enabled, these lines of rtwdemo_deadpathElim.c include code for the Gain and Assertion blocks.

cfile = fullfile(cgDir,'rtwdemo_deadpathElim_grt_rtw','rtwdemo_deadpathElim.c');
rtwdemodbtype(cfile,'/* Model step', '/* Model initialize function */', 0, 1);
void rtwdemo_deadpathElim_step(void)
{
  /* Sum: '<Root>/Sum1' incorporates:
   *  Constant: '<Root>/Constant1'
   *  Inport: '<Root>/In1'
   */
  rtwdemo_deadpathElim_Y.Out1 = rtwdemo_deadpathElim_U.In1 + 1.0;

  /* Assertion: '<Root>/Assert1' incorporates:
   *  Gain: '<Root>/G1'
   */
  utAssert(2.0 * rtwdemo_deadpathElim_Y.Out1 != 0.0);
}

Generate Code with a Disabled Assertion Block

Disable the Assertion block to generate a dead code path. The code generator detects the dead code path and eliminates it from the generated code.

  1. For the Assertion block, open the Block Parameters dialog box.
  2. Deselect the Enable assertion box.

Alternatively, use the command-line API to disable the Assertion block.

set_param([model '/Assert1'], 'Enabled', 'off');

Build the model.

rtwbuild(model)
### Starting build procedure for model: rtwdemo_deadpathElim
### Successful completion of build procedure for model: rtwdemo_deadpathElim

Because the Assertion block is disabled, these lines of rtwdemo_deadpathElim.c do not include code for the Gain and Assertion blocks.

rtwdemodbtype(cfile,'/* Model step', '/* Model initialize function */', 0, 1);
void rtwdemo_deadpathElim_step(void)
{
  /* Outport: '<Root>/Out1' incorporates:
   *  Constant: '<Root>/Constant1'
   *  Inport: '<Root>/In1'
   *  Sum: '<Root>/Sum1'
   */
  rtwdemo_deadpathElim_Y.Out1 = rtwdemo_deadpathElim_U.In1 + 1.0;
}

Close the model and clean-up.

bdclose(model)
rtwdemoclean;
cd(currentDir)

For another example of how the code generator eliminates dead code paths in the generated code, see rtwdemo_deadpath.