Home

MSP430 Optimizing C/C++ Compiler User`s Guide

image

Contents

1. MOV W 0 r12 7 17 ADD W 2 SP 7 17 RET 7 171 7 17 PERELEA ALLELE AAA LEAR RKCROROK RAE RORCKOR OR ERA EER RE LAA ESR ERE ERR LL LAR RL RCT STRINGS J EAEE A AE RE RE FEREDE IE ERATE eC ERA AAA e AE A e E AE e e Ee e A RC CIRCE ERAEKKEBRKEAKAEREKEEEAEKAEKERER EKA 50 Using the C C Compiler SLAU132K September 2015 Submit Documentation Feedback Copyright O 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS www ti com Controlling Application Binary Interface Example 2 1 An Interlisted Assembly Language File continued sect const align 2 SCSSL1 string Hello world 10 0 RUE EE R TE TERETE FEER FE IE AE KICK CK AE AE e ICE GR ICI KR GC ICI E A CACERES UR RC KK CK e ehe ke e he Ke ee UNDEFINED EXTERNAL REFERENCES JR kk e e kc kc kk ke kc kk kc kk kk kk kk kk ke kk kk kk kk ke kk ke ke kk kk ke ke kk kk kk kk k kk ke ko ke ke kk k kk ke ke ke e ke ke k ke global printf 2 13 Controlling Application Binary Interface An Application Binary Interface ABI defines the low level interface between object files and between an executable and its execution environment An ABI allows ABI compliant object files to be linked together regardless of their source and allows the resulting executable to run on any system that supports that ABI Object files conforming to different ABIs cannot be linked together The linker detects this situation and g
2. 80 5 4 Using the ULP Advisor ceceece eee eee e ener e tere nee e ee ee nen e ee ee reas eneseneneneneneneneeeneeeasonasenenenenanenaner 81 5 5 Advice on Hardware Configuration cccecceee cece cree eerste nent eee ene e nee nennen nennen nenne n nn nenne 81 5 6 pH E E OEE A E a EE 82 5 64 Size OF Enum TYPES quo n m 83 5 7 aA elg 83 571 Theconst Capo RP 84 5 7 2 The interrupt Keyword c i eoe eeie ree cae rien nan nhu rantur ura rasa WR KR AERE RE RR ER eee ewan 84 5 7 3 The sued m 85 5 7 4 The volatile Keyword c cesses nn HI Im HI nm nnn nnm nnn nn nnm n nnn nn 86 5 8 etse Exceptionblandlifds sek ese eE EEA ee secl als euet accel aiatasta RUE MUN EUMSES EUREN EE ERES 87 5 9 Register Variables and Parameters essseessseeseeeesee eene nnne nemen nenne nnn 87 510 The asm Statement zuo coxa e Sure Ern e nmn nE DAE e eint e RXNENNUERNDM NURK NEU eU UM NR dE 88 STi Pragma BIS ITI ILLI TIITILILUMMEUMM 89 5 11 The BIS AET INTERRUPT sexe sectantes oe norte Diaen n etc emuix uidetur m pasa EHS S EE EEEa 90 5 11 2 The CHECK MISRA Pragma ceeesseesseesene enn enne nne e hene hene e nnn ne enn e nnn nen 90 5 11 97 The CHECK OLP Pragitidis i ee ead oeidu uae EEE E e etemuim eame uie aee s 90 SATA The CLINIC PEagimiaissssueieon oe tnter a a E a E a E a RUD nei MEE ERE 90 5 11 5 The CODE SECTION Pragira
3. The pathnames are directories that contain input files The pathnames must follow these constraints Pathnames must be separated with a semicolon Spaces or tabs at the beginning or end of a path are ignored For example the space before and after the semicolon in the following is ignored set MSP430_C_DIR c path one to tools c path two to tools Spaces and tabs are allowed within paths to accommodate Windows directories that contain spaces For example the pathnames in the following are valid set MSP430_C_DIR c first path to tools d second path to tools The environment variable remains set until you reboot the system or reset the variable by entering Operating System Enter UNIX Bourne shell unset MSP430_C_DIR Windows set MSP430_C_DIR Using the C C Compiler SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS www ti com Controlling the Preprocessor 2 5 Controlling the Preprocessor This section describes features that control the preprocessor which is part of the parser A general description of C preprocessing is in section A12 of K amp R The C C compiler includes standard C C preprocessing functions which are built into the first pass of the compiler The preprocessor handles Macro definitions and expansions include files Conditional compilation Various preprocessor directives specified in the source
4. pragma PERSISTENT x int x 10 SLAU132K September 2015 MSP430 C C Language Implementation 99 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS Pragma Directives www ti com The syntax of the pragmas in C is pragma NOINIT int x pragma PERSISTENT int x 10 The syntax of the GCC attributes is int x__attribute__ noinit int x attribute persistent 0 5 11 20 The NO HOOKS Pragma The NO HOOKS pragma prevents entry and exit hook calls from being generated for a function The syntax of the pragma in C is pragma NO HOOKS func The syntax of the pragma in C is pragma NO_HOOKS See Section 2 14 for details on entry and exit hooks 5 11 21 The PACK Pragma The PACK pragma can be used to control the alignment of fields within a class struct or union type The syntax of the pragma in C C can be any of the following pragma PACK n The above form of the PACK pragma affects all class struct or union type declarations that follow this pragma in a file It forces the maximum alignment of each field to be the value specified by n Valid values for nare 1 2 4 8 and 16 bytes pragma PACK push n pragma PACK pop The above form of the PACK pragma affects only class struct and union type declarations between push and p
5. Inlines calls to small functions Reorders function declarations the called functions attributes are known when the caller is optimized Propagates arguments into function bodies when all calls pass the same value in the same argument position Identifies file level variable characteristics If you use opt_level 3 O3 see Section 3 2 and Section 3 3 for more information opt_level 4 or 04 Performs link time optimization See Section 3 4 for details By default debugging is enabled and the default optimization level is unaffected by the generation of debug information However the optimization level used is affected by whether or not the command line includes the g symdebug dwarf option and the opt level option as shown in the following table Optimizing Your Code SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Performing File Level Optimization opt level 3 option Table 3 1 Interaction Between Debugging and Optimization Options Optimization no g g no opt level opt_level 0 opt_level 0 opt_level opt_level 2 opt_level 0 opt_level n optimized as specified optimized as specified The levels of optimizations described above are performed by the stand alone optimization pass The code generator performs several additional optimizations particularly processor specific optimiza
6. The syntax of the operator is Pragma string literal The argument string literal is interpreted in the same way the tokens following a pragma directive are processed The string literal must be enclosed in quotes A quotation mark that is part of the string literal must be preceded by a backward slash You can use the Pragma operator to express pragma directives in macros For example the DATA SECTION syntax pragma DATA SECTION func section Is represented by the Pragma operator syntax Pragma DATA SECTION func section The following code illustrates using Pragma to specify the DATA SECTION pragma in a macro define EMIT PRAGMA x _Pragma x define COLLECT_DATA var EMIT_PRAGMA DATA SECTION var mysection COLLECT_DATA x ine xg The EMIT PRAGMA macro is needed to properly expand the quotes that are required to surround the section argument to the DATA SECTION pragma MSP430 C C Language Implementation SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated l TEXAS INSTRUMENTS www ti com Application Binary Interface 5 13 5 14 Application Binary Interface An Application Binary Interface ABI defines how functions that are compiled or assembled separately possibly by compilers from different vendors can work together This involves standardizing the data type representation register conventions and
7. void my alias attribute alias myFunc See Section 5 11 17 for more about the interrupt function attribute The format attribute is applied to the declarations of printf fprintf sprintf snprintf vprintf vfprintf vsprintf vsnprintf scanf fscanf vfscanf vscanf vsscanf and sscanf in stdio h Thus when GCC extensions are enabled the data arguments of these functions are type checked against the format specifiers in the format string argument and warnings are issued when there is a mismatch These warnings can be suppressed in the usual ways if they are not desired The malloc attribute is applied to the declarations of malloc calloc realloc and memalign in stdlib h The ramfunc attribute specifies that a function will be placed in and executed from RAM The ramfunc attribute allows the compiler to optimize functions for RAM execution as well as to automatically copy functions to RAM on flash based devices For example attribute ramfunc void f void The ramfunc on option specifies that all functions compiled with this option are placed in and executed from RAM even if this function attribute is not used Newer TI linker command files support the ramfunc attribute automatically by placing functions with this attribute in the Tl ramfunc section If you have a linker command file that does not include a section specification for the Tl ramfunc section you can modify the linker command file to place t
8. 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS What Kind of Optimization Is Being Performed www ti com 3 11 3 Branch Optimizations and Control Flow Simplification The compiler analyzes the branching behavior of a program and rearranges the linear sequences of operations basic blocks to remove branches or redundant conditions Unreachable code is deleted branches to branches are bypassed and conditional branches over unconditional branches are simplified to a single conditional branch When the value of a condition is determined at compile time through copy propagation or other data flow analysis the compiler can delete a conditional branch Switch case lists are analyzed in the same way as conditional branches and are sometimes eliminated entirely Some simple control flow constructs are reduced to conditional instructions totally eliminating the need for branches 3 11 4 Data Flow Optimizations Collectively the following data flow optimizations replace expressions with less costly ones detect and remove unnecessary assignments and avoid operations that produce values that are already computed The compiler with optimization enabled performs these data flow optimizations both locally within basic blocks and globally across entire functions Copy propagation Following an assignment to a variable the compiler replaces references to the variable with its value The value can be another variable a constant or
9. 6 9 4 Initialization Tables The tables in the cinit section consist of variable size initialization records Each variable that must be autoinitialized has a record in the cinit section Figure 6 6 shows the format of the cinit section and the initialization records Figure 6 6 Format of Initialization Records in the cinit Section cinit section Initialization record 1 Initialization record 2 TONER EN Initialization record Initialization record 3 I O I Size in Pointer to Initialization bytes bss area data The fields of an initialization record contain the following information Initialization record n The first field of an initialization record contains the size in bytes of the initialization data The second field contains the starting address of the area within the bss section where the initialization data must be copied The third field contains the data that is copied into the bss section to initialize the variable Each variable that must be autoinitialized has an initialization record in the cinit section 138 Run Time Environment SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com System Initialization Example 6 10 shows initialized global variables defined in C Example 6 11 shows the corresponding initialization table The section cinit c is a subsection in the cinit secti
10. Arithmetic on void pointers and function pointers Initializers Non constant initializers Compound literals Compound literals give structures unions or arrays as values Designated initializers Labeling elements of initializers Cast to union Casting to union type from any member of the union Case ranges Case 1 9 and such Mixed declarations Mixing declarations and code Function attributes Declaring that functions have no side effects or that they can never return Attribute syntax Formal syntax for attributes Function prototypes Prototype declarations and old style definitions C comments C comments are recognized Dollar signs A dollar sign is allowed in identifiers Character escapes The character ESC is represented as e Variable attributes Specifying the attributes of variables Type attributes Specifying the attributes of types Alignment Inquiring about the alignment of a type or variable Feature defined for GCC 3 0 definition and examples at http gcc gnu org onlinedocs gcc 4 7 2 gcc C Extensions htmlitC Extensions 110 MSP430 C C Language Implementation SLAU132K September 2015 Submit Documentation Feedback Copyright O 2015 Texas Instruments Incorporated TEXAS www ti com INSTRUMENTS GNU Language Extensions Table 5 3 GCC Language Extensions continued Extensions Descriptions In
11. Follow these guidelines to interface assembly language and C You must preserve any dedicated registers modified by a function Dedicated registers include Save on entry registers R4 R10 Stack pointer SP or R1 If the SP is used normally it does not need to be explicitly preserved In other words the assembly function is free to use the stack as long as anything that is pushed onto the stack is popped back off before the function returns thus preserving SP Any register that is not dedicated can be used freely without first being saved e Interrupt routines must save all the registers they use For more information see Section 6 7 When you call a C C function from assembly language load the designated registers with arguments and push the remaining arguments onto the stack as described in Section 6 4 1 Remember that a function can alter any register not designated as being preserved without having to restore it If the contents of any of these registers must be preserved across the call you must explicitly save them Functions must return values correctly according to their C C declarations Double values are returned in R12 and R13 and structures are returned as described in Step 2 of Section 6 4 1 Any other values are returned in R12 Run Time Environment SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Interfa
12. The library includes the header files lt string h gt and strings h which provide the following functions for string handling beyond those required string h strdup which duplicates a string strings h bcmp which is equivalent to memcmp bcopy which is equivalent to memmove bzero which replaces memory locations with zero valued bytes ffs which finds the first bit set and returns the index of that bit index which is equivalent to strchr rindex which is equivalent to strrchr Sstrcasecmp and strncasecmp which perform case insensitive string comparisons 7 1 5 Minimal Support for Internationalization The library includes the header files lt locale h gt wchar h and lt wctype h gt which provide APIs to support non ASCII character sets and conventions Our implementation of these APIs is limited in the following ways The library has minimal support for wide and multibyte characters The type wchar t is implemented as unsigned int The wide character set is equivalent to the set of values of type char The library includes the header files wchar h and wctype h but does not include all the functions specified in the standard So called multibyte characters are limited to single characters There are no shift states The mapping between multibyte characters and wide characters is simple equivalence that is each wide character maps to and from exactly a s
13. 16 32 F5 none 2 3 5 Symbolic Debugging Options Changing the Compiler s Behavior with Options By default the MSP430 compiler uses a varying size for every enum When you use the small enum option the smallest possible byte size for the enumeration type is used For details about enum sizes see Section 5 6 1 The linker generates errors if an attempt is made to combine object files with incompatible enumeration types This option is now a compiler option It should be placed on the command line before the z option MSP430 devices do not have a multiply instruction and some devices have no hardware multiply at all Multiplication is performed by a library function that either uses the hardware multiply capability or simulates it in software By default the compiler generates references to the version that does not use the hardware multiplier peripheral that is available on some versions of the MSP430 device If your MSP430 device has multiply hardware you can choose to use the library routine matching your hardware for best performance When compiling for a device where the hardware multiplier is available use the use hw mpy compiler option At compile time using this option causes hardware multiply calls to be inlined during code generation if opt for speed is set to 4 or 5 and opt level is set to any value other than off See the disable interrupts around hw mpy zoff option if you want to control whether interrupt
14. 7 11 1 1 No signal handling is supported 7 14 1 1 The INF INF inf inf NAN and nan styles can be used to print an infinity or NaN 7 19 6 1 7 24 2 1 The output for p conversion in the fprintf or fwprintf function is the same as x of the appropriate size 7 19 6 1 7 24 2 1 The termination status returned to the host environment by the abort exit or Exit function is not returned to the host environment 7 20 4 1 7 20 4 3 7 20 4 4 The system function is not supported 7 20 4 6 J 3 13 Architecture The values or expressions assigned to the macros specified in the headers float h limits h and stdint h are described along with the sizes and format of integer types are described in Section 5 6 5 2 4 2 7 18 2 7 18 3 The number order and encoding of bytes in any object are described in Section 6 2 1 6 2 6 1 The value of the result of the sizeof operator is the storage size for each type in terms of bytes See Section 6 2 6 5 3 4 SLAU132K September 2015 MSP430 C C Language Implementation 79 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Characteristics of MSP430 C www ti com 5 2 Characteristics of MSP430 C The MSP430 compiler supports C as defined in the ANSI ISO IEC 14882 2003 standard including these features Complete C standard library support with exceptions noted below Templates Except
15. NOTE Order of Processing Arguments in the Linker The order in which the linker processes arguments is important The compiler passes arguments to the linker in the following order 1 Object filenames from the command line 2 Arguments following the run linker option on the command line 3 Arguments following the run linker option from the MSP430 C OPTION environment variable 4 1 3 Disabling the Linker compile only Compiler Option 68 You can override the run linker option by using the compile only compiler option The run linker option s short form is z and the compile only option s short form is c The compile only option is especially helpful if you specify the run linker option in the MSP430 C OPTION environment variable and want to selectively disable linking with the compile only option on the command line Linking C C Code SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated l TEXAS INSTRUMENTS www ti com Linker Code Optimizations 4 2 Linker Code Optimizations 4 2 1 Conditional Linking With ELF conditional linking all sections are considered eligible for removal through conditional linking except the reset section Sections are not removed if they are referenced or if they are marked with the retain directive A section that is never referenced by any other section in the program is removed from the program automatically unl
16. Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Function Structure and Calling Conventions 6 4 1 How a Function Makes a Call A function parent function performs the following tasks when it calls another function child function 1 2 The calling function parent is responsible for preserving any save on call registers across the call that are live across the call The save on call registers are R11 R15 If the called function child returns a structure the caller allocates space for the structure and passes the address of that space to the called function as the first argument The caller places the first arguments in registers R12 R15 in that order The caller moves the remaining arguments to the argument block in reverse order placing the leftmost remaining argument at the lowest address Thus the leftmost remaining argument is placed at the top of the stack An argument with a type larger than 16 bits that would start in a save on call register may be split between R15 and the stack The caller calls the function Functions defined in C that must be called in asm must be defined extern C and functions defined in asm that must be called in C must be prototyped extern C in the C file 6 4 2 How a Called Function Responds A called function child function must perform the following tasks 1 If the function is declared with an ell
17. W 4 SP W r12 0 SP 441 MOV W 0 SP 2 SP 161 W 2 SP r12 461 W 4 SP SLAU132K September 2015 MSP430 C C Language Implementation 91 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated Pragma Directives Example 5 6 Using the CODE SECTION Pragma C Source File I TEXAS INSTRUMENTS www ti com pragma CODE_SECTION codeB int i_arg int x return 1 int f_arg float x return 2 Example 5 7 Generated Assembly Code From Example 5 6 sect codeB align 2 clink global i arg Fi UK Be eek eoe ke koe e AER eee dee ek deae Je de Xe de Je ae Sede ee s dee Je deo e de Jede JY dee de dee Ye dee ese FUNCTION NAME i arg int Rm Regs Modified SP SR rl12 i i4 Regs Used SP SR r12 p Local Frame Size 0 Args 2 Auto 0 Save 2 byte RUCKCICE RR RR IERE IEE KORR A IE AE KC RE EKER UR CCCII KICK CRI EKER ER ERA EE RAE EREREREREERER e o i arg Fi 25 PSE Stor SSE wey Sats AN Am iei uad SEN ing SESE Seve CODE Ont der kei ier es SON dede ies Karin ier Rep ieu Kev Sn aE ker Kex SET ien SIE Sn bes Locked tex pes bec ies bec bnt A OEE Rd Ras iecit iue CY SAFE Karen inci acini i MM dat iac iud Ran dan S SUB W 2 SP MOV W r12 0 SP 421 MOV W 1 r12 amp 12 ADD W 2 SP RET sect text align 2 clink global f arg Ff USKORORCOKURETKOEONCK OK EORR RON REOR OE OKCKOREOK RC GER R IE NOR OE OR REOR OK I A A RN IIE AS KORR E KORG OE RERO
18. default integer long multiply routine with the version of the multiply routine that uses the hardware multiplier support Additionally if opt_for_speed is set to 4 or 5 hardware multiplication is inlined during code generation Table 2 15 Entry Exit Hook Options Option Alias Effect Section entry_hook name Enables entry hooks Section 2 14 entry_parm none name Specifies the parameters to the function to the entry_hook option Section 2 14 address exit hook 2name Enables exit hooks Section 2 14 exit parm none name address Specifies the parameters to the function to the exit hook option Section 2 14 Table 2 16 Library Function Assumptions Options Option Alias Effect Section printf_support nofloat full Enables support for smaller limited versions of the printf function Section 2 3 3 minimal family sprintf fprintf etc and the scanf function family sscanf fscanf etc run time support functions std lib func defined ol1 or oL1 Informs the optimizer that your file declares a standard library Section 3 2 1 function std lib func not defined ol2 or oL2 Informs the optimizer that your file does not declare or alter library Section 3 2 1 functions Overrides the ol0 and ol1 options default std lib func redefined olO or oLO Informs the optimizer that your file alters a standard library function Section 3 2 1 SLAU132K September 2015 Using the C C Compiler 23 Submit D
19. deprecated MOV W src R5 void Set SP register unsigned short src MOV src SP unsigned short swap bytes unsigned short src MOV src dst SWPB dst 6 8 2 Deprecated Intrinsics The following intrinsics have been deprecated Using them is not recommended because they may not be supported in future releases Table 6 6 Deprecated Intrinsics Intrinsic get R4 register get R5 register Set R4 register Set H5 register 6 8 3 The delay cycle Intrinsic The delay cycles intrinsic inserts code to consume precisely the number of specified cycles with no side effects The number of cycles delayed must be a compile time constant 130 Run Time Environment Copyright 2015 Texas Instruments Incorporated SLAU132K September 2015 Submit Documentation Feedback I TEXAS INSTRUMENTS www ti com Using Intrinsics to Access Assembly Language Statements 6 8 4 The never executed Intrinsic The MSP430 C C Compiler supports a never executed intrinsic that can be used to assert that a default label in a switch block is never executed If you assert that a default label is never executed the compiler can generate more efficient code based on the values specified in the case labels within a switch block 6 8 4 1 Using never executed With a Vector Generator The never executed intrinsic is specifically useful for testing the values of an MSP430 interrupt vector generator such as the vector gene
20. optimizer_interlist Options main p o 22 2222222 2222222 2222222222222222222222222222 2222222 2222 222 222 2 2 SUB W 2 SP Bee OSS SaaS SS printf const unsigned char Hello world n MOV W SCSSL1 0 0 SP a Sl CALL printf 15 7 I5 p return 0 MOV W 0 r12 gt Wl ADD W 2 SP RET Example 3 2 The Function From Example 2 1 Compiled with the opt_level 2 optimizer_interlist and c_src_interlist Options main OE pea ee ge ee ee ee eee ee ee ee eee SUB W 2 SP eii MN d printf const unsigned char Hello world Nn 5 printf Hello world n MOV W SCSSL1 0 0 SP 451 CALL printf 451 451 gkde Oo ee e erem return 0 n 6 return 0 MOV W 0 r12 461 ADD W 2 SP RET SLAU132K September 2015 Optimizing Your Code 61 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Debugging Optimized Code www ti com 3 9 3 10 62 Debugging Optimized Code Generating symbolic debugging information no longer affects the ability to optimize code The same executable code is generated regardless of whether generation of debug information is turned on or off For this reason debug information is now generated by default You do not need to specify the g option in order to debug yo
21. 1 TEXAS INSTRUMENTS www ti com Changing the ANSI ISO C C Language Mode wcscat wcschr wcscmp wcsncmp wescpy wesncpy wcsftime wcsrtombs wcsstr wcstok wosxfrm Wide character print scan functions Wide character conversion functions 5 15 2 Compatibility With K amp R C kr compatible Option ANSI ISO C is a superset of the de facto C standard defined in Kernighan and Ritchie s The C Programming Language K amp R C mode does not apply to C code nor does it accept the strict interpretation option Most programs written for other non ANSI ISO compilers correctly compile and run without modification However subtle changes in the language can affect existing code Appendix C in The C Programming Language second edition referred to in this manual as K amp R summarizes differences between ANSI ISO C and the first edition s C standard the first edition is referred to in this manual as K amp R C To simplify the process of compiling existing C programs with the ANSI ISO C C compiler the compiler has a K amp R option kr compatible that modifies some semantic rules of the language for compatibility with older code In general the kr compatible option relaxes requirements that are stricter for ANSI ISO C than for K amp R C The kr compatible option does not disable any new features of the language such as function prototypes enumerations initiali
22. Because floating point values are of limited precision and because floating point operations round floating point arithmetic is neither associative nor distributive For instance 1 3e100 3e100 is not equal to 1 3e100 3e100 If strictly following IEEE 754 the compiler cannot in general reassociate floating point operations Using fp reassoc on allows the compiler to perform the algebraic reassociation at the cost of a small amount of precision for some operations SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com keep_unneeded_statics no_const_clink misra_advisory error warning remark suppress misra_required error warning remark suppress preinclude filename printf_support full nofloat minimal 2 3 4 Run Time Model Options Changing the Compiler s Behavior with Options Prevents the compiler from deleting unreferenced static variables The parser by default remarks about and then removes any unreferenced static variables The keep unneeded statics option keeps the parser from deleting unreferenced static variables and any static functions that are referenced by these variable definitions Unreferenced static functions will still be removed Tells the compiler to not generate clink directives for const global arrays By default these arrays are placed in a const subsection and conditionall
23. Linking PIOCeSS a e iren ue rennen ntm a Re se Ls pM DUE a DRE SE RO rR ee FR SER de 69 4 3 1 Including the Run Time Support Library eesseeeeeeen n HII III 70 4 3 2 Run Time Initialization cece cece ee eee ee eee eee en en nn nnm mn mnm hm he ehe ene mee ne nnne i 4 3 3 Initialization by the Interrupt Vector 20 cece cece ee ee cee eee n I I II IH Hm HI n nnn 71 4 3 4 Initialization of the FRAM Memory Protection Unit ceesseeeseeeeee m Hmm 71 4 3 5 Initialization of Cinit and Watchdog Timer Hold cessesseeeenen HH 71 4 3 6 Global Object ConstrUCtOrS rossisoromean esnea a aaa Giaa 72 4 3 7 Specifying the Type of Global Variable Initialization esee 72 4 3 8 Specifying Where to Allocate Sections in Memory ssssssssssssrsnssssussrnnrnnunununnrnnnnnnunnnnnrnnne 73 SLAU132K September 2015 Contents 3 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS www ti com 43 9 A Sampl Linker Command File 5 25 2 rene per rum Rn De Ro RRIx Ox EE EE 74 MSP430 C C Language Implementation c eceeeee cece eee cena eee eee ee eee esses sees eaeeeeeees 75 5 1 ChiaracteristicS OF MSPAJO oc CP t 76 5 1 1 Implementation Defined Behavior cccceeeee cece eeeee eee nee nnnm nm Hm ene nnn nennen nnn 76 5 2 Characteristics Of MSP430 GEF Dr 80 5 3 Using MISRA C2004 ec R
24. Submit Documentation Feedback Copyright O 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com The C I O Functions 7 2 2 Overview of Low Level I O Implementation The low level functions are comprised of seven basic I O functions open read write close Iseek rename and unlink These low level routines provide the interface between the high level functions and the device level drivers that actually perform the I O command on the specified device The low level functions are designed to be appropriate for all I O methods even those which are not actually disk files Abstractly all O channels can be treated as files although some operations such as Iseek may not be appropriate See Section 7 2 3 for more details The low level functions are inspired by but not identical to the POSIX functions of the same names The low level functions operate on file descriptors A file descriptor is an integer returned by open representing an opened file Multiple file descriptors may be associated with a file each has its own independent file position indicator open Open File for I O Syntax include lt file h gt int open const char path unsigned flags int file_descriptor Description The open function opens the file specified by path and prepares it for I O The path is the filename of the file to be opened including an optional directory path and an optional device specifier see Section 7 2
25. Table 2 1 Processor Options Option Alias Effect Section silicon_version msp mspx V Selects the instruction set Section 2 3 4 abi eabi This option is deprecated The only supported ABI is eabi Section 2 13 code_model small large Specifies the code memory model Section 6 1 1 data_model small large Specifies the data memory model Section 6 1 2 restricted near_data globals none Specifies what data must be near Default is globals Section 6 1 3 Table 2 2 Optimization Options Option Alias Effect Section opt_level off Disables all optimization Section 3 1 opt_level n On Level 0 O0 optimizes register usage only default Section 3 1 Level 1 O1 uses Level 0 optimizations and optimizes locally Section 3 2 Level 2 O2 uses Level 1 optimizations and optimizes globally Section 3 4 Level 3 O3 uses Level 2 optimizations and optimizes the file Level 4 O4 uses Level 3 optimizations and performs link time optimization opt_for_speed n mf Controls the tradeoff between size and speed 0 5 range If this Section 3 10 option is specified without n the default value is 4 If this option is not specified the default setting is 1 fp_mode relaxed strict Enables or disables relaxed floating point mode Section 2 3 3 Note Machine specific options see Table 2 14 can also affect optimization SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorpor
26. This may require padding before inside or at the end of the structure to ensure that the long is aligned accordingly and that the sizeof value for the structure is an even value All non field types are aligned on word or byte boundaries Fields are allocated as many bits as requested Adjacent fields are packed into adjacent bits of a word but they do not overlap words If a field would overlap into the next word the entire field is placed into the next word Fields are packed as they are encountered the least significant bits of the structure word are filled first Example 6 1 shows the C code definition of var while Figure 6 1 shows the memory layout of var Example 6 1 C Code Definition of var struct example char c long 1 int bfl 1 int bf2 2 int bf3 3 int bf4 4 int bf5 5 int bf6 6 Figure 6 1 Memory Layout of var 1615 14 131211109 8 76 54 32 1 0 L var 0 lt pad gt var 2 long var 4 long var 6 5 var 8 lt pad 10 bits gt 6 2 2 Character String Constants In C a character string constant is used in one of the following ways To initialize an array of characters For example char s abc When a string is used as an initializer it is simply treated as an initialized array each character is a separate initializer For more information about initialization see Section 6 9 nan expression For example strcpy s abco When a str
27. Writes preprocessed output to a file Section 2 5 4 with the same name as the input but with a pp extension preproc_with_comment ppc Performs preprocessing only Writes preprocessed output keeping Section 2 5 6 the comments to a file with the same name as the input but with a pp extension preproc_with_compile ppa Continues compilation after preprocessing with any of the pp lt x gt Section 2 5 5 options that normally disable compilation preproc_with_line ppl Performs preprocessing only Writes preprocessed output with line Section 2 5 7 control information line directives to a file with the same name as the input but with a pp extension Table 2 12 Predefined Symbols Options Option Alias Effect Section define name def D Predefines name Section 2 3 2 undefine name U Undefines name Section 2 3 2 Table 2 13 Diagnostic Message Options Option Alias Effect Section compiler_revision Prints out the compiler release revision and exits diag_error num pdse Categorizes the diagnostic identified by num as an error Section 2 7 1 diag_remark num pdsr Categorizes the diagnostic identified by num as a remark Section 2 7 1 diag_suppress num pds Suppresses the diagnostic identified by num Section 2 7 1 diag_warning num pdsw Categorizes the diagnostic identified by num as a warning Section 2 7 1 diag_wrap onl off Wrap diagnostic messages default is on display_error_number pden
28. and a list of the intrinsics see Section 6 8 1 The abs function is considered an intrinsic operator 2 11 2 Inlining Restrictions The compiler makes decisions about which functions to inline based on the factors mentioned in Section 2 11 In addition there are several restrictions that can disqualify a function from being inlined by automatic inlining or inline keyword based inlining The FUNC ALWAYS INLINE pragma overrides these disqualifications so you should be aware of situations that can cause problems if you are using the FUNC ALWAYS INLINE pragma e Has a FUNC CANNOT INLINE pragma e Is not defined in the current compilation unit and you are not using O4 optimization Never returns e Isa recursive or nonleaf function that exceeds the depth limit Has a variable length argument list Has a different number of arguments than the call site Has an argument whose type is incompatible with the corresponding call site argument Has a class struct or union parameter Contains a volatile local variable or argument Contains local static variables but is not a static inline function ls not declared inline and contains an asm statement that is not a comment Is the main function e Is an interrupt function Is not declared inline and returns void but its return value is needed Is not declared inline and will require too much stack space for local array or structure variables Furthermore inlining should be
29. and understands how to build the library This allows the linker to automatically build application compatible versions of any vendor s library without needing to register the library in advance as long as the vendor supports mklib 7 4 3 1 Underlying Mechanism The underlying mechanism can be anything the vendor desires For the compiler run time support libraries mklib is just a wrapper that knows how to use the files in the lib src subdirectory of the compiler installation and invoke gmake with the appropriate options to build each library If necessary mklib can be bypassed and the Makefile used directly but this mode of operation is not supported by TI and you are responsible for any changes to the Makefile The format of the Makefile and the interface between mklib and the Makefile is subject to change without notice The mklib program is the forward compatible path 7 4 3 2 Libraries From Other Vendors Any vendor who wishes to distribute a library that can be rebuilt automatically by the linker must provide e An index library like libc a but with a different name Acopy of mklib specific to that library Acopy of the library source code in whatever format is convenient These things must be placed together in one directory that is part of the linker s library search path specified either in MSP430 C DIR or with the linker search path option If mklib needs extra information that is not possible to pass as command line
30. call assumptions 2 to call_assumptions 0 The compiler uses call_assumptions 0 because it presumes that the calls to the assembly language functions that have a definition in C C may call other C C functions or modify C C variables Situation Your application consists of C C source code that calls assembly functions The assembly language functions do not call C C functions but they modify C C variables Solution Try both of these solutions and choose the one that works best with your code e Compile with program level compile opt_level 3 call assumptions 1 Add the volatile keyword to those variables that may be modified by the assembly functions and compile with program level compile opt level 3 call assumptions 2 Situation Your application consists of C C source code and assembly source code The assembly functions are interrupt service routines that call C C functions the C C functions that the assembly functions call are never called from C C These C C functions act like main they function as entry points into C C 4 SLAU132K September 2015 Optimizing Your Code 57 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Link Time Optimization opt level 4 Option www ti com 3 4 3 4 1 58 Solution Add the volatile keyword to the C C variables that may be modified by the interrupts Then you can optimize your cod
31. common path of software development for C language programs The other portions are peripheral functions that enhance the development process Figure 1 1 MSP430 Software Development Flow C C compiler C C name Assembler source Archiver Macro library Archiver demangling utility Assembler Object Library build Debugging utility tools Run time Eana li support objec libra files Linker ry Executable object file Hex conversion utility EPROM Absolute lister Cross reference Object file programmer lister utilities The following list describes the tools that are shown in Figure 1 1 The compiler accepts C C source code and produces MSP430 assembly language source code See Chapter 2 The assembler translates assembly language source files into machine language relocatable object files See the MSP430 Assembly Language Tools User s Guide Thelinker combines relocatable object files into a single absolute executable object file As it creates the executable file it performs relocation and resolves external references The linker accepts relocatable object files and object libraries as input See Chapter 4 for an overview of the linker See the MSP430 Assembly Language Tools User s Guide for details SLAU132K September 2015 Introduction to the Software Development Tools 13 Submit Documentation Feedback Copyright 2015 Texas Instrumen
32. immediately used in a single precision context the computations in the expression are converted to single precision computations Double precision constants in the expression are also converted to single precision if they can be correctly represented as single precision constants Calls to double precision functions in math h are converted to their single precision counterparts if all arguments are single precision and the result is used in a single precision context The math h header file must be included for this optimization to work Division by a constant is converted to inverse multiplication In the following examples iN integer variable fN float variable and dN double variable il fl 2 5 0 gt are float 5 0 is converted to 5 0f il dl d2 d3 are float fl f2 3 1 1 gt are float 1 1 is converted to 1 1f To enable relaxed floating point mode use the fp_mode relaxed option which also sets fp_reassoc on To disable relaxed floating point mode use the fp modeesstrict option which also sets fp reassoc off If strict ansi is specified fp_mode strict is set automatically You can enable the relaxed floating point mode with strict ANSI mode by specifying fp_mode relaxed after strict ansi Enables or disables the reassociation of floating point arithmetic If strict ansi is set fp reassoc off is set since reassociation of floating point arithmetic is an ANSI violation
33. including path information and optional device prefix See Section 7 2 5 The function returns one of the following values 0 if successful 1 on failure Using Run Time Support Functions and Building Libraries 149 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS rename Rename File www ti com rename Rename File Syntax for C include lt stdio h gt lt file h gt int rename const char o d name const char new name Syntax for C include lt cstdio gt lt file h gt int std rename const char old name const char new name Description The rename function changes the name of a file The old name is the current name of the file The new name is the new name for the file NOTE The optional device specified in the new name must match the device of the old name If they do not match a file copy would be required to perform the rename and rename is not capable of this action Return Value The function returns one of the following values 0 if successful 1 on failure NOTE Although rename is a low level function it is defined by the C standard and can be used by portable applications 7 2 3 Device Driver Level I O Functions At the next level are the device level drivers They map directly to the low level I O functions The default device driver is the HOST device driver which uses the debugger to perform file operation
34. non serious warnings which are suppressed by default no warnings Suppresses diagnostic warnings errors are still issued section_sizes on off Generates section size information including sizes for sections containing executable code and constants constant or initialized data global and static variables and uninitialized data Section size information is output during both the assembly and linking phases This option should be placed on the command line with the compiler options that is before the run linker or z option set error limit num Sets the error limit to num which can be any decimal value The compiler abandons compiling after this number of errors The default is 100 Verbose diagnostics Provides verbose diagnostic messages that display the original source with line wrap and indicate the position of the error in the source line write diagnostics file Produces a diagnostic message information file with the same source file name with an err extension The write diagnostics file option is not supported by the linker 2 7 2 How You Can Use Diagnostic Suppression Options The following example demonstrates how you can control diagnostic messages issued by the compiler You control the linker diagnostic messages in a similar manner int one int I int main switch 1 case 1 return one break default return 0 break If you invoke the compiler with the quiet option this
35. pt HoUtlnes iacicececoic ice Duece ie ee rip nre re I pre pico csl D IE i xc E PR PO PEEER D EA E SE 128 6 7 3 Using Assembly Language Interrupt ROUtINGS 0c cece cece cece eee eee ee cece I HH nmn 128 6 7 4 Interrupt VECIOFS ERR 128 6 7 5 Other Interrupt Information sies ru eorr nonae nt nne men re rcr R mE nena en no Rar exa cesar RR ER ER IE ar cones 128 6 8 Using Intrinsics to Access Assembly Language StateMents cceceeeeeeeeee eee eeeeeeeeeeeeeeeeeeeeeeeeeeeeee 129 684 IMSPAS3D IBIIDSIOS atiscaseesiiseaus ciscins eeisteiboeie see a cune E ERES ANS RR 129 6 8 2 Deprecated Intrinsics ccceeeecee ee ee eee ee eeen eene nnnm nn nnne nn nn e nnne 130 6 8 8 The delay cycle INtrINSIC 0 ccc cee cece e eee eee eee eee m m I HI HH HH n nnn 130 6 8 4 The never executed INtrinSiC 2 2 0 ceee cece eee eee eee eee eee nnn nnne 131 6 9 cnra M M 133 6 9 1 Systemi Pre InitialiZatiOfkss sue esae ctu icine arareape c EE MEUM NEN NEUES 133 69 2 RUN TIME StaCK Cu DD 133 6 9 3 Automatic Initialization Of Variables cesseeeeeeenn mH HII HH mme nne 134 6 9 4 Initialization Tables cece ccee cece eee e eee ee nnnm I HI m II III Hm Hm e n e nn he nennen 138 6 10 Compiling for 20 Bit MSP430X Devices ceece cece eee e eee eee eee n III IH HH ne nne enn nennen 140 7 Using Run Time Support Functions and Building
36. the context information is useful when the front end issues a diagnostic while doing a template instantiation or while generating a constructor destructor or assignment operator function For example test c line 7 error A A is inaccessible B x detected during implicit generation of B B at line 7 Without the context information it is difficult to determine to what the error refers Controlling Diagnostic Messages The C C compiler provides diagnostic options to control compiler and linker generated diagnostic messages The diagnostic options must be specified before the run linker option diag_error num Categorizes the diagnostic identified by num as an error To determine the numeric identifier of a diagnostic message use the display_error_number option first in a separate compile Then use diag_error num to recategorize the diagnostic as an error You can only alter the severity of discretionary diagnostic messages diag_remark num Categorizes the diagnostic identified by num as a remark To determine the numeric identifier of a diagnostic message use the display_error_number option first in a separate compile Then use diag_remark num to recategorize the diagnostic as a remark You can only alter the severity of discretionary diagnostic messages diag_suppress num Suppresses the diagnostic identified by num To determine the numeric identifier of a diagnostic message use the display_error_
37. use Use the library linker option to specify the name of the library The linker will search the path specified by the search_path option and then the MSP430_C_DIR environment variable for the named library You can use the library linker option on the command line or in a command file cl430 run linker rom model ram model filenames libraryz libraryname 4 3 1 3 Library Order for Searching for Symbols 70 Generally you should specify the run time support library as the last name on the command line because the linker searches libraries for unresolved references in the order that files are specified on the command line If any object files follow a library references from those object files to that library are not resolved You can use the reread_libs option to force the linker to reread all libraries until references are resolved Whenever you specify a library as linker input the linker includes and links only those library members that resolve undefined references By default if a library introduces an unresolved reference and multiple libraries have a definition for it then the definition from the same library that introduced the unresolved reference is used Use the priority option if you want the linker to use the definition from the first library on the command line that contains the definition Linking C C Code SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instru
38. 11 4 Added C syntax for the CLINK INTERRUPT and RETAIN Section 5 11 17 pragmas Also removed unnecessary semicolons from pragma SLAU132J C C Language Section 5 11 24 and syntax specifications Also the GCC interrupt and alias function Section 5 16 2 attributes are now supported 170 Revision History SLAU132K September 2015 Submit Documentation Feedback Copyright O 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Appendix B Table B 1 Revision History continued Merson Chapter Location Additions Modifications Deletions Added SLAU132J C C Language Section 5 11 8 Added the diag_push and diag_pop diagnostic message pragmas Section 5 15 Added support for C99 and C 03 The relaxed_ansi option is now SLAU1321 C C Language Section 5 15 1 and the default and strict_ansi is the other option normal mode for Section 5 15 3 standards violation strictness is no longer available Run Time s Added reference to section on accessing linker symbols in C and SLAU132J Environment Section 6 5 C in the Assembly Language Tools User s Guide SLAU1321 Run Time Section 6 8 1 and Corrected never executed intrinsic has two underscores as the Environment Section 6 8 4 prefix SLAU1321 Sa ante Section 6 8 2 Deprecated several intrinsics for R4 and R5 access nvironment Run Time Support RTS source code is no longer provided in a rtssrc zip file Instead it SLAU132J F PP Section 7 1 3 is l
39. 157 Submit Documentation Feedback Copyright O 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Library Build Process www ti com 7 4 7 4 1 Library Build Process When using the C C compiler you can compile your code under a large number of different configurations and options that are not necessarily compatible with one another Because it would be infeasible to include all possible run time support library variants compiler releases pre build only a small number of very commonly used libraries such as rts430 eabi lib To provide maximum flexibility the run time support source code is provided as part of each compiler release You can build the missing libraries as desired The linker can also automatically build missing libraries This is accomplished with a new library build process the core of which is the executable mklib which is available beginning with CCS 5 1 Required Non Texas Instruments Software To use the self contained run time support build process to rebuild a library with custom options the following are required sh Bourne shell gmake GNU make 3 81 or later More information is available from GNU at http www gnu org software make GNU make gmake is also available in earlier versions of Code Composer Studio GNU make is also included in some UNIX support packages for Windows such as the MKS Toolkit Cygwin and Interix The GNU make used on Windows platforms should explicitly report
40. 2 3 3 warning remark suppress 20 Using the C C Compiler SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS www ti com Changing the Compiler s Behavior with Options Table 2 8 Hardware Configuration Advisor Options Option Alias Effect Section advice hw_config all none Enables checking the device configuration settings Default is none Section 2 3 3 rulespec if this option is not included on the command line Default is all if this option is used but with no value specified Table 2 9 Control Options Option Alias Effect Section compile_only C Disables linking negates run_linker Section 4 1 3 help h Prints on the standard output device a description of the options Section 2 3 2 understood by the compiler run_linker Z Causes the linker to be invoked from the compiler command line Section 2 3 2 skip_assembler n Compiles C C source file producing an assembly language output Section 2 3 2 file The assembler is not run and no object file is produced Table 2 10 Language Options Option Alias Effect Section c89 Processes C files according to the ISO C89 standard Section 5 15 c99 Processes C files according to the ISO C99 standard Section 5 15 C 03 Processes C files according to the ISO C 03 standard Section 5 15 cpp_ default fg Processes all source files with a C extension as C source files S
41. 2 8 and Added advice hw config option for ULP Advisor checking of device Section 5 5 configuration Added support for C99 and C 03 The gcc option has been see Using the Compiler Table 2 10 deprecated The relaxed_ansi option is now the default Removed documentation of precompiled headers which are not SLAU1321 Using the Compiler Table 2 10 supported for MSP430 SLAU1321 Using the Compiler Table 2 13 and Added section_sizes option for diagnostic reporting of section Section 2 7 1 sizes SLAU132J Using the Compiler le und Added disable interrupts around hw mpy option Section 2 3 4 i Table 2 14 and The use hw mpy option is now a compiler option and performs SLAU132J Using the Compiler Section 2 3 4 additional actions at compile time Documented that the warning and warn preprocessor directives SLAU132J Using the Compiler Section 2 5 3 are supported SLAU132J Using the Compiler Section 2 6 Added section on techniques for passing arguments to main Documented that the inline keyword is now enabled in all modes SLAU1321 Using the Compiler Section 2 11 except C89 strict ANSI mode SLAU132J C C Language Section 5 1 1 Added section documenting implementation defined behavior Section 5 4 SLAU1321 C C Language Section 5 11 3 and Added pragmas for enabling resetting ULP Advisor rule checks Section 5 11 23 SLAU132J C C Language Section 5 6 1 Added documentation on the size of enum types Section 5
42. 221 Gommand Files ODliOlSc s c ose sicco aime Rei eco pete messi G eE E EGE E nd qtei ideal 25 2 22 MISRA G 2004 OptlOhS scere iere nen renun nora HR EuIx Dn eR RR e x ie pee E ecKR Ue cR e esu edens Rm ia ROM DE 25 PAPAS EMI scires 26 2 24 File Search Path Oe jio ND m 26 2 25 Command File Preprocessing Options eseeeeeeeeeeeeeeeehne enne nnn nnne nennen nme 26 2 26 Diagnostic Message Options 5 ien e REN MEAN EORR Uu M NeU E RNIEM E M UEM EEUU 26 2 27 Linker Output Options esses ecu icielse acca er cinque ireteuim e ques catenis tela estesa xim cial dage EAE EE RAE 27 2 28 Symbol Management Options eesseeseeeeeseeleeeee nennen hene heh nnne nnnm nnne nnne nnne 27 2 29 Run Time Environment Options sssss seissen a a a a E a nnn nne nnn nn 27 2 30 LCink Time Optimization OptiOTs u e usando sinna ae eaa e aaa 27 223112 Miscellaneous OPLONS seniii EE DEP EN EEEE UENEN ENEKEN KE 28 2 32 Compiler Backwards Compatibility Options Summary sssssssssnsssnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnnn 37 2 83 Predefined MSP430 Macro Names cessesseeeeleleenn nennen nhe nennen hn nn nnne nnns nn nn nnne 39 2 84 Raw Listing File Identifiers 5 eooee cerne a emee noh ener an nnmeme a arn aha a na YR RE ERA REAPER DERE aEEA 47 2 35 Raw Listing File Diagnostic Identifiers cccceeeeeeee eee eee ences ence eens tees m mH Hmmm nnn 47 3 1 Interaction B
43. Application Binary Interface EABI ABI which uses the ELF object format and the DWARF debug format If you want support for the legacy COFF ABI please use the ARM v5 2 Code Generation Tools and refer to SPNU151J and SPNU118J for documentation abi eabi commonc on off code model large small SLAU132K September 2015 Submit Documentation Feedback This option is deprecated because the only supported application binary interface ABI is EABI When on the default with EABI uninitialized file scope variables are emitted as common symbols When off common symbols are not created The benefit of allowing common symbols to be created is that generated code can remove unused variables that would otherwise increase the size of the bss section Uninitialized variables of a size larger than 32 bytes are separately optimized through placement in separate subsections that can be omitted from a link Variables cannot be common symbols if they are assigned to a section other than bss Specifies the code memory model small 16 bit function pointers and low 64K memory or large 20 bit function pointers and 1MB address space See Section 6 1 1 for details Using the C C Compiler 31 Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Changing the Compiler s Behavior with Options www ti com data_model restricted large Specifies the data memory model small 16 bit data pointers and low small 6
44. Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS www ti com 5 15 4 Enabling Embedded C Mode embedded_cpp Option sees 109 5 16 GNU Language Extensions sicicsicccncciviicjeariecas enen aae amu ESO cu rc PRIM NIS NIRE niles Esa SIS Ri cide 110 MEUS M 110 5 16 2 Function AttriDUteS cc ccc cece cece eee eee ee ene e eee nn nnne n nnne hm hh nnn nn nnne nennen 111 5 16 3 Variable Attributes 0cccce cere nee e cece eens a a 112 5 16 4 Type Fruit 112 5 16 5 Bullt IAi FUNCIONS T 113 5 17 Compiler Limits E 113 6 Run Time Environment seconda 114 6 1 Memory Mod l em a E E E 115 6 14 Gode Memory Models eerie sni a a E EE 115 6 1 2 Data Memory Models cceroieee eene erase e rude ipnr arrana aaiae ag oy a Roda aar 115 6 1 3 Support for Near pici c 116 MEI 116 Bal 5 ellos SONWALE LACK qe ERE Re 117 6 1 6 Dynamic Memory Allocation cesses nm Hm HI nm Hm en nnn nnne nnn 118 6 2 Object RepresentatiON serere e E e 119 6 2 1 Data Type StOtaGe seincatvesactuataneiedeasedotnaaite sede den den dE ADR exsaM EE MANN CANNE UES 119 6 2 2 Character String
45. DIR with the following command MSP430 C DIR usr include usr ucb export MSP430 C DIR or invoke the compiler with the following command c1430 include path usr include file c and file c contains this line include lt sys proc h gt the result is that the included file is in the following path usr include sys proc h 2 5 3 Support for the warning and warn Directives In strict ANSI mode the TI preprocessor allows you to use the warn directive to cause the preprocessor to issue a warning and continue preprocessing The warn directive is equivalent to the warning directive supported by GCC IAR and other compilers If you use the relaxed ansi option on by default both the warn and warning preprocessor directives are supported 2 5 4 Generating a Preprocessed Listing File preproc only Option The preproc only option allows you to generate a preprocessed version of your source file with an 2 A of pp The compiler s preprocessing functions perform the following operations on the source Each source line ending in a backslash is joined with the following line Trigraph sequences are expanded Comments are removed e include files are copied into the file Macro definitions are processed All macros are expanded All other preprocessing directives including line directives and conditional compilation are expanded The preproc only option is useful when creating a source file for a tec
46. Defined Device Driver for C l O eeseeseeeseereer HH 154 7 2 5 The device Prefix ccecereneeeeene ee ee ence ence eee renee einen sn nnne n anne hme a nnn h nm h nnn nnne nnne nnns 155 7 3 Handling Reentrancy register lock and register unlock Functions eee 157 7 4 Library Build PrOCOSS circo kunu er ena ka pu xax EE n UoR eR Ma XDPRSE CR ESDEXRRD A RNDR E CER VR EBR AR RR R DR ERR ERR DENKERS ESKE 158 7 4 1 Required Non Texas Instruments Software ceecceee cece eee e eee eee ee eee eens eee e eee ee sees eee eae eeeeee 158 7 4 2 Using the Library Build Process ccceeeeeeeeeeeee eens I IH HII Hm e n nnne 158 7 4 8 Extending mklib cc ccececee cece ence reece ence ene e renee enee nnnm a nnne annm nnn nnne nnne 161 C Name Demangler 2 2 ona nennt sane na annus aa a e a saaa 162 8 1 Invoking the C Name Demangler cseccece eee eee eee e eee ee eee e eee ee nenne nne hene ene hn nne nene nnn nen 163 8 2 Gt Name Demangler OpllOns 3 is So eure Sue dvds cease ed Re AA ates EAA EE AEA E EAA 163 8 3 Sample Usage of the C Name Demangler eseeseeseeseeeeeee ene nenne 163 eS IEIUNII D TTL TUI T TITLE 165 REVISION FUISTONY 170 Contents SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated l TEXAS INSTRUMENTS www ti com List of Figure
47. E Error F Fatal R Remark WwW Warning Diagnostic raw listing information is displayed in the following format S filename line number column number diagnostic S One of the identifiers in Table 2 35 that indicates the severity of the diagnostic filename The source file line number The line number in the source file column number The column number in the source file diagnostic The message text for the diagnostic Diagnostic messages after the end of file are indicated as the last line of the file with a column number of 0 When diagnostic message text requires more than one line each subsequent line contains the same file line and column information but uses a lowercase version of the diagnostic identifier For more information about diagnostic messages see Section 2 7 SLAU132K September 2015 Using the C C Compiler 47 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Using Inline Function Expansion www ti com 2 11 Using Inline Function Expansion When an inline function is called a copy of the C C source code for the function is inserted at the point of the call This is known as inline function expansion commonly called function inlining or just inlining Inline function expansion can speed up execution by eliminating function call overhead This is particularly beneficial for very small functions that are called frequently Function inlining involves a
48. Each compiled module that defines static or global variables contains these data sections The linker treats the data section like any other initialized section and creates an output section In the load time initialization model the sections are loaded into memory and used by the program See Section 6 9 3 5 In the run time initialization model the linker uses the data in these sections to create initialization data and an additional compressed initialization table The boot routine processes the initialization table to copy data from load addresses to run addresses See Section 6 9 3 3 6 9 3 3 Autoinitialization of Variables at Run Time Autoinitializing variables at run time is the default method of autoinitialization To use this method invoke the linker with the xrom model option Using this method the linker creates a compressed initialization table and initialization data from the direct initialized sections in the compiled module The table and data are used by the C C boot routine to initialize variables in RAM using the table and data in ROM Figure 6 3 illustrates autoinitialization at run time Use this method in any system where your application runs from code burned into ROM 134 Run Time Environment SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com System Initialization Figure 6 3 Autoinitialization at Run Time Object fil
49. Expansion auto_inline Option When optimizing with the opt_level 3 option aliased as O3 the compiler automatically inlines small functions A command line option auto_inline size specifies the size threshold Any function larger than the size threshold is not automatically inlined You can use the auto_inline size option in the following ways If you set the size parameter to 0 auto_inline 0 automatic inline expansion is disabled If you set the size parameter to a nonzero integer the compiler uses this size threshold as a limit to the size of the functions it automatically inlines The compiler multiplies the number of times the function is inlined plus 1 if the function is externally visible and its declaration cannot be safely removed by the size of the function The compiler inlines the function only if the result is less than the size parameter The compiler measures the size of a function in arbitrary units however the optimizer information file created with the gen opt level 1 or gen opt level 2 option reports the size of each function in the same units that the auto inline option uses The auto_inline size option controls only the inlining of functions that are not explicitly declared as inline If you do not use the auto_inline size option the compiler inlines very small functions Optimization Level 3 and Inlining NOTE n order to turn on automatic inlining you must use the opt level 3
50. Gonslahis soo eee pepe Se uan Du d Ape RIS CAD PA Pa REM A DER E DL AIRES TNM A MEE 120 6 3 Register ereloi iaieig cere 121 6 4 Function Structure and Calling Conventions eeeseseesseeseeeeen enn nme nnnm nene 122 6 4 1 Howa Function Makes Call eeeioi ave asiain aria Rande ecu mam Urn rS E ROTER DEN E 123 6 4 2 How a Called Function Responds eesseessesseennn nnne I n n emen nnne nnne 123 6 4 8 Accessing Arguments and Local Variables ceseeesseeeeeee nnn mmn nnne 124 6 5 Accessing Linker Symbols in C and C ccceceeee ence eee eee e cence eee e eens nn eme nne hene nnnm nnne nene 124 6 6 Interfacing C and C With Assembly Language cceecceeeeeeee eee eee eee eee III n nne 124 6 6 1 Using Assembly Language Modules With C C Code ccceecceeee cece ee eeeeeeeeeeeeeeeeeeeeeeneee 124 6 6 2 Accessing Assembly Language Functions From C C cecce cece cece eee e ee eee eee eee eeeeeeeeeeneee 125 6 6 3 Accessing Assembly Language Variables From C C ceceeeeeeeee cece ee eeeeeeeeeeeeeeeeeneeeeneee 126 6 6 4 Sharing C C Header Files With Assembly Source cesses 127 6 6 5 Using Inline Assembly Language cccceceeeeeeeeeeeee tees I IH HII HH n n nnn nnn 127 6 7 Interrupt HANGING EET OLD T ITDTUTEDRTMMTMTMMMMRRTEHE Ter 6 7 1 Saving Registers During Interrupts 0cc cece ee eee eee ee ee eee eee eee ne II I mne nennen 127 6 7 2 Using C C Interr
51. Instruments Incorporated I TEXAS INSTRUMENTS Compiling for 20 Bit MSP430X Devices www ti com 6 10 140 The table in the pinit section simply consists of a list of addresses of constructors to be called see Figure 6 7 The constructors appear in the table after the cinit initialization Figure 6 7 Format of Initialization Records in the pinit Section pinit section Address of constructor 1 Address of constructor 2 Address of constructor 3 L Address of constructor n When you use the rom_model or ram model option the linker combines the cinit sections from all the C C modules and appends a null word to the end of the composite cinit section This terminating record appears as a record with a size field of 0 and marks the end of the initialization tables Likewise the rom model or ram model link option causes the linker to combine all of the pinit sections from all C C modules and append a null word to the end of the composite pinit section The boot routine knows the end of the global constructor table when it encounters a null constructor address The const qualified variables are initialized differently see Section 5 7 1 Compiling for 20 Bit MSP430X Devices The MSP430 tools support compiling and linking code for MSP430 and MSP430X MSP430X devices See the following for more information on options and topics that apply to compiling for the MSP430X devices Use the silic
52. TI compiler officially supports a freestanding environment The C standard does not require a freestanding environment to supply every C feature in particular the library need not be complete However the TI compiler strives to provide most features of a hosted environment The section numbers in the lists that follow correspond to section numbers in Appendix J of the C99 standard The numbers in parentheses at the end of each item are sections in the C99 standard that discuss the topic Certain items listed in Appendix J of the C99 standard have been omitted from this list J 3 1 Translation The compiler and related tools emit diagnostic messages with several distinct formats Diagnostic messages are emitted to stderr any text on stderr may be assumed to be a diagnostic If any errors are present the tool will exit with an exit status indicating failure non zero 3 10 5 1 1 3 Nonempty sequences of white space characters are preserved and are not replaced by a single space character in translation phase 3 5 1 1 2 J 3 2 Environment The compiler does not in general support multibyte characters in the physical source file so there is no mapping from multibyte characters to the source character set However in some locales the multibyte chars compiler option makes the compiler accept multibyte characters in comments string literals and character constants in the physical source file 5 1 1 2 The name of the function ca
53. a common subexpression This can result in increased opportunities for constant folding common subexpression elimination or even total elimination of the variable Common subexpression elimination When two or more expressions produce the same value the compiler computes the value once saves it and reuses it Redundant assignment elimination Often copy propagation and common subexpression elimination optimizations result in unnecessary assignments to variables variables with no subsequent reference before another assignment or before the end of the function The compiler removes these dead assignments 3 11 5 Expression Simplification For optimal evaluation the compiler simplifies expressions into equivalent forms requiring fewer instructions or registers Operations between constants are folded into single constants For example a b 4 c 1 becomes a b c 3 3 11 6 Inline Expansion of Functions The compiler replaces calls to small functions with inline code saving the overhead associated with a function call as well as providing increased opportunities to apply other optimizations 3 11 7 Function Symbol Aliasing 64 The compiler recognizes a function whose definition contains only a call to another function If the two functions have the same signature same return value and same number of parameters with the same type in the same order then the compiler can make the calling function an alias of the called f
54. all modes The __ interrupt keyword does not conflict with the ANSI ISO C standard so it is always available as a language extension __interrupt void isr void int main return 0 MSP430 C C Language Implementation SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Changing the ANSI ISO C C Language Mode The default mode is relaxed ANSI This mode can be selected with the relaxed_ansi or pr option Relaxed ANSI mode accepts the broadest range of programs It accepts all TI language extensions even those which conflict with ANSI ISO and ignores some ANSI ISO violations for which the compiler can do something reasonable The GCC language extensions described in Section 5 16 are available in relaxed ANSI ISO mode 5 15 4 Enabling Embedded C Mode embedded_cpp Option The compiler supports the compilation of embedded C In this mode some features of C are removed that are of less value or too expensive to support in an embedded system When compiling for embedded C the compiler generates diagnostic messages for the use of omitted features Embedded C is enabled by compiling with the embedded_cpp option Embedded C omits these C features Templates Exception handling Run time type information The new cast syntax The keyword mutable Multiple inheritance Virtual inheritance e lostre
55. conventions dictate how the compiler uses registers and how values are preserved across Incorrect undefined behavior function calls Table 6 3 shows the types of registers affected by these conventions Table 6 4 summarizes how the compiler uses registers and whether their values are preserved across calls For information about how values are preserved across calls see Section 6 4 Table 6 3 How Register Types Are Affected by the Conventions Register Type Description Argument register Return register Expression register Argument pointer Stack pointer Program counter Passes arguments during a function call Holds the return value from a function call Holds a value Used as a base value from which a function s parameters incoming arguments are accessed Holds the address of the top of the software stack Contains the current address of code being executed Table 6 4 Register Usage and Preservation Conventions Register Alias Usage Preserved by Function RO PC Program counter N A R1 SP Stack pointer N A R2 SR Status register N A R3 Constant generator N A R4 R10 Expression register Child R11 Expression register Parent R12 Expression register argument pointer return register Parent R13 Expression register argument pointer return register Parent R14 Expression register argument pointer return register Parent R15 Expression register argument pointer return register Parent The parent fu
56. eerte rennen ce cee spini oi EEE ce E aaa ine Ena a e 91 5 11 6 The DATA ALIGN Pragma oe sce roter ren ha nonam err nne iiep pap pps iepa a e 93 5 11 7 The DATA SECTION Pragma eren nnnm rna rry R ra iEn E Eia ine ana o 93 5 11 8 The Diagnostic Message Pragmas cccceeeee eect cece eee nn I nmn nnn nnne nnne 94 5 11 9 The FUNC ALWAYS INLINE Pragma eeeeeeeeennnnn nnnm nhe hnn nnne antenna nnne 94 5 11 10 The FUNC CANNOT INLINE Pragma ccceeeeceeeeeee eee eee eee eee eeeeee snes eeeeeeeeeenaeeeeneeeeees 95 5 11 11 The FUNC_EXT_CALLED Pragma cceeceeee eee eee III III HI Ie nh hn hehehe rn 95 5 11 12 The FUNG IS PURE Pragma ceceeceeee cece ee eee ee eee eens II I heh hn enhn n nnn nennen 96 5 11 13 The FUNC NEVER RETURNS Pragma ccecceeeeee cece eee eee en nenne nehmen nnne nennen 96 5 11 14 The FUNC NO GLOBAL ASG Pragmad cecceeeeee seen ence ence enhn me enne n heme nnn 96 5 11 15 The FUNG NO IND ASG Pragma unciiir rire tnn imer ebn eee derie rele E IU Petras 97 5 11 16 The FUNCTION OPTIONS Pragma eeseeeeennennn enhn enhn hn nnne nnne nnn 97 5 1117 The INTERRUPT Pragma uenerat mnn umn nacu re e a acu cipe n eter E Tics Dex INR E RE 97 5 11 18 The LOCATION Pragtra s ssceuimu niente mter n oso me rien une ur a renta cab naa IER rn xanax ai 98 5 11 19 The NOINIT and PERSISTENT Pragmas cceeeeeeeee eee eee ence eee II III heme nnn en nnn 99 5 1120 The NO HOOKS PragM assins aden
57. endian An addressing protocol in which bytes are numbered from right to left within a word More significant bytes in a word have higher numbered addresses Endian ordering is hardware specific and is determined at reset See also big endian loader A device that places an executable object file into system memory loop unrolling An optimization that expands small loops so that each iteration of the loop appears in your code Although loop unrolling increases code size it can improve the performance of your code SLAU132K September 2015 Glossary 167 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Appendix A www ti com 168 macro A user defined routine that can be used as an instruction macro call The process of invoking a macro macro definition A block of source statements that define the name and the code that make up a macro macro expansion The process of inserting source statements into your code in place of a macro call map file An output file created by the linker which shows the memory configuration section composition section allocation symbol definitions and the addresses at which the symbols were defined for your program memory map A map of target system memory space that is partitioned into functional blocks name mangling A compiler specific feature that encodes a function name with information regarding the function s argu
58. file as lines beginning with the character The preprocessor produces self explanatory error messages The line number and the filename where the error occurred are printed along with a diagnostic message 2 5 1 Predefined Macro Names SLAU132K September 2015 The compiler maintains and recognizes the predefined macro names listed in Table 2 33 Table 2 33 Predefined MSP430 Macro Names Macro Name Description __DATE__ Expands to the compilation date in the form mmm dd yyyy __FILE _ Expands to the current source filename LARGE_CODE_MODEL LARGE DATA MODEL LINE LONG PTRDIFF T J MSP430 _ MSP430X J MSP430X461X PTRDIFF T TYPE signed chars _ SIZE T TYPE STDC 0 STDC VERSION _ J Tl COMPILER VERSION _ TILEABI H GNU ATTRIBUTE SUPPORT TI STRICT ANSI MODE TI STRICT FP MODE TIME unsigned chars UNSIGNED LONG SIZE T Defined if code model large is specified Defined if data model large or data model restricted is specified Expands to the current line number Defined when data model large is specified Indicates ptrdiff t is a long Always defined Defined if silicon_version mspx is specified Defined if silicon_version mspx is specified Set to the type of ptrdiff_t Determined by the data_model option Defined if char types are signed by default plain_char signed Set to the type of size_t Determined by the data_m
59. function closes the file associated with file_descriptor The file_descriptor is the number assigned by open to an opened file The return value is one of the following 0 if successful 1 on failure Read Characters from a File include lt file h gt int read int file descriptor char buffer unsigned count The read function reads count characters into the buffer from the file associated with file descriptor The file descriptor is the number assigned by open to an opened file The buffer is where the read characters are placed The countis the number of characters to read from the file The function returns one of the following values 0 if EOF was encountered before any characters were read number of characters read may be less than count 1 on failure Write Characters to a File include lt file h gt int write int file_descriptor const char buffer unsigned count The write function writes the number of characters specified by count from the buffer to the file associated with file_descriptor The file descriptor is the number assigned by open to an opened file The buffer is where the characters to be written are located The count is the number of characters to write to the file The function returns one of the following values number of characters written if successful may be less than count 1 on failure SLAU132K September 2015 Submit Documentation Feedback
60. function structure and calling conventions An ABI defines linkname generation from C symbol names It defines the object file format and the debug format It defines how the system is initialized In the case of C it defines C name mangling and exception handling support The COFF ABI is not supported in v15 6 0 STS and later versions of the TI Code Generation Tools If you would like to produce COFF output files please use v4 4 of the MSP430 Code Generation Tools and refer to SPRU132J for documentation MSP430 uses the EABI ABI wheich requires the ELF object file format This format supports modern language features like early template instantiation and exporting inline functions Tl specific information on EABI mode is described in Section 6 9 3 To generate object files compatible with EABI you must use MSP430 compiler version 4 0 or greater see Section 2 13 The TI EABI predefined symbol is defined and set to 1 if compiling for EABI For low level details about the MSP430 EABI see The MSP430 Embedded Application Binary Interface SLAA534 Object File Symbol Naming Conventions Linknames Each externally visible identifier is assigned a unique symbol name to be used in the object file a so called inkname This name is assigned by the compiler according to an algorithm which depends on the name type and source language of the symbol This algorithm may add a prefix to the identifier typically an underscore and it may m
61. gt Scripting Console from the CCS menus You can use the loadProg command to load an object file and its associated symbol table into memory and pass an array of arguments to main These arguments are automatically written to the allocated args section The loadProg syntax is as follows where file is an executable file and args is an object array of arguments Use JavaScript to declare the array of arguments before using this command loadProg file args 42 Using the C C Compiler SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated l TEXAS INSTRUMENTS www ti com Understanding Diagnostic Messages 2 7 The args section is loaded with the following data for non SYS BIOS based executables where each element in the argv array contains a string corresponding to that argument Int argc Char argv 0 Char argv 1 Char argv n For SYS BIOS based executables the elements in the args section are as follows Int argc Char argv points to argv 0 Char envp ignored by loadProg command Char argv 0 Char argv 1 Char argv n For more details see the Scripting Console topic in the TI Processors Wiki Understanding Diagnostic Messages One of the primary functions of the compiler and linker is to report diagnostic messages for the source program A diagnostic message indicates that something may be wrong with the program W
62. increased from 16 bits to 32 bits in the large data model Applications that rely on size t or ptrdiff t to be a specific size may need to be updated Object files built with different data models are not compatible All files in an application must be built with the same data model Additionally a run time support library matching that data model must be used When using automatic library selection the default the linker will automatically select the correct library Section 4 3 1 1 If you select the library manually you must select the matching library according to Section 7 1 8 SLAU132K September 2015 Run Time Environment 115 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Memory Model www ti com 6 1 3 Support for Near Data All current MSP430X devices do not have any writeable memory above the 64K boundary For these devices even when the restricted or large data models are used only constant data will be placed above 64K The compiler can take advantage of this knowledge to produce more efficient code This is controlled by the near_data option When near_data globals is specified it tells the compiler that all global read write data must be located in the first 64K of memory This is the default behavior Global read write data is placed by default in the bss and data sections If near_data none is specified it tells the compiler that it cannot rely on this assumpt
63. is the result err c line 9 warning statement is unreachable err c line 12 warning statement is unreachable Because it is standard programming practice to include break statements at the end of each case arm to avoid the fall through condition these warnings can be ignored Using the display_error_number option you can find out the diagnostic identifier for these warnings Here is the result err c err c line 9 warning 111 D statement is unreachable err c line 12 warning 111 D statement is unreachable SLAU132K September 2015 Using the C C Compiler 45 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Other Messages www ti com 2 8 2 9 2 10 46 Next you can use the diagnostic identifier of 111 as the argument to the diag_remark option to treat this warning as a remark This compilation now produces no diagnostic messages because remarks are disabled by default NOTE You can suppress any non fatal errors but be careful to make sure you only suppress diagnostic messages that you understand and are known not to affect the correctness of your program Other Messages Other error messages that are unrelated to the source such as incorrect command line syntax or inability to find specified files are usually fatal They are identified by the symbol gt gt preceding the message Generating Cross Reference Listing Information g
64. numa num Treat diagnostic num as a warning diag error num pdse num num nums Treat diagnostic num as an error diag default num n a Use default severity of the diagnostic diag push n a Push the current diagnostics severity state to store it for later use diag pop n a Pop the most recent diagnostic severity state stored with pragma diag push to be the current setting The syntax of the diag suppress diag remark diag warning and diag error pragmas in C is pragma diag xxx num num num Notice that the names of these pragmas are in lowercase The diagnostic affected num is specified using either an error number or an error tag name The equal sign 2 is optional Any diagnostic can be overridden to be an error but only diagnostic messages with a severity of discretionary error or below can have their severity reduced to a warning or below or be suppressed The diag default pragma is used to return the severity of a diagnostic to the one that was in effect before any pragmas were issued i e the normal severity of the message as modified by any command line options The diagnostic identifier number is output with the message when you use the pden command line option The following example suppresses a diagnostic message and then restores the previous diagnostics severity state pragma diag push pragma diag suppress 551 pragma CHECK MISRA 9 1 pragma diag pop 5 11 9 The FUNC ALWAY
65. option If you desire the opt_level 3 optimizations but not automatic inlining use auto inlinezO with the opt level 3 option Inlining and Code Size NOTE Expanding functions inline increases code size especially inlining a function that is called in a number of places Function inlining is optimal for functions that are called only from a small number of places and for small functions To prevent increases in code size because of inlining use the auto_inline 0 and no inlining options These options used together cause the compiler to inline intrinsics only Using the Interlist Feature With Optimization You control the output of the interlist feature when compiling with optimization the opt_level n or On option with the optimizer interlist and c src interlist options The optimizer interlist option interlists compiler comments with assembly source statements The c src interlist and optimizer_interlist options together interlist the compiler comments and the original C C source with the assembly code When you use the optimizer_interlist option with optimization the interlist feature does not run as a separate pass Instead the compiler inserts comments into the code indicating how the compiler has rearranged and optimized the code These comments appear in the assembly language file as comments starting with The C C source code is not interlisted unless you use the c src interlist op
66. pr Enables relaxed mode ignores strict ISO violations This is on by Section 5 15 3 default To disable this mode use the strict_ansi option rtti rtti Enables C run time type information RTTI strict ansi ps Enables strict ANSI ISO mode for C C not for K amp R C In this Section 5 15 3 mode language extensions that conflict with ANSI ISO C C are disabled In strict ANSI ISO mode most ANSI ISO violations are reported as errors Violations that are considered discretionary may be reported as warnings instead SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated Using the C C Compiler 21 1 TEXAS INSTRUMENTS Changing the Compiler s Behavior with Options www ti com Table 2 11 Parser Preprocessing Options Option Alias Effect Section preproc_dependency filename ppd Performs preprocessing only but instead of writing preprocessed Section 2 5 8 output writes a list of dependency lines suitable for input to a standard make utility preproc_includes filename ppi Performs preprocessing only but instead of writing preprocessed Section 2 5 9 output writes a list of files included with the include directive preproc_macros filename ppm Performs preprocessing only Writes list of predefined and user Section 2 5 10 defined macros to a file with the same name as the input but with a pp extension preproc_only ppo Performs preprocessing only
67. run linker option on the command line but otherwise may be in any order Options are discussed in detail in the MSP430 Assembly Language Tools User s Guide output_file name out Names the output file library library Identifies the appropriate archive library containing C C run time support and floating point math functions or linker command files If you are linking C C code you must use a run time support library You can use the libraries included with the compiler or you can create your own run time support library If you have specified a run time support library in a linker command file you do not need this parameter The library option s short form is l Ink cmd Contains options filenames directives or commands for the linker When you specify a library as linker input the linker includes and links only those library members that resolve undefined references The linker uses a default allocation algorithm to allocate your program into memory You can use the MEMORY and SECTIONS directives in the linker command file to customize the allocation process For information see the MSP430 Assembly Language Tools User s Guide You can link a C C program consisting of object files prog1 obj prog2 obj and prog3 obj with an executable object file filename of prog out with the command c1430 run linker rom model progl prog2 prog3 output file prog out library rts430 1lib SLAU132K September 2015 Linking C C Co
68. structures are aligned as specified in See Section 6 2 6 7 2 1 The integer type underlying each enumerated type is described in Section 5 6 1 6 7 2 2 J 3 10 Qualifiers The TI compiler does not shrink or grow volatile accesses It is the user s responsibility to make sure the access size is appropriate for devices that only tolerate accesses of certain widths The TI compiler does not change the number of accesses to a volatile variable unless absolutely necessary This is significant for read modify write expressions such as for an architecture which does not have a MSP430 C C Language Implementation SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS www ti com Characteristics of MSP430 C corresponding read modify write instruction the compiler will be forced to use two accesses one for the read and one for the write Even for architectures with such instructions it is not guaranteed that the compiler will be able to map such expressions to an instruction with a single memory operand It is not guaranteed that the memory system will lock that memory location for the duration of the instruction In a multi core system some other core may write the location after a RMW instruction reads it but before it writes the result The TI compiler will not reorder two volatile accesses but it may reorder a volatile and a non volatile access so volatile
69. the integer type and whether it is signed is based on the range of values of the enumerated constants In strict C89 or C99 mode the compiler allows only enumeration constants with values that will fit in int or unsigned int For C and relaxed C89 C99 the compiler allows enumeration constants up to the largest integral type 64 bits The default which is recommended is for the underlying type to be the first type in the following list in which all the enumerated constant values can be represented int unsigned int long unsigned long long long unsigned long long If you use the small enum option the smallest possible byte size for the enumeration type is used The underlying type is the first type in the following list in which all the enumerated constant values can be represented signed char unsigned char short unsigned short int unsigned int long unsigned long long long unsigned long long The following example uses 8 bits instead of 16 bits when the small enum option is used enum example enum first 128 second 0 third 127 un NOTE Do not link object files compiled with the small enum option with object files that were compiled without it If you use the small enum option you must use it with all of your C C files otherwise you will encounter errors that cannot be detected until run time 5 7 Keywords The MSP430 C C compiler supports all of the standard C89 keywords including c
70. these options Table 2 32 lists the deprecated options that have been replaced by other options Table 2 32 Compiler Backwards Compatibility Options Summary Old Option Effect Option to Use Instead abi The only supported ABI is now EABI symdebug profile coff This option applied only to the COFF ABI which has been deprecated no sym merge This option applied only to the COFF ABI which has been deprecated diable clink This option applied only to the COFF ABI which has been deprecated gcc Enabled support for GCC extensions relaxed_ansi gp Allowed function level profiling of optimized code symdebug dwarf or g gw Enabled symbolic debugging using the DWARF debugging format symdebug dwarf or g symdebug skeletal Enabled minimal debugging Now has no effect symdebug none optimize with debug Enabled optimization with debugging Now this is default behavior Option has no effect The large memory model ml option is deprecated for MSP430 Use data model large instead Controlling the Compiler Through Environment Variables An environment variable is a system symbol that you define and assign a string to Setting environment variables is useful when you want to run the compiler repeatedly without re entering options input filenames or pathnames NOTE C_OPTION and C_DIR The C_OPTION and C_DIR environment variables are deprecated Use device specific environment variables instead Setting
71. ti com video Mailing Address Texas Instruments Post Office Box 655303 Dallas Texas 75265 Copyright 2015 Texas Instruments Incorporated
72. treats memory as a single linear block that is partitioned into subblocks of code and data Each subblock of code or data generated by a C program is placed in its own continuous memory space The compiler assumes that the full 16 bit for MSP430 or 20 bit for MSP430X address space is available in target memory Code Memory Models The MSP430 compiler supports two different code memory models small and large which are controlled by the code model option The small code model uses 16 bit function pointers and requires all code and all text sections to be placed in the low 64K of memory This is the only valid code model for 16 bit MSP430 devices The large code model provides a 1 MB address space for code and uses 20 bit function pointers It is the default for MSP430X devices including the MSP430F5xxx and MSP430F6xxx families Interrupt service routines must still be placed in the low 64 KB of memory see Section 6 7 5 The small code model is slightly more efficient in terms of run time performance and memory usage when compared to the large code model Therefore it is beneficial to use the small code model when all code and text sections will fit in the low 64K of memory Modules assembled compiled using the small code model are not compatible with modules that are assembled compiled using large code model The linker generates an error if any attempt is made to combine object files that use different code memory models An appropria
73. used for small functions or functions that are called in a few places though the compiler does not enforce this NOTE Excessive Inlining Can Degrade Performance Excessive inlining can make the compiler dramatically slower and degrade the performance of generated code SLAU132K September 2015 Using the C C Compiler 49 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Using Interlist www ti com 2 12 Using Interlist The compiler tools include a feature that interlists C C source statements into the assembly language output of the compiler The interlist feature enables you to inspect the assembly code generated for each C statement The interlist behaves differently depending on whether or not the optimizer is used and depending on which options you specify The easiest way to invoke the interlist feature is to use the c_src_interlist option To compile and run the interlist on a program called function c enter c1430 c src interlist function The c src interlist option prevents the compiler from deleting the interlisted assembly language output file The output assembly file function asm is assembled normally When you invoke the interlist feature without the optimizer the interlist runs as a separate pass between the code generator and the assembler It reads both the assembly and C C source files merges them and writes the C C statements into the a
74. uses the Section 2 3 10 current directory output_file filename fe Specifies a compilation output file name can override Section 2 3 10 pp_directory dir temp_directory directory obj_directory Specifies a preprocessor file directory By default the compiler uses the current directory ft Specifies a temporary file directory By default the compiler uses the current directory Section 2 3 10 Section 2 3 10 24 Using the C C Compiler SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Changing the Compiler s Behavior with Options Table 2 20 Default File Extensions Options Option Alias Effect Section asm_extension extension ea Sets a default extension for assembly source files Section 2 3 9 c_extension extension ec Sets a default extension for C source files Section 2 3 9 cpp extension extension ep Sets a default extension for C source files Section 2 3 9 listing_extension extension es Sets a default extension for listing files Section 2 3 9 obj extension extension eo Sets a default extension for object files Section 2 3 9 Table 2 21 Command Files Options Option Alias Effect Section cmd_file filename Interprets contents of a file as an extension to the command line Section 2 3 2 Multiple instances can be used Table 2 22 MISRA C 2004 Options Option A
75. variables to special memory locations like memory mapped registers without generating unwanted writes The NOINIT pragma may only be used with uninitialized variables The PERSISTENT pragma is similar to the NOINIT pragma except that it may only be used with statically initialized variables Persistent variables disable startup initialization they are given an initial value when the code is loaded but are never again initialized NOTE When using these pragmas in non volatile FRAM memory the memory region could be protected against unintended writes through the device s Memory Protection Unit Some devices have memory protection enabled by default Please see the information about memory protection in the datasheet for your device If the Memory Protection Unit is enabled it first needs to be disabled before modifying the variables If you are using non volatile RAM you can define a persistent variable with an initial value of zero loaded into RAM The program can increment that variable over time as a counter and that count will not disappear if the device loses power and restarts because the memory is non volatile and the boot routines do not initialize it back to zero For example pragma PERSISTENT x pragma location 0xC200 memory address in RAM int x 0 void main run init while 1 run actions x delay cycles 1000000 xtt The syntax of the pragmas in C is pragma NOINIT x int x
76. with the same name as a standard library function std lib func redefined Contains but does not alter functions declared in the standard library std lib func defined Does not alter standard library functions but you used the std lib func redefined or std lib func not defined std lib func defined option in a command file or an environment variable The std lib func not defined option restores the default behavior of the optimizer 3 2 2 Creating an Optimization Information File gen opt info Option When you invoke the compiler with the opt_level 3 option you can use the gen opt info option to create an optimization information file that you can read The number following the option denotes the level 0 1 or 2 The resulting file has an nfo extension Use Table 3 4 to select the appropriate level to append to the option Table 3 4 Selecting a Level for the gen opt info Option If you Use this option Do not want to produce an information file but you used the gen opt level 1 or gen opt level 2 X gen opt info 0 option in a command file or an environment variable The gen_opt_level 0 option restores the default behavior of the optimizer Want to produce an optimization information file gen opt info 1 Want to produce a verbose optimization information file gen opt info 2 SLAU132K September 2015 Optimizing Your Code 55 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorp
77. www ti com 2 3 11 Assembler Options Following are assembler options that you can use with the compiler For more information see the MSP430 Assembly Language Tools User s Guide absolute listing asm define name def asm dependency asm includes asm listing asm undefine name copy file filename cross reference include_file filename output_all_syms syms_ignore_case 36 Using the C C Compiler Generates a listing with absolute addresses rather than section relative offsets Predefines the constant name for the assembler produces a set directive for a constant or an arg directive for a string If the optional 2def is omitted the name is set to 1 If you want to define a quoted string and keep the quotation marks do one of the following For Windows use asm define2namez string def For example asm_define car sedan For UNIX use asm_define name asm define car sedan For Code Composer Studio enter the definition in a file and include that file with the cmd_file option Performs preprocessing for assembly files but instead of writing preprocessed output writes a list of dependency lines suitable for input to a standard make utility The list is written to a file with the same name as the source file but with a ppa extension Performs preprocessing for assembly files but instead of writing preprocessed output writes a list of files included with the includ
78. zero 5 17 Compiler Limits Due to the variety of host systems supported by the C C compiler and the limitations of some of these systems the compiler may not be able to successfully compile source files that are excessively large or complex In general exceeding such a system limit prevents continued compilation so the compiler aborts immediately after printing the error message Simplify the program to avoid exceeding a system limit Some systems do not allow filenames longer than 500 characters Make sure your filenames are shorter than 500 The compiler has no arbitrary limits but is limited by the amount of memory available on the host system On smaller host systems such as PCs the optimizer may run out of memory If this occurs the optimizer terminates and the shell continues compiling the file with the code generator This results in a file compiled with no optimization The optimizer compiles one function at a time so the most likely cause of this is a large or extremely complex function in your source module To correct the problem your options are Don t optimize the module in question Identify the function that caused the problem and break it down into smaller functions Extract the function from the module and place it in a separate module that can be compiled without optimization so that the remaining functions can be optimized SLAU132K September 2015 MSP430 C C Language Implementation 113 Submit Documenta
79. 128 bytes Table 2 24 File Search Path Options Option Alias Description library file l Names an archive library or link command file as linker input search_path pathname I Alters library search algorithms to look in a directory named with pathname before looking in the default location This option must appear before the library option priority priority Satisfies unresolved references by the first library that contains a definition for that symbol reread_libs X Forces rereading of libraries which resolves back references disable auto rts Disables the automatic selection of a run time support library See Section 4 3 1 1 Table 2 25 Command File Preprocessing Options Option Alias Description define name value undefine name Predefines name as a preprocessor macro Removes the preprocessor macro name disable_pp Disables preprocessing for command files Table 2 26 Diagnostic Message Options Option Alias Description diag_error num Categorizes the diagnostic identified by num as an error diag_remark num Categorizes the diagnostic identified by num as a remark diag_suppress num Suppresses the diagnostic identified by num diag_warning num Categorizes the diagnostic identified by num as a warning display_error_number Displays a diagnostic s identifiers along with its text emit_warnings_as_errors pdew Treat warnings as errors issue_remarks Issues remarks non serio
80. 15 Texas Instruments Incorporated I TEXAS INSTRUMENTS Interfacing C and C With Assembly Language www ti com 6 6 3 Accessing Assembly Language Variables From C C It is sometimes useful for a C C program to access variables or constants defined in assembly language There are several methods that you can use to accomplish this depending on where and how the item is defined a variable defined in the bss section a variable not defined in the bss section or a linker symbol 6 6 3 1 Accessing Assembly Language Global Variables Accessing variables from the bss section or a section named with usect is straightforward 1 Use the bss or usect directive to define the variable 2 Use the def or global directive to make the definition external 3 Use the appropriate linkname in assembly language 4 In C C declare the variable as extern and access it normally Example 6 5 and Example 6 4 show how you can access a variable defined in bss Example 6 4 Assembly Language Variable Program bss var 4 4 Define the variable global var Declare it as external Example 6 5 C Program to Access Assembly Language From Example 6 4 var 1 Use the variable extern int var External variable 6 6 3 2 Accessing Assembly Language Constants You can define global constants in assembly language by using the set directive in combination with either the def or global directive or you can define them
81. 32K September 2015 Submit Documentation Feedback Using the C C Compiler 33 Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS Changing the Compiler s Behavior with Options www ti com 2 3 6 Specifying Filenames The input files that you specify on the command line can be C source files C source files assembly source files or object files The compiler uses filename extensions to determine the file type Extension File Type asm abs or s extension begins with s Assembly source Ko C source C Depends on operating system Cpp CXX CC C source obj o dll so Object NOTE Case Sensitivity in Filename Extensions Case sensitivity in filename extensions is determined by your operating system If your operating system is not case sensitive a file with a C extension is interpreted as a C file If your operating system is case sensitive a file with a C extension is interpreted as a C file For information about how you can alter the way that the compiler interprets individual filenames see Section 2 3 7 For information about how you can alter the way that the compiler interprets and names the extensions of assembly source and object files see Section 2 3 10 You can use wildcard characters to compile or assemble multiple files Wildcard specifications vary by system use the appropriate form listed in your operating system manual For example to compile all of the files
82. 4 The advice power_severity option sets the diagnostic severity for ULP Advisor rules The syntax is advice power_severity error warning remark suppress The syntax of the pragmas is pragma CHECK ULP all none ru espec pragma RESET ULP all ru espec 5 5 Advice on Hardware Configuration The advice hw config option lets you enable disable or configure the checks to perform related to the device s configuration settings For example the FRAM waitstate configuration is checked Information about resolving a device configuration issue can be found by clicking the link provided in Code Composer Studio when one of these checks produces a warning The syntax is advice hw_config all none ru espec The rulespec parameter is a comma separated list of rule numbers to enable SLAU132K September 2015 MSP430 C C Language Implementation 81 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Data Types www ti com 5 6 Data Types Table 5 1 lists the size representation and range of each scalar data type for the MSP430 compiler Many of the range values are available as standard macros in the header file limits h Table 5 1 MSP430 C C Data Types Range Type Size Alignment Representation Minimum Maximum signed char 8 bits 8 Binary 128 127 char 8 bits 8 ASCII 0 or 128 255 or 127 unsigned char 8 bits 8 Binary 0 255 bool C99 8 bits 8 Binary 0 fal
83. 4K memory restricted 32 bit data pointers objects restricted to 64K and 1MB memory and large 32 bit data pointers and 1MB memory See Section 6 1 2 for details disable_interrupts_around_hw_mpy off Setting this option to off leaves interrupts enabled during inlined hardware multiplication Inlined hardware multiplication is controlled by the use_hw_mpy and opt_for_speed options This option should only be used if all ISRs in the application do not use multiplication and do not call other functions By default if hardware multiplication is inlined interrupts are disabled during hardware multiplication because such operations are not re entrant If this option is set to off and an ISR uses multiplication the linker issues a warning that multiplication within the ISR will use the RTS software multiply routine instead of the RTS hardware multiply routine If this option is set to off and an ISR calls other functions the linker generates a non fatal error diagnostic indicating that the option disable_interrupts_around_hw_mpy off cannot be used if the application includes ISRs with calls to other functions The reason for this is that if an ISR calls a routine that does multiplication using the hardware multiplier then the inlined hardware multipliers with interrupts left enabled are no longer safe large_memory_model This option is deprecated Use data_model large near_data globals none Specifies that global
84. 5 The flags are attributes that specify how the file is manipulated The flags are specified using the following symbols O RDONLY 0x0000 O WRONLY 0x0001 O RDWR 0x0002 O APPEND 0x0008 O CREAT 0x0200 O TRUNC 0x0400 O BINARY 0x8000 open for reading open for writing open for read amp write append on each write open with file create open with truncation open in binary mode Low level I O routines allow or disallow some operations depending on the flags used when the file was opened Some flags may not be meaningful for some devices depending on how the device implements files The file descriptor is assigned by open to an opened file The next available file descriptor is assigned to each new file opened Return Value The function returns one of the following values non negative file descriptor if successful 1 SLAU132K September 2015 Submit Documentation Feedback on failure Using Run Time Support Functions and Building Libraries 147 Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS close Close File for I O www ti com close Syntax Description Return Value read Syntax Description Return Value write Syntax Description Return Value 148 Using Run Time Support Functions and Building Libraries Close File for I O include lt file h gt int close int file_descriptor The close
85. ADD op2 low dst low DADD op2 hi dst hi unsigned short bic SR register unsigned short mask BIC mask SR unsigned short bic SR register on exit unsigned short mask BIC mask saved SR unsigned short bis SR register unsigned short mask BIS mask SR unsigned short bis SR register on exit unsigned short mask BIS mask saved SR unsigned long datai6 read addr unsigned short addr MOV W addr Rx MOVA 0 Rx dst void __data16_write_addr unsigned short addr unsigned long src MOV W addr Rx MOVA src 0 Rx unsigned char data20 read char unsigned long addr MOVA adar Rx MOVX B 0 Rx dst unsigned long data20 read long unsigned long addr MOVA adar Rx MOVX W 0 Rx dst lo MOVX W 2 Rx dst hi unsigned short data20 read short unsigned long adar MOVA adar Rx MOVX W O Rx dst void data20 write char unsigned long adar unsigned char sro MOVA adar Rx MOVX B src O Rx void data20 write long unsigned long addr unsigned long sro MOVA adar Rx MOVX W src lo O Rx MOVX W src hi 2 Rx void data20 write short unsigned long addr unsigned short sro MOVA adar Rx MOVX W src 0 Rx void delay cycles unsigned long See Section 6 8 3 void disable interrupt void DINT OR disable interrupts void Intrinsic encodes multiple instructions depending on the code The most common instructions produced are presented here SLAU132K September 2015 Run Time Environment 129 Submit Documentation Feedback Copyr
86. AS INSTRUMENTS Controlling the Compiler Through Environment Variables www ti com In the following examples each time you run the compiler it runs the linker Any options following run_linker on the command line or in MSP430_C_OPTION are passed to the linker Thus you can use the MSP430_C_OPTION environment variable to specify default compiler and linker options and then specify additional compiler and linker options on the command line If you have set run_linker in the environment variable and want to compile only use the compiler compile_only option These additional examples assume MSP430 C OPTION is set as shown above c1430 c compiles and links c1430 compile only c only compiles c1430 c run linker lnk cmd compiles and links using a command file c1430 compile only c run linker lnk cmd only compiles compile only overrides run linker For details on compiler options see Section 2 3 For details on linker options see the Linker Description chapter in the MSP430 Assembly Language Tools User s Guide 2 4 2 Naming One or More Alternate Directories MSP430 C DIR 38 The linker uses the MSP430 C DIR environment variable to name alternate directories that contain object libraries The command syntaxes for assigning the environment variable are Operating System Enter UNIX Bourne shell MSP430 C DIR z pathname pathname export MSP430 C DIR Windows set MSP430 C DIRz pathname pathname
87. Alternate version of the 1989 C Standard American National Standards Institute ISO IEC 9899 1989 International Standard Programming Languages C The 1989 C Standard International Organization for Standardization ISO IEC 9899 1999 International Standard Programming Languages C The 1999 C Standard International Organization for Standardization ISO IEC 14882 2003 International Standard Programming Languages C The 2003 C Standard International Organization for Standardization The C Programming Language second edition by Brian W Kernighan and Dennis M Ritchie published by Prentice Hall Englewood Cliffs New Jersey 1988 The Annotated C Reference Manual Margaret A Ellis and Bjarne Stroustrup published by Addison Wesley Publishing Company Reading Massachusetts 1990 C A Reference Manual fourth edition by Samuel P Harbison and Guy L Steele Jr published by Prentice Hall Englewood Cliffs New Jersey Programming Embedded Systems in C and C by Michael Barr Andy Oram Editor published by O Reilly amp Associates ISBN 1565923545 February 1999 Programming in C Steve G Kochan Hayden Book Company The C Programming Language second edition Bjarne Stroustrup published by Addison Wesley Publishing Company Reading Massachusetts 1990 Tool Interface Standards TIS DWARF Debugging Information Format Specification Version 2 0 TIS Committee 1995 DWARF Debugging Information Format Ve
88. C source file If the optional 2def is omitted the name is set to 1 The define option s short form is D If you want to define a quoted string and keep the quotation marks do one of the following For Windows use define name string def For example define car sedan For UNIX use define name define car sedan For Code Composer Studio enter the definition in a file and include that file with the cmd_file option Displays the syntax for invoking the compiler and lists available options If the help option is followed by another option or phrase detailed information about the option or phrase is displayed For example to see information about debugging options use help debug Adds directory to the list of directories that the compiler searches for include files The include_path option s short form is l You can use this option several times to define several directories be sure to separate the include_path options with spaces If you do not specify a directory name the preprocessor ignores the include_path option See Section 2 5 2 1 string def For example SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com keep asm quiet run linker Sskip assembler src_interlist tool_version undefine name verbose Changing the Compiler s Behavior with Options R
89. Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS www ti com Invoking the Linker Through the Compiler z Option 4 1 Invoking the Linker Through the Compiler z Option This section explains how to invoke the linker after you have compiled and assembled your programs as a separate step or as part of the compile step 4 1 1 Invoking the Linker Separately This is the general syntax for linking C C programs as a separate step cl430 run linker rom_model ram_model filenames options output_file name out library library Ink cma cl430 run_linker The command that invokes the linker rom_model ram_model Options that tell the linker to use special conventions defined by the C C environment When you use cl430 run_linker you must use rom_model or ram_model The rom_model option uses automatic variable initialization at run time the ram_model option uses variable initialization at load time filenames Names of object files linker command files or archive libraries The default extension for all input files is obj any other extension must be explicitly specified The linker can determine whether the input file is an object or ASCII file that contains linker commands The default output filename is a out unless you use the output file option to name the output file options Options affect how the linker handles your object files Linker options can only appear after the
90. Copyright O 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Iseek Syntax for C Description Return Value unlink Syntax Description Return Value SLAU132K September 2015 Iseek Set File Position Indicator Set File Position Indicator include lt file h gt off t Iseek int file_descriptor off t offset int origin The Iseek function sets the file position indicator for the given file to a location relative to the specified origin The file position indicator measures the position in characters from the beginning of the file The file descriptor is the number assigned by open to an opened file The offset indicates the relative offset from the origin in characters The origin is used to indicate which of the base locations the offset is measured from The origin must be one of the following macros SEEK SET 0x0000 Beginning of file SEEK CUR 0x0001 Current value of the file position indicator SEEK END 0x0002 End of file The return value is one of the following new value of the file position indicator if successful off_t 1 on failure Delete File include lt file h gt int unlink const char path The unlink function deletes the file specified by path Depending on the device a deleted file may still remain until all file descriptors which have been opened for that file have been closed See Section 7 2 3 The path is the filename of the file
91. DD IKE DU RUM MEE UNDE 33 29 6 Specifying Filenames erede eaa a te sona RASENE ver ska Dax ar Ea a 34 2 3 7 Changing How the Compiler Interprets Filenames eese 34 2 3 8 Changing How the Compiler Processes C Files esee 34 2 3 9 Changing How the Compiler Interprets and Names Extensions seeueeeeeeeeeeeeeeeee 35 2 3 10 Specifying DiteCtOries yiicsn m oiana n od cere a a a cnet a a 35 2 3 11 C puni 36 2 3 12 Deprecated ODOM us esiinispi equino OE E E eiectus N nd ent ust NEMO EESE 37 2 4 Controlling the Compiler Through Environment Variables eeeeeeeeen HH rd 2 4 14 Setting Default Compiler Options MSP430 C OPTION cceeennHHIHHIHHHHHHe d7 2 4 Naming One or More Alternate Directories MSP430 C DIR eee 38 2 5 Controlling the Preprocessor 2 5 eoru IR emn aD RR Ens aiR S e ETISRRRESRR DERE DER RSS RAS RDERRIRTOXR a DER ons RANA 39 2 5 1 Predefined Macro Names eccceceee cece ee ene een r ener leen enema hn nenne hme an meae nna nnnm 39 2 5 2 The Search Path for include Files cseeeeee cece cece ence eee ee eee eee nn e II mem nnne 40 2 5 3 Support for the warning and warn Directives cceceeeeeee eee e ee eee eee eee e nese eens nnne nnne 41 2 5 4 Generating a Preprocessed Listing File preproc only Option eese 41 2 5 5 Continuing Compilation After Prep
92. Default Compiler Options MSP430_C_OPTION You might find it useful to set the compiler assembler and linker default options using the MSP430_C_OPTION environment variable If you do this the compiler uses the default options and or input filenames that you name MSP430_C_OPTION every time you run the compiler Setting the default options with these environment variables is useful when you want to run the compiler repeatedly with the same set of options and or input files After the compiler reads the command line and the input filenames it looks for the MSP430_C_OPTION environment variable and processes it The table below shows how to set the MSP430 C OPTION environment variable Select the command for your operating system Operating System Enter UNIX Bourne shell MSP430 C OPTION option option export MSP430 C OPTION Windows set MSP430 C OPTION option option Environment variable options are specified in the same way and have the same meaning as they do on the command line For example if you want to always run quietly the quiet option enable C C source interlisting the src interlist option and link the run linker option for Windows set up the MSP430 C OPTION environment variable as follows set MSP430 C OPTION quiet src interlist run linker 32K September 2015 Using the C C Compiler 37 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEX
93. Demangler sees 163 8 2 C Name Demangler Options esineen nnne ere eea e eee e ae aE EE aaa 163 8 3 Sample Usage of the C Name Demangler eese 163 162 C Name Demangler SLAU132K September 2015 Submit Documentation Feedback Copyright O 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS www ti com Invoking the C Name Demangler 8 1 Invoking the C Name Demangler The syntax for invoking the C name demangler is dem430 options filenames dem430 Command that invokes the C name demangler options Options affect how the name demangler behaves Options can appear anywhere on the command line Options are discussed in Section 8 2 filenames Text input files such as the assembly file output by the compiler the assembler listing file the disassembly file and the linker map file If no filenames are specified on the command line dem430 uses standard input By default the C name demangler outputs to standard output You can use the o file option if you want to output to a file 8 2 C Name Demangler Options The following options apply only to the C name demangler abi eabi Demangles EABI identifiers This is on by default debug Prints debug messages diag wrap on off Sets diagnostic messages to wrap at 79 columns on which is the default or not off help Prints a help screen that provides an online summary of the C name demangler options o
94. Displays a diagnostic s identifiers along with its text Section 2 7 1 emit_warnings_as_errors pdew Treat warnings as errors Section 2 7 1 issue_remarks pdr Issues remarks non serious warnings Section 2 7 1 no_warnings pdw Suppresses diagnostic warnings errors are still issued Section 2 7 1 quiet q Suppresses progress messages quiet section sizes on off Generates section size information including sizes for sections Section 2 7 1 containing executable code and constants constant or initialized data global and static variables and uninitialized data Default is off if this option is not included on the command line Default is on if this option is used with no value specified set error limitznum pdel Sets the error limit to num The compiler abandons compiling after Section 2 7 1 this number of errors The default is 100 super quiet qq Super quiet mode tool_version version Displays version number for each tool verbose Display banner and function progress information 7 verbose_diagnostics pdv Provides verbose diagnostic messages that display the original Section 2 7 1 source with line wrap write_diagnostics_file pdf Generates a diagnostic message information file Compiler only Section 2 7 1 option 22 Using the C C Compiler SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Chan
95. EV open const char path unsigned flags int lv fd This function finds a file matching path and opens it for I O as requested by flags The path is the filename of the file to be opened If the name of a file passed to open has a device prefix the device prefix will be stripped by open so DEV open will not see it See Section 7 2 5 for details on the device prefix The flags are attributes that specify how the file is manipulated The flags are specified using the following symbols O_RDONLY 0x0000 open for reading O WRONLY 0x0001 open for writing O_RDWR 0x0002 open for read amp write O APPEND 0x0008 append on each write O CREAT 0x0200 open with file create O_TRUNC 0x0400 open with truncation O_BINARY 0x8000 open in binary mode See POSIX for further explanation of the flags The lv fd is treated as a suggested low level file descriptor This is a historical artifact newly defined device drivers should ignore this argument This differs from the low level I O open function This function must arrange for information to be saved for each file descriptor typically including a file position indicator and any significant flags For the HOST version all the bookkeeping is handled by the debugger running on the host machine If the device uses an internal buffer the buffer can be created when a file is opened or the buffer can be created during a read or write Th
96. GNU C compiler see Section 5 16 The compiler supports some features of C99 in the default relaxed ANSI mode with C89 support It supports all language features of C99 in C99 mode See Section 5 15 The ANSI ISO standard identifies some features of the C language that may be affected by characteristics of the target processor run time environment or host environment This set of features can differ among standard compilers Unsupported features of the C library are The run time library has minimal support for wide and multibyte characters The type wchar tis implemented as unsigned int 16 bits The wide character set is equivalent to the set of values of type char The library includes the header files lt wchar h gt and lt wctype h gt but does not include all the functions specified in the standard The run time library includes the header file lt locale h gt but with a minimal implementation The only supported locale is the C locale That is library behavior that is specified to vary by locale is hard coded to the behavior of the C locale and attempting to install a different locale by way of a call to setlocale will return NULL Some run time functions and features in the C99 specification are not supported See Section 5 15 Implementation Defined Behavior The C standard requires that conforming implementations provide documentation on how the compiler handles instances of implementation defined behavior The
97. In C the hooks are declared extern C Thus you can define them in C or assembly without being concerned with name mangling Hooks can be declared inline in which case the compiler tries to inline them using the same criteria as other inline functions Entry hooks and exit hooks are independent You can enable one but not the other or both The same function can be used as both the entry and exit hook You must take care to avoid recursive calls to hook functions The hook function should not call any function which itself has hook calls inserted To help prevent this hooks are not generated for inline functions or for the hook functions themselves You can use the remove hooks when inlining option to remove entry exit hooks for functions that are auto inlined by the optimizer See Section 5 11 20 for information about the NO HOOKS pragma Using the C C Compiler SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I8 TEXAS INSTRUMENTS Chapter 3 SLAU132K September 2015 Optimizing Your Code The compiler tools can perform many optimizations to improve the execution speed and reduce the size of C and C programs by simplifying loops rearranging statements and expressions and allocating variables into registers This chapter describes how to invoke different levels of optimization and describes which optimizations are performed at each level This chapter also d
98. KR OR GE OK NOR EORR DEOR WORD FUNCTION NAME f arg float i P Regs Modified SP SR r12 m D Regs Used SP SR rl12 r13 p Local Frame Size 0 Args 4 Auto 0 Save 4 byte FAROE RRB AA WR BA My Bae Ne NTO de Re NO Pe REO ae A aR A AY NN Wa A KOKORONORO NONSE RON RO A a OA A f_arg_Ff il M SUB W 4 SP MOV W r12 0 SP 40631 MOV W r13 2 SP s I3 MOV W 1 2 r12 13 ADD W 4 SP RET 92 MSP430 C C Language Implementation Copyright 2015 Texas Instruments Incorporated SLAU132K September 2015 Submit Documentation Feedback 1 TEXAS INSTRUMENTS www ti com Pragma Directives 5 11 6 The DATA_ALIGN Pragma The DATA_ALIGN pragma aligns the symbol in C or the next symbol declared in C to an alignment boundary The alignment boundary is the maximum of the symbol s default alignment value or the value of the constant in bytes The constant must be a power of 2 The maximum alignment is 32768 The DATA ALIGN pragma cannot be used to reduce an object s natural alignment The syntax of the pragma in C is pragma DATA ALIGN symbol constant The syntax of the pragma in C is pragma DATA_ALIGN constant 5 11 7 The DATA_SECTION Pragma The DATA_SECTION pragma allocates space for the symbol in C or the next symbol declared in C in a section
99. Libraries eseeeeeeeeueeeseee 141 7 1 C and C Run Time Support Libraries cccece eee eee ee ence eee nena ee eeeeeeea snes nnne nnne nnne nnn nnne 142 7 1 1 Linking Code With the Object Library cseeeeeee ee eect eee eee I III HII ne enne 142 7 1 2 Header Files eLLeeeeeeeeeeeeeeeeeeeeerielliuin naO 142 7 1 8 Modifying a Library Function c eese Im HI HI Hmmm eme enn nn nnn 142 SLAU132K September 2015 Contents 5 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS www ti com TAA Support for String Handling ri seen rn na ne eoe Rr same raaswadtaneeaencasect scare TESE 143 7 1 5 Minimal Support for Internationalization ecceeee eee cence eee eee eee ee eee nese ee m nennen 143 7 1 6 Allowable Number of Open Files ceeceeee eee ee ee ee eee e ee eee eee e II III mH eee nnne 143 7 1 7 Nonstandard Header Files in the Source Tree ceceeeee eee ee eee eee ee ee eee eee eee mI 144 FAS Library Naming Conventions esiseina ea E 144 7 2 The C VO FUNCTIONS inca E 145 721 High Level BUSES Ile e C 146 7 2 2 Overview of Low Level I O Implementation eeseeeseeeeennn nn IH mne enne 147 7 2 3 Device Driver Level I O Functions eeeeeeeeeeeeeeeeene nennen nennen nenne nne nennen nnns 150 7 2 4 Adding a User
100. MSP430 Optimizing C C Compiler v15 9 0 STS User s Guide X TEXAS INSTRUMENTS Literature Number SLAU132K September 2015 I TEXAS INSTRUMENTS Contents laine EE 9 1 Introduction to the Software Development Tools sess 12 1 1 Software Development Tools Overview eeeseesseeeeeeeehn eene nnne nnne nnne ne nnne nnn 18 1 2 Compiler Interface eoi cete o rnm n nme uc PIER DER P NT E DATUM MAD EEIE NNNM MC RC ET nS Mei ES 15 1 3 ANSIISO SIandar ussid gran densos ossi eiduea cums rudi caussae critica serge ue aaa AME Dx Ep E EEE MEE 15 1 4 OUTPUT Files Josie aeooodU oe E ovi puEuc ade Ih E E DEM IGE DID UNDE EMEN ERE 15 1 5 Brrrsce erm 16 2 Using the C CE Compile cm 17 2 1 Psogu Heneipme nep nam ana n a i dee eesdtesecenceveeent ecsdeebcederecerecaveesswiuic s 18 2 2 oe joue caeviilm 18 2 3 Changing the Compiler s Behavior with Options cceceeeeeee eee eee e eee cence eee III I Ime 19 zs ANEEI genis MW m 26 23 2 Preguently Used ODptioris ecce c us o nio enr er omae uasan naaa ance ree Ree aE aE NS NUES Uia Eana 28 2 3 8 Miscellaneous Useful Options ccece cece ence eee e eee cence eee n eee nene nne eh hn nnne nnn nnn 29 2 3 4 Run Time Model OptionS ccccceceeeeeceeee cece ee eee enne nennen nnnm nnn nnne nnn nn nnn 31 239 9 symbolic Debugging Options isses eno a de EIK DINE QUEUE REED
101. MSP430x4xx MSP430x5xx MSP430 are trademarks of Texas Instruments All other trademarks are the property of their respective owners SLAU132K September 2015 Read This First 11 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 12 Chapter 1 l oc OMENS SLAU132K September 2015 Introduction to the Software Development Tools The MSP430 is supported by a set of software development tools which includes an optimizing C C compiler an assembler a linker and assorted utilities This chapter provides an overview of these tools and introduces the features of the optimizing C C compiler The assembler and linker are discussed in detail in the MSP430 Assembly Language Tools User s Guide Topic Page 1 1 Software Development Tools Overview eese 13 1 298 Compiler Interface 0 creare T RT eT E ITE TEE IE T TE EE E TREE 15 1 3 ANSI ISO Standard sciences a aa EREE A EERE E EAEE AEE RE EERE EAA smonenene a AEA AERE 15 1 4 Output E E A E A E A A EIE E 15 15 Utilities 50 cere E E A E EE A AE E E EE A E ORE 16 Introduction to the Software Development Tools SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Software Development Tools Overview 1 4 Software Development Tools Overview Figure 1 1 illustrates the software development flow The shaded portion of the figure highlights the most
102. OE registers POP r10 RET Return 6 4 3 Accessing Arguments and Local Variables 6 5 6 6 6 6 1 124 A function accesses its local nonregister variables and stack arguments indirectly through the stack pointer SP or R1 The SP always points to the top of the stack the most recently pushed value Since the stack grows toward smaller addresses the local data on the stack for the C C function is accessed with a positive offset from the SP register Accessing Linker Symbols in C and C See the section on Using Linker Symbols in C C Applications in the MSP430 Assembly Language Tools User s Guide for information about referring to linker symbols in C C code Interfacing C and C With Assembly Language The following are ways to use assembly language with C C code Use separate modules of assembled code and link them with compiled C C modules see Section 6 6 1 Use assembly language variables and constants in C C source see Section 6 6 3 Use inline assembly language embedded directly in the C C source see Section 6 6 5 Using Assembly Language Modules With C C Code Interfacing C C with assembly language functions is straightforward if you follow the calling conventions defined in Section 6 4 and the register conventions defined in Section 6 3 C C code can access variables and call functions defined in assembly language and assembly code can access C C variables and call C C functions
103. P430 C C Language Implementation SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Pragma Directives 5 11 5 The CODE SECTION Pragma The CODE SECTION pragma allocates space for the symbol in C or the next symbol declared in C in a section named section name The syntax of the pragma in C is pragma CODE SECTION symbol section name The syntax of the pragma in C is pragma CODE SECTION section name The CODE SECTION pragma is useful if you have code objects that you want to link into an area separate from the text section The following example demonstrates the use of the CODE SECTION pragma Example 5 4 Using the CODE SECTION Pragma C Source File pragma CODE SECTION funcA codeA int funcA int a int i return i a Example 5 5 Generated Assembly Code From Example 5 4 sect codeA align 2 clink global funcA UOCE ERROR DR RR EUK KORR REA AAA AAA a IGNI ORI DG EK Ke oe ek ERAS FUNCTION NAME funcA Regs Modified SP SR r12 Regs Used SP SR r12 Local Frame Size 0 Args 4 Auto 0 Save 4 byte ck ck ck ck ke ck ke ck Sk ck ck ck ck ck ck ck ck ck ke ck ke ce ke ck ke ck ck ke ke ck ke ck ck ke ck ke ce ke ck ck kk ke ke ck ck ck ck ke ck kk kk ck kk ko ko ck Sk sk Sk Sk kv ko ke ko ko PE
104. R EE 58 3 4 2 Incompatible Types ccccceeeee eee e ee ee eee n nm II HI HII HH HI hme nhe nnn ene ne nnn 59 3 5 Accessing Aliased Variables in Optimized Code cceeccece eee eee eee eee eee e eee eee sees eeeeeeeeeeeeeeeeneneeeeeeeee 59 3 6 Use Caution With asm Statements in Optimized Code ccc ecceee cece ence eee ee eee nese eeeeeeeaeeeeeeeeeeeeaeee 59 3 7 Automatic Inline Expansion auto_inline Option ceceee eee eee eee eee eee HII 60 3 8 Using the Interlist Feature With OptimiZation 2 cceee eee ee eee eee ee ee m III III mne 60 3 9 Debugging Optimized Cod Dn 62 3 10 Controlling Code Size Versus Speed ceccecee eee e tence eee e eee ee eee eee eeeeeeeenaeeaeeeeneeeeaseeeeeeneeenaeeeeees 62 3 11 What Kind of Optimization Is Being Performed ceceeee cece ee eee cece ee eee eee ease en eee eee nennen 63 3 11 1 Cost Based Register Allocation ccc cceeee cece eee e eee eee a a aa aa a aa aat aa aaa E 63 3 11 2 Alias DISAMDIQUATLION weissiniwveneveterenanduincneine raro aenmea nari aso k rona sa Eus evened deaveedevelevedavernituninn 63 3 11 3 Branch Optimizations and Control Flow Simplification eeeeeeee ern 64 3 14 Data Elow Optimizations siscices somai nie ee con irk ue PUe acne ietcinednie dumedutmpudam NE Ce quete quibruid V asia d rie 64 3 115 Expression SimiplifiGatiODi seszsesice sucesos oues A E Ei 64 3 11 6 Inline Expansion of Functions eseeeeesee
105. S INLINE Pragma 94 The FUNC ALWAYS INLINE pragma instructs the compiler to always inline the named function The compiler only inlines the function if it is legal to inline the function and the compiler is invoked with any level of optimization opt_level 0 See Section 2 11 for details about interaction between various types of inlining This pragma must appear before any declaration or reference to the function that you want to inline In C the argument func is the name of the function that will be inlined In C the pragma applies to the next function declared This pragma can be used to force inlining at link time across C files The syntax of the pragma in C is pragma FUNC ALWAYS INLINE func The syntax of the pragma in C is pragma FUNC ALWAYS INLINE MSP430 C C Language Implementation SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Pragma Directives The following example uses this pragma pragma FUNC_ALWAYS_INLINE functionThatMustGet Inlined static inline void functionThatMustGetInlined void P1OUT 0x01 P1OUT amp 0x01 Use Caution with the FUNC_ALWAYS_INLINE Pragma NOTE The FUNC_ALWAYS_INLINE pragma overrides the compiler s inlining decisions Overuse of this pragma could result in increased compilation times or memory usage potentially enough to consume all available
106. SRs are placed into low memory If you do not specify an ISR for some interrupt vectors an ISR will be provided for those vectors from the RTS library and the RTS library will automatically be linked with your application The default ISR puts the device in low power mode You can override the ISR provided by the RTS with the pragma vector and the unused_interrupts keyword as shown in Section 5 11 26 6 7 5 Other Interrupt Information An interrupt routine can perform any task performed by any other function including accessing global variables allocating local variables and calling other functions When you write interrupt routines keep the following points in mind e Itis your responsibility to handle any special masking of interrupts A C C interrupt routine cannot be called directly from C C code You need to arrange for an interrupt signal to happen In a system reset interrupt such as c int0O you cannot assume that the run time environment is set up therefore you cannot allocate local variables and you cannot save any information on the run time stack 128 Run Time Environment SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS www ti com Using Intrinsics to Access Assembly Language Statements 6 8 Using Intrinsics to Access Assembly Language Statements The compiler recognizes a numb
107. See Chapter 4 for more information link options Options that control the linking process object files Names of the object files for the linking process The arguments to the compiler are of three types Compiler options Link options Filenames The run linker option indicates linking is to be performed If the run linker option is used any compiler options must precede the run linker option and all link options must follow the run linker option Source code filenames must be placed before the run linker option Additional object file filenames can be placed after the run linker option For example if you want to compile two files named symtab c and file c assemble a third file named seek asm and link to create an executable program called myprogram out you will enter c1430 symtab c file c seek asm run linker library lnk cmd output file smyprogram out 18 Using the C C Compiler SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Changing the Compiler s Behavior with Options 2 3 Changing the Compiler s Behavior with Options Options control the operation of the compiler This section provides a description of option conventions and an option summary table It also provides detailed descriptions of the most frequently used options including options used for type checking and assembling For a help sc
108. The accuracy of library functions that return floating point results is not specified 5 2 4 2 2 The compiler does not provide non standard values for FLT ROUNDS 5 2 4 2 2 The compiler does not provide non standard negative values of FLT EVAL METHOD 5 2 4 2 2 The rounding direction when an integer is converted to a floating point number is IEEE 754 round to even 6 3 1 4 The rounding direction when a floating point number is converted to a narrower floating point number is IEEE 754 round to even 6 3 1 5 For floating point constants that are not exactly representable the implementation uses the nearest representable value 6 4 4 2 The compiler does not contract float expressions 6 5 The default state for the FENV ACCESS pragma is off 7 6 1 The Tl compiler does not define any additional float exceptions 7 6 7 12 The default state for the FP CONTRACT pragma is off 7 12 2 The inexact floating point exception cannot be raised if the rounded result equals the mathematical result F 9 The underflow and inexact floating point exceptions cannot be raised if the result is tiny but not inexact F 9 J 3 7 Arrays and pointers When converting a pointer to an integer or vice versa the pointer is considered an unsigned integer of the same size and the normal integer conversion rules apply Some pointers are not the same size as any integral type but the conversion proceeds as if such a
109. This program build for Windows32 when the following is executed from the Command Prompt window gmake h All three of these programs are provided as a non optional feature of CCS 5 1 They are also available as part of the optional XDC Tools feature if you are using an earlier version of CCS The mklib program looks for these executables in the following order 1 in your PATH 2 in the directory getenv CCS_UTILS_DIR cygwin 3 in the directory getenv CCS UTILS DIR bin 4 in the directory getenv XDCROOT 5 in the directory getenv XDCROOT bin If you are invoking mklib from the command line and these executables are not in your path you must set the environment variable CCS UTILS DIR such that getenv CCS UTILS DIR bin contains the correct programs 7 4 2 Using the Library Build Process 7 4 2 1 158 You should normally let the linker automatically rebuild libraries as needed If necessary you can run mklib directly to populate libraries See Section 7 4 2 2 for situations when you might want to do this Automatic Standard Library Rebuilding by the Linker The linker looks for run time support libraries primarily through the MSP430 C DIR environment variable Typically one of the pathnames in MSP430 C DIR is your install directory lib which contains all of the pre built libraries as well as the index library libc a The linker looks in MSP430 C DIR to find a library that is the best match for the build attrib
110. _misra option The syntax of the pragma in C is pragma CHECK MISRA all required advisory none rulespec The rulespec parameter is a comma separated list of rule numbers See Section 5 3 for details The RESET MISRA pragma can be used to reset any CHECK MISRA pragmas see Section 5 11 22 5 11 3 The CHECK ULP Pragma The CHECK ULP pragma enables disables ULP Advisor rules at the source level This pragma is equivalent to using the advice power option The syntax of the pragma in C is pragma CHECK ULP all none rulespec The rulespec parameter is a comma separated list of rule numbers See Section 5 3 for the syntax The RESET ULP pragma can be used to reset any CHECK ULP pragmas see Section 5 11 23 5 11 4 The CLINK Pragma 90 The CLINK pragma can be applied to a code or data symbol It causes a clink directive to be generated into the section that contains the definition of the symbol The clink directive tells the linker that a section is eligible for removal during conditional linking Thus if the section is not referenced by any other section in the application being compiled and linked it will not be included in the resulting output file The syntax of the pragma in C is pragma CLINK symbol The syntax of the pragma in C is pragma CLINK The RETAIN pragma has the opposite effect of the CLINK pragma See Section 5 11 24 for more details MS
111. a model data pointer manipulation must be performed using 20 bit operations OP A 6 6 2 Accessing Assembly Language Functions From C C Functions defined in C that will be called from assembly should be defined as extern C in the C file Functions defined in assembly that will be called from C must be prototyped as extern C in C Example 6 2 illustrates a C function called main which calls an assembly language function called asmfunc Example 6 3 The asmfunc function takes its single argument adds it to the C global variable called gvar and returns the result Example 6 2 Calling an Assembly Language Function From a C C Program extern C extern int asmfunc int a declare external asm function int gvar 0 define global variable void main int var 5 var asmfunc var call function normally Example 6 3 Assembly Language Program Called by Example 6 2 global asmfunc global gvar asmfunc MOV amp gvar R11 ADD R11 R12 RET In the C program in Example 6 2 the extern C declaration tells the compiler to use C naming conventions i e no name mangling When the linker resolves the global asmfunc reference the corresponding definition in the assembly file will match The parameter var is passed in R12 and the result is returned in R12 SLAU132K September 2015 Run Time Environment 125 Submit Documentation Feedback Copyright 20
112. a niana nasce a Gate dicla ciere Sic ui temen neut a dete desinet 100 51121 The PACK Praga carats cesta oen sioe ioeae necatur a thee Esimeescu A ANE 100 5 11 22 The RESET MISRA Pragma indica srcesaict ostendat cum c icis miouisinuduitiegeituie e mesieu msc Ea 101 5 11 23 The RESET ULP Pragma ss escaxs eese r eo seen n qu mpra EEEO EAEAN EEE EEKAN 101 5 1124 The RETAIN Pragma ee ixenc nuu perum mtn n Rie men RR Roe Re EPONE AEAEE RR caer eueereens 101 5 11 25 The SET CODE SECTION and SET DATA SECTION Pragmas eee 102 5 11 26 The vector Pragma isver a to rknuan asia o VERRE NXRIR RSEN REIAM eaa SR TA E REM Fare Ys 103 5 12 The Pragma Operator 3 5 ie edocet doe EEE eunte eu acc EE EAEE 104 5 13 Application Binary Interface ccccceeeeeee ee ee ee ee eee nnn I HH hm em e nenne hene nhe nn nnne nnn 105 5 14 Object File Symbol Naming Conventions LINKNAMES cseceeee eee eee eee eee ee cnet ee m Hn 105 5 15 Changing the ANSI ISO C C Language MOde ceeceeeeee eect eee eee eeeee eee III mne nnn 106 5 15 1 Enabling C99 Mode C99 cniessiienaueiainrneiiaeuieniaiserctemsmiecininmduialnainwieauinmaust viet ay sess EET M cup EMEN UU EE 106 5 15 2 Compatibility With K amp R C kr compatible Option eeeeeeeeeenIHI 107 5 15 3 Enabling Strict ANSI ISO Mode and Relaxed ANSI ISO Mode strict ansi and relaxed ansi elim DIET 108 Contents SLAU132K September 2015 Submit Documentation Feedback
113. ainst this total SLAU132K September 2015 Using Run Time Support Functions and Building Libraries 145 Submit Documentation Feedback Copyright O 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS The C I O Functions www ti com 7 2 1 High Level I O Functions The high level functions are the standard C library of stream I O routines printf scanf fopen getchar and so on These functions call one or more low level I O functions to carry out the high level I O request The high level I O routines operate on FILE pointers also called streams Portable applications should use only the high level I O functions To use the high level I O functions include the header file stdio h or cstdio for C code for each module that references a C I O function For example given the following C program in a file named main c include lt stdio h gt void main FILE fid fid fopen myfile w fprintf fid Hello world n fclose fid printf Hello again world n Issuing the following compiler command compiles links and creates the file main out from the run time support library cl430 main c run linker heap size 400 library rts430_eabi lib output_file main out Executing main out results in Hello world being output to a file and Hello again world being output to your host s stdout window 146 Using Run Time Support Functions and Building Libraries SLAU132K September 2015
114. am see below Under the standard definition of embedded C namespaces and using declarations are not supported The MSP430 compiler nevertheless allows these features under embedded C because the C run time support library makes use of them Furthermore these features impose no run time penalty The default run time support library does not support using iostream under embedded C Embedded C equivalents of some header files such as iostream are not included in the RTS source code distributed with the compiler These features cannot be used in Embedded C without new header files and an appropriately configured library SLAU132K September 2015 MSP430 C C Language Implementation 109 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated GNU Language Extensions I TEXAS INSTRUMENTS www ti com 5 16 GNU Language Extensions The GNU compiler collection GCC defines a number of language features not found in the ANSI ISO C and C standards The definition and examples of these extensions for GCC version 4 7 can be found at the GNU web site http gcc gnu org onlinedocs gcc 4 7 2 gcc C Extensions html C Extensions Most of these extensions are also available for C source code 5 16 1 Extensions Most of the GCC language extensions are available in the TI compiler when compiling in relaxed ANSI mode relaxed_ansi Note that the gcc option is deprecated The extensions that the TI
115. ambiguation A technique that determines when two pointer expressions cannot point to the same location allowing the compiler to freely optimize such expressions aliasing The ability for a single object to be accessed in more than one way such as when two pointers point to a single object It can disrupt optimization because any indirect reference could refer to any other object allocation A process in which the linker calculates the final memory addresses of output sections ANSI American National Standards Institute an organization that establishes standards voluntarily followed by industries archive library A collection of individual files grouped into a single file by the archiver archiver A software program that collects several individual files into a single file called an archive library With the archiver you can add delete extract or replace members of the archive library assembler A software program that creates a machine language program from a source file that contains assembly language instructions directives and macro definitions The assembler substitutes absolute operation codes for symbolic operation codes and absolute or relocatable addresses for symbolic addresses assignment statement A statement that initializes a variable with a value autoinitialization The process of initializing global C variables contained in the cinit section before program execution begins autoinitiali
116. ambiguation See alias disambiguation dynamic memory allocation A technique used by several functions such as malloc calloc and realloc to dynamically allocate memory for variables at run time This is accomplished by defining a large memory pool heap and using the functions to allocate memory from the heap ELF Executable and Linkable Format a system of object files configured according to the System V Application Binary Interface specification emulator A hardware development system that duplicates the MSP430 operation entry point A point in target memory where execution starts environment variable A system symbol that you define and assign to a string Environmental variables are often included in Windows batch files or UNIX shell scripts such as cshrc or profile epilog The portion of code in a function that restores the stack and returns executable object file A linked executable object file that is downloaded and executed on a target system expression A constant a symbol or a series of constants and symbols separated by arithmetic operators Glossary SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Appendix A external symbol A symbol that is used in the current program module but defined or declared in a different program module file level optimization A level of optimization where the c
117. angle the name User defined symbols in C code and in assembly code are in the same namespace which means you are responsible for making sure that your C identifiers do not collide with your assembly code identifiers You may have identifiers that collide with assembly keywords for instance register names in this case the compiler automatically uses an escape sequence to prevent the collision The compiler escapes the identifier with double parallel bars which instructs the assembler not to treat the identifier as a keyword You are responsible for making sure that C identifiers do not collide with user defined assembly code identifiers Name mangling encodes the types of the parameters of a function in the linkname for a function Name mangling only occurs for C functions which are not declared extern C Mangling allows function overloading operator overloading and type safe linking Be aware that the return value of the function is not encoded in the mangled name as C functions cannot be overloaded based on the return value For example the general form of a C linkname for a function named func is func F parmcodes Where parmcodes is a sequence of letters that encodes the parameter types of func For this simple C source file int foo int i global C function This is the resulting assembly code foo Fi The linkname of foo is foo Fi indicating that foo is a function that takes a single argument of type int To a
118. are combined according to the linker command file to generate initialized output sections The loader loads the initialized output sections into memory After the load the variables are assigned their initial values Since the linker does not generate the C autoinitialization tables no boot time initialization is performed Figure 6 4 illustrates the initialization of variables at load time Figure 6 4 Initialization at Load Time Object file Memory data section data section initialized RAM SLAU132K September 2015 Run Time Environment 137 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS System Initialization www ti com 6 9 3 6 Global Constructors All global C variables that have constructors must have their constructor called before main The compiler builds a table of global constructor addresses that must be called in order before main in a section called init array The linker combines the init array section form each input file to form a single table in the init array section The boot routine uses this table to execute the constructors The linker defines two symbols to identify the combined init array table as shown below This table is not null terminated by the linker Figure 6 5 Constructor Table TLINITARRAY Base Address of constructor 1 Address of constructor 2 Address of constructor n TI INITARRAY Limit
119. are listed next and indicated by the source filename 2 6 Passing Arguments to main Some programs pass arguments to main via argc and argv This presents special challenges in an embedded program that is not run from the command line In general argc and argv are made available to your program through the args section There are various ways to populate the contents of this section for use by your program To cause the linker to allocate an args section of the appropriate size use the arg_size size linker option This option tells the linker to allocate an uninitialized section named args which can be used by the loader to pass arguments from the command line of the loader to the program The size is the number of bytes to be allocated When you use the arg_size option the linker defines the c args symbol to contain the address of the args section It is the responsibility of the loader to populate the args section The loader and the target boot code can use the args section and the __c_args__ symbol to determine whether and how to pass arguments from the host to the target program The format of the arguments is an array of pointers to char on the target Due to variations in loaders it is not specified how the loader determines which arguments to pass to the target If you are using Code Composer Studio to run your application you can use the Scripting Console tool to populate the args section To open this tool choose View
120. as synonyms for standard types typedef unsigned int wchar t typedef unsigned int wint t MSP devices support multiple data and code memory models The code and data model affects the size alignment and storage space used for function pointers data pointers the size t type and the ptrdiff t type Pointers with sizes that are not a power of 2 are always stored in a container with a size of a power of 2 bits That is 20 bit types are stored in 32 bits Table 5 2 Data Sizes for MSP430 Pointers Code or Data Model Type Size Storage Alignment small code model function pointer 16 16 16 large code model function pointer 20 32 16 small data model data pointer 16 16 16 small data model size t 16 16 16 small data model ptrdiff t 16 16 16 82 MSP430 C C Language Implementation SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Data Types Table 5 2 Data Sizes for MSP430 Pointers continued Code or Data Model Type Size Storage Alignment restricted data model data pointer 20 32 16 restricted data model size t 16 16 16 restricted data model ptrdiff t 16 16 16 large data model data pointer 20 32 16 large data model size t 32 32 16 large data model ptrdiff t 32 32 16 MSP430X large data model is specified by silicon_version mspx data model large 5 6 1 Size of Enum Types An enum type is represented by an underlying integer type The size of
121. ate definition resulting in multiple definitions of the same object and usually an error For example int a int a illegal if kr compatible used OK if not Under ANSI ISO the result of these two definitions is a single definition for the object a For most K amp R compilers this sequence is illegal because int a is defined twice SLAU132K September 2015 MSP430 C C Language Implementation 107 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Changing the ANSI ISO C C Language Mode www ti com e ANSI ISO prohibits but K amp R allows objects with external linkage to be redeclared as static extern int a static int a illegal unless kr compatible used Unrecognized escape sequences in string and character constants are explicitly illegal under ANSI ISO but ignored under K amp R char c q same as q if kr compatible used error if not e ANSI ISO specifies that bit fields must be of type int or unsigned With kr compatible bit fields can be legally defined with any integral type For example struct s short f 2 illegal unless kr compatible used K amp R syntax allows a trailing comma in enumerator lists enum a b c illegal unless kr compatible used K amp R syntax allows trailing tokens on preprocessor directives endif NAME illegal unless kr compatible used 5 15 3 Enabling Strict ANSI ISO Mo
122. ated Using the C C Compiler 19 I TEXAS INSTRUMENTS Changing the Compiler s Behavior with Options www ti com Table 2 3 Advanced Optimization Options Option Alias Effect Section auto_inline size oi Sets automatic inlining size opt_level 3 only If size is not Section 3 7 specified the default is 1 call_assumptions n opn Level 0 op0 specifies that the module contains functions and Section 3 3 1 variables that are called or modified from outside the source code provided to the compiler Level 1 op1 specifies that the module contains variables modified from outside the source code provided to the compiler but does not use functions called from outside the source code Level 2 op2 specifies that the module contains no functions or variables that are called or modified from outside the source code provided to the compiler default Level 3 op3 specifies that the module contains functions that are called from outside the source code provided to the compiler but does not use variables modified from outside the source code gen_opt_info n onn Level 0 on0 disables the optimization information file Section 3 2 2 Level 1 on2 produces an optimization information file Level 2 on2 produces a verbose optimization information file optimizer_interlist OS Interlists optimizer comments with assembly statements Section 3 8 remove hooks when inlining Removes entry exit hooks fo
123. ations on the file will silently fail If a call to printf mysteriously fails this may be the reason The heap needs to be at least large enough to allocate a block of size BUFSIZ defined in stdio h for every file on which I O is performed including stdout stdin and stderr plus allocations performed by the user s code plus allocation bookkeeping overhead Alternately declare a char array of size BUFSIZ and pass it to setvbuf to avoid dynamic allocation To set the heap size use the heap_size option when linking refer to the Linker Description chapter in the MSP430 Assembly Language Tools User s Guide Open Mysteriously Fails The run time support limits the total number of open files to a small number relative to general purpose processors If you attempt to open more files than the maximum you may find that the open will mysteriously fail You can increase the number of open files by extracting the source code from rts src and editing the constants controlling the size of some of the C I O data structures The macro _NFILE controls how many FILE fopen objects can be open at one time stdin stdout and stderr count against this total See also FOPEN MAX The macro NSTREAM controls how many low level file descriptors can be open at one time the low level files underlying stdin stdout and stderr count against this total The macro NDEVICE controls how many device drivers are installed at one time the HOST device counts ag
124. aw listing file has the same name as the corresponding source file with an r extension The raw listing file contains the following information Each original source line Transitions into and out of include files Diagnostic messages Preprocessed source line if nontrivial processing was performed comment removal is considered trivial other preprocessing is nontrivial Using the C C Compiler SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Generating a Raw Listing File gen_acp_raw Option Each source line in the raw listing file begins with one of the identifiers listed in Table 2 34 Table 2 34 Raw Listing File Identifiers Identifier Definition N Normal line of source X Expanded line of source It appears immediately following the normal line of source if nontrivial preprocessing occurs Skipped source line false if clause L Change in source position given in the following format L line number filename key Where ine number is the line number in the source file The key is present only when the change is due to entry exit of an include file Possible values of key are 1 entry into an include file 2 exit from an include file The gen_acp_raw option also includes diagnostic identifiers as defined in Table 2 35 Table 2 35 Raw Listing File Diagnostic Identifiers Diagnostic Identifier Definition
125. ber 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated l www ti com 3 11 TEXAS INSTRUMENTS What Kind of Optimization Is Being Performed worsening or impacting code size Oopt for speed 5 Enables optimizations geared towards improving the code performance speed with a high risk of worsening or impacting code size If you specify the opt for speed option without a parameter the default setting is opt for speed 4 If you do not specify the opt for speed option the default setting is 1 What Kind of Optimization Is Being Performed The MSP430 C C compiler uses a variety of optimization techniques to improve the execution speed of your C C programs and to reduce their size Following are some of the optimizations performed by the compiler Optimization See Cost based register allocation Alias disambiguation Branch optimizations and control flow simplification Data flow optimizations Copy propagation Common subexpression elimination Redundant assignment elimination Expression simplification Inline expansion of functions Function Symbol Aliasing Induction variable optimizations and strength reduction Loop invariant code motion Loop rotation Instruction scheduling Section 3 11 1 Section 3 11 1 Section 3 11 3 Section 3 11 4 Section 3 11 5 Section 3 11 6 Section 3 11 7 Section 3 11 8 Section 3 11 9 Section 3 11 10 Section 3 11 11 MSP430 Spe
126. bility In addition to the ANSI ISO specified functions the run time support library includes routines that give you processor specific commands and direct C language I O requests These are detailed in Section 7 1 and Section 7 2 A library build utility is provided with the code generation tools that lets you create customized run time support libraries This process is described in Section 7 4 Topic Page 7 4 Cand C Run Time Support Libraries eeeeseeeeeeeeeeseeneneeeenre 142 71 2 2 The GVO Functions onto ERE annem ncete UE RE EE ERE EHE ERU Ee 145 7 3 Handling Reentrancy register lock and register unlock Functions 157 7 4 Bibrary Build Process eene saan saci EAn EE AEAEE AE A EERE aaa aeaa an 158 SLAU132K September 2015 Using Run Time Support Functions and Building Libraries 141 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS C and C Run Time Support Libraries www ti com 7 1 Cand C Run Time Support Libraries MSP430 compiler releases include pre built run time support RTS libraries that provide all the standard capabilities Separate libraries are provided for each ABI and C exception support See Section 7 1 8 for information on the library naming conventions The run time support library contains the following e ANSI ISO C C standard library CI O library Low level support functions that pro
127. cannot be used to create a critical section Use some sort of lock if you need to create a critical section 6 7 3 J 3 11 Preprocessing directives Include directives may have one of two forms or lt gt For both forms the compiler will look for a real file on disk by that name using the include file search path See Section 2 5 2 6 4 7 The value of a character constant in a constant expression that controls conditional inclusion matches the value of the same character constant in the execution character set both are ASCII 6 10 1 The compiler uses the file search path to search for an included delimited header file See Section 2 5 2 6 10 2 he compiler uses the file search path to search for an included delimited header file See Section 2 5 2 6 10 2 6 10 2 There is no arbitrary nesting limit for include processing 6 10 2 See Section 5 11 for a description of the recognized non standard pragmas 6 10 6 The date and time of translation are always available from the host 6 10 8 J 3 12 Library functions Almost all of the library functions required for a hosted implementation are provided by the TI library with exceptions noted in Section 5 15 1 5 1 2 1 The format of the diagnostic printed by the assert macro is Assertion failed assertion macro argument file file line line 7 2 1 1 No strings other than C and may be passed as the second argument to the setlocale function
128. case the signature for the hook function is void hook const char name The address parameter specifies that the address of the calling function is passed to the hook function In this case the signature for the hook function is void hook void addr The none parameter specifies that the hook is called with no parameters This is the default In this case the signature for the hook function is void hook void exit_hook name Enables exit hooks If specified the hook function is called name Otherwise the default exit hook function name is exit hook exit parm name Specify the parameters to the hook function The name parameter specifies address none that the name of the calling function is passed to the hook function as an argument In this case the signature for the hook function is void hook const char name The address parameter specifies that the address of the calling function is passed to the hook function In this case the signature for the hook function is void hook void addr The none parameter specifies that the hook is called with no parameters This is the default In this case the signature for the hook function is void hook void The presence of the hook options creates an implicit declaration of the hook function with the given signature If a declaration or definition of the hook function appears in the compilation unit compiled with the options it must agree with the signatures listed above
129. cation Binary Interface 7 ne naccneccansne senna cananenciecmaccnnecancmamenascenmneats 105 5 14 Object File Symbol Naming Conventions Linknames esses 105 5 15 Changing the ANSI ISO C C Language Mode ceeeeeeeeeeeees 106 5 16 GNU Eanguage Extensions eoe eerie IR aE AE r RETE a 110 5l Compilerl imiis nes ee cer A M AM saree aera ences 113 SLAU132K September 2015 Submit Documentation Feedback MSP430 C C Language Implementation 75 Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Characteristics of MSP430 C www ti com 5 1 76 Characteristics of MSP430 C The C compiler supports the 1989 and 1999 versions of the C language C89 Compiling with the c89 option causes the compiler to conform to the ISO IEC 9899 1990 C standard which was previously ratified as ANSI X3 159 1989 The names C89 and C90 refer to the same programming language C89 is used in this document C99 Compiling with the c99 option causes the compiler to conform to the ISO IEC 9899 1999 C standard This standard supports several features not part of C89 such as inline functions new data types and one line comments beginning with The C language is also described in the second edition of Kernighan and Ritchie s The C Programming Language K amp R The compiler can also accept many of the language extensions found in the
130. cent 32 bits aligned to 16 bit boundary long Two registers which need not be adjacent 32 bits aligned to 16 bit boundary unsigned long Two registers which need not be adjacent 32 bits aligned to 16 bit boundary long long Four registers which need not be adjacent 64 bits aligned to 16 bit boundary unsigned long long double Four registers which need not be adjacent Four registers which need not be adjacent 64 bits aligned to 16 bit boundary 64 bits aligned to 16 bit boundary long double Four registers which need not be adjacent 64 bits aligned to 16 bit boundary struct Members are stored as their individual types Multiple of 8 bits aligned to boundary of largest require member type members are stored and aligned as their individual types require array Members are stored as their individual types Members are stored as their individual types require require All arrays inside a structure are aligned according to the type of each element in the array pointer to data member Bits 0 15 of register for MSP430 Bits 0 19 of register for MSP430X Components stored as their individual types require varies see Table 5 2 pointer to member function 64 bits aligned to 32 bit boundary The size of an enum varies by the size of the largest enum value and by whether it is packed or not For details about the size of an enum type see Section 5 6 1 6 2 1 1 Pointer to Member Function Types Pointer to member function obj
131. cific Optimization See Tail merging Integer division with constant divisor Section 3 11 12 Section 3 11 13 3 11 1 Cost Based Register Allocation The compiler when optimization is enabled allocates registers to user variables and compiler temporary values according to their type use and frequency Variables used within loops are weighted to have priority over others and those variables whose uses do not overlap can be allocated to the same register Induction variable elimination and loop test replacement allow the compiler to recognize the loop as a simple counting loop and unroll or eliminate the loop Strength reduction turns the array references into efficient pointer references with autoincrements 3 11 2 Alias Disambiguation C and C programs generally use many pointer variables Frequently compilers are unable to determine whether or not two or more values lowercase L symbols pointer references or structure references refer to the same memory location This aliasing of memory locations often prevents the compiler from retaining values in registers because it cannot be sure that the register and memory continue to hold the same values over time Alias disambiguation is a technique that determines when two pointer expressions cannot point to the same location allowing the compiler to freely optimize such expressions SLAU132K September 2015 Submit Documentation Feedback Optimizing Your Code 63 Copyright
132. cing C and C With Assembly Language No assembly module should use the cinit section for any purpose other than autoinitialization of global variables The C C startup routine assumes that the cinit section consists entirely of initialization tables Disrupting the tables by putting other information in cinit can cause unpredictable results The compiler assigns linknames to all external objects Thus when you write assembly language code you must use the same linknames as those assigned by the compiler See Section 5 14 for details Any object or function declared in assembly language that is accessed or called from C C must be declared with the def or global directive in the assembly language modifier This declares the symbol as external and allows the linker to resolve references to it Likewise to access a C C function or object from assembly language declare the C C object with the ref or global directive in the assembly language module This creates an undeclared external reference that the linker resolves Any assembly routines that interface with MSP430x C programs are required to conform to the large code model Use CALLA RETA instead of CALL RET Use PUSHM A POPM A to save and restore any used save on entry registers The entire 20 bit register must be saved restored Manipulation of function pointers requires 20 bit operations OP A If interfacing with C code compiled for the large dat
133. compiler supports are listed in Table 5 3 which is based on the list of extensions found at the GNU web site The shaded rows describe extensions that are not supported Table 5 3 GCC Language Extensions Extensions Descriptions Statement expressions Putting statements and declarations inside expressions useful for creating smart safe macros Local labels Labels local to a statement expression Labels as values Pointers to labels and computed gotos Nested functions As in Algol and Pascal lexical scoping of functions Constructing calls Dispatching a call to another function Naming types Giving a name to the type of an expression typeof operator typeof referring to the type of an expression Generalized lvalues Using question mark and comma and casts in lvalues Conditionals Omitting the middle operand of a expression Hex floats Hexadecimal floating point constants Complex Data types for complex numbers Zero length Zero length arrays Variadic macros Macros with a variable number of arguments Variable length Arrays whose length is computed at run time Empty structures Structures with no members Subscripting Any array can be subscripted even if it is not an lvalue Escaped newlines Slightly looser rules for escaped newlines Multi line strings String literals with embedded newlines Pointer arithmetic
134. ctors to be called during program initialization and their destructors to be called during program termination The C compiler produces a table of constructors to be called at startup Constructors for global objects from a single module are invoked in the order declared in the source code but the relative order of objects from different object files is unspecified Global constructors are called after initialization of other global variables and before the main function is called Global destructors are invoked during the exit run time support function similar to functions registered through atexit Section 6 9 3 6 discusses the format of the global constructor table for EABI mode 4 3 7 Specifying the Type of Global Variable Initialization 72 The C C compiler produces data tables for initializing global variables Section 6 9 3 4 discusses the format of these initialization tables The initialization tables are used in one of the following ways Global variables are initialized at run time Use the rom_model linker option see Global variables are initialized at load time Use the ram_model linker option see When you link a C C program you must use either the rom_model or ram_model option These options tell the linker to select initialization at run time or load time When you compile and link programs the rom_model option is the default If used the rom_model option must follow the run_linker option
135. cture instruction set pipeline and interrupts for these ultra low power microcontrollers SLAU012 MSP430x3xx Family User s Guide Describes the MSP430x3xx CPU architecture instruction set pipeline and interrupts for these ultra low power microcontrollers SLAU056 MSP430x4xx Family User s Guide Describes the MSP430x4xx CPU architecture instruction set pipeline and interrupts for these ultra low power microcontrollers SLAU208 MSP430x5xx Family User s Guide Describes the MSP430x5xx CPU architecture instruction set pipeline and interrupts for these ultra low power microcontrollers SLAU134 MSP430FE42x ESP30CE1 Peripheral Module User s Guide Describes common peripherals available on the MSP430FE42x and ESP430CE1 ultra low power microcontrollers This book includes information on the setup operation and registers of the ESP430CE1 SPRAAB5 The Impact of DWARF on TI Object Files Describes the Texas Instruments extensions to the DWARF specification SPRUEX3 TI SYS BIOS Real time Operating System User s Guide SYS BIOS gives application developers the ability to develop embedded real time software SYS BIOS is a scalable real time kernel It is designed to be used by applications that require real time scheduling and synchronization or real time instrumentation SYS BIOS provides preemptive multithreading hardware abstraction real time analysis and configuration tools MSP430x1xx MSP430x2xx MSP430x3xx
136. d l TEXAS INSTRUMENTS www ti com 2 11 1 inlining Intrinsic ODeFrators ssec e ee cuni our rap RR seececuee stats Tae aaa a snes ct SEa 49 2 11 22 IMINING Restrictions omm 49 2 12 Using INteriS acssitadicncccareantane saad dleeuenamaaaias a a a a 50 2 43 Controlling Application Binary Interface cccceee eee ence eee eee e eee cece eee II I mmn nn n emn mn nnne 51 2 14 Enabling Entry Hook and Exit Hook Functions cceeeeee cece eee ence ee eeee eens nnnm nmn nnne nnne 52 3 OptiMIZiIng YOUr COdG c 53 3 1 INVOKING Optimization EET LLLI LTD 54 3 2 Performing File Level Optimization opt level 3 option eeeeeseeeeeere HH 55 3 2 4 Controlling File Level Optimization std lib func def Options seeesueeuuueeesue 55 3 2 2 Creating an Optimization Information File gen opt info Option 0 scceeseeeeeeeeeeeeeeeeeeeeeeees 55 3 3 Program Level Optimization program_level_compile and opt level 3 options s 56 3 3 1 Controlling Program Level Optimization call assumptions Option e esses 56 3 3 2 Optimization Considerations When Mixing C C and Assembly eese 57 3 4 Link Time Optimization opt_level 4 Option ceeseeseeeee I HII IH mmn nnn 58 94 1 SOptonHandlitigitsseeusacidiscus elsi neu uisi c eit nic cioe bins cien io eda sedeo cie dubeuiseeme as heleeein c
137. d according to a standard developed by AT amp T This ABI is no longer supported command file A file that contains options filenames directives or commands for the linker or hex conversion utility comment A source statement or portion of a source statement that documents or improves readability of a source file Comments are not compiled assembled or linked they have no effect on the object file compiler program A utility that lets you compile assemble and optionally link in one step The compiler runs one or more source modules through the compiler including the parser optimizer and code generator the assembler and the linker configured memory Memory that the linker has specified for allocation constant A type whose value cannot change cross reference listing An output file created by the assembler that lists the symbols that were defined what line they were defined on which lines referenced them and their final values data section One of the default object file sections The data section is an initialized section that contains initialized data You can use the data directive to assemble code into the data section direct call A function call where one function calls another using the function s name directives Special purpose commands that control the actions and functions of a software tool as opposed to assembly language instructions which control the actions of a device dis
138. de 67 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Invoking the Linker Through the Compiler z Option www ti com 4 1 2 Invoking the Linker as Part of the Compile Step This is the general syntax for linking C C programs as part of the compile step cl430 filenames options run linker rom_model ram_model filenames options output_file name out library library Ink cma The run_linker option divides the command line into the compiler options the options before run_linker and the linker options the options following run_linker The run_linker option must follow all source files and compiler options on the command line All arguments that follow run_linker on the command line are passed to the linker These arguments can be linker command files additional object files linker options or libraries These arguments are the same as described in Section 4 1 1 All arguments that precede run_linker on the command line are compiler arguments These arguments can be C C source files assembly files or compiler options These arguments are described in Section 2 2 You can compile and link a C C program consisting of object files prog1 c prog2 c and prog3 c with an executable object file filename of prog out with the command c1430 progl c prog2 c prog3 c run linker rom model output file prog out library rts430 1lib
139. de and Relaxed ANSI ISO Mode strict ansi and 108 relaxed ansi Options Under relaxed ANSI ISO mode the default the compiler accepts language extensions that could potentially conflict with a strictly conforming ANSI ISO C C program Under strict ANSI mode these language extensions are suppressed so that the compiler will accept all strictly conforming programs Use the strict ansi option when you know your program is a conforming program and it will not compile in relaxed mode In this mode language extensions that conflict with ANSI ISO C C are disabled and the compiler will emit error messages where the standard requires it to do so Violations that are considered discretionary by the standard may be emitted as warnings instead Examples The following is strictly conforming C code but will not be accepted by the compiler in the default relaxed mode To get the compiler to accept this code use strict ANSI mode The compiler will suppress the interrupt keyword language exception and interrupt may then be used as an identifier in the code int main int interrupt 0 return 0 The following is not strictly conforming code The compiler will not accept this code in strict ANSI mode To get the compiler to accept it use relaxed ANSI mode The compiler will provide the interrupt keyword extension and will accept the code interrupt void isr void int main return 0 The following code is accepted in
140. de path option s short form is l The format of the include path option is include path directory1 include pathz directory2 There is no limit to the number of include path options per invocation of the compiler each include path option names one directory In C source you can use the include directive without specifying any directory information for the file instead you can specify the directory information with the include path option For example assume that a file called source c is in the current directory The file source c contains the following directive statement include alt h Assume that the complete pathname for alt h is UNIX tools files alt h Windows c tools files alt h The table below shows how to invoke the compiler Select the command for your operating system Operating System Enter UNIX c1430 include path tools files source c Windows c1430 include_path c tools files source c Using the C C Compiler SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Controlling the Preprocessor NOTE Specifying Path Information in Angle Brackets If you specify the path information in angle brackets the compiler applies that information relative to the path information specified with include path options and the MSP430 C DIR environment variable For example if you set up MSP430 C
141. disrupts the run time environment causing your program to fail Be sure to allow enough space for the stack to grow You can use the entry_hook option to add code to the beginning of each function to check for stack overflow see Section 2 14 6 1 6 Dynamic Memory Allocation 118 The run time support library supplied with the MSP430 compiler contains several functions such as malloc calloc and realloc that allow you to allocate memory dynamically for variables at run time Memory is allocated from a global pool or heap that is defined in the sysmem section You can set the size of the sysmem section by using the heap_size size option with the linker command The linker also creates a global symbol SYSMEM SIZE and assigns it a value equal to the size of the heap in bytes The default size is 128 bytes For more information on the heap size option see the linker description chapter in the MSP430 Assembly Language Tools User s Guide If you use any C I O function the RTS library allocates an I O buffer for each file you access This buffer will be a bit larger than BUFSIZ which is defined in stdio h and defaults to 256 Make sure you allocate a heap large enough for these buffers or use setvbuf to change the buffer to a statically allocated buffer Dynamically allocated objects are not addressed directly they are always accessed with pointers and the memory pool is in a separate section sysmem therefore the dynamic memor
142. e and opt_for_speed For example if you use the single_inline option the compiler inlines all functions that are called exactly once In most cases single inlining will reduce the code size by a small amount NOTE Using the no_inlining Option with Level 3 Optimizations The no_inlining option turns off prioritizing inlining for functions declared with the inline keyword If you use no_inlining with opt_level 3 automatic inlining is still performed 48 Using the C C Compiler SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Using Inline Function Expansion 2 11 1 Inlining Intrinsic Operators The compiler has built in function like operations called intrinsics The implementation of an intrinsic function is handled by the compiler which substitutes a sequence of instructions for the function call This is similar to the way inline function are handled however because the compiler knows the code of the intrinsic function it can perform better optimization Intrinsic operations look like function calls and can be implemented very efficiently with the target s instruction set The compiler automatically inlines the intrinsic operators of the target system by default Inlining happens whether or not you use the optimizer Intrinsic inlining can be disabled with the no intrinsics compiler option For details about intrinsics
143. e directive The list is written to a file with the same name as the source file but with a ppa extension Produces an assembly listing file Undefines the predefined constant name This option overrides any asm define options for the specified name Copies the specified file for the assembly module acts like a copy directive The file is inserted before source file statements The copied file appears in the assembly listing files Produces a symbolic cross reference in the listing file Includes the specified file for the assembly module acts like an include directive The file is included before source file statements The included file does not appear in the assembly listing files Puts labels in the symbol table Label definitions are written to the symbol table for use with symbolic debugging Makes letter case insignificant in assembly language source files For example syms ignore case makes ABC and abc equivalent f you do not use this option case is significant string def For example SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated l www t TEXAS INSTRUMENTS i com Changing the Compiler s Behavior with Options 2 3 12 Deprecated Options 2 4 2 4 1 SLAU1 Several compiler options have been deprecated The compiler continues to accept these options but they are not recommended for use Future releases of the tools will not support
144. e Limit The encoded data that follows the 8 bit index can be in one of the following format types For clarity the 8 bit index is also depicted for each format SLAU132K September 2015 Run Time Environment 135 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS System Initialization www ti com 6 9 3 4 1 Length Followed by Data Format 8 bit index 24 bit padding 32 bit length N N byte initialization data not compressed The compiler uses 24 bit padding to align the length field to a 32 bit boundary The 32 bit length field encodes the length of the initialization data in bytes N N byte initialization data is not compressed and is copied to the run address as is The run time support library has a function TI zero init to process this type of initialization data The first argument to this function is the address pointing to the byte after the 8 bit index The second argument is the run address from the C auto initialization record 6 9 3 4 2 Zero Initialization Format 8 bit index 24 bit padding 32 bit length N The compiler uses 24 bit padding to align the length field to a 32 bit boundary The 32 bit length field encodes the number of bytes to be zero initialized The run time support library has a function TI zero init to process the zero initialization The first argument to this function is the address pointing to
145. e Memory C auto init C auto init ac table and data cinit section ROM Boot routine data uninitialized RAM 6 9 3 4 Autoinitialization Tables The compiled object files do not have initialization tables The variables are initialized directly The linker when the rom model option is specified creates C auto initialization table and the initialization data The linker creates both the table and the initialization data in an output section named cinit The autoinitialization table has the following format Tl CINIT Base 32 bit load address 32 bit run address 32 bit load address 32 bit run address TI CINT Limit The linker defined symbols TI CINIT Base and TI CINIT Limit point to the start and end of the table respectively Each entry in this table corresponds to one output section that needs to be initialized The initialization data for each output section could be encoded using different encoding The load address in the C auto initialization record points to initialization data with the following format 8 bit index Encoded data The first 8 bits of the initialization data is the handler index It indexes into a handler table to get the address of a handler function that knows how to decode the following data The handler table is a list of 32 bit function pointers TI Handler Table Base 32 bit handler 1 address 32 bit handler n address TI Handler Tabl
146. e allocated into internal program memory The linker provides MEMORY and SECTIONS directives for allocating sections For more information about allocating sections into memory see the MSP430 Assembly Language Tools User s Guide SLAU132K September 2015 Submit Documentation Feedback Linking C C Code 73 Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Controlling the Linking Process www ti com 4 3 9 A Sample Linker Command File Example 4 2 shows a typical linker command file that links a 32 bit C program The command file in this example is named Ink32 cmd and lists several link options rom model Tells the linker to use autoinitialization at run time stack size Tells the linker to set the C stack size at 0x140 bytes heap size Tells the linker to set the heap size to 0x120 bytes library Tells the linker to use an archive library file rts430 lib To link the program enter cl430 run linker object file s output_file file map filez file Ink cmd Example 4 2 Linker Command File rom model stack size 0x0140 heap size 0x120 library rts430 1lib J E E K k k k ko kk Ck kk Ck ke kk Ck kk Ck kk Ck kk Ck ke kk Ck Kk Ck kk Ck Ck kk Ck Ck kk ck ck kk k kk kckckckckck ck kck ck ckckck ck ck ck k ck ck ck ck ck k kk SPECIFY THE SYSTEM MEMORY MAP J FCKCKCKCkCk Ck kk Ck kk Ck k kk Ck kk k k kk Ck kk Ck Ck kk k k Kk Ck kk Ck Ck kk Ck Kk Ck kk k k k k kk kckckck ck kck kckckckckc
147. e called or modified The opt level 3 option combines this information with its own file level analysis to decide whether to treat this module s external function and variable declarations as if they had been declared static Use Table 3 5 to select the appropriate level to append to the call assumptions option Table 3 5 Selecting a Level for the call assumptions Option If Your Module Use this Option Has functions that are called from other modules and global variables that are modified in other call_assumptions 0 modules Does not have functions that are called by other modules but has global variables that are modified in call_assumptions 1 other modules Does not have functions that are called by other modules or global variables that are modified in other call_assumptions 2 modules Has functions that are called from other modules but does not have global variables that are modified call_assumptions 3 in other modules In certain circumstances the compiler reverts to a different call_assumptions level from the one you specified or it might disable program level optimization altogether Table 3 6 lists the combinations of call_assumptions levels and conditions that cause the compiler to revert to other call_assumptions levels Optimizing Your Code SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Program Level Opt
148. e copy tables This is a read only section For details on BINIT see the MSP430 Assembly Language Tools User s Guide for linker command file information The cinit section contains tables for initializing variables and constants This is a read only section The compiler does not create this section instead the linker does The init array section contains the table of pointers to initialization routines for global C objects The data section contains initialized global and static variables For EABI only the mspabi exidx section contains the index table for exception handling The mspabi extab section contains unwinding instructions for exception handling These sections are read only See the exceptions option for details The const section contains string constants string literals switch tables and data defined with the C C qualifier const provided the constant is not also defined as volatile This is a read only section String literals are placed in the const string subsection to enable greater link time placement control The text section contains all the executable code and compiler generated constants This section is usually read only Uninitialized sections reserve space in memory usually RAM A program can use this space at run time to create and store variables The compiler creates the following uninitialized sections The bss section reserves space for global and static variab
149. e in one of these ways You achieve the best optimization by applying the FUNC_EXT_CALLED pragma to all of the entry point functions called from the assembly language interrupts and then compiling with program_level_compile opt_level 3 call_assumptions 2 Be sure that you use the pragma with all of the entry point functions If you do not the compiler might remove the entry point functions that are not preceded by the FUNC EXT CALLED pragma e Compile with program level compile opt_level 3 call assumptions 3 Because you do not use the FUNC EXT CALLED pragma you must use the call assumptions 3 option which is less aggressive than the call assumptions 2 option and your optimization may not be as effective Keep in mind that if you use program level compile opt_level 3 without additional options the compiler removes the C functions that the assembly functions call Use the FUNC EXT CALLED pragma to keep these functions Link Time Optimization opt levelz4 Option Link time optimization is an optimization mode that allows the compiler to have visibility of the entire program The optimization occurs at link time instead of compile time like other optimization levels Link time optimization is invoked by using the opt_level 4 option This option must be used in both the compilation and linking steps At compile time the compiler embeds an intermediate representation of the file being compiled into the resulting ob
150. e interrupt routine must preserve the contents of all machine registers that are used by the routine or by any function called by the routine When you use the interrupt keyword with the definition of the function the compiler generates register saves based on the rules for interrupt functions and the special return sequence for interrupts You can only use the interrupt keyword with a function that is defined to return void and that has no parameters The body of the interrupt function can have local variables and is free to use the stack or global variables For example interrupt void int handler unsigned int flags ix The name c int00 is the C C entry point This name is reserved for the system reset interrupt This special interrupt routine initializes the system and calls the main function Because it has no caller c intOO does not save any registers Hwi Objects and the interrupt Keyword NOTE The interrupt keyword must not be used when SYS BIOS Hwi objects are used in conjunction with C functions The Hwi enter Hwi exit macros and the Hwi dispatcher already contain this functionality and the use of the C modifier can cause unwanted conflicts 84 MSP430 C C Language Implementation SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Keywords Interrupt service routine ISR warning NOTE The linker emits a warn
151. e linker assumes you are using the C and C conventions and the entry point for the program normally c intO0O is not resolved by any specified object file or library the linker attempts to automatically include the most compatible run time support library for your program The run time support library chosen by the compiler is searched after any other libraries specified with the library option on the command line or in the linker command file If libc a is explicitly used the appropriate run time support library is included in the search order where libc a is specified You can disable the automatic selection of a run time support library by using the disable auto rts option If the issue remarks option is specified before the run linker option during the linker a remark is generated indicating which run time support library was linked in If a different run time support library is desired than the one reported by issue remarks you must specify the name of the desired run time support library using the library option and in your linker command files when necessary Example 4 1 Using the issue remarks Option cl1430 issue remarks main c run linker rom model Linking remark linking in libc a remark linking in rts430 lib in place of libc a 4 3 1 2 Manual Run Time Support Library Selection You can bypass automatic library selection by explicitly specifying the desired run time support library to
152. e linker supports initialization of the FRAM memory protection unit MPU The linker uses a boot routine that performs MPU initialization based on the definition of certain symbols The Tl provided linker command files that are used by default for different devices define the necessary symbols so MPU initialization happens automatically Code and data sections are automatically given the correct access permissions If you want to manually adjust how the MPU is initialized you can modify the __mpuseg and mpusam definitions in the linker command file The MPU specific boot routine is used when these two symbols are defined and it sets the value of the MPUSEG and MPUSAM registers based on these values If you do not want the MPU initialized you can remove these definitions from the linker command file 4 3 5 Initialization of Cinit and Watchdog Timer Hold You can use the cinit hold wdt option to specify whether the watchdog timer should be held on or not held off during cinit auto initialization Setting this option causes an RTS auto initialization routine to be linked in with the program to handle the desired watchdog timer behavior SLAU132K September 2015 Linking C C Code 71 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Controlling the Linking Process www ti com 4 3 6 Global Object Constructors Global C variables that have constructors and destructors require their constru
153. e ona ea a E Ea EE uk eva aul ru EE EDU dpud PRU RENE 20 2 4 ULP Advisor Oplions sisse esses E etu x O DUE MERE EEN AUN I MN END EB ERE MEAE 20 2 8 Hardware Configuration Advisor Options cseceeee eee eee eee eee eee eee eee eee nnm mnm n mn nnne 21 2 9 GohlrolODHOFS seed ces tceatae E E a E E EAE R E dean ocem etciaemmacmaacunls 21 2 10 E Le EET 0 Tolle 21 2 11 Parser Preprocessing Optllons oe creare ce nre rne nre d ER rp RD Ace p pU RT NA Ue MEE A RENDUM a NM ENDE 22 2 12 Predefined Symbols Option seve csieicineiccwcacenciethaciaacieatiltisnindaa vince a P NOE ND RARE NE DENIM NER 22 2 13 Diagnostic Message Options s2 cixsei eee eR eoi oc tee eR po REA ERR AOEREREARCRRERNDKR NEA RENE IA NER UNA UEEE 22 2 14 Run Timie Model Options sesiones e e EEEE EE EOE E EES 23 2 15 Entty Exit HOOK ODIIODS s s xeu ionis ox ra oe xo cipis ueta ee enses icu Ue uou Dee MES le rio Ein nem tuR eia pdt eura as n 23 2 16 Library Function Assumptions Options 2 0 cecce eee eee eee eee en en I nm ne n e nnn ne nne en nnne 23 ASPEN 24 2 18 File Type Sp cifier OPtlOnS x sssri Seed euer a edu eva vuuscp ra pde E VM EE IE U N EP ATE ERE MEE 24 2 19 Directory Sp cifier Options esses ce ose erases cise o eG EE DEUM DI NMIEEE A EPA DEM UR IEEE CMEN ENDE MS mcm UE 24 2 20 Default File Extensions Optlons evseacacinsuscp assu ue E o DER DAE SEesSMM RUEDA EADEM DIE AE UEC GN MM M SEI E 25
154. e saves all the save on call registers if any other functions are called This excludes banked registers Do not call interrupt handling functions directly Interrupts can be handled directly with C C functions by using the INTERRUPT pragma or the interrupt keyword For information see Section 5 11 17 and Section 5 7 2 respectively 6 7 3 Using Assembly Language Interrupt Routines You can handle interrupts with assembly language code as long as you follow the same register conventions the compiler does Like all assembly functions interrupt routines can use the stack 16 bit limit access global C C variables and call C C functions normally When calling C C functions be sure that any save on call registers are preserved before the call because the C C function can modify any of these registers You do not need to save save on entry registers because they are preserved by the called C C function 6 7 4 Interrupt Vectors The interrupt vectors for the MSP430 and MSP430X devices are 16 bits Therefore interrupt service routines ISRs must be placed into the low 64K of memory Convenience macros are provided in the MSP430X device headers file to declare interrupts to ensure 16 bit placement when linking Alternatively use the CODE_SECTIONS pragma to place the code for ISRs into sections separate from the default text sections Use the linker command file and the SECTIONS directive to ensure the code sections associated with I
155. e value f Sets default fill value for holes within output sections ram_model cr Initializes variables at load time rom model C Autoinitializes variables at run time use hw mpy This option is now a compiler option It should be placed on the command line before the run linker or z option See Section 2 3 4 Table 2 30 Link Time Optimization Options Option Description cinit compression compression kind copy compression compression kind Specifies the type of compression to apply to the C auto initialization data Default is rle Compresses data copied by linker copy tables Default is rle SLAU132K September 2015 Submit Documentation Feedback Using the C C Compiler 27 Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Changing the Compiler s Behavior with Options www ti com Table 2 31 Miscellaneous Options Option Alias Description linker_help help preferred_order function strict_compatibility off on Displays information about syntax and available options Prioritizes placement of functions Performs more conservative and rigorous compatibility checking of input object files Default is on 2 3 2 Frequently Used Options 28 Following are detailed descriptions of options that you will probably use frequently c_src_interlist cmd_file filename compile_only define name def help include path directory Usi
156. ead MYDEVICE write MYDEVICE lseek MYDEVICE unlink MYDEVICE rename if freopen mydevice stderrfile w stderr puts Failed to freopen stderr exit EXIT FAILURE Sa a RR stderr should not be fully buffered we want errors to be seen as soon as possible Normally stderr is line buffered but this example doesn t buffer stderr at all This means that there will be one call to write for each character in the message if setvbuf stderr NULL _IONBF 0 puts Failed to setvbuf stderr exit EXIT_FAILURE Try it out printf This goes to stdout An fprintf stderr This goes to stderr n Ww y Ey y Wf M ey NOTE Use Unique Function Names The function names open read write close Iseek rename and unlink are used by the low level routines Use other names for the device level functions that you write 154 Using Run Time Support Functions and Building Libraries Copyright O 2015 Texas Instruments Incorporated SLAU132K September 2015 Submit Documentation Feedback 1 TEXAS INSTRUMENTS www ti com The C I O Functions Use the low level function add_device to add your device to the device_table The device table is a statically defined array that supports n devices where n
157. ecified with silicon_version mspx saving and restoring save on entry registers requires 32 bits of stack space for each register saved on the stack When you are porting code originally written for 16 bit MSP430 devices you may need to increase the C stack size from previous values At system initialization SP is set to a designated address for the top of the stack This address is the first location past the end of the stack section Since the position of the stack depends on where the stack section is allocated the actual address of the stack is determined at link time SLAU132K September 2015 Run Time Environment 117 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Memory Model www ti com The C C environment automatically decrements SP at the entry to a function to reserve all the space necessary for the execution of that function The stack pointer is incremented at the exit of the function to restore the stack to the state before the function was entered If you interface assembly language routines to C C programs be sure to restore the stack pointer to the same state it was in before the function was entered For more information about using the stack pointer see Section 6 3 for more information about the stack see Section 6 4 Stack Overflow NOTE The compiler provides no means to check for stack overflow during compilation or at run time A stack overflow
158. ection 2 3 7 embedded_cpp pe Enables embedded C mode Section 5 15 4 exceptions Enables C exception handling Section 5 8 extern_c_can_throw Allow extern C functions to propagate exceptions EABI only zx float operations allowed none Restricts the types of floating point operations allowed Section 2 3 3 all 32 64 gen_acp_raw pl Generates a raw listing file rl Section 2 10 gen_acp_xref px Generates a cross reference listing file crl Section 2 9 keep_unneeded_statics Keeps unreferenced static variables Section 2 3 3 kr_compatible pk Allows K amp R compatibility Applies only to C code not to C code Section 5 15 2 The strict_ansi option cannot be used with the kr_compatible option multibyte_chars pc Accepts multibyte character sequences in comments string literals and character constants If you use multibyte characters in your Source code enable this option no inlining pi Disables definition controlled inlining but opt_level 3 or O3 Section 2 11 optimizations still perform automatic inlining no intrinsics pn Disables intrinsic functions No compiler supplied intrinsic functions will be predefined Intrinsic functions can be enabled or disabled in both strict and relaxed ANSI mode The no intrinsics setting has no effect on the strict ansi setting and vice versa program level compile pm Combines source files to perform program level optimization Section 3 3 relaxed ansi
159. ects are stored as a structure with three members and the layout is equivalent to struct short int d short int i union void f long 0 The parameter d is the offset added to the beginning of the class object for this pointer The parameter is the index into the virtual function table offset by 1 The index enables the NULL pointer to be represented Its value is 1 if the function is nonvirtual The parameter f is the pointer to the member function if it is nonvirtual when is 0 The 0 is the offset to the virtual function pointer within the class object SLAU132K September 2015 Submit Documentation Feedback Run Time Environment 119 Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Object Representation www ti com 6 2 1 2 Structure and Array Alignment Structures are aligned according to the member with the most restrictive alignment requirement Structures do not contain padding after the last member Elements of arrays are stored in the same manner as if they were individual objects The minimum alignment for arrays is that required by the type of its elements 6 2 1 3 Field Structure Alignment When the compiler allocates space for a structure it allocates as many words as are needed to hold all of the structure s members and to comply with alignment constraints for each member When a structure contains a 32 bit long member the long is aligned to a 1 word 16 bit boundary
160. ee Section 5 15 Example 5 1 Use of the restrict Type Qualifier With Pointers void funcl int restrict a int restrict b funcl s code here Example 5 2 illustrates using the restrict keyword when passing arrays to a function Here the arrays c and d must not overlap nor may c and d point to the same array Example 5 2 Use of the restrict Type Qualifier With Arrays void func2 int c restrict int d restrict int i for i 0 i lt 64 itt eli d i d i 1 For more information about restrict see http processors wiki ti com index php Restrict Type Qualifier especially the Performance Tuning with the Restrict Keyword article SLAU132K September 2015 MSP430 C C Language Implementation 85 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Keywords www ti com 5 74 The volatile Keyword The C C compiler supports the volatile keyword in all modes except K amp R compatibility mode kr compatible In addition the __ volatile keyword is supported in relaxed ANSI mode for C89 C99 and C The volatile keyword indicates to the compiler that there is something about how the variable is accessed that requires that the compiler not use overly clever optimization on expressions involving that variable For example the variable may also be accessed by an external program an interrupt another t
161. eee nn I HH HI mnn nm nne nnn nnn 64 3 11 7 Function Symbol Aliasing 5x32 cies runner Ronin team men mre euin mem Dua na ERR R MR OPEN E NEN EMT a 64 3 11 8 Induction Variables and Strength Reduction ceeee eee ee eee eee ee eee eee e eee e ee eee sees eee eeeeaeenee eee 65 3 11 9 Loop Invariant Code Motion cceceeee cece cence eee e eee eee e nnne Inn nnnm hn nme nene nn nnne 65 cxt 65 Sol tld INSTHUCTON SCHEGUIING rmm 65 cu LAE Tal feline n 65 3 11 18 Integer Division With Constant Divisor eeeeeeeeeeeen n IH II HH Innen nnne 65 4 Linking C C COS cissi rianan a aaa a Naa aE 66 4 1 Invoking the Linker Through the Compiler z Option cceeeeeeeee eee eee eee e eee eee eee eeeeeeeeeeeeeeeeeeeeaees 67 4 1 1 Invoking the Linker Separa tely i cose oen ir ene mE DOR RISE R DU Dex R n RUD UNT EAE KR DUDEN SENE 67 4 1 2 Invoking the Linker as Part of the Compile Step eese 68 4 1 3 Disabling the Linker compile only Compiler Option eeeeeeeerrnnIHRIe 68 4 2 Linker Code OptimiZations eesis ennen ken ia curas sav eeGiea ueri i a a esa rep cea duae a DAR I Er ER RENS 69 4 2 1 Conditional Linking eio cuin reno R nu annor tnm cele a ERN NU 69 4 2 2 Generating Function Subsections gen func subsections Compiler Option 69 4 3 Controlling the
162. eful for inserting directives at the very beginning of a compiled module The A asm statement does not provide any way to refer to local variables If your assembly code needs to refer to local variables you will need to write the entire function in assembly code For more information refer to Section 6 6 5 NOTE Avoid Disrupting the C C Environment With asm Statements Be careful not to disrupt the C C environment with asm statements The compiler does not check the inserted instructions Inserting jumps and labels into C C code can cause unpredictable results in variables manipulated in or around the inserted code Directives that change sections or otherwise affect the assembly environment can also be troublesome Be especially careful when you use optimization with __ asm statements Although the compiler cannot remove __asm statements it can significantly rearrange the code order near them and cause undesired results MSP430 C C Language Implementation SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS www ti com Pragma Directives 5 11 Pragma Directives Pragma directives tell the compiler how to treat a certain function object or section of code The MSP430 C C compiler supports the following pragmas BIS IE1 INTERRUPT See Section 5 11 1 CHECK MISRA See Section 5 11 2 CHECK ULP See Section 5 11 3 CLINK See Sectio
163. en_acp_xref Option The gen_acp_ xref option generates a cross reference listing file that contains reference information for each identifier in the source file The gen_acp_xref option is separate from cross_reference which is an assembler rather than a compiler option The cross reference listing file has the same name as the source file with a cr extension The information in the cross reference listing file is displayed in the following format sym id name X filename line number column number sym id An integer uniquely assigned to each identifier name The identifier name X One of the following values D Definition d Declaration not a definition M Modification A Address taken U Used C Changed used and modified in a single operation R Any other kind of reference E Error reference is indeterminate filename The source file line number The line number in the source file column number The column number in the source file Generating a Raw Listing File gen_acp_raw Option The gen_acp_raw option generates a raw listing file that can help you understand how the compiler is preprocessing your source file Whereas the preprocessed listing file generated with the preproc only preproc with comment preproc with line and preproc dependency preprocessor options shows a preprocessed version of your source file a raw listing file provides a comparison between the original source line and the preprocessed output The r
164. enerates an error The MSP430 compiler now supports only the Embedded Application Binary Interface EABI ABI which uses the ELF object format and the DWARF debug format If you want support for the legacy COFF ABI please use the ARM v5 2 Code Generation Tools and refer to SPNU151J and SPNU118J for documentation All code in an EABI application must be built for EABI Make sure all your libraries are available in EABI mode before migrating COFF ABI systems to MSP430 EABI For more details on the ABI see Section 5 13 SLAU132K September 2015 Using the C C Compiler 51 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Enabling Entry Hook and Exit Hook Functions www ti com 2 14 Enabling Entry Hook and Exit Hook Functions 52 An entry hook is a routine that is called upon entry to each function in the program An exit hook is a routine that is called upon exit of each function Applications for hooks include debugging trace profiling and stack overflow checking Entry and exit hooks are enabled using the following options entry_hook name Enables entry hooks If specified the hook function is called name Otherwise the default entry hook function name is __ entry hook entry_parm name Specify the parameters to the hook function The name parameter specifies address none that the name of the calling function is passed to the hook function as an argument In this
165. ent directory If you want the compiler program to place these files in different directories use the following options abs_directory directory asm_directory directory list_directory directory obj directory directory o0utput file filename pp directory directory temp_directory directory SLAU132K September 2015 Submit Documentation Feedback Specifies the destination directory for absolute listing files The default is to use the same directory as the object file directory For example c1430 abs directory d Nabso list Specifies a directory for assembly files For example c1430 asm directory d assembly Specifies the destination directory for assembly listing files and cross reference listing files The default is to use the same directory as the object file directory For example c1430 list directory d listing Specifies a directory for object files For example 1430 obj directory d object Specifies a compilation output file name can override obj directory For example c1430 output file transfer pecifies a preprocessor file directory for object files default is For xample 1430 pp_directory d preproc pecifies a directory for temporary intermediate files For example 1430 temp directory d temp a 22M an Using the C C Compiler 35 Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Changing the Compiler s Behavior with Options
166. entry in the device table is predefined to be the HOST device on which the debugger is running The function add device finds the first empty position in the device table and initializes the fields of the structure that represent a device To open a stream on a newly added device use fopen with a string of the format devicename filename as the first argument The name is a character string denoting the device name The name is limited to 8 characters The flags are device characteristics The flags are as follows _SSA Denotes that the device supports only one open stream at a time MSA Denotes that the device supports multiple open streams More flags can be added by defining them in file h The dopen dclose dread dwrite dlseek dunlink and drename specifiers are function pointers to the functions in the device driver that are called by the low level functions to perform I O on the specified device You must declare these functions with the interface specified in Section 7 2 2 The device driver for the HOST that the MSP430 debugger is run on are included in the C I O library Return Value The function returns one of the following values 0 if successful 1 on failure SLAU132K September 2015 Using Run Time Support Functions and Building Libraries 155 Submit Documentation Feedback Copyright O 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS add device Add Device to Device Table www ti com Example Exam
167. er 39 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Controlling the Preprocessor www ti com 2 5 2 The Search Path for Zinclude Files 2 5 2 1 40 The include preprocessor directive tells the compiler to read source statements from another file When specifying the file you can enclose the filename in double quotes or in angle brackets The filename can be a complete pathname partial path information or a filename with no path information f you enclose the filename in double quotes the compiler searches for the file in the following directories in this order 1 The directory of the file that contains the include directive and in the directories of any files that contain that file 2 Directories named with the include path option 3 Directories set with the MSP430 C DIR environment variable e If you enclose the filename in angle brackets lt gt the compiler searches for the file in the following directories in this order 1 Directories named with the include path option 2 Directories set with the MSP430 C DIR environment variable See Section 2 5 2 1 for information on using the include path option See Section 2 4 2 for more information on input file directories Adding a Directory to the include File Search Path include path Option The include path option names an alternate directory that contains include files The inclu
168. er can embed assembly language instructions or directives directly into the assembly language output of the compiler This capability is an extension to the C C language implemented through the asm keyword The asm keyword provides access to hardware features that C C cannot provide The alternate keyword asm may also be used except in strict ANSI C mode It is available in relaxed C and C modes Using asm is syntactically performed as a call to a function named asm with one string constant argument asm assembler text The compiler copies the argument string directly into your output file The assembler text must be enclosed in double quotes All the usual character string escape codes retain their definitions For example you can insert a byte directive that contains quotes as follows asm STR byte abc The inserted code must be a legal assembly language statement Like all assembly language statements the line of code inside the quotes must begin with a label a blank a tab or a comment asterisk or semicolon The compiler performs no checking on the string if there is an error the assembler detects it For more information about the assembly language statements see the MSP430 Assembly Language Tools User s Guide The A asm statements do not follow the syntactic restrictions of normal C C statements Each can appear as a statement or a declaration even outside of blocks This is us
169. er for each tool in the compiler No compiling occurs Undefines the predefined constant name This option overrides any define options for the specified constant The undefine option s short form is U Displays progress information and toolset version while compiling Resets the quiet option 2 3 3 Miscellaneous Useful Options Following are detailed descriptions of miscellaneous options advice hw_config all none rulespec advice power all none rulespec Enables checking the device configuration For example the FRAM waitstate configuration is checked Information about resolving a device configuration issue can be found by clicking the link provided in Code Composer Studio when one of these checks produces a warning See Section 5 5 for details Enables checking code against ULP ultra low power Advisor rules for possible power inefficiencies More detailed information can be found at www ti com ulpadvisor The rulespec parameter is a comma separated list of specifiers See Section 5 4 for details advice power_severity error Sets the diagnostic severity for ULP Advisor rules warning remark suppress check misra all required advisory none rulespec SLAU132K September 2015 Submit Documentation Feedback Displays the specified amount or type of MISRA C documentation The rulespec parameter is a comma separated list of specifiers See Section 5 3 for details Using the C C Compiler 29 Copyr
170. er of intrinsic operators Intrinsics are used like functions and produce assembly language statements that would otherwise be inexpressible in C C You can use C C variables with these intrinsics just as you would with any normal function The intrinsics are specified with a double leading underscore and are accessed by calling them as you do a function Both single and double leading underscores can be used with intrinsics but a double underscore is preferred For example short state state _ get SR register No declaration of the intrinsic functions is necessary 6 8 1 MSP430 Intrinsics Table 6 5 lists all of the intrinsic operators in the MSP430 C C compiler A function like prototype is presented for each intrinsic that shows the expected type for each parameter If the argument type does not match the parameter type conversions are performed on the argument The intrinsics h file in the compiler s include directory contains function like prototypes for all supported intrinsics For more information on the resulting assembly language mnemonics see the MSP430x1xx Family User s Guide the MSP430x3xx Family User s Guide and the MSP430x4xx Family User s Guide Table 6 5 MSP430 Intrinsics Intrinsic Generated Assembly unsigned short bcd add short unsigned short op1 unsigned short op2 MOV op1 dst CLRC DADD op2 dst unsigned long bcd add long unsigned long op1 unsigned long op2 MOV op1 low dst low MOV op1 hi dst hi CLRC D
171. er recognizes only the C C source code and not any assembly code that might be present Because the compiler does not recognize the assembly code calls and variable modifications to C C functions the program level compile option optimizes out those C C functions To keep these functions place the FUNC EXT CALLED pragma see Section 5 11 11 before any declaration or reference to a function that you want to keep Another approach you can take when you use assembly functions in your program is to use the call assumptions n option with the program level compile and opt_level 3 options See Section 3 3 1 for information about the call assumptions n option In general you achieve the best results through judicious use of the FUNC EXT CALLED pragma in combination with program level compile opt_level 3 and call assumptions 1 or call assumptions 2 If any of the following situations apply to your application use the suggested solution Situation Your application consists of C C source code that calls assembly functions Those assembly functions do not call any C C functions or modify any C C variables Solution Compile with program level compile opt_level 3 call assumptions 2 to tell the compiler that outside functions do not call C C functions or modify C C variables If you compile with the program level compile opt_level 3 options only the compiler reverts from the default optimization level
172. escribes how you can use the Interlist feature when performing optimization and how you can debug optimized code Topic Page Sele e Invoking Optimizationz 5 secre scree cies anaes E E EA A AEA E E E AEEA EA EEE A AA AEREE n 54 3 2 Performing File Level Optimization opt_level 3 option 55 3 3 Program Level Optimization program level compile and opt levelz3 options 56 3 4 Link Time Optimization opt levelz4 Option eeeeeeeeeeeeeeeeeeeee 58 3 5 Accessing Aliased Variables in Optimized Code esee 59 3 6 X Use Caution With asm Statements in Optimized Code 59 3 7 Automatic Inline Expansion auto inline Option eeseseeee eere 60 3 8 Using the Interlist Feature With Optimization cesses 60 3 9 Debugging Optimized Godes eeen e a e aea aE e a E aa eeaeee 62 3 10 Controlling Code Size Versus Speed 2 2 cccceceeeeeeee cece ceeeeee ee eseeeeseeseeeeeeeeeeees 62 3 11 What Kind of Optimization Is Being Performed Lees 63 SLAU132K September 2015 Optimizing Your Code 53 Submit Documentation Feedback Copyright O 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Invoking Optimization www ti com 3 1 54 Invoking Optimization The C C compiler is able to per
173. ess it is marked with retain or is the reset section Conditional linking is disabled when performing a partial link or when relocation information is kept with the output of the link 4 2 2 Generating Function Subsections gen func subsections Compiler Option 4 3 The compiler translates a source module into an object file It may place all of the functions into a single code section or it may create multiple code sections The benefit of multiple code sections is that the linker may omit unused functions from the executable When the linker collects code to be placed into an executable file it cannot split code sections If the compiler did not use multiple code sections and any function in a particular module needs to be linked into the executable then all functions in that module are linked in even if they are not used An example is a library obj file that contains a signed divide routine and an unsigned divide routine If the application requires only signed division then only the signed divide routine is required for linking If only one code section was used both the signed and unsigned routines are linked in since they exist in the same obj file The gen func subsections compiler option remedies this problem by placing each function in a file in its own subsection Thus only the functions that are referenced in the application are linked into the final executable This can result in an overall code size reduction The de
174. etains the assembly language output from the compiler or assembly optimizer Normally the compiler deletes the output assembly language file after assembly is complete The keep asm option s short form is k Suppresses banners and progress information from all the tools Only source filenames and error messages are output The quiet option s short form is q Runs the linker on the specified object files The run linker option and its parameters follow all other options on the command line All arguments that follow run linker are passed to the linker The run linker option s short form is z See Section 4 1 Compiles only The specified source files are compiled but not assembled or linked The skip assembler option s short form is n This option overrides run linker The output is assembly language output from the compiler Invokes the interlist feature which interweaves optimizer comments or C C source with assembly source If the optimizer is invoked opt_level n option optimizer comments are interlisted with the assembly language output of the compiler which may rearrange code significantly If the optimizer is not invoked C C source statements are interlisted with the assembly language output of the compiler which allows you to inspect the code generated for each C C statement The src_interlist option implies the keep asm option The src_interlist option s short form is s Prints the version numb
175. eturns to its caller The pragma must appear before any declaration or reference to the function that you want to keep In C the argument func is the name of the function that does not return In C the pragma applies to the next function declared The syntax of the pragma in C is pragma FUNC NEVER RETURNS func The syntax of the pragma in C is pragma FUNC_NEVER_RETURNS 5 11 14 The FUNC_NO_GLOBAL_ASG Pragma 96 The FUNC_NO_GLOBAL_ASG pragma specifies to the compiler that the function makes no assignments to named global variables and contains no asm statements The pragma must appear before any declaration or reference to the function that you want to keep In C the argument func is the name of the function that makes no assignments In C the pragma applies to the next function declared The syntax of the pragma in C is pragma FUNC NO GLOBAL ASG func The syntax of the pragma in C is pragma FUNC NO GLOBAL ASG MSP430 C C Language Implementation SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Pragma Directives 5 11 15 The FUNC_NO_IND_ASG Pragma The FUNC_NO_IND_ASG pragma specifies to the compiler that the function makes no assignments through pointers and contains no asm statements The pragma must appear before any declaration or reference to the func
176. etween Debugging and Optimization Options esses 55 3 2 Options That You Can Use With opt_level 3 cceeceee cece eee ee eee eee eee en nnne nnn emen nn nnn nnne nne 55 SLAU132K September 2015 List of Figures 7 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 8 lj TEXAS INSTRUMENTS www ti com 3 3 Selecting a File Level Optimization Option cccceeeeeee ence eee cence eee n em m menn nnne 55 3 4 Selecting a Level for the gen opt info Option cesececeeeeeee eee e eee ee eens eee III m nnn 55 3 5 Selecting a Level for the call assumptions OptiOn eceeeeeeeeeeeee eee e neces eee eee III 56 3 6 Special Considerations When Using the call assumptions Option 0 eceeeeee cece eee e eee eeeeeeeeeeeeeee 57 3 7 Interaction Between Debugging and Optimization Options sesseeeeeeeeen II 62 4 1 Initialized Sections Created by the Compiler eeeseeseeeeeeer III In 73 4 2 Uninitialized Sections Created by the Compiler eeeeeeeeeee eene nmn nemen 73 5 l iMSP430 C C xe Data TYPES ssec sions umuesiticu nisu dre em s E eric EIER E Ut abla EUER ctu E 82 5 2 DataSizes or MSPAGSO POIRDtGlS se rone siete cient ating ese n nU exe E RU r PUE EDU NE EE dee uie Ri Rai RUE 82 5 9 GCC Language Extensions secos rio rare nme enn D nn Rp R pack Rev SEEE NA INT Nada EAD NRd Sen ENT ERE UE EMT 110 6 1 Sum
177. f a rule was enabled on the command line but disabled in the source the RESET ULP pragma resets it to enabled This pragma accepts the same format as the advice power option except for the none keyword The syntax of the pragma in C is pragma RESET ULP all ru espec The rulespec parameter is a comma separated list of rule numbers See Section 5 3 for details 5 11 24 The RETAIN Pragma The RETAIN pragma can be applied to a code or data symbol It causes a retain directive to be generated into the section that contains the definition of the symbol The retain directive indicates to the linker that the section is ineligible for removal during conditional linking Therefore regardless whether or not the section is referenced by another section in the application that is being compiled and linked it will be included in the output file result of the link The syntax of the pragma in C is pragma RETAIN symbol The syntax of the pragma in C is pragma RETAIN The CLINK pragma has the opposite effect of the RETAIN pragma See Section 5 11 4 for more details SLAU132K September 2015 MSP430 C C Language Implementation 101 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Pragma Directives www ti com 5 11 25 The SET CODE SECTION and SET DATA SECTION Pragmas These pragmas can be used to set the section for all declarati
178. f you use the register keyword you can suggest variables as candidates for allocation into registers The compiler uses the same set of registers for allocating temporary expression results as it uses for allocating register variables The compiler attempts to honor all register definitions If the compiler runs out of appropriate registers it frees a register by moving its contents to memory If you define too many objects as register variables you limit the number of registers the compiler has for temporary expression results This limit causes excessive movement of register contents to memory Any object with a scalar type integral floating point or pointer can be defined as a register variable The register designator is ignored for objects of other types such as arrays The register storage class is meaningful for parameters as well as local variables Normally in a function some of the parameters are copied to a location on the stack where they are referenced during the function body The compiler copies a register parameter to a register instead of the stack which speeds access to the parameter within the function For more information about register conventions see Section 6 3 SLAU132K September 2015 MSP430 C C Language Implementation 87 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS The asm Statement www ti com 5 10 The asm Statement 88 The C C compil
179. fault setting for the gen func subsections option is on Controlling the Linking Process Regardless of the method you choose for invoking the linker special requirements apply when linking C C programs You must Include the compiler s run time support library Specify the type of boot time initialization Determine how you want to allocate your program into memory This section discusses how these factors are controlled and provides an example of the standard default linker command file For more information about how to operate the linker see the linker description in the MSP430 Assembly Language Tools User s Guide SLAU132K September 2015 Linking C C Code 69 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Controlling the Linking Process www ti com 4 3 1 Including the Run Time Support Library 4 3 1 1 You must link all C C programs with a run time support library The library contains standard C C functions as well as functions used by the compiler to manage the C C environment The following sections describe two methods for including the run time support library Automatic Run Time Support Library Selection The linker assumes you are using the C and C conventions if either the rom model or ram model linker option is specified or if the link step includes the compile step for a C or C file or if you link against the index library libc a If th
180. file includes macros and definitions used for low level I O functions This file is available to be included by the user Although it is non standard it is needed for building the library There are other header files in this same category such as cpy_tbl h The format h file includes structures and macros used in printf and scanf The 430cio h file includes low level target specific C I O macro definitions If necessary you can customize 430cio h The rtti h file includes internal function prototypes necessary to implement run time type identification The vtbl h file contains the definition of a class s virtual function table format 7 1 8 Library Naming Conventions 144 By default the linker uses automatic library selection to select the correct run time support library see Section 4 3 1 1 for your application If you select the library manually you must select the matching library according to the following naming scheme rts430 x I abi ehj lib rts430 Indicates a 16 bit MSP430 library X Optional x indicates a 20 bit MSP430X library Optional after x indicates a 20 bit large code large data model MSP430X library This format is the old style abi Indicates the application binary interface ABI used Although the COFF file format is no longer supported the library filename still contains eabi to distinguish the EABI libraries from older COFF libraries eabi EABI eh Indicates the library has exception handl
181. form various optimizations High level optimizations are performed in the optimizer and low level target specific optimizations occur in the code generator Use high level optimization levels such as opt_level 2 and opt_level 3 to achieve optimal code The easiest way to invoke optimization is to use the compiler program specifying the opt_level n option on the compiler command line You can use On to alias the opt_level option The n denotes the level of optimization 0 1 2 3 and 4 which controls the type and degree of optimization opt_level off or Ooff Performs no optimization e opt_level 0 or O0 Performs control flow graph simplification Allocates variables to registers Performs loop rotation Eliminates unused code Simplifies expressions and statements Expands calls to functions declared inline opt_level 1 or O1 Performs all opt_level 0 O0 optimizations plus Performs local copy constant propagation Removes unused assignments Eliminates local common expressions opt levelz2 or 02 Performs all opt_level 1 O1 optimizations plus Performs loop optimizations Eliminates global common subexpressions Eliminates global unused assignments Performs loop unrolling opt levelz3 or 03 Performs all opt_level 2 O2 optimizations plus Removes all functions that are never called Simplifies functions with return values that are never used
182. ging the Compiler s Behavior with Options Table 2 14 Run Time Model Options Option Alias Effect Section common on off On by default when compiling with EABI When on uninitialized file Section 2 3 4 Scope variables are emitted as common symbols When off common symbols are not created disable interrupts around hw mpy off Setting this option to off leaves interrupts enabled during inlined Section 2 3 4 hardware multiply operations This option can only be used if all ISRs do not use multiplication or call other functions fp_reassoc onl off Enables or disables the reassociation of floating point arithmetic Section 2 3 3 gen_func_subsections on off Puts each function in a separate subsection in the object file Section 4 2 2 global_register r4 r5 Reserves register for use by user large_memory_model ml Uses a large memory model when compiling for the MSP430X Section 2 3 4 Deprecated plain_char signed unsigned mc Changes variables of type char from unsigned to signed Section 2 3 4 ramfunc on off If set to on specifies that all functions should be placed in the Section 2 3 4 Tl ramfunc section which is placed in RAM silicon_errata errata Generates code to work around the specified silicon errata small_enum Uses the smallest possible size for the enumeration type Section 2 3 4 use_hw_mpy 16 32 F5 none If opt_for_speed is set to 1 or higher replaces all references to the Section 2 3 4
183. gned and intended for use in military aerospace applications or environments Buyer acknowledges and agrees that any military or aerospace use of Tl components which have not been so designated is solely at the Buyer s risk and that Buyer is solely responsible for compliance with all legal and regulatory requirements in connection with such use TI has specifically designated certain components as meeting ISO TS16949 requirements mainly for automotive use In any case of use of non designated products TI will not be responsible for any failure to meet ISO TS16949 Products Applications Audio www ti com audio Automotive and Transportation www ti com automotive Amplifiers amplifier ti com Communications and Telecom www ti com communications Data Converters DLP Products DSP Clocks and Timers Interface Logic Power Mgmt Microcontrollers RFID OMAP Applications Processors Wireless Connectivity dataconverter ti com www dlp com www ti com clocks interface ti com logic ti com microcontroller ti com www ti rfid com www ti com omap Computers and Peripherals Consumer Electronics Energy and Lighting Industrial Medical Security Space Avionics and Defense Video and Imaging TI E2E Community www ti com wirelessconnectivity www ti com computers www ti com consumer apps www ti com energy www ti com industrial www ti com medical www ti com security www ti com space avionics defense www
184. gram might Ifthe object has automatic storage function scope In both cases the storage for the object is the same as if the const keyword were not used The placement of the const keyword within a definition is important For example the first statement below defines a constant pointer p to a modifiable int The second statement defines a modifiable pointer q to a constant int int const p amp x const int q amp x Using the const keyword you can define large constant tables and allocate them into system ROM For example to allocate a ROM table you could use the following definition const int digits 0 1 2 3 4 5 6 7 8 9 5 72 The interrupt Keyword The compiler extends the C C language by adding the interrupt keyword which specifies that a function is treated as an interrupt function This keyword is an IRQ interrupt The alternate keyword interrupt may also be used except in strict ANSI C or C modes Note that the interrupt function attribute described in Section 5 11 17 is the recommended syntax for declaring interrupt functions Functions that handle interrupts follow special register saving rules and a special return sequence The implementation stresses safety The interrupt routine does not assume that the C run time conventions for the various CPU register and status bits are in effect instead it re establishes any values assumed by the run time environment When C C code is interrupted th
185. hen the compiler or linker detects a suspect condition it displays a message in the following format file c line n diagnostic severity diagnostic message file c The name of the file involved line n The line number where the diagnostic applies diagnostic severity The diagnostic message severity severity category descriptions follow diagnostic message The text that describes the problem Diagnostic messages have a severity as follows Afatal error indicates a problem so severe that the compilation cannot continue Examples of such problems include command line errors internal errors and missing include files If multiple source files are being compiled any source files after the current one will not be compiled An error indicates a violation of the syntax or semantic rules of the C C language Compilation may continue but object code is not generated Awarning indicates something that is likely to be a problem but cannot be proven to be an error For example the compiler emits a warning for an unused variable An unused variable does not affect program execution but its existence suggests that you might have meant to use it Compilation continues and object code is generated if no errors are detected Aremark is less serious than a warning It may indicate something that is a potential problem in rare cases or the remark may be strictly informational Compilation continues and object code is generated if n
186. his section in RAM See the Placing functions in RAM wiki page for more about the ramfunc attribute and option See the MSP430 Assembly Language Tools User s Guide for details on section placement SLAU132K September 2015 Submit Documentation Feedback MSP430 C C Language Implementation 111 Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS GNU Language Extensions www ti com 5 16 3 Variable Attributes The following variable attributes are supported aligned deprecated mode noinit persistent section transparent union unused used and weak The used attribute is defined in GCC 4 2 see http gcc gnu org onlinedocs gcc 4 2 4 gcc Variable Attributes html Variable Attributes In addition the packed attribute may be applied to individual fields within a struct or union The behavior of the packed attribute for structure and union fields is described in Section 5 16 4 5 16 4 Type Attributes 112 The following type attributes are supported aligned deprecated packed transparent union unused and visibility The packed attribute is supported for struct and union types if the relaxed ansi option is used Members of a packed structure are stored as closely to each other as possible omitting additional bytes of padding usually added to preserve word alignment For example assuming a word size of 4 bytes ordinarily has 3 bytes of padding between members c1 and i and another 3 bytes of
187. hnical support case or to ask a question about your code It allows you to reduce the test case to a single source file because include files are incorporated when the preprocessor runs 2 5 5 Continuing Compilation After Preprocessing preproc with compile Option If you are preprocessing the preprocessor performs preprocessing only it does not compile your source code To override this feature and continue to compile after your source code is preprocessed use the preproc with compile option along with the other preprocessing options For example use preproc with compile with preproc only to perform preprocessing write preprocessed output to a file with a pp extension and compile your source code 2 5 6 Generating a Preprocessed Listing File with Comments preproc with comment Option The preproc with comment option performs all of the preprocessing functions except removing comments and generates a preprocessed version of your source file with a pp extension Use the preproc with comment option instead of the preproc only option if you want to keep the comments SLAU132K September 2015 Using the C C Compiler 41 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Controlling the Preprocessor www ti com 2 5 7 Generating Preprocessed Listing with Line Control Details preproc with line Option By default the preprocessed output file contains no preproce
188. hread or a peripheral device The compiler eliminates redundant memory accesses whenever possible using data flow analysis to figure out when it is legal However some memory accesses may be special in some way that the compiler cannot see and in such cases you should use the volatile keyword to prevent the compiler from optimizing away something important The compiler does not optimize out any accesses to variables declared volatile The number of volatile reads and writes will be exactly as they appear in the C C code no more and no less and in the same order Any variable which might be modified by something external to the obvious control flow of the program such as an interrupt service routine must be declared volatile This tells the compiler that an interrupt function might modify the value at any time so the compiler should not perform optimizations which will change the number or order of accesses of that variable This is the primary purpose of the volatile keyword In the following example the loop intends to wait for a location to be read as OxFF unsigned int ctrl while ctrl 0xFF However in this example ctrl is a loop invariant expression so the loop is optimized down to a single memory read To get the desired result define ctrl as volatile unsigned int ctrl Here the ctrl pointer is intended to reference a hardware location such as an interrupt flag The volatile keyword must also be used when accessi
189. ibrary 7 4 2 2 Invoking mklib Manually You may need to invoke mklib directly in special circumstances The compiler installation directory is read only or shared You want to build a variant of the run time support library that is not pre configured in the index library libc a or known to mklib e g a variant with source level debugging turned on 7 4 2 2 1 Building Standard Libraries You can invoke mklib directly to build any or all of the libraries indexed in the index library libc a The libraries are built with the standard options for that library the library names and the appropriate standard option sets are known to mklib This is most easily done by changing the working directory to be the compiler run time support library directory lib and invoking the mklib executable there mklib pattern rts430 eabi lib 7 4 2 2 2 Shared or Read Only Library Directory If the compiler tools are to be installed in shared or read only directory mklib cannot build the standard libraries at link time the libraries must be built before the library directory is made shared or read only At installation time the installing user must build all of the libraries which will be used by any user To build all possible libraries change the working directory to be the compiler RTS library directory lib and invoke the mklib executable there mklib all Some targets have many libraries so this step can take a long time To build a subset
190. icant in assembly source files Section 2 3 11 Table 2 18 File Type Specifier Options Option Alias Effect Section asm_file filename fa Identifies filename as an assembly source file regardless of its Section 2 3 7 extension By default the compiler and assembler treat asm files as assembly source files c_file filename fc Identifies filename as a C source file regardless of its extension By Section 2 3 7 default the compiler treats c files as C source files cpp_file filename fp Identifies filename as a C file regardless of its extension By Section 2 3 7 default the compiler treats C cpp cc and cxx files as a C files obj_file filename fo Identifies filename as an object code file regardless of its extension Section 2 3 7 By default the compiler and linker treat obj files as object code files Table 2 19 Directory Specifier Options Option Alias Effect Section abs_directory directory fb Specifies an absolute listing file directory By default the compiler Section 2 3 10 uses the obj directory asm_directory directory fs Specifies an assembly file directory By default the compiler uses Section 2 3 10 the current directory list_directory directory ff Specifies an assembly listing file and cross reference listing file Section 2 3 10 directory By default the compiler uses the obj directory obj_directory directory fr Specifies an object file directory By default the compiler
191. id inspection and debugging a name demangling utility is provided that demangles names into those found in the original C source See Chapter 8 for more information The mangling algorithm follows that described in the Itanium C ABI http www codesourcery com cxx abi abi html int foo int i would be mangled Z3fooi SLAU132K September 2015 MSP430 C C Language Implementation 105 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Changing the ANSI ISO C C Language Mode www ti com 5 15 Changing the ANSI ISO C C Language Mode The language mode command line options determine how the compiler interprets your source code You specify one option to identify which language standard your code follows You can also specify a separate option to specify how strictly the compiler should expect your code to conform to the standard Specify one of the following language options to control the language standard that the compiler expects the source to follow The options are e ANSI ISO C89 c89 default for C files e ANSI ISO C99 c99 see Section 5 15 1 e Kernighan and Ritchie K amp R C kr_compatible or pk see Section 5 15 2 Does not apply to C code SO C 03 c 03 default for C files Embedded C embedded cpp or pe see Section 5 15 4 Use one of the following options to specify how strictly the code conforms to the standard e Rela
192. ight 2015 Texas Instruments Incorporated Changing the Compiler s Behavior with Options float operations allowed none all 32 64 fp_mode relaxed strict fp_reassoc onloff 30 Using the C C Compiler I TEXAS INSTRUMENTS www ti com Restricts the type of floating point operations allowed in the application The default is all If set to none 32 or 64 the application is checked for operations that will be performed at runtime For example if float_operations_allowed 32 is specified on the command line the compiler issues an error if a double precision operation will be generated This can be used to ensure that double precision operations are not accidentally introduced into an application The checks are performed after relaxed mode optimizations have been performed so illegal operations that are completely removed result in no diagnostic messages The default floating point mode is strict To enable relaxed floating point mode use the fp_mode relaxed option Relaxed floating point mode causes double precision floating point computations and storage to be converted to single precision floating point or integers where possible This behavior does not conform with ISO but it results in faster code with some loss in accuracy The following specific changes occur in relaxed mode If the result of a double precision floating point expression is assigned to a single precision floating point or an integer or
193. ight O 2015 Texas Instruments Incorporated Using Intrinsics to Access Assembly Language Statements Table 6 5 MSP430 Intrinsics continued I TEXAS INSTRUMENTS www ti com Intrinsic Generated Assembly void enable interrupt void EINT OR enable interrupts void unsigned int even in range unsigned int unsigned int See Section 5 11 26 unsigned short get interrupt state void MOV SR dst unsigned short get R4 register void deprecated MOV W R4 dst unsigned short get R5 register void deprecated MOV W R5 dst unsigned short get SP register void MOV SP dst unsigned short get SR register void MOV SR dst unsigned short get SR register on exit void MOV saved SR dst void low power mode O void BIS W 20x18 SR void low power mode 1 void BIS W 0x58 SR void low power mode 2 void BIS W 0x98 SR void low power mode S3 void BIS W 0xD8 SR void low power mode 4 void BIS W 0xF8 SR void low power mode off on exit void BIC W 0xF0 saved SR void never executed void See Section 6 8 4 void no operation void NOP void Op code unsigned short Encodes whatever instruction corresponds to the argument void Set interrupt state unsigned short src MOV src SR void Set R4 register unsigned short src deprecated MOV W src R4 void Set R5 register unsigned short src
194. imization program level compile and opt level 3 options Table 3 6 Special Considerations When Using the call assumptions Option Then the call assumptions If call assumptions is Under these Conditions Level Not specified The opt_level 3 optimization level was specified Defaults to call assumptions 2 Not specified The compiler sees calls to outside functions under the Reverts to call_assumptions 0 opt level 3 optimization level Not specified Main is not defined Reverts to call_assumptions 0 call assumptions 1 or No function has main defined as an entry point and no interrupt Reverts to call_assumptions 0 call_assumptions 2 functions are defined and no functions are identified by the FUNC_EXT_CALLED pragma call_assumptions 1 or A main function is defined or an interrupt function is defined ora Remains call_assumptions 1 call_assumptions 2 function is identified by the FUNC_EXT_CALLED pragma or call_assumptions 2 call assumptions 3 Any condition Remains call assumptions 3 In some situations when you use program level compile and opt_level 3 you must use a call assumptions option or the FUNC EXT CALLED pragma See Section 3 3 2 for information about these situations 3 3 2 Optimization Considerations When Mixing C C and Assembly If you have any assembly functions in your program you need to exercise caution when using the program level compile option The compil
195. implemented through the CIO interface If the program is run under a system that supports CIO the system performs getenv calls on the host system and passes the result back to the program Otherwise the operation of getenv is undefined No method of changing the environment from inside the target program is provided 7 20 4 5 The system function is not supported 7 20 4 6 J 3 3 Identifiers The compiler does not support multibyte characters in identifiers 6 4 2 The number of significant initial characters in an identifier is unlimited 5 2 4 1 6 4 2 J 3 4 Characters The number of bits in a byte CHAR BIT is 8 See Section 5 6 for details about data types 3 6 The execution character set is the same as the basic execution character set plain ASCII 5 2 1 The values produced for the standard alphabetic escape sequences are as follows 5 2 2 Escape Sequence ASCII Meaning Integer Value a BEL bell 7 b BS backspace 8 f FF form feed 12 n LF line feed 10 r CR carriage 13 return t HT horizontal tab 9 v VT vertical tab 11 The value of a char object into which any character other than a member of the basic execution character set has been stored is the ASCII value of that character 6 2 5 Plain char is identical to unsigned char but can be changed to signed char with the plain charzsigned option 6 2 5 6 3 1 1 The source character set and execution character set are b
196. in Example 8 2 ct 6bananaFv calories 6bananaFv and dt amp 6bananaFv are demangled Example 8 3 Result After Running the C Name Demangler calories in a banana PUSH W r10 SUB W 2 S5P MOV W SP r12 CALL banana banana MOV W SP r12 CALL banana calories MOV W r12 r10 MOV W SP r12 CALL dbanana banana MOV W ri0 ri2 ADD W 2 SP POP r10 RET 164 C Name Demangler Copyright 2015 Texas Instruments Incorporated SLAU132K September 2015 Submit Documentation Feedback I8 TEXAS INSTRUMENTS Appendix A SLAU132K September 2015 Glossary absolute lister A debugging tool that allows you to create assembler listings that contain absolute addresses Application Binary Interface ABI A standard that specifies the interface between two object modules An ABI specifies how functions are called and how information is passed from one program component to another assignment statement A statement that initializes a variable with a value autoinitialization The process of initializing global C variables contained in the cinit section before program execution begins autoinitialization at run time An autoinitialization method used by the linker when linking C code The linker uses this method when you invoke it with the rom model link option The linker loads the cinit section of data tables into memory and variables are initialized at run time alias dis
197. in a directory with the extension cpp enter the following c1430 cpp NOTE No Default Extension for Source Files is Assumed If you list a filename called example on the command line the compiler assumes that the entire filename is example not example c No default extensions are added onto files that do not contain an extension 2 3 7 Changing How the Compiler Interprets Filenames You can use options to change how the compiler interprets your filenames If the extensions that you use are different from those recognized by the compiler you can use the filename options to specify the type of file You can insert an optional space between the option and the filename Select the appropriate option for the type of file you want to specify asm_file filename for an assembly language source file c_file filename for a C source file cpp_file filename for a C source file obj file filename for an object file For example if you have a C source file called file s and an assembly language source file called assy use the asm file and c file options to force the correct interpretation c1430 c file file s asm file assy You cannot use the filename options with wildcard specifications 2 3 8 Changing How the Compiler Processes C Files 34 The cpp default option causes the compiler to process C files as C files By default the compiler treats files with a c extension as C files See Section 2 3 9 for more infor
198. in a linker command file using a linker assignment statement These constants are accessible from C C only with the use of special operators For variables defined in C C or assembly language the symbol table contains the address of the value contained by the variable When you access an assembly variable by name from C C the compiler gets the value using the address in the symbol table For assembly constants however the symbol table contains the actual value of the constant The compiler cannot tell which items in the symbol table are addresses and which are values If you access an assembly or linker constant by name the compiler tries to use the value in the symbol table as an address to fetch a value To prevent this behavior you must use the amp address of operator to get the value _symval In other words if x is an assembly language constant its value in C C is amp x See the section on Using Linker Symbols in C C Applications in the MSP430 Assembly Language Tools User s Guide for more examples that use _symval For more about symbols and the symbol table refer to the section on Symbols in the MSP430 Assembly Language Tools User s Guide You can use casts and defines to ease the use of these symbols in your program as in Example 6 6 and Example 6 7 Example 6 6 Accessing an Assembly Language Constant From C extern int table size external ref define TABLE SIZE int symval amp table size
199. ine eligible functions even if they are not declared as inline functions The same list of decision factors listed for functions explicitly defined with the inline keyword is used For more about automatic function inlining see Section 3 7 The pragma FUNC ALWAYS INLINE forces a function to be inlined where it is legal to do so unless opt_level off That is the pragma FUNC ALWAYS INLINE forces function inlining even if opt_level 0 or opt_level 1 The pragma FUNC_CANNOT_INLINE prevents a function from being inlined NOTE Function Inlining Can Greatly Increase Code Size Function inlining increases code size especially inlining a function that is called in a number of places Function inlining is optimal for functions that are called only from a small number of places and for small functions The semantics of the inline keyword in C code follow the C99 standard The semantics of the inline keyword in C code follow the C standard The inline keyword is supported in all C modes in relaxed ANSI mode for all C standards and in strict ANSI mode for C99 It is disabled in strict ANSI mode for C89 because it is a language extension that could conflict with a strictly conforming program If you want to define inline functions while in strict ANSI C89 mode use the alternate keyword inline Compiler options that affect inlining are opt_level no_inlining auto_inline remove_hooks_when_inlining single_inlin
200. ing for any device specific interrupts that do not have an associated interrupt service routine However a default vector handler is now provided by the run time support RTS library so you should not see this error if you are linking with the provided RTS library 5 7 3 The restrict Keyword To help the compiler determine memory dependencies you can qualify a pointer reference or array with the restrict keyword The restrict keyword is a type qualifier that can be applied to pointers references and arrays Its use represents a guarantee by you the programmer that within the scope of the pointer declaration the object pointed to can be accessed only by that pointer Any violation of this guarantee renders the program undefined This practice helps the compiler optimize certain sections of code because aliasing information can be more easily determined In Example 5 1 the restrict keyword is used to tell the compiler that the function func1 is never called with the pointers a and b pointing to objects that overlap in memory You are promising that accesses through a and b will never conflict therefore a write through one pointer cannot affect a read from any other pointers The precise semantics of the restrict keyword are described in the 1999 version of the ANSI ISO C Standard The restrict keyword is a C99 keyword and cannot be accepted in strict ANSI C89 mode Use the restrict keyword if the strict ANSI C89 mode must be used S
201. ing for faster compilation Stand alone preprocessing or preprocessed listing is also available interlist feature A feature that inserts as comments your original C C source statements into the assembly language output from the assembler The C C statements are inserted next to the equivalent assembly instructions intrinsics Operators that are used like functions and produce assembly language code that would otherwise be inexpressible in C or would take greater time and effort to code ISO International Organization for Standardization a worldwide federation of national standards bodies which establishes international standards voluntarily followed by industries K amp R C Kernighan and Ritchie C the de facto standard as defined in the first edition of The C Programming Language K amp R Most K amp R C programs written for earlier non ISO C compilers should correctly compile and run without modification label A symbol that begins in column 1 of an assembler source statement and corresponds to the address of that statement A label is the only assembler statement that can begin in column 1 linker A software program that combines object files to form an executable object file that can be allocated into system memory and executed by the device listing file An output file created by the assembler which lists source statements their line numbers and their effects on the section program counter SPC little
202. ing is used in an expression the string itself is defined in the const section with the string assembler directive along with a unique label that points to the string the terminating O byte is included For example the following lines define the string abc and the terminating O byte the label SL5 points to the string sect const SL5 string abc 0 String labels have the form SL n where n is a number assigned by the compiler to make the label unique The number begins at 0 and is increased by 1 for each string defined All strings used in a source module are defined at the end of the compiled assembly language module The label SLn represents the address of the string constant The compiler uses this label to reference the string expression 120 Run Time Environment SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Register Conventions Because strings are stored in the const section possibly in ROM and shared it is bad practice for a program to modify a string constant The following code is an example of incorrect string use const char a a 1 x 6 3 Register Conventions Strict conventions associate specific registers with specific operations in the C C environment If you plan to interface an assembly language routine to a C C program you must understand and follow these register conventions The register
203. ing support lc Indicates the library supports large code SC Indicates the library supports small code ld Indicates the library supports large data rd Indicates the library supports restricted data _sd Indicates the library supports small data Using Run Time Support Functions and Building Libraries SLAU132K September 2015 Submit Documentation Feedback Copyright O 2015 Texas Instruments Incorporated l TEXAS INSTRUMENTS www ti com The C I O Functions The C I O functions make it possible to access the host s operating system to perform I O The capability to perform I O on the host gives you more options when debugging and testing code 7 2 The C I O Functions The I O functions are logically divided into layers high level low level and device driver level With properly written device drivers the C standard high level I O functions can be used to perform I O on custom user defined devices This provides an easy way to use the sophisticated buffering of the high level I O functions on an arbitrary device NOTE NOTE NOTE Debugger Required for Default HOST For the default HOST device to work there must be a debugger to handle the C I O requests the default HOST device cannot work by itself in an embedded system To work in an embedded system you will need to provide an appropriate driver for your system C I O Mysteriously Fails If there is not enough space on the heap for a C I O buffer oper
204. ingle multibyte character having the same value The C library includes the header file lt locale h gt but with a minimal implementation The only supported locale is the C locale That is library behavior that is specified to vary by locale is hard coded to the behavior of the C locale and attempting to install a different locale via a call to setlocale will return NULL 7 1 6 Allowable Number of Open Files In the lt stdio h gt header file the value for the macro FOPEN MAX has the value of the macro _NFILE which is set to 10 The impact is that you can only have 10 files simultaneously open at one time including the pre defined streams stdin stdout stderr The C standard requires that the minimum value for the FOPEN MAX macro is 8 The macro determines the maximum number of files that can be opened at one time The macro is defined in the stdio h header file and can be modified by changing the value of the NFILE macro and recompiling the library SLAU132K September 2015 Using Run Time Support Functions and Building Libraries 143 Submit Documentation Feedback Copyright O 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS C and C Run Time Support Libraries www ti com 7 1 7 Nonstandard Header Files in the Source Tree The source code in the lib src subdirectory of the compiler installation contains certain files that are not specified by the ISO ANSI standard but are needed to build the library The file h
205. inting to the byte after the 8 bit index The second argument is the run address from the C auto initialization record RLE Decompression Routine NOTE The previous decompression routine Tl decompress rle is included in the run time support library for decompressing RLE encodings generated by older versions of the linker Run Time Environment SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com System Initialization 6 9 3 4 4 Lempel Ziv Storer Szymanski Compression LZSS Format 8 bit index Initialization data compressed using LZSS The data following the 8 bit index is compressed using LZSS compression The run time support library has the routine TI decompress lzss to decompress the data compressed using LZSS The first argument to this function is the address pointing to the byte after the 8 bit index The second argument is the run address from the C auto initialization record 6 9 3 5 Initialization of Variables at Load Time Initialization of variables at load time enhances performance by reducing boot time and by saving the memory used by the initialization tables To use this method invoke the linker with the ram model option When you use the ram model link option the linker does not generate C autoinitialization tables and data The direct initialized sections data in the compiled object files
206. ion Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Chapter 5 SLAU132K September 2015 MSP430 C C Language Implementation The C C compiler supports the C C language standard that was developed by a committee of the American National Standards Institute ANSI and subsequently adopted by the International Standards Organization ISO The C language supported by the MSP430 is defined by the ANSI ISO IEC 14882 2003 standard with certain exceptions Topic Page SI Characteristics of MSP430 C 7er sexes Nee E a E a EEE 76 5 298 Characteristics ofiMSP430 C pono E EE DIETE TEE 80 5 3 Using MISRA C 2004 e e aaa EEA EEE EAE EEEE EA EAA E EE AE A AE eseREEET EE ERES 80 5 4 Using the ULP AdVISON eee ee E E E EEEE e IRE eT rr ER A En a 81 5 5 Advice on Hardware Configuration cceeeeeeee eee ee eee eee eee eee eee eee eeeee sees eeeeeee 81 56 Data Types cscs ccas snes E aA EE e E E suit anauanneosenan a Ear EEE e aA EEEE aa 82 Sra e AYANT a A O O 83 5 8 C Exception Handlingens ee ee aE re eI E EAEE AEAEE AEAEE EE AA 87 5 9 Register Variables and ParametersS 2 cceeeeeeeeeee eee eens eee ee eeeeeeeeeneeeeaeeeeaees 87 5 10 The asm Statement tevccice ceceerecn ccececeeeccececececccerec ecececececcececceececerecedsececceecesteces 88 511 Pragma Directives eee e a E E a E E E E A AE EE SE EEE EERE EEE 89 E Ae EKOT EO E r EE A A T 104 5 13 Appli
207. ion to generate more efficient code The Linker Defines the Memory Map NOTE The linker not the compiler defines the memory map and allocates code and data into target memory The compiler assumes nothing about the types of memory available about any locations not available for code or data holes or about any locations reserved for I O or control purposes The compiler produces relocatable code that allows the linker to allocate code and data into the appropriate memory spaces For example you can use the linker to allocate global variables into on chip RAM or to allocate executable code into external ROM You can allocate each block of code or data individually into memory but this is not a general practice an exception to this is memory mapped I O although you can access physical memory locations with C C pointer types 6 1 4 Sections The compiler produces relocatable blocks of code and data called sections The sections are allocated into memory in a variety of ways to conform to a variety of system configurations For more information about sections and allocating them see the introductory object file information in the MSP430 Assembly Language Tools User s Guide There are two basic types of sections Initialized sections contain data or executable code Initialized sections are usually but not always read only The C C compiler creates the following initialized sections The binit section contains boot tim
208. ional parameter cl430 options filenames run linker ink options object files e Braces and indicate that you must choose one of the parameters within the braces you do not enter the braces themselves This is an example of a command with braces that are not included in the actual syntax but indicate that you must specify either the rom model or ram model option cl430 run linker rom model ram model filenames output filez name out library ibraryname SLAU132K September 2015 Read This First 9 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS Related Documentation www ti com In assembler syntax statements the leftmost column is reserved for the first character of a label or symbol If the label or symbol is optional it is usually not shown If a label or symbol is a required parameter it is shown starting against the left margin of the box as in the example below No instruction command directive or parameter other than a symbol or label can begin in the leftmost column symbol usect section name size in bytes alignment Some directives can have a varying number of parameters For example the byte directive This syntax is shown as parameter Related Documentation You can use the following books to supplement this user s guide ANSI X3 159 1989 Programming Language C
209. ions which are enabled with the exceptions option see Section 5 8 Run time type information RTTI which can be enabled with the rtti compiler option The exceptions to the standard are as follows The compiler does not support embedded C run time support libraries The library supports wide chars wchar t in that template functions and classes that are defined for char are also available for wchar t For example wide char stream classes wios wiostream wstreambuf and so on corresponding to char classes ios iostream streambuf are implemented However there is no low level file I O for wide chars Also the C library interface to wide char support through the C headers lt cwchar gt and cwctype is limited as described above in the C library Thereinterpret cast type does not allow casting a pointer to member of one class to a pointer to member of another class if the classes are unrelated Two phase name binding in templates as described in tesp res and temp dep of the standard is not implemented The export keyword for templates is not implemented Atypedef of a function type cannot include member function cv qualifiers A partial specialization of a class member template cannot be added outside of the class definition 5 3 Using MISRA C 2004 MISRA C is a set of software development guidelines for the C programming language It promotes best practices in developing safety related electronic syste
210. ipsis it can be called with a variable number of arguments The called function pushes these arguments on the stack if they meet both of these criteria The argument includes or follows the last explicitly declared argument The argument is passed in a register The called function pushes register values of all the registers that are modified by the function and that must be preserved upon exit of the function onto the stack Normally these registers are the save on entry registers R4 R10 if the function contains calls If the function is an interrupt additional registers may need to be preserved For more information see Section 6 7 The called function allocates memory for the local variables and argument block by subtracting a constant from the SP This constant is computed with the following formula size of all local variables max constant The max argument specifies the size of all parameters placed in the argument block for each call The called function executes the code for the function If the called function returns a value it places the value in R12 R12 and R13 or R12 through R15 depending on the size of the return type If the called function returns a structure it copies the structure to the memory block that the first argument R12 points to If the caller does not use the return value R12 is set to 0 This directs the called function not to copy the return structure Structures and unions with size 32 bits
211. is defined by the macro NDEVICE found in stdio h cstdio The first entry in the device table is predefined to be the host device on which the debugger is running The low level routine add device finds the first empty position in the device table and initializes the device fields with the passed in arguments For a complete description see the add device function 7 2 5 The device Prefix A file can be opened to a user defined device driver by using a device prefix in the pathname The device prefix is the device name used in the call to add device followed by a colon For example FILE fptr fopen mydevice filel r int fd open mydevice file2 O RDONLY 0 If no device prefix is used the HOST device will be used to open the file add device Add Device to Device Table Syntax for C include lt file h gt int add_device char name unsigned flags int dopen const char path unsigned flags int Ilv_fd int dclose int dev_fd int dread intdev fd char buf unsigned count int dwrite int dev fd const char buf unsigned count off t diseek int dev fd off t offset int origin int dunlink const char path int drename const char old name const char new name Defined in lowlev c in the lib src subdirectory of the compiler installation Description The add device function adds a device record to the device table allowing that device to be used for I O from C The first
212. is function must return 1 to indicate an error if for some reason the file could not be opened such as the file does not exist could not be created or there are too many files open The value of errno may optionally be set to indicate the exact error the HOST device does not set errno Some devices might have special failure conditions for instance if a device is read only a file cannot be opened O_WRONLY On success this function must return a non negative file descriptor unique among all open files handled by the specific device The file descriptor need not be unique across devices The device file descriptor is used only by low level functions when calling the device driver level functions The low level function open allocates its own unique file descriptor for the high level functions to call the low level functions Code that uses only high level I O functions need not be aware of these file descriptors Using Run Time Support Functions and Building Libraries 151 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS DEV close Close File for I O www ti com DEV_close Syntax Description Return Value DEV_read Syntax Description Return Value DEV_write Syntax Description Return Value 152 Using Run Time Support Functions and Building Libraries Close File for I O int DEV_close int dev fd This function closes a valid open file descripto
213. ject file At link time this representation is extracted from every object file which contains it and is used to optimize the entire program If you use opt level 4 O4 the program level compile option cannot also be used because link time optimization provides the same optimization opportunities as program level optimization Section 3 3 Link time optimization provides the following benefits Each source file can be compiled separately One issue with program level compilation is that it requires all source files to be passed to the compiler at one time This often requires significant modification of a customer s build process With link time optimization all files can be compiled separately References to C C symbols from assembly are handled automatically When doing program level compilation the compiler has no knowledge of whether a symbol is referenced externally When performing link time optimization during a final link the linker can determine which symbols are referenced externally and prevent eliminating them during optimization Third party object files can participate in optimization If a third party vendor provides object files that were compiled with the opt_level 4 option those files participate in optimization along with user generated files This includes object files supplied as part of the TI run time support Object files that were not compiled with opt level 4 can still be used in a link that is perf
214. kckck ck kckok kk ke ek f MEMORY SFR R origin 0x0000 length 0x0010 PERIPHERALS 8BIT origin 0x0010 length 0x00F0 PERIPHERALS 16BIT origin 0x0100 length 0x0100 RAM RW origin 0x0200 length 0x0800 INFOA origin 0x1080 length 0x0080 INFOB origin 0x1000 length 0x0080 FLASH origin 0x1100 length OxEEEO VECTORS R origin OxFFEO length 0x001E RESET origin OxFFFE length 0x0002 RK K k KI KK KK IR IK I IR IIA II IIR IIA k k RIA II A k k IR k kk II k kk I kkk f SPECIFY THE SECTIONS ALLOCATION INTO MEMORY E E K k k kk e e e e k e k e e e k e e k k Ae k Ck e ke ke k k k k k k k A k k k kk k kk k k k k k kk k kk k k k k k k k k kk k kk k kk k k kk k k f SECTIONS bss gt RAM UNINITIALIZED GLOBAL STATIC af sysmem gt RAM DYNAMIC MEMORY ALLOCATION AREA Stack gt RAM SOFTWARE SYSTEM STACK cio RAM C I O BUFFER text FLASH PROGRAM CODE data FLASH INITIALIZED GLOBAL STATIC Ej const gt FLASH CONSTANT DATA args FLASH PROGRAM ARGUMENTS cinit FLASH GLOBAL INITIALIZATION DATA init array FLASH EABI C GLOBAL CONSTRUCTOR TABLE mspabi exidx FLASH EABI TDEH METADATA mspabi extab FLASH EABI TDEH METADATA intvecs gt VECTORS INTERRUPT VECTORS j reset gt RESET 74 Linking C C Code SLAU132K September 2015 Submit Documentat
215. l 0 opt_level n optimized as specified optimized as specified Debug information increases the size of object files but it does not affect the size of code or data on the target If object file size is a concern and debugging is not needed use symdebug none to disable the generation of debug information The optimize with debug and symdebug skeletal options have been deprecated and no longer have any effect Controlling Code Size Versus Speed The latest mechanism for controlling the goal of optimizations in the compiler is represented by the opt for speed2num option The num denotes the level of optimization 0 5 which controls the type and degree of code size or code speed optimization opt for speed 0 Enables optimizations geared towards improving the code size with a high risk of worsening or impacting performance Oopt for speed 1 Enables optimizations geared towards improving the code size with a medium risk of worsening or impacting performance Oopt for speed 2 Enables optimizations geared towards improving the code size with a ow risk of worsening or impacting performance e opt for speed 3 Enables optimizations geared towards improving the code performance speed with a ow risk of worsening or impacting code size Oopt for speed 4 Enables optimizations geared towards improving the code performance speed with a medium risk of Optimizing Your Code SLAU132K Septem
216. les At boot or load time the C C boot routine or the loader copies data out of the cinit section which can be in ROM and stores it in the bss section For EABI only the bss section reserves space for uninitialized global and static variables 116 Run Time Environment SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Memory Model Uninitialized variables that are also unused are usually created as common symbols unless you specify commonczoff instead of being placed in bss so that they can be excluded from the resulting application The stack section reserves memory for the C C software stack The sysmem section reserves space for dynamic memory allocation The reserved space is used by dynamic memory allocation routines such as malloc calloc realloc or new If a C C program does not use these functions the compiler does not create the sysmem section The assembler creates the default sections text bss and data You can instruct the compiler to create additional sections by using the CODE SECTION and DATA SECTION pragmas see Section 5 11 5 and Section 5 11 7 The linker takes the individual sections from different object files and combines sections that have the same name The resulting output sections and the appropriate placement in memory for each section are listed in Table 6 1 You can place these outpu
217. lets you compile optimize assemble and optionally link in one step The compiler performs the following steps on one or more source modules The compiler accepts C C source code and assembly code It produces object code You can compile C C and assembly files in a single command The compiler uses the filename extensions to distinguish between different file types See Section 2 3 9 for more information Thelinker combines object files to create an executable object file The link step is optional so you can compile and assemble many modules independently and link them later See Chapter 4 for information about linking the files Invoking the Linker NOTE By default the compiler does not invoke the linker You can invoke the linker by using the run linker z compiler option See Section 4 1 1 for details For a complete description of the assembler and the linker see the MSP430 Assembly Language Tools User s Guide 2 2 Invoking the C C Compiler To invoke the compiler enter cl430 options filenames run linker ink options object files cl430 Command that runs the compiler and the assembler options Options that affect the way the compiler processes input files The options are listed in Table 2 9 through Table 2 31 filenames One or more C C source files and assembly language source files run_linker z Option that invokes the linker The run_linker option s short form is z
218. lias Effect Section check_misra all required Enables checking of the specified MISRA C 2004 rules Default is Section 2 3 3 advisory none rulespec all misra_advisory error warning Sets the diagnostic severity for advisory MISRA C 2004 rules Section 2 3 3 remark suppress misra_required error warning Sets the diagnostic severity for required MISRA C 2004 rules Section 2 3 3 remark suppress SLAU132K September 2015 Using the C C Compiler 25 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated Changing the Compiler s Behavior with Options 2 3 1 Linker Options I TEXAS INSTRUMENTS www ti com The following tables list the linker options See Chapter 4 of this document and the MSP430 Assembly Language Tools User s Guide for details on these options Table 2 23 Linker Basic Options Option Alias Description run_linker Z Enables linking output_file file 0 Names the executable output file The default filename is a out file map file file m Produces a map or listing of the input and output sections including holes and places the listing in filename stack_size size stack Sets C system stack size to size bytes and defines a global symbol that specifies the stack size Default 128 bytes heap_size size heap Sets heap size for the dynamic memory allocation in C to size bytes and defines a global symbol that specifies the heap size Default
219. line Defining inline functions as fast as macros Assembly labels Specifying the assembler name to use for a C symbol Extended asm Assembler instructions with C operands Constraints Constraints for asm operands Alternate keywords Header files can use const asm etc Explicit reg vars Defining variables residing in specified registers Incomplete enum types Define an enum tag without specifying its possible values Function names Printable strings which are the name of the current function Return address Getting the return or frame address of a function limited support Other built ins Other built in functions see Section 5 16 5 Vector extensions Using vector instructions through built in functions Target built ins Built in functions specific to particular targets Pragmas Pragmas accepted by GCC Unnamed fields Unnamed struct union fields within structs unions Thread local Per thread variables Binary constants Binary constants using the Ob prefix 5 16 2 Function Attributes The following GCC function attributes are supported alias always_inline const constructor deprecated format format_arg interrupt malloc noinline noreturn pure ramfunc section unused used and warn unused result For example this function declaration uses the alias attribute to make my alias a function alias for the myFunc function
220. lled at program startup is main 5 1 2 1 Program termination does not affect the environment there is no way to return an exit code to the environment By default the program is known to have halted when execution reaches the special C EXIT label 5 1 2 1 MSP430 C C Language Implementation SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS www ti com Characteristics of MSP430 C Inrelaxed ANSI mode the compiler accepts void main void and void main int argc char argv as alternate definitions of main The alternate definitions are rejected in strict ANSI mode 5 1 2 2 1 e If space is provided for program arguments at link time with the args option and the program is run under a system that can populate the args section such as CCS argv 0 will contain the filename of the executable argv 1 through argv argc 1 will contain the command line arguments to the program and argv argc will be NULL Otherwise the value of argv and argc are undefined 5 1 2 2 1 Interactive devices include stdin stdout and stderr when attached to a system that honors CIO requests Interactive devices are not limited to those output locations the program may access hardware peripherals that interact with the external state 5 1 2 3 Signals are not supported The function signal is not supported 7 14 7 14 1 1 The library function getenv is
221. lsewhere after returning For example the called function cannot assign the local variable s address to a global variable or return the local variable s address In cases where this assumption is invalid use the aliased variables compiler option to force the compiler to assume worst case aliasing In worst case aliasing any indirect reference can refer to such a variable 3 6 Use Caution With asm Statements in Optimized Code You must be extremely careful when using asm inline assembly statements in optimized code The compiler rearranges code segments uses registers freely and can completely remove variables or expressions Although the compiler never optimizes out an asm statement except when it is unreachable the surrounding environment where the assembly code is inserted can differ significantly from the original C C source code It is usually safe to use asm statements to manipulate hardware controls such as interrupt masks but asm statements that attempt to interface with the C C environment or access C C variables can have unexpected results After compilation check the assembly output to make sure your asm statements are correct and maintain the integrity of the program SLAU132K September 2015 Optimizing Your Code 59 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Automatic Inline Expansion auto inline Option www ti com 3 7 3 8 60 Automatic Inline
222. mary of Sections and Memory Placement essssseeeeeseesee nennen enne 117 6 2 Data Representation in Registers and Memory csssssseeeeee nn Hem mnm nmn nnns 119 6 3 How Register Types Are Affected by the Conventions seceeeeeeeee ence eeeeeeeee sees eene 121 6 4 Register Usage and Preservation ConventiOnS csseceeee cece ee enee eee ene eeeeeeeeee snes enn nnne 121 6 5 IMSPA SOU IASICS cer 129 6 6 Deprecated INrinSiCSisicicncviiewiwereaiesuavaneeweneneweninwinnnendetwawidulala RO ceed na UR UR Neila EI a nea ER ER a 130 7 1 TheuklibProgram ODptloris csse oou uocem etico uu entes dedu cuu nee conv iebreras reri aeu nex arc ux ram RE PI ERE 160 Bal REVISION FISIONY er DT 170 List of Tables SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated Preface l MEE MENTIS SLAU132K September 2015 Read This First About This Manual The MSP430 Optimizing C C Compiler User s Guide explains how to use these compiler tools Compiler Library build utility C name demangler The compiler accepts C and C code conforming to the International Organization for Standardization ISO standards for these languages The compiler supports both the 1989 and 1999 versions of the C language and the 2003 version of the C language This user s guide discusses the characteristics of the C C compiler It assumes that you already know how to wri
223. mation about filename extension conventions Using the C C Compiler SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Changing the Compiler s Behavior with Options 2 3 9 Changing How the Compiler Interprets and Names Extensions You can use options to change how the compiler program interprets filename extensions and names the extensions of the files that it creates The filename extension options must precede the filenames they apply to on the command line You can use wildcard specifications with these options An extension can be up to nine characters in length Select the appropriate option for the type of extension you want to specify asm extension new extension for an assembly language file c extension new extension for a C source file cpp_extension new extension for a C source file listing_extension new extension sets default extension for listing files obj extension new extension for an object file The following example assembles the file fit rrr and creates an object file named fit o c1430 asm extension rrr obj extension o fit rrr The period in the extension is optional You can also write the example above as c1430 asm extension rrr obj extension o fit rrr 2 3 10 Specifying Directories By default the compiler program places the object assembly and temporary files that it creates into the curr
224. memory and result in compilation tool failures 5 11 10 The FUNC_CANNOT_INLINE Pragma The FUNC_CANNOT_INLINE pragma instructs the compiler that the named function cannot be expanded inline Any function named with this pragma overrides any inlining you designate in any other way such as using the inline keyword Automatic inlining is also overridden with this pragma see Section 2 11 The pragma must appear before any declaration or reference to the function that you want to keep In C the argument func is the name of the function that cannot be inlined In C the pragma applies to the next function declared The syntax of the pragma in C is pragma FUNC_CANNOT_INLINE func The syntax of the pragma in C is pragma FUNC_CANNOT_INLINE 5 11 11 The FUNC EXT CALLED Pragma When you use the program level compile option the compiler uses program level optimization When you use this type of optimization the compiler removes any function that is not called directly or indirectly by main You might have C C functions that are called by hand coded assembly instead of main The FUNC EXT CALLED pragma specifies that the optimizer should keep these C functions or any functions these C C functions call These functions act as entry points into C C The pragma must appear before any declaration or reference to the function to keep In C the argument func is the name of the function to keep In C
225. ments Incorporated 1 TEXAS INSTRUMENTS www ti com Controlling the Linking Process 4 3 2 Run Time Initialization You must link all C C programs with a bootstrap routine which will initialize the C C environment and begin the program The bootstrap routine is responsible for the following tasks 1 Set up the stack 2 Process the cinit run time initialization table to autoinitialize global variables when using the rom model option 3 Call all global constructors init array for C Call the main function 5 Call exit when main returns A NOTE The c int00 Symbol If you use the ram model or rom model link option c int0O is automatically defined as the entry point for the program Otherwise an entry point is not automatically selected and you will receive a linker warning 4 3 3 Initialization by the Interrupt Vector If your C C program begins running at RESET you must set up the RESET vector to branch to a suitable bootstrap routine such as c int00 You must also make sure the interrupt vectors are included in the project typically by using the undef sym linker option to make a symbol at the start of the interrupt vector a root linker object The boot obj object in the run time support library provides a section named reset containing a reference to c intOO which is suitable to place in the RESET vector in the linker command file 4 3 4 Initialization of the FRAM Memory Protection Unit Th
226. ments return types object file An assembled or linked file that contains machine language object code object library An archive library made up of individual object files operand An argument of an assembly language instruction assembler directive or macro directive that supplies information to the operation performed by the instruction or directive optimizer A software tool that improves the execution speed and reduces the size of C programs options Command line parameters that allow you to request additional or specific functions when you invoke a software tool output section A final allocated section in a linked executable module parser A software tool that reads the source file performs preprocessing functions checks the syntax and produces an intermediate file used as input for the optimizer or code generator partitioning The process of assigning a data path to each instruction pop An operation that retrieves a data object from a stack pragma A preprocessor directive that provides directions to the compiler about how to treat a particular statement preprocessor A software tool that interprets macro definitions expands macros interprets header files interprets conditional compilation and acts upon preprocessor directives program level optimization An aggressive level of optimization where all of the source files are compiled into one intermediate file Because the compiler can
227. mization identifies expressions within loops that always compute to the same value The computation is moved in front of the loop and each occurrence of the expression in the loop is replaced by a reference to the precomputed value 3 11 10 Loop Rotation The compiler evaluates loop conditionals at the bottom of loops saving an extra branch out of the loop In many cases the initial entry conditional check and the branch are optimized out 3 11 11 Instruction Scheduling The compiler performs instruction scheduling which is the rearranging of machine instructions in such a way that improves performance while maintaining the semantics of the original order Instruction scheduling is used to improve instruction parallelism and hide latencies It can also be used to reduce code size 3 11 12 Tail Merging If you are optimizing for code size tail merging can be very effective for some functions Tail merging finds basic blocks that end in an identical sequence of instructions and have a common destination If such a set of blocks is found the sequence of identical instructions is made into its own block These instructions are then removed from the set of blocks and replaced with branches to the newly created block Thus there is only one copy of the sequence of instructions rather than one for each block in the set 3 11 13 Integer Division With Constant Divisor The optimizer attempts to rewrite integer divide operations with constant divis
228. ms in road vehicles and other embedded systems MISRA C was originally launched in 1998 by the Motor Industry Software Reliability Association and has since been adopted across a wide variety of industries A subsequent update to the guidelines was publishes as MISRA C 2004 You can alter your code to work with the MISRA C 2004 rules The following options and pragmas enable disable the rules The check misra option enables checking of the specified MISRA C 2004 rules The CHECK MISRA pragma enables disables MISRA C 2004 rules at the source level This pragma is equivalent to using the check misra option See Section 5 11 2 RESET MISRA pragma resets the specified MISRA C 2004 rules to their state before any CHECK MISRA pragmas were processed See Section 5 11 22 The syntax of the option and pragmas is check_misra all required advisory none rulespec pragma CHECK_MISRA all required advisory none rulespec pragma RESET MISRA all required advisory ru espec The rulespec parameter is a comma separated list of rule numbers to enable Example check_misra 1 1 1 4 1 5 2 1 2 7 7 1 7 2 8 4 Enables rules 1 1 1 4 1 5 2 1 2 7 7 1 7 2 and 8 4 80 MSP430 C C Language Implementation SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated l TEXAS INSTRUMENTS www ti com Using the ULP Advisor Two options control the severity of certain MISRA C 2004 rule
229. n 5 11 4 CODE SECTION See Section 5 11 5 DATA ALIGN See Section 5 11 6 DATA SECTION See Section 5 11 7 diag suppress diag remark diag warning diag error diag default diag push diag pop See Section 5 11 8 e FUNC ALWAYS INLINE See Section 5 11 9 e FUNC CANNOT INLINE See Section 5 11 10 e FUNC EXT CALLED See Section 5 11 11 e FUNC IS PURE See Section 5 11 12 e FUNC NEVER RETURNS See Section 5 11 13 FUNC NO GLOBAL ASG See Section 5 11 14 FUNC NO IND ASG See Section 5 11 15 FUNCTION OPTIONS See Section 5 11 16 NTERRUPT See Section 5 11 17 LOCATION See Section 5 11 18 e NOINIT See Section 5 11 19 NO HOOKS See Section 5 11 20 PACK See Section 5 11 21 e PERSISTENT See Section 5 11 19 RESET MISRA See Section 5 11 22 RESET ULP See Section 5 11 23 e RETAIN See Section 5 11 24 SET CODE SECTION See Section 5 11 25 SET DATA SECTION See Section 5 11 25 e vector See Section 5 11 26 The arguments func and symbol cannot be defined or declared inside the body of a function You must specify the pragma outside the body of a function and the pragma specification must occur before any declaration definition or reference to the func or symbol argument If you do not follow these rules the compiler issues a warning and may ignore the pragma For pragmas that apply to functions or symbols the syntax differs between C and C n C you must supply the
230. n Feedback Copyright 2015 Texas Instruments Incorporated l TEXAS INSTRUMENTS www ti com Handling Reentrancy register lock and register unlock Functions 7 3 Handling Reentrancy register lock and register unlock Functions The C standard assumes only one thread of execution with the only exception being extremely narrow support for signal handlers The issue of reentrancy is avoided by not allowing you to do much of anything in a signal handler However SYS BIOS applications have multiple threads which need to modify the same global program state such as the CIO buffer so reentrancy is a concern Part of the problem of reentrancy remains your responsibility but the run time support environment does provide rudimentary support for multi threaded reentrancy by providing support for critical sections This implementation does not protect you from reentrancy issues such as calling run time support functions from inside interrupts this remains your responsibility The run time support environment provides hooks to install critical section primitives By default a single threaded model is assumed and the critical section primitives are not employed In a multi threaded system such as SYS BIOS the kernel arranges to install semaphore lock primitive functions in these hooks which are then called when the run time support enters code that needs to be protected by a critical section Throughout the run time support envi
231. n a non zero value In order to perform application specific initializations you can create a customized version of System pre init and add it to the application project The customized version will replace the default definition included in the run time library if it is linked in before the run time library The default stubbed version of system pre init is included with the run time support RTS library A zip file containing the source files for the RTS library including the pre init c file is located in compiler installation at lt ccs_install_dir gt ccsv6 tools compiler lt target_family gt _ A lib 6 9 2 Run Time Stack SLAU1 The run time stack is allocated in a single continuous block of memory and grows down from high addresses to lower addresses The SP points to the top of the stack The code does not check to see if the run time stack overflows Stack overflow occurs when the stack grows beyond the limits of the memory space that was allocated for it Be sure to allocate adequate memory for the stack The stack size can be changed at link time by using the stack_size link option on the linker command line and specifying the stack size as a constant directly after the option The C C boot routine shipped with the compiler sets up the user thread mode run time stack If your program uses a run time stack when it is in other operating modes you must also allocate space and set up the run time stack corresponding to
232. n bit simulator A software development system that simulates MSP430 operation source file A file that contains C C code or assembly language code that is compiled or assembled to form an object file stand alone preprocessor A software tool that expands macros include files and conditional compilation as an independent program It also performs integrated preprocessing which includes parsing of instructions static variable A variable whose scope is confined to a function or a program The values of static variables are not discarded when the function or program is exited their previous value is resumed when the function or program is reentered storage class An entry in the symbol table that indicates how to access a symbol string table A table that stores symbol names that are longer than eight characters symbol names of eight characters or longer cannot be stored in the symbol table instead they are stored in the string table The name portion of the symbol s entry points to the location of the string in the string table structure A collection of one or more variables grouped together under a single name subsection A relocatable block of code or data that ultimately will occupy continuous space in the memory map Subsections are smaller sections within larger sections Subsections give you tighter control of the memory map symbol A string of alohanumeric characters that represents an address or a
233. n precede either the function s definition or its declaration attribute interrupt void func void The return address of the interrupt function is placed on the stack SLAU132K September 2015 MSP430 C C Language Implementation 97 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Pragma Directives www ti com The interrupt attribute syntax allows you to optionally specify a numeric argument that indicates the vector location as specified for the vector pragma For example define TIMER_AO 20 define TIMER A1 10 attribute interrupt TIMER A0 void fool int ij for i 1 i lt 1000 i global ptr i i Except for c int0O which is the name reserved for the system reset interrupt for C programs the name of the interrupt the func argument does not need to conform to a naming convention Hwi Objects and the INTERRUPT Pragma NOTE The INTERRUPT pragma must not be used when SYS BIOS Hwi objects are used in conjunction with C functions The Hwi_enter Hwi_exit macros and the Hwi dispatcher contain this functionality and the use of the C modifier can cause negative results Interrupt service routine ISR warning NOTE The linker emits a warning for any device specific interrupts with no associated interrupt service routine However a default vector handler is provided by the run time support RTS library so you should not see
234. name of the object or function to which you are applying the pragma as the first argument Because the entity operated on is specified a pragma in C can appear some distance way from the definition of that entity n C pragmas are positional They do not name the entity on which they operate as an argument Instead they always operate on the next entity defined after the pragma SLAU132K September 2015 MSP430 C C Language Implementation 89 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Pragma Directives www ti com 5 11 1 The BIS IE1 INTERRUPT The BIS IE1 INTERRUPT pragma treats the named function as an interrupt routine Additionally the compiler generates a BIS operation on the IE1 special function register upon function exit The mask value which must be an 8 bit constant literal is logically ORed with the IE1 SFR just before the RETI instruction The compiler assumes the IE1 SFR is mapped to address 0x0000 The syntax of the pragma in C is pragma BIS IE1 INTERRUPT func mask The syntax of the pragma in C is pragma BIS IE1 INTERRUPT mask In C the argument func is the name of the function that is an interrupt In C the pragma applies to the next function declared 5 11 2 The CHECK MISRA Pragma The CHECK MISRA pragma enables disables MISRA C 2004 rules at the source level This pragma is equivalent to using the check
235. named section name The syntax of the pragma in C is pragma DATA SECTION symbol section name The syntax of the pragma in C is pragma DATA SECTION section name The DATA SECTION pragma is useful if you have data objects that you want to link into an area separate from the bss section Example 5 8 through Example 5 10 demonstrate the use of the DATA SECTION pragma Example 5 8 Using the DATA SECTION Pragma C Source File pragma DATA SECTION bufferB my sect char bufferA 512 char bufferB 512 Example 5 9 Using the DATA SECTION Pragma C Source File char bufferA 512 pragma DATA SECTION my sect char bufferB 512 Example 5 10 Using the DATA SECTION Pragma Assembly Source File global bufferA bss bufferA 512 2 global bufferB bufferB usect my sect 512 2 SLAU132K September 2015 MSP430 C C Language Implementation Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 93 I TEXAS INSTRUMENTS Pragma Directives www ti com 5 11 8 The Diagnostic Message Pragmas The following pragmas can be used to control diagnostic messages in the same ways as the corresponding command line options Pragma Option Description diag_suppress num pds num num num s Suppress diagnostic num diag remark num pdsr2num nume num Treat diagnostic num as a remark diag warning num pdsw2num
236. nction refers to the function making the function call The child function refers to the function being called The SP is preserved by the convention that everything pushed on the stack is popped off before returning SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated Run Time Environment 121 I TEXAS INSTRUMENTS Function Structure and Calling Conventions www ti com 6 4 122 Function Structure and Calling Conventions The C C compiler imposes a strict set of rules on function calls Except for special run time support functions any function that calls or is called by a C C function must follow these rules Failure to adhere to these rules can disrupt the C C environment and cause a program to fail The following sections use this terminology to describe the function calling conventions of the C C compiler Argument block The part of the local frame used to pass arguments to other functions Arguments are passed to a function by moving them into the argument block rather than pushing them on the stack The local frame and argument block are allocated at the same time Register save area The part of the local frame that is used to save the registers when the program calls the function and restore them when the program exits the function Save on call registers Registers R11 R15 The called function does not preserve the values in these registers theref
237. ness practice Tl is not responsible or liable for any such statements Buyer acknowledges and agrees that it is solely responsible for compliance with all legal regulatory and safety related requirements concerning its products and any use of TI components in its applications notwithstanding any applications related information or support that may be provided by TI Buyer represents and agrees that it has all the necessary expertise to create and implement safeguards which anticipate dangerous consequences of failures monitor failures and their consequences lessen the likelihood of failures that might cause harm and take appropriate remedial actions Buyer will fully indemnify TI and its representatives against any damages arising out of the use of any TI components in safety critical applications In some cases TI components may be promoted specifically to facilitate safety related applications With such components TI s goal is to help enable customers to design and create their own end product solutions that meet applicable functional safety standards and requirements Nonetheless such components are subject to these terms No TI components are authorized for use in FDA Class III or similar life critical medical equipment unless authorized officers of the parties have executed a special agreement specifically governing such use Only those TI components which TI has specifically designated as military grade or enhanced plastic are desi
238. ng memory locations that represent memory mapped peripheral devices Such memory locations might change value in ways that the compiler cannot predict These locations might change if accessed or when some other memory location is accessed or when some signal occurs Volatile must also be used for local variables in a function which calls setjmp if the value of the local variables needs to remain valid if a longjmp occurs Example 5 3 Volatile for Local Variables With setjmp include lt stdlib h gt jmp buf context void function volatile int x 3 switch setjmp context case 0 setup break default printf x S d n x We can only reach here if longjmp has occurred because x s lifetime begins before the setjmp and lasts through the longjmp the C standard requires x be declared volatile break 86 MSP430 C C Language Implementation SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated l TEXAS INSTRUMENTS www ti com C Exception Handling 5 8 5 9 C Exception Handling The compiler supports all the C exception handling features as defined by the ANSI ISO 14882 C Standard More details are discussed in The C Programming Language Third Edition by Bjarne Stroustrup The compiler exceptions option enables exception handling The compiler s default is no exception handling support For exceptions t
239. ng the C C Compiler Invokes the interlist feature which interweaves original C C source with compiler generated assembly language The interlisted C statements may appear to be out of sequence You can use the interlist feature with the optimizer by combining the optimizer interlist and c src interlist options See Section 3 8 The c src interlist option can have a negative performance and or code size impact Appends the contents of a file to the option set You can use this option to avoid limitations on command line length or C style comments imposed by the host operating system Use a or at the beginning of a line in the command file to include comments You can also include comments by delimiting them with and To specify options surround hyphens with quotation marks For example quiet You can use the cmd file option multiple times to specify multiple files For instance the following indicates that file3 should be compiled as source and file1 and file2 are cmd file files c1430 cmd file filel cmd file file2 file3 Suppresses the linker and overrides the run linker option which specifies linking The compile only option s short form is c Use this option when you have run linker specified in the MSP430 C OPTION environment variable and you do not want to link See Section 4 1 3 Predefines the constant name for the preprocessor This is equivalent to inserting define name def at the top of each
240. nges made to this document The left column identifies the first version of this document in which that particular change appeared Table B 1 Revision History Musa Chapter Location Additions Modifications Deletions Added The COFF object file format is no longer supported The MSP430 Code Generation Tools now support only the Embedded Application Binary Interface EABI ABI which works only with object files that use the ELF object file format and the DWARF debug format i f thi h f h FF SLAU132K introduction Baelnnd al Sections of this document that referred to the COFF format have been removed or simplified If you would like to produce COFF output files please use v4 4 of the MSP430 Code Generation Tools and refer to SLAU132J for documentation The abi coff symdebug profile coff no sym merge and diable clink options have been deprecated The ramfunc option has been added If set this option places all SLAU132K Using the Compiler Section 2 3 4 functions in RAM The ramfunc function attribute has been added It specifies that a SLAU132K C C Language Section 5 16 2 function should be placed in RAM Run Time SLAU132K Environment Section 6 1 5 Corrected documentation to state that R1 is the stack pointer Previous Revisions SLAU1321 Introduction Section 1 3 Added support for C99 and C 03 SLAU132I Using the Compiler Table
241. nsible for their products and applications using Tl components To minimize the risks associated with Buyers products and applications Buyers should provide adequate design and operating safeguards TI does not warrant or represent that any license either express or implied is granted under any patent right copyright mask work right or other intellectual property right relating to any combination machine or process in which TI components or services are used Information published by TI regarding third party products or services does not constitute a license to use such products or services or a warranty or endorsement thereof Use of such information may require a license from a third party under the patents or other intellectual property of the third party or a license from TI under the patents or other intellectual property of TI Reproduction of significant portions of TI information in TI data books or data sheets is permissible only if reproduction is without alteration and is accompanied by all associated warranties conditions limitations and notices TI is not responsible or liable for such altered documentation Information of third parties may be subject to additional restrictions Resale of TI components or services with statements different from or beyond the parameters stated by TI for that component or service voids all express and any implied warranties for the associated TI component or service and is an unfair and deceptive busi
242. nstruments Incorporated I TEXAS INSTRUMENTS Utilities www ti com 1 5 Utilities These features are compiler utilities Library build utility The library build utility lets you custom build object libraries from source for any combination of run time models For more information see Section 7 4 C name demangler The C name demangler dem430 is a debugging aid that translates each mangled name it detects in compiler generated assembly code disassembly output or compiler diagnostic messages to its original name found in the C source code For more information see Chapter 8 Hexconversion utility For stand alone embedded applications the compiler has the ability to place all code and initialization data into ROM allowing C C code to run from reset The ELF files output by the compiler can be converted to EPROM programmer data files by using the hex conversion utility as described in the MSP430 Assembly Language Tools User s Guide 16 Introduction to the Software Development Tools SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I8 TEXAS INSTRUMENTS Using the C C Compiler Chapter 2 SLAU132K September 2015 The compiler translates your source program into machine language object code that the MSP430 can execute Source code must be compiled assembled and linked to create an executable object file All of these steps are executed at once by
243. nt DEV write int dev fd const char buf unsigned count This function writes count bytes to the output file The dev fd is the number assigned by open to an opened file The buffer is where the write characters are placed The countis the number of characters to write to the file This function must return 1 to indicate an error if for some reason no bytes could be written to the file This could be because of an attempt to read from a O RDONLY file or for device specific reasons SLAU132K September 2015 Submit Documentation Feedback Copyright O 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com DEV Iseek Syntax Description Return Value DEV unlink Syntax Description Return Value DEV rename Syntax Description Return Value SLAU132K September 2015 DEV Iseek Set File Position Indicator Set File Position Indicator off t Iseek int dev fd off t offset int origin This function sets the file s position indicator for this file descriptor as Iseek If Iseek is supported it should not allow a seek to before the beginning of the file but it should support seeking past the end of the file Such seeks do not change the size of the file but if it is followed by a write the file size will increase If successful this function returns the new value of the file position indicator This function must return 1 to indicate an error if for some reason n
244. nterrupts If the system is initialized by way of a hardware reset interrupts are disabled If your system uses interrupts you must handle any required enabling or masking of interrupts Such operations have no effect on the C C environment and are easily incorporated with asm statements or calling an assembly language function 6 7 1 Saving Registers During Interrupts When C C code is interrupted the interrupt routine must preserve the contents of all machine registers that are used by the routine or by any functions called by the routine Register preservation must be explicitly handled by the interrupt routine SLAU132K September 2015 Run Time Environment 127 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS Interrupt Handling www ti com 6 7 2 Using C C Interrupt Routines A C C interrupt routine is like any other C C function in that it can have local variables and register variables Except for software interrupt routines an interrupt routine must be declared with no arguments and must return void For example interrupt void example void e If a C C interrupt routine does not call any other functions only those registers that the interrupt handler uses are saved and restored However if a C C interrupt routine does call other functions these functions can modify unknown registers that the interrupt handler does not use For this reason the routin
245. number option first in a separate compile Then use diag_suppress num to suppress the diagnostic You can only suppress discretionary diagnostic messages Using the C C Compiler SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS www ti com Understanding Diagnostic Messages diag_warning num Categorizes the diagnostic identified by num as a warning To determine the numeric identifier of a diagnostic message use the display_error_number option first in a separate compile Then use diag_warning num to recategorize the diagnostic as a warning You can only alter the severity of discretionary diagnostic messages display error number Displays a diagnostic s numeric identifier along with its text Use this option in determining which arguments you need to supply to the diagnostic suppression options diag suppress diag error diag remark and diag warning This option also indicates whether a diagnostic is discretionary A discretionary diagnostic is one whose severity can be overridden A discretionary diagnostic includes the suffix D otherwise no suffix is present See Section 2 7 emit warnings as Treats all warnings as errors This option cannot be used with the errors no warnings option The diag remark option takes precedence over this option This option takes precedence over the diag warning option issue remarks Issues remarks
246. o bytes could be written to the file For many devices the Iseek operation is nonsensical e g a computer monitor Delete File int DEV unlink const char path Remove the association of the pathname with the file This means that the file may no longer be opened using this name but the file may not actually be immediately removed Depending on the device the file may be immediately removed but for a device which allows open file descriptors to point to unlinked files the file will not actually be deleted until the last file descriptor is closed See Section 7 2 3 This function must return 1 to indicate an error if for some reason the file could not be unlinked delayed removal does not count as a failure to unlink If successful this function returns 0 Rename File int DEV rename const char old name const char new name This function changes the name associated with the file The old name is the current name of the file The new name is the new name for the file This function must return 1 to indicate an error if for some reason the file could not be renamed such as the file doesn t exist or the new name already exists NOTE It is inadvisable to allow renaming a file so that it is on a different device In general this would require a whole file copy which may be more expensive than you expect If successful this function returns 0 Using Run Time Support Functions and Building Lib
247. o errors are detected By default remarks are not issued Use the issue remarks compiler option to enable remarks Advice provides information about recommended usage It is not provided in the same way as the other diagnostic categories described here Instead it is only available in Code Composer Studio in the Advice area which is a tab that appears next to the Problems tab This advice cannot be controlled or accessed via the command line The advice provided includes suggested settings for the opt level and opt for speed options In addition messages about suggested code changes from the ULP Ultra Low Power Advisor are provided in this tab Diagnostic messages are written to standard error with a form like the following example test c line 5 error a break statement may only be used within a loop or switch break By default the source code line is not printed Use the verbose diagnostics compiler option to display the source line and the error position The above example makes use of this option SLAU132K September 2015 Using the C C Compiler 43 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Understanding Diagnostic Messages www ti com 2 7 1 44 The message identifies the file and line involved in the diagnostic and the source line itself with the position indicated by the character follows the message If several diagnostic messages apply
248. o work correctly all C files in the application must be compiled with the exceptions option regardless of whether exceptions occur in a particular file Mixing exception enabled object files and libraries with object files and libraries that do not have exceptions enabled can lead to undefined behavior Exception handling requires support in the run time support library which come in exception enabled and exception disabled forms you must link with the correct form When using automatic library selection the default the linker automatically selects the correct library Section 4 3 1 1 If you select the library manually you must use run time support libraries whose name contains eh if you enable exceptions Using the exceptions option causes the compiler to insert exception handling code This code will increase the size of the program but the EABI implementation requires smaller code size overhead by moving the information to const data sections See Section 7 1 for details on the run time libraries Register Variables and Parameters The C C compiler treats register variables variables defined with the register keyword differently depending on whether you use the opt_level O option Compiling with optimization The compiler ignores any register definitions and allocates registers to variables and temporary values by using an algorithm that makes the most efficient use of registers Compiling without optimization I
249. ocated in separate files in the lib src subdirectory of the compiler unctions installation C Name SLAU132J Demangler Section 8 2 Corrected information about name demangler options SLAU132K September 2015 Submit Documentation Feedback Revision History 171 Copyright 2015 Texas Instruments Incorporated IMPORTANT NOTICE Texas Instruments Incorporated and its subsidiaries Tl reserve the right to make corrections enhancements improvements and other changes to its semiconductor products and services per JESD46 latest issue and to discontinue any product or service per JESD48 latest issue Buyers should obtain the latest relevant information before placing orders and should verify that such information is current and complete All semiconductor products also referred to herein as components are sold subject to Tl s terms and conditions of sale supplied at the time of order acknowledgment TI warrants performance of its components to the specifications applicable at the time of sale in accordance with the warranty in Tl s terms and conditions of sale of semiconductor products Testing and other quality control techniques are used to the extent TI deems necessary to support this warranty Except where mandated by applicable law testing of all parameters of each component is not necessarily performed TI assumes no liability for applications assistance or the design of Buyers products Buyers are respo
250. ocumentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Changing the Compiler s Behavior with Options www ti com Table 2 17 Assembler Options Option Alias Effect Section keep_asm k Keeps the assembly language asm file Section 2 3 11 asm_listing al Generates an assembly listing file Section 2 3 11 c src interlist SS Interlists C source and assembly statements Section 2 12 Section 3 8 src_interlist S Interlists optimizer comments if available and assembly source Section 2 3 2 statements otherwise interlists C and assembly source statements absolute listing aa Enables absolute listing Section 2 3 11 asm define name def ad Sets the name symbol Section 2 3 11 asm dependency apd Performs preprocessing lists only assembly dependencies Section 2 3 11 asm includes api Performs preprocessing lists only included include files Section 2 3 11 asm_undefine name au Undefines the predefined constant name Section 2 3 11 copy_file filename ahc Copies the specified file for the assembly module Section 2 3 11 cross_reference ax Generates the cross reference file Section 2 3 11 include_file filename ahi Includes the specified file for the assembly module Section 2 3 11 no_const_clink Stops generation of clink directives for const global arrays Section 2 3 3 output_all_syms as Puts labels in the symbol table Section 2 3 11 syms_ignore_case ac Makes case insignif
251. odel option Defined to indicate that compiler conforms to ISO C Standard See Section 5 1 for exceptions to ISO C conformance C standard macro Defined to a 7 9 digit integer depending on if X has 1 2 or 3 digits The number does not contain a decimal For example version 3 2 1 is represented as 3002001 The leading zeros are dropped to prevent the number being interpreted as an octal Defined to 1 if the EABI is enabled see Section 2 13 otherwise it is undefined Defined if GCC extensions are enabled the gcc option is used otherwise it is undefined Deprecated Defined if strict ANSI ISO mode is enabled the strict_ansi option is used otherwise it is undefined Defined to 1 if fp mode strict is used or implied otherwise it is undefined Expands to the compilation time in the form hh mm ss Defined if char types are unsigned by default default or plain_char unsigned Defined when data model large is specified Indicates size t is an unsigned long INLINE Expands to 1 if optimization is used opt level or O option undefined otherwise Regardless of any optimization always undefined when no inlining is used Specified by the ISO standard You can use the names listed in Table 2 33 in the same manner as any other defined name For example printf s s TIME DATE translates to a line such as printf s ts 13 58 17 dan 14 1997 Using the C C Compil
252. of the libraries invoke mklib individually for each desired library SLAU132K September 2015 Using Run Time Support Functions and Building Libraries 159 Submit Documentation Feedback Copyright O 2015 Texas Instruments Incorporated Library Build Process 1 TEXAS INSTRUMENTS www ti com 7 4 2 2 3 Building Libraries With Custom Options You can build a library with any extra custom options desired This is useful for building a debugging version of the library or with silicon exception workarounds enabled The generated library is not a standard library and must not be placed in the lib directory It should be placed in a directory local to the project which needs it To build a debugging version of the library rts430 eabi lib change the working directory to the lib directory and run the command mklib pattern rts430 eabi lib name rts430 dbg lib install to Project Debug extra options g 7 4 2 2 4 The mklib Program Option Summary Run the following command to see the full list of options These are described in Table 7 1 160 mklib help Table 7 1 The mklib Program Options Option Effect index filename pattern filename all install tozdirectory compiler bin dirz directory name filename options sir extra_options sir list_libraries log filename tmpdir directory gmake filename parallel N query filename help or h quiet or q verbose o
253. ompiler uses the information that it has about the entire file to optimize your code as opposed to program level optimization where the compiler uses information that it has about the entire program to optimize your code function inlining The process of inserting code for a function at the point of call This saves the overhead of a function call and allows the optimizer to optimize the function in the context of the surrounding code global symbol A symbol that is either defined in the current module and accessed in another or accessed in the current module but defined in another high level language debugging The ability of a compiler to retain symbolic and high level language information such as type and function definitions so that a debugging tool can use this information indirect call A function call where one function calls another function by giving the address of the called function initialization at load time An autoinitialization method used by the linker when linking C C code The linker uses this method when you invoke it with the ram model link option This method initializes variables at load time instead of run time initialized section A section from an object file that will be linked into an executable object file input section A section from an object file that will be linked into an executable object file integrated preprocessor A C C preprocessor that is merged with the parser allow
254. on Global and static non const variables that are explicitly initialized init_array Table of constructors to be called at startup name load Compressed image of section name read only See the MSP430 Assembly Language Tools User s Guide for information on copy tables rodata Global and static variables that have const qualifiers TI noinit The pragma NOINIT causes a non initailized variable to be placed in the Tl noinit section The default Tl persistent linker command file places this section with bss See Section 5 11 19 for details about the NOINIT and PERSISTENT pragmas The pragma PERSISTENT causes an initialized variable to be placed in the Tl persistent section The default linker command file places this section with data Table 4 2 Uninitialized Sections Created by the Compiler Name Contents args Linker created section used to pass arguments from the command line of the loader to the program bss Uninitialized global and static variables cio Buffers for stdio functions from the run time support library Stack Function call frame stack sysmem Memory pool heap for dynamic memory allocation malloc etc When you link your program you must specify where to allocate the sections in memory In general initialized sections are linked into ROM or RAM uninitialized sections are linked into RAM With the exception of text the initialized and uninitialized sections created by the compiler cannot b
255. on 2 1 The compiler has straightforward calling conventions so you can write assembly and C functions that call each other For more information about calling conventions see Chapter 6 1 3 ANSI ISO Standard The compiler supports both the 1989 and 1999 versions of the C language and the 2003 version of the C language The C and C language features in the compiler are implemented in conformance with the following ISO standards e ISO standard C The C compiler supports the 1989 and 1999 versions of the C language C89 Compiling with the c89 option causes the compiler to conform to the ISO IEC 9899 1990 C standard which was previously ratified as ANSI X3 159 1989 The names C89 and C90 refer to the same programming language C89 is used in this document C99 Compiling with the c99 option causes the compiler to conform to the ISO IEC 9899 1999 C standard This standard supports several features not part of C89 such as inline functions new data types and one line comments beginning with The C language is also described in the second edition of Kernighan and Ritchie s The C Programming Language K amp R SO standard C Compiling with the c 03 option causes the C compiler to conform to the C Standard ISO IEC 14882 2003 The language is also described in Ellis and Stroustrup s The Annotated C Reference Manual ARM but this is not the standard The compiler also supports embedded C For a descrip
256. on that contains all scalar data The subsection is handled as one record during initialization which minimizes the overall size of the cinit section Example 6 10 Initialized Variables Defined in C int x short i 23 int p int a 5 1 2 3 4 5 Example 6 11 Initialized Information for Variables Defined in Example 6 10 global _x bss _x 4 4 sect cind3teo align 8 field CIR 8 32 field 170 32 field 23 16 Pareu sect text global I us usect bss c 2 2 sect socnagteo align 4 field x32 peo sect text global p _p usect bss c 4 4 sect ocxpit align 8 field IR 1 32 field _at0 32 field 1 32 a 0 e 0 field 2 32 a 1 32 field 3 32 a 2 64 field 4 32 Qa 3 96 field 5 32 a 4 128 IR 1 set 20 sect text global a bss a 20 4 BURN deese e deseo eoe koe ek eee ARE RARE ee aeg ede e ee e e X a eee de dee Je e dede ew ege Y dede ER ERE MARK THE END OF THE SCALAR INIT RECORD IN CINIT C d OEOKOEOEOKUKCRCEOKCKOROKOREWON OK NOR EORR OE OK RORIS ee RR ERRORS OE E OE e RO OE e NOE OK EO WOO OK Wo Oo oe Wo CIR sect conditio The cinit section must contain only initialization tables in this format When interfacing assembly language modules do not use the cinit section for any other purpose SLAU132K September 2015 Run Time Environment 139 Submit Documentation Feedback Copyright 2015 Texas
257. on_version mspx option to compile for MSP430X devices See Section 2 3 4 Function pointers are 20 bits See Section 5 6 and Table 6 2 The compiler supports a large code memory model while generating code for MSP430X devices See Section 6 1 1 The compiler supports a large data memory model while generating code for MSP430X devices See Section 6 1 2 Any assembly routines that interface with MSP430X C programs must fit the large code model See Section 6 6 1 Interrupt service routines must be placed into low memory See Section 6 7 4 Link with the rts430x lib or rts430x eh lib run time support library Run Time Environment SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated j Chapter 7 oc ER SLAU132K September 2015 Using Run Time Support Functions and Building Libraries Some of the features of C C such as I O dynamic memory allocation string operations and trigonometric functions are provided as an ANSI ISO C C standard library rather than as part of the compiler itself The TI implementation of this library is the run time support library RTS The C C compiler implements the ISO standard library except for those facilities that handle exception conditions signal and locale issues properties that depend on local language nationality or culture Using the ANSI ISO standard library ensures a consistent set of functions that provide for greater porta
258. ons below the pragma The syntax of the pragmas in C C is pragma SET CODE SECTION section name pragma SET DATA SECTION section name In Example 5 11 x and y are put in the section mydata To reset the current section to the default used by the compiler a blank parameter should be passed to the pragma An easy way to think of the pragma is that it is like applying the CODE SECTION or DATA SECTION pragma to all symbols below it Example 5 11 Setting Section With SET DATA SECTION Pragma pragma SET DATA SECTION mydata int x int y pragma SET DATA SECTION The pragmas apply to both declarations and definitions If applied to a declaration and not the definition the pragma that is active at the declaration is used to set the section for that symbol Here is an example Example 5 12 Setting a Section With SET CODE SECTION Pragma pragma SET CODE SECTION funcl extern void funcl pragma SET CODE SECTION void funcl In Example 5 12 func1 is placed in section func1 If conflicting sections are specified at the declaration and definition a diagnostic is issued The current CODE SECTION and DATA SECTION pragmas and GCC attributes can be used to override the SET CODE SECTION and SET DATA SECTION pragmas For example Example 5 13 Overriding SET DATA SECTION Setting pragma DATA SECTION x x data pragma SET DATA SECTION mydata int X int y
259. onst volatile and register It also supports all of the standard C99 keywords including inline and restrict It also supports TI extension keywords interrupt and __asm Some keywords are not available in strict ANSI mode The following keywords may appear in other target documentation and require the same treatment as the interrupt and restrict keywords trap reentrant cregister SLAU132K September 2015 MSP430 C C Language Implementation 83 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Keywords www ti com 5 71 The const Keyword The C C compiler supports the ANSI ISO standard keyword const in all modes except K amp R compatibility mode kr_compatible This keyword gives you greater optimization and control over allocation of storage for certain data objects You can apply the const qualifier to the definition of any variable or array to ensure that its value is not altered Global objects qualified as const are placed in the const section The linker allocates the const section from ROM or FLASH which are typically more plentiful than RAM The const data storage allocation rule has two exceptions If the keyword volatile is also specified in the definition of an object for example volatile const int x Volatile keywords are assumed to be allocated to RAM The program is not allowed to modify a const volatile object but something external to the pro
260. op directives A pop directive with no prior push results in a warning diagnostic from the compiler The maximum alignment of all fields declared is n Valid values for n are 1 2 4 8 and 16 bytes pragma PACK show 100 MSP430 C C Language Implementation SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Pragma Directives The above form of the PACK pragma sends a warning diagnostic to stderr to record the current state of the pack pragma stack You can use this form while debugging For more about packed fields see Section 5 16 4 5 11 22 The RESET_MISRA Pragma The RESET_MISRA pragma resets the specified MISRA C 2004 rules to the state they were before any CHECK_MISRA pragmas see Section 5 11 2 were processed For instance if a rule was enabled on the command line but disabled in the source the RESET_MISRA pragma resets it to enabled This pragma accepts the same format as the check_misra option except for the none keyword The syntax of the pragma in C is pragma RESET MISRA all required advisory rulespec The rulespec parameter is a comma separated list of rule numbers See Section 5 3 for details 5 11 23 The RESET ULP Pragma The RESET ULP pragma resets the specified ULP Advisor rules to the state they were before any CHECK ULP pragmas see Section 5 11 3 were processed For instance i
261. options to the compiler the vendor will need to provide some other means of discovering the information such as a configuration file written by a wizard run from inside CCS The vendor supplied mklib must at least accept all of the options listed in Table 7 1 without error even if they do not do anything SLAU132K September 2015 Using Run Time Support Functions and Building Libraries 161 Submit Documentation Feedback Copyright O 2015 Texas Instruments Incorporated j Chapter 8 MEE MENTIS SLAU132K September 2015 C Name Demangler The C compiler implements function overloading operator overloading and type safe linking by encoding a function s prototype and namespace in its link level name The process of encoding the prototype into the linkname is often referred to as name mangling When you inspect mangled names such as in assembly files disassembler output or compiler or linker diagnostic messages it can be difficult to associate a mangled name with its corresponding name in the C source code The C name demangler is a debugging aid that translates each mangled name it detects to its original name found in the C source code These topics tell you how to invoke and use the C name demangler The C name demangler reads in input looking for mangled names All unmangled text is copied to output unaltered All mangled names are demangled before being copied to output Topic Page 8 1 Invoking the C Name
262. or less are passed by value either in registers or on the stack Structures and unions larger than 32 bits are passed by reference In this way the caller can be smart about telling the called function where to return the structure For example in the statement s func x where s is a structure and f is a function that returns a structure the caller can simply pass the address of s as the first argument and call f The function f then copies the return structure directly into s performing the assignment automatically You must be careful to properly declare functions that return structures both at the point where they are called so the caller properly sets up the first argument and at the point where they are declared so the function knows to copy the result The called function deallocates the frame and argument block by adding the constant computed in Step 3 The called function restores all registers saved in Step 2 The called function func returns SLAU132K September 2015 Run Time Environment 123 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Function Structure and Calling Conventions www ti com The following example is typical of how a called function responds to a call func Called function entry point PUSH W r10 PUSH W r9 Save SOE registers SUB W 2 SP Allocate the frame Body of function ADD W 2 SP Deallocate the frame POP r9 Restore S
263. or you See Section 4 3 1 for further information When a library is linked the linker includes only those library members required to resolve undefined references For more information about linking see the MSP430 Assembly Language Tools User s Guide C C and mixed C and C programs can use the same run time support library Run time support functions and variables that can be called and referenced from both C and C will have the same linkage 7 1 2 Header Files You must use the header files provided with the compiler run time support when using functions from C C standard library Set the MSP C DIR environment variable to the absolute path of the include directory in the compiler release 7 1 3 Modifying a Library Function 142 You can inspect or modify library functions by examining the source code in the lib src subdirectory of the compiler installation For example C ti ccsv6 tools compiler msp430_ lib src One you have located the relevant source code change the specific function file and rebuild the library You can use this source tree to rebuild the rts430 lib library or to build a new library See Section 7 4 for details on building Using Run Time Support Functions and Building Libraries SLAU132K September 2015 Submit Documentation Feedback Copyright O 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com C and C Run Time Support Libraries 7 1 4 Support for String Handling
264. orated 1 TEXAS INSTRUMENTS Program Level Optimization program level compile and opt level 3 options www ti com 3 3 3 3 1 56 Program Level Optimization program_level_compile and opt_level 3 options You can specify program level optimization by using the program_level_compile option with the opt_level 3 option aliased as O3 If you use opt_level 4 O4 the program_level_compile option cannot be used because link time optimization provides the same optimization opportunities as program level optimization With program level optimization all of your source files are compiled into one intermediate file called a module The module moves to the optimization and code generation passes of the compiler Because the compiler can see the entire program it performs several optimizations that are rarely applied during file level optimization fa particular argument in a function always has the same value the compiler replaces the argument with the value and passes the value instead of the argument e If areturn value of a function is never used the compiler deletes the return code in the function e lfafunction is not called directly or indirectly by main the compiler removes the function The program level compile option requires use of opt level 3 or higher in order to perform these optimizations To see which program level optimizations the compiler is applying use the gen opt level 2 option
265. ore the calling function must save them if their values need to be preserved e Save on entry registers Registers R4 R10 It is the called function s responsibility to preserve the values in these registers If the called function modifies these registers it saves them when it gains control and preserves them when it returns control to the calling function Figure 6 2 illustrates a typical function call In this example arguments are passed to the function and the function uses local variables and calls another function The first four arguments are passed to registers R12 R15 This example also shows allocation of a local frame and argument block for the called function Functions that have no local variables and do not require an argument block do not allocate a local frame Figure 6 2 Use of the Stack During a Function Call Move arguments to argument block Allocate new frame and Before call call function argument block Low Low Callee s argument block Callee s local variables Register save area sp argument Argument 1 gt register R12 Argument 5 block argument n Argument 2 register R13 argument n Argument 3 register R14 Caller s Caller s Argument 4 gt register R15 Caller s local variables local variables local variables Register Register High save area save area High save area Legend SP stack pointer Caller s Argument 5 Run Time Environment SLAU132K September 2015
266. orming link time optimization Those files that were not compiled with opt level 4 do not participate in the optimization Source files can be compiled with different option sets With program level compilation all source files must be compiled with the same option set With link time optimization files can be compiled with different options If the compiler determines that two options are incompatible it issues an error Option Handling When performing link time optimization source files can be compiled with different options When possible the options that were used during compilation are used during link time optimization For options which apply at the program level auto_inline for instance the options used to compile the main function are used If main is not included in link time optimization the option set used for the first object file specified on the command line is used Some options opt for speed for instance can affect a wide range of optimizations For these options the program level behavior is derived from main and the local optimizations are obtained from the original option set Some options are incompatible when performing link time optimization These are usually options which conflict on the command line as well but can also be options that cannot be handled during link time optimization Optimizing Your Code SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incor
267. ors The integer divides are rewritten as a multiply with the reciprocal of the divisor This occurs at optimization level 2 opt_level 2 or O2 and higher You must also compile with the opt for speed option which selects compile for speed SLAU132K September 2015 Optimizing Your Code 65 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated F Chapter 4 l MEE MENTIS SLAU132K September 2015 Linking C C Code The C C compiler and assembly language tools provide two methods for linking your programs You can compile individual modules and link them together This method is especially useful when you have multiple source files You can compile and link in one step This method is useful when you have a single source module This chapter describes how to invoke the linker with each method It also discusses special requirements of linking C C code including the run time support libraries specifying the type of initialization and allocating the program into memory For a complete description of the linker see the MSP430 Assembly Language Tools User s Guide Topic Page 4 4 Invoking the Linker Through the Compiler z Option Lsseessss 67 4 2 Linker Code Optimizations aeaea a ee E a Terea aE e stan 69 4 3 ConNtrollingthelEinkingi Process eee MES 69 66 Linking C C Code SLAU132K September 2015 Submit Documentation Feedback
268. oth plain ASCII so the mapping between them is one to one This behavior can be modified using the multibyte chars option 6 4 4 4 5 1 1 2 The compiler currently supports only one locale C 6 4 4 4 The compiler currently supports only one locale C 6 4 5 J 3 5 Integers No extended integer types are provided 6 2 5 Integer types are represented as two s complement and there are no trap representations 6 2 6 2 No extended integer types are provided so there is no change to the integer ranks 6 3 1 1 Whenan integer is converted to a signed integer type which cannot represent the value the value is truncated without raising a signal by discarding the bits which cannot be stored in the destination type the lowest bits are not modified 6 3 1 3 Right shift of a signed integer value performs an arithmetic signed shift The bitwise operations other than right shift operate on the bits in exactly the same way as on an unsigned value That is after the usual arithmetic conversions the bitwise operation is performed without regard to the format of the SLAU132K September 2015 MSP430 C C Language Implementation 77 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Characteristics of MSP430 C www ti com 78 integer type in particular the sign bit 6 5 J 3 6 Floating point The accuracy of floating point operations is bit exact
269. ple 7 2 does the following Adds the device mydevice to the device table Opens a file named test on that device and associates it with the FILE pointer fid Writes the string Hello world into the file Closes the file Example 7 2 illustrates adding and using a device for C I O Example 7 2 Program for C I O Device include lt file h gt include lt stdio h gt RK RIK KK KK IK KK II I I II A II RR IIA k k IIA II I k k k k k kk k k k I A kk k k kk k k Declarations of the user defined device drivers a E E K k k k k e e e e k e e k e e kk e k k A k k e k k k kk k Ak k A k k k k k k kk k k k k k k k k kk k k k k k kk k kk k kk k kk k k kk k k f extern int MYDEVICE_open const char path unsigned flags int fno extern int MYDEVICE_close int fno extern int MYDEVICE_read int fno char buffer unsigned count extern int MYDEVICE_write int fno const char buffer unsigned count extern off_t MYDEVICE_lseek int fno off_t offset int origin extern int MYDEVICE unlink const char path extern int MYDEVICE rename const char old name char new name main FILE fid add device mydevice _MSA MYDEVICE open MYDEVICE close MYDEVICE read MYDEVICE write MYDEVICE lseek MYDEVICE unlink MYDEVICE rename fid fopen mydevice test w fprintf fid Hello world n fclose fid 156 Using Run Time Support Functions and Building Libraries SLAU132K September 2015 Submit Documentatio
270. porated 1 TEXAS INSTRUMENTS www ti com Link Time Optimization opt_level 4 Option 3 4 2 Incompatible Types During a normal link the linker does not check to make sure that each symbol was declared with the same type in different files This is not necessary during a normal link When performing link time optimization however the linker must ensure that all symbols are declared with compatible types in different source files If a symbol is found which has incompatible types an error is issued The rules for compatible types are derived from the C and C standards 3 5 Accessing Aliased Variables in Optimized Code Aliasing occurs when a single object can be accessed in more than one way such as when two pointers point to the same object or when a pointer points to a named object Aliasing can disrupt optimization because any indirect reference can refer to another object The optimizer analyzes the code to determine where aliasing can and cannot occur then optimizes as much as possible while still preserving the correctness of the program The optimizer behaves conservatively If there is a chance that two pointers are pointing to the same object then the optimizer assumes that the pointers do point to the same object The compiler assumes that if the address of a local variable is passed to a function the function changes the local variable by writing through the pointer This makes the local variable s address unavailable for use e
271. pragma SET DATA SECTION In Example 5 13 x is placed in x data and y is placed in mydata No diagnostic is issued for this case The pragmas work for both C and C In C the pragmas are ignored for templates and for implicitly created objects such as implicit constructors and virtual function tables 102 MSP430 C C Language Implementation SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Pragma Directives 5 11 26 The vector Pragma The vector pragma indicates that the function that follows is to be used as the interrupt vector routine for the listed vectors The syntax of the pragma is pragma vector veci vec2 vec3 The vector pragma requires linker command file support The command file must specify output sections for each interrupt vector of the form intxx where xx is the number of the interrupt vector The output sections must map to the physical memory location of the appropriate interrupt vector The standard linker command files are set up to handle the vector pragma See Section 6 7 4 If you do not specify an ISR routine for some interrupt vectors an ISR routine will be provided for those vectors from the RTS library and the RTS library will automatically be linked with your application The default ISR routine puts the device in low power mode You can override the ISR provided by the RTS with the unu
272. quire many manual operations See the MSP430 Assembly Language Tools User s Guide The cross reference lister uses object files to produce a cross reference listing showing symbols their definitions and their references in the linked source files See the MSP430 Assembly Language Tools User s Guide The C name demangler is a debugging aid that converts names mangled by the compiler back to their original names as declared in the C source code As shown in Figure 1 1 you can use the C name demangler on the assembly file that is output by the compiler you can also use this utility on the assembler listing file and the linker map file See Chapter 8 The disassembler decodes object files to show the assembly instructions that they represent See the MSP430 Assembly Language Tools User s Guide The main product of this development process is an executable object file that can be executed in a MSP430 device Introduction to the Software Development Tools SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Compiler Interface 1 2 Compiler Interface The compiler is a command line program named cl430 This program can compile optimize assemble and link programs in a single step Within Code Composer Studio the compiler is run automatically to perform the steps needed to build a project For more information about compiling a program see Secti
273. r On some devices DEV close may need to be responsible for checking if this is the last file descriptor pointing to a file that was unlinked If so it is responsible for ensuring that the file is actually removed from the device and the resources reclaimed if appropriate This function should return 1 to indicate an error if the file descriptor is invalid in some way such as being out of range or already closed but this is not required The user should not call close with an invalid file descriptor Read Characters from a File int DEV read int dev fd char buf unsigned count The read function reads count bytes from the input file associated with dev fd The dev fdis the number assigned by open to an opened file The bufis where the read characters are placed The countis the number of characters to read from the file This function must return 1 to indicate an error if for some reason no bytes could be read from the file This could be because of an attempt to read from a O WRONLY file or for device specific reasons If count is 0 no bytes are read and this function returns 0 This function returns the number of bytes read from O to count 0 indicates that EOF was reached before any bytes were read It is not an error to read less than count bytes this is common if the are not enough bytes left in the file or the request was larger than an internal device buffer size Write Characters to a File i
274. r v The index library libc a for this release Used to find a template library for custom builds and to find the source files in the lib src subdirectory of the compiler installation REQUIRED Pattern for building a library If neither extra_options nor options are specified the library will be the standard library with the standard options for that library If either extra_options or options are specified the library is a custom library with custom options REQUIRED unless all is used Build all standard libraries at once The directory into which to write the library For a standard library this defaults to the same directory as the index library libc a For a custom library this option is REQUIRED The directory where the compiler executables are When invoking mklib directly the executables should be in the path but if they are not this option must be used to tell mklib where they are This option is primarily for use when mklib is invoked by the linker File name for the library with no directory part Only useful for custom libraries Options to use when building the library The default options see below are replaced by this string If this option is used the library will be a custom library Options to use when building the library The default options see below are also used If this option is used the library will be a custom library List the libraries this script is capable of building and exit o
275. r auto inlined functions Section 2 14 single inline Inlines functions that are only called once Section 2 11 aliased variables ma Assumes variables are aliased Section 3 5 Note Machine specific options see Table 2 14 can also affect optimization Table 2 4 Debug Options Option Alias Effect Section symdebug dwarf g Default behavior Enables symbolic debugging The generation of Section 2 3 5 debug information no longer impacts optimization Therefore Section 3 9 generating debug information is enabled by default If you explicitly use the g option but do not specify an optimization level no optimization is performed symdebug none Disables all symbolic debugging Section 2 3 5 Section 3 9 symdebug skeletal Deprecated has no effect optimize with debug mn Deprecated has no effect Table 2 5 Advanced Debug Options Option Alias Effect Section symdebug keep all types Keep unreferenced type information Section 2 3 5 Table 2 6 Include Options Option Alias Effect Section include path directory i Adds the specified directory to the include search path Section 2 5 2 1 preinclude filename Includes filename at the beginning of compilation Section 2 3 3 Table 2 7 ULP Advisor Options Option Alias Effect Section advice power all none rulespec Enables checking the specified ULP Advisor rules Default is all Section 2 3 3 advice power_severity error Sets the diagnostic severity for ULP Advisor rules Section
276. raries 153 Submit Documentation Feedback Copyright O 2015 Texas Instruments Incorporated The C I O Functions 7 2 4 Adding a User Defined Device Driver for C I O l TEXAS INSTRUMENTS www ti com The function add_device allows you to add and use a device When a device is registered with add device the high level I O routines can be used for I O on that device You can use a different protocol to communicate with any desired device and install that protocol using add_device however the HOST functions should not be modified The default streams stdin stdout and stderr can be remapped to a file on a user defined device instead of HOST by using freopen as in Example 7 1 If the default streams are reopened in this way the buffering mode will change to IOFBF fully buffered To restore the default buffering behavior call setvbuf on each reopened file with the appropriate value _IOLBF for stdin and stdout IONBF for stderr The default streams stdin stdout and stderr can be mapped to a file on a user defined device instead of HOST by using freopen as shown in Example 7 1 Each function must set up and maintain its own data structures as needed Some function definitions perform no action and should just return Example 7 1 Mapping Default Streams to Device include lt stdio h gt include lt file h gt include mydevice h void main add device mydevice MSA MYDEVICE open MYDEVICE close MYDEVICE r
277. rator for Timer A TAIV MSP430 vector generator values are mapped to an interrupt source and are characterized in that they fall within a specific range and can only take on even values A common way to handle a particular interrupt source represented in a vector generator is to use a switch statement However a compiler is constrained by the C language in that it can make no assumptions about what values a switch expression may have The compiler will have to generate code to handle every possible value which leads to what would appear to be inefficient code The never executed intrinsic can be used to assert to the compiler that a switch expression can only take on values represented by the case labels within a switch block Having this assertion the compiler can avoid generating test code for handling values not specified by the switch case labels Having this assertion is specifically suited for handling values that characterize a vector generator Example 6 8 illustrates a switch block that handles the values of the Timer B TBIV vector generator Example 6 8 TBIV Vector Generator interrupt void Timer B1 void switch TBIV case 0 break Do nothing case 2 TBCCR1 255 state 1 break case 4 TBCCRO 254 TBCCR1 159 state 200 break case 6 break case 8 break case 10 break case 12 break case 14 break default never executed In Example 6 8 using the never executed in
278. rdinary system specific directory Save the build log as filename Use directory for scratch space instead of the ordinary system specific directory Gmake compatible program to invoke instead of gmake Compile N files at once gmake j N Does this script know how to build FILENAME Display this help Operate silently Extra information to debug this executable Examples To build all standard libraries and place them in the compiler s library directory mklib all index C DIR lib To build one standard library and place it in the compiler s library directory mklib pattern rts430 eabi lib index C DIR lib To build a custom library that is just like rts430 eabi lib but has symbolic debugging support enabled mklib pattern zrts430 eabi lib extra options g index C DIR lib install to Project Debug name rts430 debug lib Using Run Time Support Functions and Building Libraries SLAU132K September 2015 Submit Documentation Feedback Copyright O 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS www ti com Library Build Process 7 4 3 Extending mklib The mklib API is a uniform interface that allows Code Composer Studio to build libraries without needing to know exactly what underlying mechanism is used to build it Each library vendor e g the TI compiler provides a library specific copy of mklib in the library directory that can be invoked which understands a standardized set of options
279. read write data must be located in the first 64K of memory See Section 6 1 3 for details plain_char unsigned signed Specifies how to treat C C plain char variables Default is unsigned ramfunc on off If set to on specifies that all functions should be placed in the Tl ramfunc section which is placed in RAM If set to off only functions with the ramfunc function attribute are treated this way See Section 5 16 2 Newer TI linker command files support the ramfunc option automatically by placing functions in the Tl ramfunc section If you have a linker command file that does not include a section specification for the Tl ramfunc section you can modify the linker command file to place this section in RAM See the MSP430 Assembly Language Tools User s Guide for details on section placement silicon version Selects the instruction set version Using silicon_version mspx generates code for MSP430X devices 20 bit code addressing Using silicon_version msp generates code for 16 bit MSP430 devices Modules assembled compiled for 16 bit MSP430 devices are not compatible with modules that are assembled compiled for 20 bit MSPx devices The linker generates errors if an attempt is made to combine incompatible object files 32 Using the C C Compiler SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com small enum use hw mpy
280. reen summary of the options enter cl430 with no parameters on the command line The following apply to the compiler options There are typically two ways of specifying a given option The long form uses a two hyphen prefix and is usually a more descriptive name The short form uses a single hyphen prefix and a combination of letters and numbers that are not always intuitive Options are usually case sensitive Individual options cannot be combined An option with a parameter should be specified with an equal sign before the parameter to clearly associate the parameter with the option For example the option to undefine a constant can be expressed as undefine name Likewise the option to specify the maximum amount of optimization can be expressed as O 3 You can also specify a parameter directly after certain options for example O3 is the same as O 3 No space is allowed between the option and the optional parameter so O 3 is not accepted Files and options except the run linker option can occur in any order The run linker option must follow all compiler options and precede any linker options You can define default options for the compiler by using the MSP430 C OPTION environment variable For a detailed description of the environment variable see Section 2 4 1 Table 2 9 through Table 2 31 summarize all options including link options Use the references in the tables for more complete descriptions of the options
281. rocessing preproc with compile Option 41 2 5 6 Generating a Preprocessed Listing File with Comments preproc with comment Option 41 2 5 7 Generating Preprocessed Listing with Line Control Details preproc with line Option 42 2 5 8 Generating Preprocessed Output for a Make Utility preproc dependency Option 42 2 5 9 Generating a List of Files Included with include preproc includes Option 42 2 5 10 Generating a List of Macros in a File preproc macros Option 0cseceeeeeeeeeeeeee eee eeeeeeeeeees 42 2 6 Passing Argument to M iN 2 ceceeeceteeeneee nee ence eee eene snnm hh nhanh nea nma ann anna ananas nne ener 42 2 7 Understanding Diagnostic Messages cessseeeeen nn I IH HI He hh n nhe nnn nne nen 43 2 7 1 Controlling Diagnostic Messages ceee eee eee eee III HII mH menn nnne 44 2 7 2 How You Can Use Diagnostic Suppression Options ceeeeeeeeeere HI 45 2 8 Other MCSSAGES e E c 46 2 9 Generating Cross Reference Listing Information gen acp xref Option esee eene 46 2 10 Generating a Raw Listing File gen acp raw Option eeseeeeee HH 46 2 11 Using Inline Function Expansion sees nm mH mI HI HI ee hne nnnm enn nnn 48 2 Contents SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporate
282. ronment where a global state is accessed and thus needs to be protected with a critical section there are calls to the function _lock This calls the provided primitive if installed and acquires the semaphore before proceeding Once the critical section is finished unlock is called to release the semaphore Usually SYS BIOS is responsible for creating and installing the primitives so you do not need to take any action However this mechanism can be used in multi threaded applications that do not use the SYS BIOS locking mechanism You should not define the functions _lock and _unlock functions directly instead the installation functions are called to instruct the run time support environment to use these new primitives void register lock void lock 0 void register unlock void unlock The arguments to register lock and register unlock should be functions which take no arguments and return no values and which implement some sort of global semaphore locking extern volatile sig atomic t sema SHARED SEMAPHORE LOCATION static int sema depth 0 static void my lock void while ATOMIC TEST AND SET sema MY UNIQUE ID MY UNIQUE ID sema depth t static void my unlock void if sema depth ATOMIC CLEAR sema The run time support nests calls to lock so the primitives must keep track of the nesting level SLAU132K September 2015 Using Run Time Support Functions and Building Libraries
283. rsion 3 DWARF Debugging Information Format Workgroup Free Standards Group 2005 http dwarfstd org System V ABI specification http www sco com developers gabi 10 Head This First SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Related Documentation From Texas Instruments Related Documentation From Texas Instruments See the following resources for further information about the TI Code Generation Tools Texas Instruments Wiki Compiler topics Texas Instruments E2E Community Compiler forum You can use the following documents to supplement this user s guide SLAU131 MSP430 Assembly Language Tools User s Guide Describes the assembly language tools the assembler linker and other tools used to develop assembly language code assembler directives macros object file format and symbolic debugging directives for the MSP430 devices SLAA534 MSP430 Embedded Application Binary Interface Application Report Specifies the ELF based ABI for MSP430 processors The ABI is a broad standard that specifies the low level interface between tools programs and program components SLAU049 MSP430x1xx Family User s Guide Describes the MSP430x1xx CPU architecture instruction set pipeline and interrupts for these ultra low power microcontrollers SLAU144 MSP430x2xx Family User s Guide Describes the MSP430x2xx CPU archite
284. s The misra_required option sets the diagnostic severity for required MISRA C 2004 rules The misra advisory option sets the diagnostic severity for advisory MISRA C 2004 rules The syntax for these options is misra_advisory error warning remark suppress misra_required error warning remark suppress 5 4 Using the ULP Advisor You can get feedback about your code from the ULP Ultra Low Power Advisor For detailed information about the ULP rules see www ti com ulpadvisor You can enable disable the rules using any of the following Using multiple advice options on the command line is permitted The advice power option lets you specify which rules to check The advice power_severity option lets you specify whether ULP Advisor rule violations are errors warnings remarks or not reported The CHECK ULP pragma enables disables ULP Advisor rules at the source level This pragma is equivalent to using the advice power option See Section 5 11 3 The RESET ULP pragma resets the specified ULP Advisor rules to their state before any CHECK ULP pragmas were processed See Section 5 11 23 The advice power option enables checking specified ULP Advisor rules The syntax is advice power all none ru espec The rulespec parameter is a comma separated list of rule numbers to enable For example advice power 1 1 7 2 7 3 7 4 enables rules 1 1 7 2 7 3 and 7
285. s 1 1 MSP430 Software Development FIOW 0 ccceeeeee ence eee eee eee neces eee e eee Ie mne nem nennen nenne nnne 13 0 1 Memory Layout Of Val sicesiasacuevinieeauua vee rave abavebdndeuueiedeuets vn idusGauensuduevabadiaet Var Xa a ek UA sauna 120 6 2 Use of the Stack During a Function Calll ceceeseeeeeeeeeeeeeeeeeeeeeeeeeeeeeeneeeeeeeeeeeenaeeeeeeneeeeqanees 122 6 3 Autoinitialization at Run Time cece cece eee eee eee e ee ee nn n m nnn meme EE 135 6 4 lnitialization at Load TIME cuisse corren aene kae rt rtu rimua Panorama sa nipnie diu aaa o RR REX ERe DrE AERE R FR YE vines 137 6 5 IGONMSUIUCIOF Table e M 138 6 6 Format of Initialization Records in the cinit Section cceeee eee eee eee eee eee ee eee sees eeeeeeeeaeeeeeeeeeeeeaeee 138 6 7 Format of Initialization Records in the pinit Section ceeee eee e ee eee eee eee ee eee eee ee IH 140 List of Tables 2 l Processor Options 2 52 Ere eR E Du xREUMR EEEO EEA A EE a PUN ONAI EM MM CE 19 2 2 Optimization OPTIONS sss esie cesiepu UE Dese nues uma eee UE IR eaten DE DUE E DU EUER M EDS DM UN DE DEM LED UE 19 2 3 Advanced Optimizatiorn ODIlIOFIS s cucina nione a aere diee irmoaimele sicud ea sei deie sca E Dee Ie citu 20 2 4 Debug OPtiONS S 20 2 5 Advanced Debug Options eese ern reru rur enun rue Run a WiN mra a Wi Ea RR EREN ENNS SER a 20 2 6 lhnol de OplODS wee tetrad ide
286. s The HOST device driver is automatically used for the default C streams stdin stdout and stderr The HOST device driver shares a special protocol with the debugger running on a host system so that the host can perform the C I O requested by the program Instructions for C I O operations that the program wants to perform are encoded in a special buffer named _CIOBUF_ in the cio section The debugger halts the program at a special breakpoint C 1O reads and decodes the target memory and performs the requested operation The result is encoded into CIOBUF the program is resumed and the target decodes the result The HOST device is implemented with seven functions HOSTopen HOSTclose HOSTread HOSTwrite HOSTIseek HOSTunlink and HOSTrename which perform the encoding Each function is called from the low level I O function with a similar name A device driver is composed of seven required functions Not all function need to be meaningful for all devices but all seven must be defined Here we show the names of all seven functions as starting with DEV but you may choose any name except for HOST 150 Using Run Time Support Functions and Building Libraries SLAU132K September 2015 Submit Documentation Feedback Copyright O 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com DEV open Syntax Description Return Value SLAU132K September 2015 DEV open Open File for I O Open File for I O int D
287. s are enabled during inlined hardware multiplication If inlining is not enabled but other optimization is enabled opt for speed is set to 1 2 or 3 using this option causes the linker to replace all references to the default multiply routine with the version of the multiply routine that uses the hardware multiplier support The optional argument indicates which version of the hardware multiply is being used and must be one of the following 16 uses the F1xx 2xx 4xx family 16 bit hardware multiplier default 32 uses the F4xx 32 bit hardware multiplier F5 uses the F5xx 6xx family 32 bit hardware multiplier none does not use a hardware multiplier For more information regarding the hardware multiplier see the Family User s Guide for the MSP430x1 xx MSP430x3xx MSP430x4xx and MSP430x5xx The following options are used to select symbolic debugging symdebug dwarf Default Generates directives that are used by the C C source level debugger and enables assembly source debugging in the assembler The symdebug dwarf option s short form is g See Section 3 9 For more information on the DWARF debug format see The DWARF Debugging Standard symdebug none Disables all symbolic debugging output This option is not recommended it prevents debugging and most performance analysis capabilities symdebug skeletal Deprecated Has no effect See Section 2 3 12 for a list of deprecated symbolic debugging options SLAU1
288. se 1 true Bool C99 8 bits 8 Binary 0 false 1 true bool C 8 bits 8 Binary 0 false 1 true short signed short 16 bits 16 2s complement 32 768 32 767 unsigned short 16 bits 16 Binary 0 65 535 int signed int 16 bits 16 2s complement 32 768 32 767 unsigned int 16 bits 16 Binary 0 65 535 long signed long 32 bits 16 2s complement 2 147 483 648 2 147 483 647 unsigned long 32 bits 16 Binary 0 4 294 967 295 long long signed long long 64 bits 16 2s complement 9 223 372 036 854 9 223 372 036 854 775 808 775 807 unsigned long long 64 bits 16 Binary 0 18 446 744 073 709 551 615 enum varies 16 2s complement varies varies float 32 bits 16 IEEE 32 bit 1 175 494e 38 3 40 282 346e 38 double 64 bits 16 IEEE 64 bit 2 22 507 385e 308 1 79 769 313e 308 long double 64 bits 16 IEEE 64 bit 2 22 507 385e 308 9 1 79 769 313e 308 function and data pointers varies see 16 Table 5 2 Plain char has the same representation as either signed char or unsigned char The plain char option specifies whether plain char is signed or unsigned The default is unsigned For details about the size of an enum type see Section 5 6 1 9 Figures are minimum precision The char type is unsigned by default This is in contrast to the signed char and unsigned char types which specify their sign behavior You can change the default for the char type using the plain charzsigned compiler option The additional types from C C99 and C are defined
289. sed interrupts keyword as follows pragma vector unused interrupts interrupt void user trap function void code for handling all interrupts that do not have specific ISRs The even in range intrinsic provides a hint to the compiler when generating switch statements for interrupt vector routines The intrinsic is usually used as follows switch even in range x NUM The even in range intrinsic returns the value x to control the switch statement but also tells the compiler that x must be an even value in the range of 0 to NUM inclusive Interrupt service routine ISR warning NOTE The linker emits a warning for any device specific interrupts that do not have an associated interrupt service routine However a default vector handler is now provided by the run time support RTS library so you should not see this error if you are linking with the provided RTS library For more details see the MSP430 Assembly Language Tools User s Guide section for the intvec directive SLAU132K September 2015 MSP430 C C Language Implementation 103 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS The Pragma Operator www ti com 5 12 The Pragma Operator 104 The MSP430 C C compiler supports the C99 preprocessor _Pragma operator This preprocessor operator is similar to pragma directives However _Pragma can be used in preprocessing macros defines
290. see Section 4 1 For details on linking conventions for EABI used with rom_model and ram_model see Section 6 9 3 3 and Section 6 9 3 5 respectively NOTE Boot Loader A loader is not included as part of the C C compiler tools See the Program Loading and Running chapter of the MSP430 Assembly Language Tools User s Guide for more about boot loading Linking C C Code SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Controlling the Linking Process 4 3 8 Specifying Where to Allocate Sections in Memory The compiler produces relocatable blocks of code and data These blocks called sections are allocated in memory in a variety of ways to conform to a variety of system configurations See Section 6 1 4 for a complete description of how the compiler uses these sections The compiler creates two basic kinds of sections initialized and uninitialized Table 4 1 summarizes the initialized sections Table 4 2 summarizes the uninitialized sections Table 4 1 Initialized Sections Created by the Compiler Name Contents binit Boot time copy tables See the Assembly Language Tools User s Guide for information on BINIT in linker command files mspabi exidx Index table for exception handling read only see exceptions option mspabi extab data Unwinded instructions for exception handling read only see exceptions opti
291. see the entire program several optimizations are performed with program level optimization that are rarely applied during file level optimization prolog The portion of code in a function that sets up the stack push An operation that places a data object on a stack for temporary storage quiet run An option that suppresses the normal banner and the progress information raw data Executable code or initialized data in an output section relocation A process in which the linker adjusts all the references to a symbol when the symbol s address changes run time environment The run time parameters in which your program must function These parameters are defined by the memory and register conventions stack organization function call conventions and system initialization run time support functions Standard ISO functions that perform tasks that are not part of the C language such as memory allocation string conversion and string searches Glossary SLAU132K September 2015 Submit Documentation Feedback Copyright O 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Appendix A run time support library A library file rts src which contains the source for the run time support functions section A relocatable block of code or data that ultimately will be contiguous with other sections in the memory map sign extend A process that fills the unused MSBs of a value with the value s sig
292. sets up the initial value of the stack pointer SP 2 It initializes global variables by copying the data from the initialization tables to the storage allocated for the variables in the bss section If you are initializing variables at load time ram model option a loader performs this step before the program runs it is not performed by the boot routine For more information see Section 6 9 3 3 Executes the global constructors found in the global constructors table For more information see Section 6 9 3 6 4 Calls the main function to run the C C program You can replace or modify the boot routine to meet your system requirements However the boot routine must perform the operations listed above to correctly initialize the C C environment System Pre Initialization The c intOO initialization routine also provides a mechanism for an application to perform the setup set I O registers enable disable timers etc before the C C environment is initialized Before calling the routine that initializes C C global data and calls any C constructors the boot routine makes a call to the function system pre init A developer can implement a customized version of system pre init to perform any application specific initialization before proceeding with C C environment setup In addition the default C C data initialization can be bypassed if system pre init returns a 0 By default system pre init should retur
293. ssembly file as comments Using the c src interlist option can cause performance and or code size degradation Example 2 1 shows a typical interlisted assembly file For more information about using the interlist feature with the optimizer see Section 3 8 Example 2 1 An Interlisted Assembly Language File FRR NRA IR BW BRE REI IB BERS e ore e e DR KI SKI KORR Ke OK SKK REIR SCR KK e DER KC DE RR NR A A IRR SON AN AIR A MSP430 C C Codegen Unix v0 2 0 Date Time created Tue Jun 29 14 54 28 2004 R TEIE Ae Aee AE TEE Ae EUR KORR EAERAE EA EAE e e e AE e E RARER KEKE OR ROCK ICE ICI UR IGICUR ICE UK ek ee he Ke e ek compiler opts mem model code flat mem model data flat symdebug none acp430 GQ var tmp TI764 AAAvO0aGVG Sect Mitext align 2 clink global main poe 2222l22l2llll2llllllll2lll2l2lll2lll2l222222222222222222222222222222 H 3 int main BOR Week eee e e kW ARE CO C e e C eee ede ege ede e Y ee eae de Je e ee Je dee Y ede e Y ege ed eese EKER EER ege se eee eee FUNCTION NAME main P ds Regs Modified SP SR rll r12 r13 r14 r15 S Regs Used SP SR rll r12 r13 r14 r15 HE Local Frame Size 2 Args 0 Auto 0 Save 2 byte i OK UKCKCKCRCKCKCRCKOROACRUR KICK KK CICER e AE e RC KC Ree e Ce KR UC K EK CIC KC KICKER OAK CK KICK KK eK e e e e e 5 printf Hello world n MOV W SCSSL1 0 0 SP 15 CALL printf 151 5l Pae 7 return 0 T
294. ssor directives To include the line directives use the preproc with line option The preproc with line option performs preprocessing only and writes preprocessed output with line control information line directives to a file named as the source file but with a pp extension 2 5 8 Generating Preprocessed Output for a Make Utility preproc dependency Option The preproc dependency option performs preprocessing only Instead of writing preprocessed output it writes a list of dependency lines suitable for input to a standard make utility If you do not supply an optional filename the list is written to a file with the same name as the source file but a pp extension 2 5 9 Generating a List of Files Included with include preproc includes Option The preproc includes option performs preprocessing only but instead of writing preprocessed output writes a list of files included with the include directive If you do not supply an optional filename the list is written to a file with the same name as the source file but with a pp extension 2 5 10 Generating a List of Macros in a File preproc macros Option The preproc macros option generates a list of all predefined and user defined macros If you do not supply an optional filename the list is written to a file with the same name as the source file but with a pp extension Predefined macros are listed first and indicated by the comment Predefined User defined macros
295. t of MSPA430 C DIR in the same directory as the index library so it is available for subsequent compilations Things to watch out for The linker invokes mklib and waits for it to finish before finishing the link so you will experience a one time delay when an uncommonly used library is built for the first time Build times of 1 5 minutes have been observed This depends on the power of the host number of CPUS etc na shared installation where an installation of the compiler is shared among more than one user it is possible that two users might cause the linker to rebuild the same library at the same time The mklib program tries to minimize the race condition but it is possible one build will corrupt the other In a shared environment all libraries which might be needed should be built at install time see Section 7 4 2 2 for instructions on invoking mklib directly to avoid this problem The index library must exist or the linker is unable to rebuild libraries automatically The index library must be in a user writable directory or the library is not built If the compiler installation must be installed read only a good practice for shared installation any missing libraries must be built at installation time by invoking mklib directly The mklib program is specific to a certain version of a certain library you cannot use one compiler version s run time support s mklib to build a different compiler version s run time support l
296. t of a link Table 2 28 Symbol Management Options Option Alias Description entry_point symbol e ee a global symbol that specifies the primary entry point for the executable object ile globalize pattern Changes the symbol linkage to global for symbols that match pattern hide pattern Hides symbols that match the specified pattern localize pattern Make the symbols that match the specified pattern local make_global symbol g Makes symbol global overrides h make static h Makes all global symbols static no symtable S Strips symbol table information and line number entries from the executable object file scan_libraries scanlibs Scans all libraries for duplicate symbol definitions symbol_map refname defname Specifies a symbol mapping references to the refname symbol are replaced with references to the defname symbol The symbol_map option is now supported when used with opt_level 4 undef sym symbol u Adds symbol to the symbol table as an unresolved symbol unhide pattern Excludes symbols that match the specified pattern from being hidden Table 2 29 Run Time Environment Options Option Alias Description arg_size size args Reserve size bytes for the argc argv memory area cinit_hold_wdt on off Link in an RTS auto initialization routine that either holds on or does not hold off the watchdog timer during cinit auto initialization See Section 4 3 5 fill_valu
297. t sections anywhere in the address space as needed to meet system requirements Table 6 1 Summary of Sections and Memory Placement Section Type of Memory Section Type of Memory bss RAM pinit or ROM or RAM init array cinit ROM or RAM stack RAM const ROM or RAM sysmem RAM data RAM text ROM or RAM You can use the SECTIONS directive in the linker command file to customize the section allocation process For more information about allocating sections into memory see the linker description chapter in the MSP430 Assembly Language Tools User s Guide 6 1 5 C C Software Stack The C C compiler uses a function frame stack to Allocate local variables Pass arguments to functions Save register contents The run time stack grows from the high addresses to the low addresses The compiler uses the R1 register to manage this stack R1 is the stack pointer SP which points to the next unused location on the stack The linker sets the stack size creates a global symbol Tl STACK SIZE and assigns it a value equal to the stack size in bytes The default stack size is 80 bytes You can change the stack size at link time by using the stack size option with the linker command For more information on the stack size option see the linker description chapter in the MSP430 Assembly Language Tools User s Guide Save On Entry Registers and C C Stack Size NOTE Since register sizes increase for MSP430X devices sp
298. te C C programs The C Programming Language second edition by Brian W Kernighan and Dennis M Ritchie describes C based on the ISO C standard You can use the Kernighan and Ritchie hereafter referred to as K amp R book as a supplement to this manual References to K amp R C as opposed to ISO C in this manual refer to the C language as defined in the first edition of Kernighan and Ritchie s The C Programming Language Notational Conventions This document uses the following conventions Program listings program examples and interactive displays are shown in a special typeface Interactive displays use a bold version of the special typeface to distinguish commands that you enter from items that the system displays such as prompts command output error messages etc Here is a sample of C code include lt stdio h gt main printf Hello WorldNn n syntax descriptions instructions commands and directives arein a bold typeface and parameters are in an italic typeface Portions of a syntax that are in bold should be entered as shown portions of a syntax that are in italics describe the type of information that should be entered Square brackets and identify an optional parameter If you use an optional parameter you specify the information within the brackets Unless the square brackets are in the bold typeface do not enter the brackets themselves The following is an example of a command that has an opt
299. te run time library must be used as well 6 1 2 Data Memory Models The MSP430 compiler supports three different data memory models small restricted and large The data model used is controlled by the data model option The 16 bit MSP430 devices always use the small data memory model The 20 bit MSP430X devices can use any data memory model and use the small data model by default The small data model requires that all data sections be located in the low 64K of memory Data pointers are 16 bits in size This is the most efficient data model in terms of performance and application size The restricted data model allows data to be located throughout the entire 1MB address space available on MSP430X devices with only a minimal efficiency penalty over the small data model It is restricted because individual objects structures arrays etc cannot be larger than 64K in size Data pointers are 32 bits in size The large data model also allows data to be located throughout the entire 1MB address space and also places no restriction on the maximum size of an individual object Permitting individual objects to be greater than 64K in size causes code generated for the large data model to be less efficient than code generated for the restricted data model Data memory is also affected by the near data option as described in Section 6 1 3 The maximum size of an object size t and the maximum difference between two pointers ptrdiff t are
300. th no intervening code For more information see Section 5 10 The asm statement is useful for inserting comments in the compiler output Simply start the assembly code string with a semicolon as shown below asm this is an assembly language comment NOTE Using the asm Statement Keep the following in mind when using the asm statement e Be extremely careful not to disrupt the C C environment The compiler does not check or analyze the inserted instructions A Avoid inserting jumps or labels into C C code because they can produce unpredictable results by confusing the register tracking algorithms that the code generator uses Do not change the value of a C C variable when using an asm statement This is because the compiler does not verify such statements They are inserted as is into the assembly code and potentially can cause problems if you are not sure of their effect Do not use the asm statement to insert assembler directives that change the assembly environment Avoid creating assembly macros in C code and compiling with the symdebug dwarf or g option The C environment s debug information and the assembly macro expansion are not compatible 6 7 Interrupt Handling As long as you follow the guidelines in this section you can interrupt and return to C C code without disrupting the C C environment When the C C environment is initialized the startup routine does not enable or disable i
301. the byte after the 8 bit index The second argument is the run address from the C auto initialization record 6 9 3 4 3 Run Length Encoded RLE Format 136 8 bit index Initialization data compressed using run length encoding The data following the 8 bit index is compressed using Run Length Encoded RLE format uses a simple run length encoding that can be decompressed using the following algorithm 1 Read the first byte Delimiter D 2 Read the next byte B 3 If B D copy B to the output buffer and go to step 2 4 Read the next byte L a If L 0 then length is either a 16 bit a 24 bit value or we ve reached the end of the data read next byte L i If L 0 length is a 24 bit value or the end of the data is reached read next byte L i If L 0 the end of the data is reached go to step 7 ii Else L lt lt 16 read next two bytes into lower 16 bits of L to complete 24 bit value for L ii Else L lt lt 8 read next byte into lower 8 bits of L to complete 16 bit value for L b Else if L gt 0 and L 4 copy D to the output buffer L times Go to step 2 c Else length is 8 bit value L 5 Read the next byte C C is the repeat character 6 Write C to the output buffer L times go to step 2 7 End of processing The run time support library has a routine Tl decompress rle24 to decompress data compressed using RLE The first argument to this function is the address po
302. the pragma applies to the next function declared The syntax of the pragma in C is pragma FUNC EXT CALLED func The syntax of the pragma in C is pragma FUNC_EXT_CALLED Except for c intOO which is the name reserved for the system reset interrupt for C C programs the name of the interrupt the func argument does not need to conform to a naming convention When you use program level optimization you may need to use the FUNC_EXT_CALLED pragma with certain options See Section 3 3 2 SLAU132K September 2015 MSP430 C C Language Implementation 95 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS Pragma Directives www ti com 5 11 12 The FUNC_IS_PURE Pragma The FUNC_IS_PURE pragma specifies to the compiler that the named function has no side effects This allows the compiler to do the following Delete the call to the function if the function s value is not needed Delete duplicate functions The pragma must appear before any declaration or reference to the function In C the argument func is the name of a function In C the pragma applies to the next function declared The syntax of the pragma in C is pragma FUNC IS PURE func The syntax of the pragma in C is pragma FUNC IS PURE 5 11 13 The FUNC NEVER RETURNS Pragma The FUNC NEVER RETURNS pragma specifies to the compiler that the function never r
303. this error if you are linking with the provided RTS library 5 11 18 The LOCATION Pragma 98 The compiler supports the ability to specify the run time address of a variable at the source level This can be accomplished with the LOCATION pragma or attribute The syntax of the pragma in C is pragma LOCATION x address int x The syntax of the pragmas in C is pragma LOCATION adaress int x The syntax of the pragma for IAR is pragma location address int x The syntax of the GCC attribute is intx attribute location address MSP430 C C Language Implementation SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Pragma Directives The NOINIT pragma may be used in conjunction with the LOCATION pragma to map variables to special memory locations see Section 5 11 19 5 11 19 The NOINIT and PERSISTENT Pragmas Global and static variables are zero initialized However in applications that use non volatile memory it may be desirable to have variables that are not initialized Noinit variables are global or static variables that are not zero initialized at startup or reset Persistent and noinit variables behave identically with the exception of whether or not they are initialized at load time The NOINIT pragma may be used in conjunction with the LOCATION pragma to map
304. those modes 32K September 2015 Run Time Environment 133 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS System Initialization www ti com 6 9 3 Automatic Initialization of Variables Any global variables declared as preinitialized must have initial values assigned to them before a C C program starts running The process of retrieving these variables data and initializing the variables with the data is called autoinitialization Internally the compiler and linker coordinate to produce compressed initialization tables Your code should not access the initialization table 6 9 3 1 Zero Initializing Variables In ANSI C global and static variables that are not explicitly initialized must be set to 0 before program execution The C C compiler supports preinitialization of uninitialized variables by default This can be turned off by specifying the linker option zero_init off 6 9 3 2 Direct Initialization The compiler uses direct initialization to initialize global variables For example consider the following C code int i 23 int alsi 1 2 3 4 5 Y The compiler allocates the variables i and a to data section and the initial values are placed directly global i data align 4 as field 23 32 ie0 global a data align 4 at field 1 32 a 0 0 field 2 32 a l 32 field 3 32 a 2 64 field 4 32 a 3 96 field 5 32 a 4 128
305. tion Feedback Copyright 2015 Texas Instruments Incorporated 114 I8 TEXAS INSTRUMENTS This chapter describes the MSP430 C C run time environment To ensure successful execution of C C programs it is critical that all run time code maintain this environment It is also important to follow Chapter 6 Run Time Environment the guidelines in this chapter if you write assembly language functions that interface with C C code Topic Page 6 1 Memory Model eere E EEEE S dunce ceenuaaamaecaen Ea e a EEan 115 O SEA lR Ae O a a eee E O E TO I DO 119 6 33 ETTA NE a E A A A A A 121 6 4 Function Structure and Calling Conventions Lees 122 6 5 Accessing Linker Symbols in C and C44 ccccceceeeeec eee ee cence eeeee essa eeeeeeeeeeeees 124 6 6 Interfacing C and C With Assembly Language sees 124 6 ZUInterruptictandlingE eee Meu NER E EE ER EE ERE E E TE 127 6 8 Using intrinsics to Access Assembly Language Statements 129 6 9 System Initialization eee erre eene ree Eee ere UTEM MxEE Ee EE 133 6 10 Compiling for 20 Bit MSP430X Devices esses 140 Run Time Environment Copyright 2015 Texas Instruments Incorporated SLAU132K September 2015 SLAU132K September 2015 Submit Documentation Feedback l TEXAS INSTRUMENTS www ti com Memory Model 6 1 6 1 1 Memory Model The MSP430 compiler
306. tion also The interlist feature can affect optimized code because it might prevent some optimization from crossing C C statement boundaries Optimization makes normal source interlisting impractical because the compiler extensively rearranges your program Therefore when you use the optimizer interlist option the compiler writes reconstructed C C statements Example 3 1 shows a function that has been compiled with optimization opt level 2 and the optimizer interlist option The assembly file contains compiler comments interlisted with assembly code Impact on Performance and Code Size NOTE The c src interlist option can have a negative effect on performance and code size Optimizing Your Code SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Using the Interlist Feature With Optimization When you use the c_src_interlist and optimizer_interlist options with optimization the compiler inserts its comments and the interlist feature runs before the assembler merging the original C C source into the assembly file Example 3 2 shows the function from Example 3 1 compiled with the optimization opt_level 2 and the c_src_interlist and optimizer_interlist options The assembly file contains compiler comments and C source interlisted with assembly code Example 3 1 The Function From Example 2 1 Compiled With the O2 and
307. tion of unsupported C features see Section 5 2 ISO standard run time support The compiler tools come with an extensive run time library Library functions conform to the ISO C C library standard unless otherwise stated The library includes functions for standard input and output string manipulation dynamic memory allocation data conversion timekeeping trigonometry and exponential and hyperbolic functions Functions for signal handling are not included because these are target system specific For more information see Chapter 7 See Section 5 15 for command line options to select the C or C standard your code uses 1 4 Output Files The following types of output files are created by the compiler ELF object files Executable and Linking Format ELF enables supporting modern language features like early template instantiation and exporting inline functions ELF is part of the System V Application Binary Interface ABI The ELF format used for MSP430 is extended by the MSP430 Embedded Application Binary Interface EABI which is documented in SLAA534 COFF object files are not supported in v15 6 0 STS and later versions of the TI Code Generation Tools If you would like to produce COFF output files please use v4 4 of the MSP430 Code Generation Tools and refer to SLAU132J for documentation SLAU132K September 2015 Introduction to the Software Development Tools 15 Submit Documentation Feedback Copyright 2015 Texas I
308. tion that you want to keep In C the argument func is the name of the function that makes no assignments In C the pragma applies to the next function declared The syntax of the pragma in C is pragma FUNC NO IND ASG func The syntax of the pragma in C is pragma FUNC NO IND ASG 5 11 16 The FUNCTION OPTIONS Pragma The FUNCTION OPTIONS pragma allows you to compile a specific function in a C or C file with additional command line compiler options The affected function will be compiled as if the specified list of options appeared on the command line after all other compiler options In C the pragma is applied to the function specified In C the pragma is applied to the next function The syntax of the pragma in C is pragma FUNCTION OPTIONS func additional options The syntax of the pragma in C is pragma FUNCTION_OPTIONS additional options 5 11 17 The INTERRUPT Pragma The INTERRUPT pragma enables you to handle interrupts directly with C code In C the argument func is the name of a function In C the pragma applies to the next function declared The syntax of the pragma in C is pragma INTERRUPT func The syntax of the pragma in C is pragma INTERRUPT void func void The GCC interrupt attribute syntax which has the same effects as the INTERRUPT pragma is as follows Note that the interrupt attribute ca
309. tionally using the never executed intrinsic results in the assertion that if val is not 0 or 5 then it has to be 14 and the compiler has no need to generate code to test for val 14 The never executed intrinsic is only defined when specified as the single statement following a default case label The compiler ignores the use of the intrinsic in any other context 132 Run Time Environment SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated l www t 6 9 6 9 1 TEXAS INSTRUMENTS i com System Initialization System Initialization Before you can run a C C program you must create the C C run time environment The C C boot routine performs this task using a function called _c_int00 The run time support source library rts src contains the source to this routine in a module named boot c or boot asm To begin running the system the c intOO function can be called by reset hardware You must link the c intOO function with the other object files This occurs automatically when you use the rom_model or ram model link option and include a standard run time support library as one of the linker input files When C C programs are linked the linker sets the entry point value in the executable output file to the symbol c int0O The c int0O function performs the following tasks to initialize the environment 1 Reserves space for the user mode run time stack and
310. tions It does so regardless of whether you invoke the optimizer These optimizations are always enabled although they are more effective when the optimizer is used 3 2 Performing File Level Optimization opt levelz3 option The opt_level 3 option aliased as the O3 option instructs the compiler to perform file level optimization You can use the opt_level 3 option alone to perform general file level optimization or you can combine it with other options to perform more specific optimizations The options listed in Table 3 2 work with opt_level 3 to perform the indicated optimization Table 3 2 Options That You Can Use With opt_level 3 If You Use this Option See Have files that redeclare standard library functions std lib func defined Section 3 2 1 std lib func redefined Want to create an optimization information file gen_opt_level n Section 3 2 2 Want to compile multiple source files program_level_compile Section 3 3 3 2 1 Controlling File Level Optimization std lib func def Options When you invoke the compiler with opt_level 3 some of the optimizations use known properties of the standard library functions If your file redeclares any standard library functions these optimizations become ineffective Use Table 3 3 to select the appropriate file level optimization option Table 3 3 Selecting a File Level Optimization Option If Your Source File Use this Option Declares a function
311. to generate an information file See Section 3 2 2 for more information In Code Composer Studio when the program level compile option is used C and C files that have the same options are compiled together However if any file has a file specific option that is not selected as a project wide option that file is compiled separately For example if every C and C file in your project has a different set of file specific options each is compiled separately even though program level optimization has been specified To compile all C and C files together make sure the files do not have file specific options Be aware that compiling C and C files together may not be safe if previously you used a file specific option Compiling Files With the program level compile and keep asm Options NOTE f you compile all files with the program level compile and keep asm options the compiler produces only one asm file not one for each corresponding source file Controlling Program Level Optimization call assumptions Option You can control program level optimization which you invoke with program level compile opt level 3 by using the call assumptions option Specifically the call assumptions option indicates if functions in other modules can call a module s external functions or modify a module s external variables The number following call assumptions indicates the level you set for the module that you are allowing to b
312. to one source line each diagnostic has the form shown the text of the source line is displayed several times with an appropriate position indicated each time Long messages are wrapped to additional lines when necessary You can use the display error number command line option to request that the diagnostic s numeric identifier be included in the diagnostic message When displayed the diagnostic identifier also indicates whether the diagnostic can have its severity overridden on the command line If the severity can be overridden the diagnostic identifier includes the suffix D for discretionary otherwise no suffix is present For example Test name c line 7 error 64 D declaration does not declare anything Struct i Test name c line 9 error 77 this declaration has no storage class or type specifier XXXXX Because errors are determined to be discretionary based on the severity in a specific context an error can be discretionary in some cases and not in others All warnings and remarks are discretionary For some messages a list of entities functions local variables source files etc is useful the entities are listed following the initial error message test c line 4 error more than one instance of overloaded function f matches the argument list function f int function f flost argument types are double 1 5 5 In some cases additional context information is provided Specifically
313. tradeoff between execution speed and code size because the code is duplicated at each function call site Large functions that are called frequently are poor candidates for inlining Function inlining is triggered by the following situations The use of built in intrinsic operations Intrinsic operations look like function calls and are inlined automatically even though no function body exists Use of the inline keyword or the equivalent inline keyword Functions declared with the inline keyword may be inlined by the compiler if you set opt_level 3 or greater The inline keyword is a suggestion from the programmer to the compiler Even if your optimization level is high inlining is still optional for the compiler The compiler decides whether to inline a function based on the length of the function the number of times it is called your opt_for_speed setting and any contents of the function that disqualify it from inlining see Section 2 11 2 Functions can be inlined at opt_level 3 if the function body is visible in the same module or if pm is also used and the function is visible in one of the modules being compiled Functions may be inlined at link time if the file containing the definition and the call site were both compiled with opt_level 4 Use of static inline functions Functions defined as both static and inline are more likely to be inlined When opt_level 3 or greater is used the compiler may automatically inl
314. trailing padding after member c2 leading to a total size of 12 bytes struct unpacked struct char cl int i char c2 However the members of a packed struct are byte aligned Thus the following does not have any bytes of padding between or after members and totals 6 bytes struct _ attribute packed packed struct char cl int i char c2 Subsequently packed structures in an array are packed together without trailing padding between array elements Bit fields of a packed structure are bit aligned The byte alignment of adjacent struct members that are not bit fields does not change However there are no bits of padding between adjacent bit fields The packed attribute can only be applied to the original definition of a structure or union type It cannot be applied with a typedef to a non packed structure that has already been defined nor can it be applied to the declaration of a struct or union object Therefore any given structure or union type can only be packed or non packed and all objects of that type will inherit its packed or non packed attribute The packed attribute is not applied recursively to structure types that are contained within a packed structure Thus in the following example the member s retains the same internal layout as in the first example above There is no padding between c and s so s falls on an unaligned boundary struct attribute packed outer packed struct char c struct unpacked str
315. trinsic asserts that the value of TBIV can only take on the values specified by the case labels namely the even values from 0 to 14 Normally the compiler would have to generate code to handle any value which would result in extra range checks Instead for this example the compiler will generate a switch table where the value of TBIV is simply added to the PC to jump to the appropriate code block handling each value represented by the case labels SLAU132K September 2015 Run Time Environment 131 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Using Intrinsics to Access Assembly Language Statements www ti com 6 8 4 2 Using never executed With General Switch Expressions Using the __never_executed intrinsic at the default label can also improve the generated switch code for more general switch expressions that do not involve vector generator type values Example 6 9 General Switch Statement switch val case 0 case 5 action a break case 14 action b break default never executed Normally for the switch expression values 0 and 5 the compiler generates code to test for both 0 and 5 since the compiler must handle the possible values 1 4 The __ never_executed intrinsic in Example 6 9 asserts that val cannot take on the values 1 4 and therefore the compiler only needs to generate a single test val lt 6 to handle both case labels Addi
316. ts Incorporated 14 1 TEXAS INSTRUMENTS Software Development Tools Overview www ti com The archiver allows you to collect a group of files into a single archive file called a library The archiver allows you to modify such libraries by deleting replacing extracting or adding members One of the most useful applications of the archiver is building a library of object files See the MSP430 Assembly Language Tools User s Guide The run time support libraries contain the standard ISO C and C library functions compiler utility functions floating point arithmetic functions and C I O functions that are supported by the compiler See Chapter 7 The library build utility automatically builds the run time support library if compiler and linker options require a custom version of the library See Section 7 4 Source code for the standard run time support library functions for C and C is provided in the lib src subdirectory of the directory where the compiler is installed The hex conversion utility converts an object file into other object formats You can download the converted file to an EPROM programmer See the MSP430 Assembly Language Tools User s Guide The absolute lister accepts linked object files as input and creates abs files as output You can assemble these abs files to produce a listing that contains absolute rather than relative addresses Without the absolute lister producing such a listing would be tedious and would re
317. type did exist with the rules implied by normal integer conversion When converting a pointer to an integer or vice versa if the bitwise representation of the destination can hold all of the bits in the bitwise representation of the source the bits are copied exactly 6 3 2 3 The size of the result of subtracting two pointers to elements of the same array is the size of ptrdiff t which is defined in Section 5 6 6 5 6 J 3 8 Hints When the optimizer is used the register storage class specifier is ignored When the optimizer is not used the compiler will preferentially place register storage class objects into registers to the extent possible The compiler reserves the right to place any register storage class object somewhere other than a register 6 7 1 Theinline function specifier is ignored unless the optimizer is used For other restrictions on inlining see Section 2 11 2 6 7 4 J 3 9 Structures unions enumerations and bit fields A plain int bit field is treated as a signed int bit field 6 7 2 6 7 2 1 n addition to Bool signed int and unsigned int the compiler allows char signed char unsigned char signed short unsigned shot signed long unsigned long signed long long unsigned long long and enum types as bit field types 6 7 2 1 Bit fields may not straddle a storage unit boundary 6 7 2 1 Bit fields are allocated in endianness order within a unit 6 7 2 1 e Non bit field members of
318. uct s Jj It is illegal to implicitly or explicitly cast the address of a packed struct member as a pointer to any non packed type except an unsigned char In the following example p1 p2 and the call to foo are all illegal void foo int param Struct packed struct ps int pl amp ps i int p2 int amp ps i foo amp ps i However it is legal to explicitly cast the address of a packed struct member as a pointer to an unsigned char unsigned char pc unsigned char amp ps i The packed attribute can also be applied to enumerated types On an enum packed indicates that the smallest integral type should be used The TI compiler also supports an unpacked attribute for an enumeration type to allow you to indicate that the representation is to be an integer type that is no smaller than int in other words it is not packed MSP430 C C Language Implementation SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com GNU Language Extensions 5 16 5 Built In Functions The following built in functions are supported builtin abs builtin classify type builtin constant p builtin expect builtin fabs builtin fabsf builtin frame address builtin labs builtin memcpy and builtin return address The builtin frame address function always returns zero The builtin return address function always returns
319. unction For example consider the following int bbb int argl char arg2 int aaa int n char str return bbb n str For this example the compiler makes aaa an alias of bbb so that at link time all calls to function aaa should be redirected to bbb If the linker can successfully redirect all references to aaa then the body of function aaa can be removed and the symbol aaa is defined at the same address as bbb For information about using the GCC function attribute syntax to declare function aliases see Section 5 16 2 Optimizing Your Code SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com What Kind of Optimization Is Being Performed 3 11 8 Induction Variables and Strength Reduction Induction variables are variables whose value within a loop is directly related to the number of executions of the loop Array indices and control variables for loops are often induction variables Strength reduction is the process of replacing inefficient expressions involving induction variables with more efficient expressions For example code that indexes into a sequence of array elements is replaced with code that increments a pointer through the array Induction variable analysis and strength reduction together often remove all references to your loop control variable allowing its elimination 3 11 9 Loop Invariant Code Motion This opti
320. ur application If you do not specify the g option and allow the default generation of debug information to be used the default level of optimization is used unless you specify some other optimization level The symdebug dwarf option no longer disables optimization because generation of debug information no longer impacts optimization If you specify the g option explicitly but do not specify an optimization level no optimization is performed This is because while generating debug information does not affect the ability to optimize code optimizing code does make it more difficult to debug code At higher levels of optimization the compiler s extensive rearrangement of code and the many to many allocation of variables to registers often make it difficult to correlate source code with object code for debugging purposes It is recommended that you perform debugging using the lowest level of optimization possible If you specify an opt_level aliased as O option that optimization level is used no matter what type of debugging information you enabled The optimization level used if you do not specify the level on the command line is affected by whether or not the command line includes the g option and the opt_level option as shown in the following table Table 3 7 Interaction Between Debugging and Optimization Options Optimization no g g no opt level opt_level 0 opt_level 0 opt_level opt_level 2 opt_leve
321. us warnings no_demangle Disables demangling of symbol names in diagnostic messages no_warnings Suppresses diagnostic warnings errors are still issued set_error_limit count Sets the error limit to count The linker abandons linking after this number of errors The default is 100 verbose_diagnostics Provides verbose diagnostic messages that display the original source with line wrap warn_sections W Displays a message when an undefined output section is created 26 Using the C C Compiler SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Changing the Compiler s Behavior with Options Table 2 27 Linker Output Options Option Alias Description absolute exe a Produces an absolute executable object file This is the default if neither absolute exe nor relocatable is specified the linker acts as if absolute exe were specified ecc data error Inject specified errors into the output file for testing ecc ecc error Inject specified errors into the Error Correcting Code ECC for testing mapfile_contents attribute Controls the information that appears in the map file relocatable r Produces a nonexecutable relocatable output object file rom Creates a ROM object run_abs abs Produces an absolute listing file xml link info file Generates a well formed XML file containing detailed information about the resul
322. use cast to hide address of for I 0 i TABLE SIZE I use like normal symbol 126 Run Time Environment SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS www ti com Interfacing C and C With Assembly Language Example 6 7 Assembly Language Program for Example 6 6 table size set 10000 define the constant global table size make it global Because you are referencing only the symbol s value as stored in the symbol table the symbol s declared type is unimportant In Example 6 6 int is used You can reference linker defined symbols in a similar manner 6 6 4 Sharing C C Header Files With Assembly Source You can use the cdecls assembler directive to share C headers containing declarations and prototypes between C and assembly code Any legal C C can be used in a cdecls block and the C C declarations will cause suitable assembly to be generated automatically allowing you to reference the C C constructs in assembly code For more information see the C C header files chapter in the MSP430 Assembly Language Tools User s Guide 6 6 5 Using Inline Assembly Language Within a C C program you can use the asm statement to insert a single line of assembly language into the assembly language file created by the compiler A series of asm statements places sequential lines of assembly language into the compiler output wi
323. using the compiler Topic Page 21 About the Compilen e eea ae a a eee see e r e EE teure NaR eR EHE 18 22088 Invoking the C C Compiler e E e E AA E R 18 2 3 Changing the Compiler s Behavior with Options eeeeeeeeeeeeeeeeeeeee 19 2 4 Controlling the Compiler Through Environment Variables 37 2 5 Controlling the Preprocessor eneee 0er e ee E ae aeee EERE EAE EEE RENE STE 39 26 Passing Arguments to main e eee aaee E e e EE E AAEE E at act 42 2 7 Understanding Diagnostic Messages 2 0 ceeceeeeeeee tence eee sense eeeseeeeeeeeeeeeseeeees 43 2 8 Other Messages eee aae AEE eE sutra EE ste te E AE E AEE AA EAE aR Sates 46 2 9 Generating Cross Reference Listing Information gen acp xref Option 46 2 10 Generating a Raw Listing File gen acp raw Option esueseesse 46 211 Using Inline EunctioniExpansion 92m eaea eae ee aaae aar ana rernm 48 PA A a a NE T AE EE ERE STER 50 2 13 Controlling Application Binary Interface cceeeeee cece eee ee eee eeeeaeeeeeeeeeeees 51 2 14 Enabling Entry Hook and Exit Hook Functions esee 52 SLAU132K September 2015 Using the C C Compiler 17 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS About the Compiler www ti com 2 1 About the Compiler The compiler
324. utes of the application The build attributes are set indirectly according to the command line options used to build the application Build attributes include things like CPU revision If the library is explicitly named e g rts430 eabi lib run time support looks for that library exactly otherwise it uses the index library libc a to pick an appropriate library The index library describes a set of libraries with different build attributes The linker will compare the build attributes for each potential library with the build attributes of the application and will pick the best fit For details on the index library see the archiver chapter in the MSP430 Assembly Language Tools User s Guide Using Run Time Support Functions and Building Libraries SLAU132K September 2015 Submit Documentation Feedback Copyright O 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS www ti com Library Build Process Now that the linker has decided which library to use it checks whether the run time support library is present in MSP430 C DIR The library must be in exactly the same directory as the index library libc a If the library is not present the linker invokes mklib to build it This happens when the library is missing regardless of whether the user specified the name of the library directly or allowed the linker to pick the best library from the index library The mklib program builds the requested library and places it in lib directory par
325. utput file Outputs to the specified file rather than to standard out quiet Reduces the number of messages generated during execution u Specifies that external names do not have a C prefix V Enables verbose mode outputs a banner 8 3 Sample Usage of the C Name Demangler The examples in this section illustrate the demangling process Example 8 1 shows a sample C program Example 8 2 shows the resulting assembly that is output by the compiler In this example the linknames of all the functions are mangled that is their signature information is encoded into their names Example 8 1 C Code for calories_in_a_banana class banana public int calories void banana banana int calories in a banana void banana x return x calories SLAU132K September 2015 C Name Demangler 163 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated Sample Usage of the C Name Demangler Example 8 2 Resulting Assembly for calories in a banana 1 TEXAS INSTRUMENTS www ti com PUSH W r10 SUB W 2 SP MOV W SP r12 CALL _ZN6bananaClEv MOV W SP r12 CALL _ZN6banana8caloriesEv MOV W r12 r10 MOV W SP r12 CALL 4 ZN6bananaD1Ev MOV W r10 r12 ADD W 2 SP POP r10 RET Executing the C name demangler demangles all names that it believes to be mangled Enter dem430 calories in a banana asm The result is shown in Example 8 3 The linknames
326. value symbolic debugging The ability of a software tool to retain symbolic information that can be used by a debugging tool such as an emulator or simulator target system The system on which the object code you have developed is executed text section One of the default object file sections The text section is initialized and contains executable code You can use the text directive to assemble code into the text section trigraph sequence A 3 character sequence that has a meaning as defined by the ISO 646 1983 Invariant Code Set These characters cannot be represented in the C character set and are expanded to one character For example the trigraph is expanded to unconfigured memory Memory that is not defined as part of the memory map and cannot be loaded with code or data uninitialized section A object file section that reserves space in the memory map but that has no actual contents These sections are built with the bss and usect directives unsigned value A value that is treated as a nonnegative number regardless of its actual sign variable A symbol representing a quantity that can assume any of a set of values word A 16 bit addressable location in target memory SLAU132K September 2015 Glossary 169 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated Appendix B I ME MENTIS SLAU132K September 2015 Revision History Table B 1 lists significant cha
327. vide I O to the host operating system Fundamental arithmetic routines e System startup routine c intOO Compiler helper functions to support language features that are not directly efficiently expressible in C C The run time support libraries do not contain functions involving signals and locale issues The C library supports wide chars in that template functions and classes that are defined for char are also available for wide char For example wide char stream classes wios wiostream wstreambuf and so on corresponding to char classes ios iostream streambuf are implemented However there is no low level file I O for wide chars Also the C library interface to wide char support through the C headers lt cwchar gt and lt cwctype gt is limited as described in Section 5 1 TI does not provide documentation that covers the functionality of the C library Tl suggests referring to one of the following sources The Standard C Library A Tutorial and Reference Nicolai M Josuttis Addison Wesley ISBN 0 201 37926 0 The C Programming Language Third or Special Editions Bjarne Stroustrup Addison Wesley ISBN 0 201 88954 4 or 0 201 70073 5 7 1 1 Linking Code With the Object Library When you link your program you must specify the object library as one of the linker input files so that references to the I O and run time support functions can be resolved You can either specify the library or allow the compiler to select one f
328. xed ANSI ISO relaxed ansi or pr This is the default Strict ANSI ISO strict ansi or ps The default is relaxed ANSI ISO mode Under relaxed ANSI ISO mode the compiler accepts language extensions that could potentially conflict with ANSI ISO C C Under strict ANSI mode these language extensions are suppressed so that the compiler will accept all strictly conforming programs See Section 5 15 3 5 15 1 Enabling C99 Mode c99 106 The compiler supports the 1999 standard of C as standardized by the ISO However the following list of run time functions and features are not implemented or fully supported complex h ctype h isblank float h DECIMAL DIG FLT EVAL METHOD inttypes h wcstoimax wcstoumax Stdarg h va copy macro Stdio h 96a and 96A format specifiers for hexadecimal float The 96e specifier may produce 0 when 0 is expected by the standard snprintf does not properly pad with spaces when writing to a wide character array Stdlib h Strtof atof strtod strtold do not support hexadecimal float strings vfscanf vscanf vsscanf return value on floating point matching failure is incorrect tgmath h time h strftime wchar h getws fputws mbrlen mbsrtowcs MSP430 C C Language Implementation SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated
329. y linked Sets the diagnostic severity for advisory MISRA C 2004 rules Sets the diagnostic severity for required MISRA C 2004 rules Includes the source code of filename at the beginning of the compilation This can be used to establish standard macro definitions The filename is searched for in the directories on the include search list The files are processed in the order in which they were specified Enables support for smaller limited versions of the printf function family sprintf fprintf etc and the scanf function family sscanf fscanf etc run time support functions The valid values are full Supports all format specifiers This is the default nofloat Excludes support for printing and scanning floating point values Supports all format specifiers except 96a 96A f F g G 96e and E minimal Supports the printing and scanning of integer char or string values without width or precision flags Specifically only the 9696 9d 960 9ec S and x format specifiers are supported There is no run time error checking to detect if a format specifier is used for which support is not included The printf support option precedes the run linker option and must be used when performing the final link These options are specific to the MSP430 toolset See the referenced sections for more information MSP430 specific assembler options are listed in Section 2 3 11 The MSP430 compiler now supports only the Embedded
330. y pool can have a size limited only by the amount of available memory in your system To conserve space in the bss section you can allocate large arrays from the heap instead of defining them as global or static For example instead of a definition such as struct big table 100 Use a pointer and call the malloc function struct big table table struct big malloc 100 sizeof struct big Run Time Environment SLAU132K September 2015 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated 1 TEXAS INSTRUMENTS www ti com Object Representation 6 2 Object Representation For general information about data types see Section 5 6 This section explains how various data objects are sized aligned and accessed 6 2 1 Data Type Storage Table 6 2 lists register and memory storage for various data types Table 6 2 Data Representation in Registers and Memory Data Type Register Storage Memory Storage char unsigned char short unsigned short Bits 0 7 of register Bits 0 7 of register Bits 0 15 of register Bits 0 15 of register 8 bits aligned to 8 bit boundary 8 bits aligned to 8 bit boundary 16 bits aligned to 16 bit boundary 16 bits aligned to 16 bit boundary int Entire register 16 bits aligned to 16 bit boundary unsigned int Entire register 16 bits aligned to 16 bit boundary enum Entire register 16 bits aligned to 16 bit boundary float Two registers which need not be adja
331. zation at run time An autoinitialization method used by the linker when linking C code The linker uses this method when you invoke it with the rom model link option The linker loads the cinit section of data tables into memory and variables are initialized at run time big endian An addressing protocol in which bytes are numbered from left to right within a word More significant bytes in a word have lower numbered addresses Endian ordering is hardware specific and is determined at reset See also little endian BIS Bit instruction set block A set of statements that are grouped together within braces and treated as an entity SLAU132K September 2015 Glossary 165 Submit Documentation Feedback Copyright 2015 Texas Instruments Incorporated I TEXAS INSTRUMENTS Appendix A www ti com 166 bss section One of the default object file sections You use the assembler bss directive to reserve a specified amount of space in the memory map that you can use later for storing data The bss section is uninitialized byte Per ANSI ISO C the smallest addressable unit that can hold a character C C compiler A software program that translates C source statements into assembly language source statements code generator A compiler tool that takes the file produced by the parser or the optimizer and produces an assembly language source file COFF Common object file format a system of object files configure
332. zations or preprocessor constructs Instead kr compatible simply liberalizes the ANSI ISO rules without revoking any of the features The specific differences between the ANSI ISO version of C and the K amp R version of C are as follows The integral promotion rules have changed regarding promoting an unsigned type to a wider signed type Under K amp R C the result type was an unsigned version of the wider type under ANSI ISO the result type is a signed version of the wider type This affects operations that perform differently when applied to signed or unsigned operands namely comparisons division and mod and right shift unsigned short u int i if u lt i SIGNED comparison unless kr compatible used ANSI ISO prohibits combining two pointers to different types in an operation In most K amp R compilers this situation produces only a warning Such cases are still diagnosed when kr compatible is used but with less severity int p char q p error without kr compatible warning with kr compatible External declarations with no type or storage class only an identifier are illegal in ANSI ISO but legal in K amp R a illegal unless kr compatible used ANSI ISO interprets file scope definitions that have no initializers as tentative definitions In a single module multiple definitions of this form are fused together into a single definition Under K amp R each definition is treated as a separ

Download Pdf Manuals

image

Related Search

Related Contents

TS Series interactive whiteboard Benutzerhandbuch  AirLive FE-200CU surveillance camera  Frequenzumrichter SE 6XX  Télécharger la notice PDF  JV150-130/160 取扱説明書  

Copyright © All rights reserved.
Failed to retrieve file