c30 Users Guide 51284f
c30 Users Guide 51284f
DS51284F
Note the following details of the code protection feature on Microchip devices: Microchip products meet the specification contained in their particular Microchip Data Sheet. Microchip believes that its family of products is one of the most secure families of its kind on the market today, when used in the intended manner and under normal conditions. There are dishonest and possibly illegal methods used to breach the code protection feature. All of these methods, to our knowledge, require using the Microchip products in a manner outside the operating specifications contained in Microchips Data Sheets. Most likely, the person doing so is engaged in theft of intellectual property. Microchip is willing to work with the customer who is concerned about the integrity of their code. Neither Microchip nor any other semiconductor manufacturer can guarantee the security of their code. Code protection does not mean that we are guaranteeing the product as unbreakable.
Code protection is constantly evolving. We at Microchip are committed to continuously improving the code protection features of our products. Attempts to break Microchips code protection feature may be a violation of the Digital Millennium Copyright Act. If such acts allow unauthorized access to your software or other copyrighted work, you may have a right to sue for relief under that Act.
Information contained in this publication regarding device applications and the like is provided only for your convenience and may be superseded by updates. It is your responsibility to ensure that your application meets with your specifications. MICROCHIP MAKES NO REPRESENTATIONS OR WARRANTIES OF ANY KIND WHETHER EXPRESS OR IMPLIED, WRITTEN OR ORAL, STATUTORY OR OTHERWISE, RELATED TO THE INFORMATION, INCLUDING BUT NOT LIMITED TO ITS CONDITION, QUALITY, PERFORMANCE, MERCHANTABILITY OR FITNESS FOR PURPOSE. Microchip disclaims all liability arising from this information and its use. Use of Microchip devices in life support and/or safety applications is entirely at the buyers risk, and the buyer agrees to defend, indemnify and hold harmless Microchip from any and all damages, claims, suits, or expenses resulting from such use. No licenses are conveyed, implicitly or otherwise, under any Microchip intellectual property rights.
Trademarks The Microchip name and logo, the Microchip logo, Accuron, dsPIC, KEELOQ, KEELOQ logo, microID, MPLAB, PIC, PICmicro, PICSTART, PRO MATE, PowerSmart, rfPIC, and SmartShunt are registered trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. AmpLab, FilterLab, Linear Active Thermistor, Migratable Memory, MXDEV, MXLAB, PS logo, SEEVAL, SmartSensor and The Embedded Control Solutions Company are registered trademarks of Microchip Technology Incorporated in the U.S.A. Analog-for-the-Digital Age, Application Maestro, CodeGuard, dsPICDEM, dsPICDEM.net, dsPICworks, ECAN, ECONOMONITOR, FanSense, FlexROM, fuzzyLAB, In-Circuit Serial Programming, ICSP, ICEPIC, Mindi, MiWi, MPASM, MPLAB Certified logo, MPLIB, MPLINK, PICkit, PICDEM, PICDEM.net, PICLAB, PICtail, PowerCal, PowerInfo, PowerMate, PowerTool, REAL ICE, rfLAB, rfPICDEM, Select Mode, Smart Serial, SmartTel, Total Endurance, UNI/O, WiperLock and ZENA are trademarks of Microchip Technology Incorporated in the U.S.A. and other countries. SQTP is a service mark of Microchip Technology Incorporated in the U.S.A. All other trademarks mentioned herein are property of their respective companies. 2007, Microchip Technology Incorporated, Printed in the U.S.A., All Rights Reserved. Printed on recycled paper.
Microchip received ISO/TS-16949:2002 certification for its worldwide headquarters, design and wafer fabrication facilities in Chandler and Tempe, Arizona, Gresham, Oregon and Mountain View, California. The Companys quality system processes and procedures are for its PIC MCUs and dsPIC DSCs, KEELOQ code hopping devices, Serial EEPROMs, microperipherals, nonvolatile memory and analog products. In addition, Microchips quality system for the design and manufacture of development systems is ISO 9001:2000 certified.
DS51284F-page ii
DS51284F-page iii
Chapter 7. Interrupts
7.1 Introduction ................................................................................................... 91 7.2 Highlights ...................................................................................................... 91 7.3 Writing an Interrupt Service Routine ............................................................ 92 7.4 Writing the Interrupt Vector .......................................................................... 94 7.5 Interrupt Service Routine Context Saving .................................................. 104 7.6 Latency ....................................................................................................... 104 7.7 Nesting Interrupts ....................................................................................... 104 7.8 Enabling/Disabling Interrupts ..................................................................... 105 7.9 Sharing Memory Between Interrupt Service Routines and Mainline Code 106 7.10 PSV Usage with Interrupt Service Routines ............................................. 109
DS51284F-page iv
Table of Contents
Chapter 8. Mixing Assembly Language and C Modules
8.1 Introduction ................................................................................................. 111 8.2 Highlights .................................................................................................... 111 8.3 Mixing Assembly Language and C Variables and Functions ..................... 111 8.4 Using Inline Assembly Language ............................................................... 113
DS51284F-page v
Appendix F. ASCII Character Set .............................................................................205 Appendix G. GNU Free Documentation License ....................................................207
G.1 Preamble ................................................................................................... 207 G.2 Applicability and Definitions ....................................................................... 207 G.3 Verbatim Copying ...................................................................................... 209 G.4 Copying in Quantity ................................................................................... 209 G.5 Modifications .............................................................................................. 209 G.6 Combining Documents .............................................................................. 211 G.7 Collections of Documents .......................................................................... 211 G.8 Aggregation with Independent Works ........................................................ 211 G.9 Translation ................................................................................................. 212 G.10 Termination .............................................................................................. 212 G.11 Future Revisions of this License .............................................................. 212
DS51284F-page vi
INTRODUCTION
This chapter contains general information that will be useful to know before using MPLAB C30. Items discussed include: Document Layout Conventions Used in this Guide Recommended Reading The Microchip Web Site Development Systems Customer Change Notification Service Customer Support
DS51284F-page 1
DS51284F-page 2
Preface
CONVENTIONS USED IN THIS GUIDE
The following conventions may appear in this documentation: DOCUMENTATION CONVENTIONS
Description Arial font: Italic characters Initial caps Referenced books Emphasized text A window A dialog A menu selection Quotes Underlined, italic text with right angle bracket Bold characters Text in angle brackets < > Courier font: Plain Courier Sample source code Filenames File paths Keywords Command-line options Bit values Constants Italic Courier Square brackets [ ] Curly brackets and pipe character: { | } Ellipses... A variable argument Optional arguments Choice of mutually exclusive arguments; an OR selection Replaces repeated text Represents code supplied by user Icon This feature supported only in the full version of the software. #define START autoexec.bat c:\mcc18\h _asm, _endasm, static -Opa+, -Opa0, 1 0xFF, A file.o, where file can be any valid filename mpasmwin [options] file [options] errorlevel {0|1} var_name [, var_name...] void main (void) { ... } A field name in a window or dialog A menu path A dialog button A tab A key on the keyboard MPLAB IDE Users Guide ...is the only compiler... the Output window the Settings dialog select Enable Programmer Save project before build File>Save Click OK Click the Power tab Press <Enter>, <F1> Represents Examples
This feature is not supported on all devices. Devices supported will be listed in the title or text.
DS51284F-page 3
DS51284F-page 4
Preface
C Reference Manuals Harbison, Samuel P. and Steele, Guy L., C A Reference Manual, Fourth Edition, Prentice-Hall, Englewood Cliffs, N.J. 07632. Kernighan, Brian W. and Ritchie, Dennis M., The C Programming Language, Second Edition. Prentice Hall, Englewood Cliffs, N.J. 07632. Kochan, Steven G., Programming In ANSI C, Revised Edition. Hayden Books, Indianapolis, Indiana 46268. Plauger, P.J., The Standard C Library, Prentice-Hall, Englewood Cliffs, N.J. 07632. Van Sickle, Ted., Programming Microcontrollers in C, First Edition. LLH Technology Publishing, Eagle Rock, Virginia 24085.
DS51284F-page 5
CUSTOMER SUPPORT
Users of Microchip products can receive assistance through several channels: Distributor or Representative Local Sales Office Field Application Engineer (FAE) Technical Support
Customers should contact their distributor, representative or field application engineer (FAE) for support. Local sales offices are also available to help customers. A listing of sales offices and locations is included in the back of this document. Technical support is available through the web site at: http://support.microchip.com
DS51284F-page 6
1.2
HIGHLIGHTS
Items discussed in this chapter are: MPLAB C30 Description MPLAB C30 and Other Development Tools MPLAB C30 Feature Set
1.3
1.4
DS51284F-page 7
C Compiler
Assembler
Archiver (Librarian)
DS51284F-page 8
Compiler Overview
1.5 MPLAB C30 FEATURE SET
The MPLAB C30 C compiler is a full-featured, optimizing compiler that translates standard ANSI C programs into dsPIC DSC assembly language source. The compiler also supports many command-line options and language extensions that allow full access to the dsPIC DSC device hardware capabilities, and affords fine control of the compiler code generator. This section describes key features of the compiler.
1.5.1
ANSI C Standard
The MPLAB C30 compiler is a fully validated compiler that conforms to the ANSI C standard as defined by the ANSI specification and described in Kernighan and Ritchie's The C Programming Language (second edition). The ANSI standard includes extensions to the original C definition that are now standard features of the language. These extensions enhance portability and offer increased capability.
1.5.2
Optimization
The compiler uses a set of sophisticated optimization passes that employ many advanced techniques for generating efficient, compact code from C source. The optimization passes include high-level optimizations that are applicable to any C code, as well as dsPIC DSC device-specific optimizations that take advantage of the particular features of the dsPIC DSC device architecture.
1.5.3
MPLAB C30 is distributed with a complete ANSI C standard library. All library functions have been validated, and conform to the ANSI C library standard. The library includes functions for string manipulation, dynamic memory allocation, data conversion, timekeeping and math functions (trigonometric, exponential and hyperbolic). The standard I/O functions for file handling are also included, and, as distributed, they support full access to the host file system using the command-line simulator. The fully functional source code for the low-level file I/O functions is provided in the compiler distribution, and may be used as a starting point for applications that require this capability.
1.5.4
The compiler supports both large and small code and data models. The small code model takes advantage of more efficient forms of call and branch instructions, while the small data model supports the use of compact instructions for accessing data in SFR space. The compiler supports two models for accessing constant data. The constants in data model uses data memory, which is initialized by the runtime library. The constants in code model uses program memory, which is accessed through the Program Space Visibility (PSV) window.
1.5.5
Compiler Driver
MPLAB C30 includes a powerful command-line driver program. Using the driver program, application programs can be compiled, assembled and linked in a single step (see Figure 1-1).
DS51284F-page 9
DS51284F-page 10
MPLAB C30 USERS GUIDE Chapter 2. Differences Between MPLAB C30 and ANSI C
2.1 INTRODUCTION
This section discusses the differences between the C language supported by MPLAB C30 syntax and the 1989 standard ANSI C.
2.2
HIGHLIGHTS
Items discussed in this chapter are: Keyword Differences Statement Differences Expression Differences
2.3
KEYWORD DIFFERENCES
This section describes the keyword differences between plain ANSI C and the C accepted by MPLAB C30. The new keywords are part of the base GCC implementation, and the discussion in this section is based on the standard GCC documentation, tailored for the specific syntax and semantics of the MPLAB C30 port of GCC. Specifying Attributes of Variables Specifying Attributes of Functions Inline Functions Variables in Specified Registers Complex Numbers Double-Word Integers Referring to a Type with typeof
DS51284F-page 11
You may also specify attributes with __ (double underscore) preceding and following each keyword (e.g., __aligned__ instead of aligned). This allows you to use them in header files without being concerned about a possible macro of the same name. To specify multiple attributes, separate them by commas within the double parentheses, for example: __attribute__ ((aligned (16), packed)). Note: It is important to use variable attributes consistently throughout a project. For example, if a variable is defined in file A with the far attribute, and declared extern in file B without far, then a link error may result.
address (addr)
The address attribute specifies an absolute address for the variable. This attribute can be used in conjunction with a section attribute. This can be used to start a group of variables at a specific address:
int foo __attribute__((section("mysection"),address(0x900))); int bar __attribute__((section("mysection"))); int baz __attribute__((section("mysection")));
A variable with the address attribute cannot be placed into the auto_psv space (see the space() attribute or the -mconst-in-code option); attempts to do so will cause a warning and the compiler will place the variable into the PSV space. If the variable is to be placed into a PSV section, the address should be a program memory address.
int var __attribute__ ((address(0x800)));
DS51284F-page 12
causes the compiler to allocate the global variable x on a 16-byte boundary. On the dsPIC DSC device, this could be used in conjunction with an asm expression to access DSP instructions and addressing modes that require aligned operands. As in the preceding example, you can explicitly specify the alignment (in bytes) that you wish the compiler to use for a given variable. Alternatively, you can leave out the alignment factor and just ask the compiler to align a variable to the maximum useful alignment for the dsPIC DSC device. For example, you could write:
short array[3] __attribute__ ((aligned));
Whenever you leave out the alignment factor in an aligned attribute specification, the compiler automatically sets the alignment for the declared variable to the largest alignment for any data type on the target machine which in the case of the dsPIC DSC device is two bytes (one word). The aligned attribute can only increase the alignment; but you can decrease it by specifying packed (see below). The aligned attribute conflicts with the reverse attribute. It is an error condition to specify both. The aligned attribute can be combined with the section attribute. This will allow the alignment to take place in a named section. By default, when no section is specified, the compiler will generate a unique section for the variable. This will provide the linker with the best opportunity for satisfying the alignment restriction without using internal padding that may happen if other definitions appear within the same aligned section.
boot
This attribute can be used to define protected variables in Boot Segment (BS) RAM:
int __attribute__((boot)) boot_dat[16];
Variables defined in BS RAM will not be initialized on startup. Therefore all variables in BS RAM must be initialized using inline code. A diagnostic will be reported if initial values are specified on a boot variable. An example of initialization is as follows:
int __attribute__((boot)) time = 0; /* not supported */ int __attribute__((boot)) time2; void __attribute__((boot)) foo() { time2 = 55; /* initial value must be assigned explicitly */ }
deprecated
The deprecated attribute causes the declaration to which it is attached to be specially recognized by the compiler. When a deprecated function or variable is used, the compiler will emit a warning. A deprecated definition is still defined and, therefore, present in any object file. For example, compiling the following file:
int __attribute__((__deprecated__)) i; int main() { return i; }
DS51284F-page 13
far
The far attribute tells the compiler that the variable will not necessarily be allocated in near (first 8 KB) data space, (i.e., the variable can be located anywhere in data memory). mode (mode) This attribute specifies the data type for the declaration as whichever type corresponds to the mode mode. This in effect lets you request an integer or floating point type according to its width. Valid values for mode are as follows:
Mode QI HI SI DI SF DF Width 8 bits 16 bits 32 bits 64 bits 32 bits 64 bits MPLAB C30 Type char int long long long float long double
This attribute is useful for writing code that is portable across all supported MPLAB C30 targets. For example, the following function adds two 32-bit signed integers and returns a 32-bit signed integer result:
typedef int __attribute__((__mode__(SI))) int32; int32 add32(int32 a, int32 b) { return(a+b); }
You may also specify a mode of byte or __byte__ to indicate the mode corresponding to a one-byte integer, word or __word__ for the mode of a one-word integer, and pointer or __pointer__ for the mode used to represent pointers. near The near attribute tells the compiler that the variable is allocated in near data space (the first 8 KB of data memory). Such variables can sometimes be accessed more efficiently than variables not allocated (or not known to be allocated) in near data space.
int num __attribute__ ((near));
noload
The noload attribute indicates that space should be allocated for the variable, but that initial values should not be loaded. This attribute could be useful if an application is designed to load a variable into memory at runtime, such as from a serial EEPROM.
int table1[50] __attribute__ ((noload)) = { 0 };
DS51284F-page 14
Note:
The device architecture requires that words be aligned on even byte boundaries, so care must be taken when using the packed attribute to avoid runtime addressing errors.
persistent
The persistent attribute specifies that the variable should not be initialized or cleared at startup. A variable with the persistent attribute could be used to store state information that will remain valid after a device reset.
int last_mode __attribute__ ((persistent));
Persistent data is not normally initialized by the C run-time. However, from a cold-restart, persistent data may not have any meaningful value. This code example shows how to safely initialize such data:
#include "p24Fxxxx.h" int last_mode __attribute__((persistent)); int main() { if ((RCONbits.POR == 0) && (RCONbits.BOR == 0)) { /* last_mode is valid */ } else { /* initialize persistent data */ last_mode = 0; } }
reverse (alignment)
The reverse attribute specifies a minimum alignment for the ending address of a variable, plus one. The alignment is specified in bytes and must be a power of two. Reverse-aligned variables can be used for decrementing modulo buffers in dsPIC DSC assembly language. This attribute could be useful if an application defines variables in C that will be accessed from assembly language.
int buf1[128] __attribute__ ((reverse(256)));
The reverse attribute conflicts with the aligned and section attributes. An attempt to name a section for a reverse-aligned variable will be ignored with a warning. It is an error condition to specify both reverse and aligned for the same variable. A variable with the reverse attribute cannot be placed into the auto_psv space (see the space() attribute or the -mconst-in-code option); attempts to do so will cause a warning and the compiler will place the variable into the PSV space.
DS51284F-page 15
The section attribute conflicts with the address and reverse attributes. In both cases, the section name will be ignored with a warning. This attribute may also conflict with the space attribute. See the space attribute description for more information.
secure
This attribute can be used to define protected variables in Secure Segment (SS) RAM:
int __attribute__((secure)) secure_dat[16];
Variables defined in SS RAM will not be initialized on startup. Therefore all variables in SS RAM must be initialized using inline code. A diagnostic will be reported if initial values are specified on a secure variable. String literals can be assigned to secure variables using inline code, but they require extra processing by the compiler. For example:
char *msg __attribute__((secure)) = "Hello!\n"; /* not supported */ char *msg2 __attribute__((secure)); void __attribute__((secure)) foo2() { *msg2 = "Goodbye..\n"; /* value assigned explicitly */ }
In this case, storage must be allocated for the string literal in a memory space which is accessible to the enclosing secure function. The compiler will allocate the string in a psv constant section designated for the secure segment.
DS51284F-page 16
The use of the extern specifier is required in order to not produce an error. Note: By convention, the sfr attribute is used only in processor header files. To define a general user variable at a specific address use the address attribute in conjunction with near or far to specify the correct addressing mode.
space (space)
Normally, the compiler allocates variables in general data space. The space attribute can be used to direct the compiler to allocate a variable in specific memory spaces. Memory spaces are discussed further in Section 4.6 Memory Spaces. The following arguments to the space attribute are accepted: data Allocate the variable in general data space. Variables in general data space can be accessed using ordinary C statements. This is the default allocation. xmemory - dsPIC30F/33F DSCs only Allocate the variable in X data space. Variables in X data space can be accessed using ordinary C statements. An example of xmemory space allocation is: int x[32] __attribute__ ((space(xmemory))); ymemory - dsPIC30F/33F DSCs only Allocate the variable in Y data space. Variables in Y data space can be accessed using ordinary C statements. An example of ymemory space allocation is: int y[32] __attribute__ ((space(ymemory))); prog Allocate the variable in program space, in a section designated for executable code. Variables in program space can not be accessed using ordinary C statements. They must be explicitly accessed by the programmer, usually using table-access inline assembly instructions, or using the program space visibility window. auto_psv Allocate the variable in program space, in a compiler-managed section designated for automatic program space visibility window access. Variables in auto_psv space can be read (but not written) using ordinary C statements, and are subject to a maximum of 32K total space allocated. When specifying space(auto_psv), it is not possible to assign a section name using the section attribute; any section name will be ignored with a warning. A variable in the auto_psv space cannot be placed at a specific address or given a reverse alignment. Note: Variables placed in the auto_psv section are not loaded into data memory at startup. This attribute may be useful for reducing RAM usage.
DS51284F-page 17
unordered
The unordered attribute indicates that the placement of this variable may move relative to other variables within the current C source file.
const int __attribute__ ((unordered)) i;
unused
This attribute, attached to a variable, means that the variable is meant to be possibly unused. MPLAB C30 will not produce an unused variable warning for this variable.
weak
The weak attribute causes the declaration to be emitted as a weak symbol. A weak symbol may be superseded by a global definition. When weak is applied to a reference to an external symbol, the symbol is not required for linking. For example:
extern int __attribute__((__weak__)) s; int foo() { if (&s) return s; return 0; /* possibly some other value */ }
In the above program, if s is not defined by some other module, the program will still link but s will not be given an address. The conditional verifies that s has been defined (and returns its value if it has). Otherwise '0' is returned. There are many uses for this feature, mostly to provide generic code that can link with an optional library.
DS51284F-page 18
In the above code, the function compress_data will be used only if it is linked in from some other module. Deciding whether or not to use the feature becomes a link-time decision, not a compile time decision. The affect of the weak attribute on a definition is more complicated and requires multiple files to describe:
/* weak1.c */ int __attribute__((__weak__)) i; void foo() { i = 1; } /* weak2.c */ int i; extern void foo(void); void bar() { i = 2; } main() { foo(); bar(); }
Here the definition in weak2.c of i causes the symbol to become a strong definition. No link error is emitted and both is refer to the same storage location. Storage is allocated for weak1.cs version of i, but this space is not accessible. There is no check to ensure that both versions of i have the same type; changing i in weak2.c to be of type float will still allow a link, but the behavior of function foo will be unexpected. foo will write a value into the least significant portion of our 32-bit float value. Conversely, changing the type of the weak definition of i in weak1.c to type float may cause disastrous results. We will be writing a 32-bit floating point value into a 16-bit integer allocation, overwriting any variable stored immediately after our i. In the cases where only weak definitions exist, the linker will choose the storage of the first such definition. The remaining definitions become in-accessible. The behavior is identical, regardless of the type of the symbol; functions and variables behave in the same manner.
DS51284F-page 19
You may also specify attributes with __ (double underscore) preceding and following each keyword (e.g., __shadow__ instead of shadow). This allows you to use them in header files without being concerned about a possible macro of the same name. You can specify multiple attributes in a declaration by separating them by commas within the double parentheses or by immediately following an attribute declaration with another attribute declaration.
address (addr)
The address attribute specifies an absolute address for the function. This attribute cannot be used in conjunction with a section attribute; the address attribute will take precedence.
void foo() __attribute__ ((address(0x100))) { ... }
alias ("target")
The alias attribute causes the declaration to be emitted as an alias for another symbol, which must be specified. Use of this attribute results in an external reference to target, which must be resolved during the link phase.
DS51284F-page 20
boot
This attribute directs the compiler to allocate a function in the boot segment of program Flash. For example, to declare a protected function:
void __attribute__((boot)) func();
An optional argument can be used to specify a protected access entry point within the boot segment. The argument may be a literal integer in the range 0 to 31 (except 16), or the word unused. Integer arguments correspond to 32 instruction slots in the segment access area, which occupies the lowest address range of each secure segment. The value 16 is excluded because access entry 16 is reserved for the secure segment interrupt vector. The value unused is used to specify a function for all of the unused slots in the access area. Access entry points facilitate the creation of application segments from different vendors that are combined at runtime. They can be specified for external functions as well as locally defined functions. For example:
/* an external function that we wish to call */ extern void __attribute__((boot(3))) boot_service3(); /* local function callable from other segments */ void __attribute__((secure(4))) secure_service4() { boot_service3(); }
To specify a secure interrupt handler, use the boot attribute in combination with the interrupt attribute:
void __attribute__((boot,interrupt)) boot_interrupts();
When an access entry point is specified for an external secure function, that function need not be included in the project for a successful link. All references to that function will be resolved to a fixed location in Flash, depending on the security model selected at link time. When an access entry point is specified for a locally defined function, the linker will insert a branch instruction into the secure segment access area. The exception is for access entry 16, which is represented as a vector (i.e, an instruction address) rather than an instruction. The actual function definition will be located beyond the access area; therefore the access area will contain a jump table through which control can be transferred from another security segment to functions with defined entry points.
DS51284F-page 21
Note that the initial value of where is based on a string literal which is allocated in the PSV constant section .boot_const. The compiler will set PSVPAG to the correct value upon entrance to the function. If necessary, the compiler will also restore PSVPAG after the call to splat().
const
Many functions do not examine any values except their arguments, and have no effects except the return value. Such a function can be subject to common subexpression elimination and loop optimization just as an arithmetic operator would be. These functions should be declared with the attribute const. For example:
int square (int) __attribute__ ((const int));
says that the hypothetical function square is safe to call fewer times than the program says. Note that a function that has pointer arguments and examines the data pointed to must not be declared const. Likewise, a function that calls a non-const function usually must not be const. It does not make sense for a const function to have a void return type.
deprecated
See Section 2.3.1 Specifying Attributes of Variables for information on the deprecated attribute.
far
The far attribute tells the compiler that the function should not be called using a more efficient form of the call instruction.
This causes the compiler to check the arguments in calls to my_printf for consistency with the printf style format string argument my_format. The parameter archetype determines how the format string is interpreted, and should be one of printf, scanf or strftime. The parameter string-index specifies which argument is the format string argument (arguments are numbered from the left, starting from 1), while first-to-check is the number of the first argument to check
DS51284F-page 22
format_arg (string-index)
The format_arg attribute specifies that a function takes printf or scanf style arguments, modifies it (for example, to translate it into another language), and passes it to a printf or scanf style function. For example, consider the declaration:
extern char * my_dgettext (char *my_domain, const char *my_format) __attribute__ ((format_arg (2)));
This causes the compiler to check the arguments in calls to my_dgettext, whose result is passed to a printf, scanf or strftime type function for consistency with the printf style format string argument my_format. The parameter string-index specifies which argument is the format string argument (starting from 1). The format-arg attribute allows you to identify your own functions which modify format strings, so that MPLAB C30 can check the calls to printf, scanf or strftime function, whose operands are a call to one of your own functions.
near
The near attribute tells the compiler that the function can be called using a more efficient form of the call instruction.
no_instrument_function
If the command line option -finstrument-function is given, profiling function calls will be generated at entry and exit of most user-compiled functions. Functions with this attribute will not be so instrumented.
DS51284F-page 23
noreturn
A few standard library functions, such as abort and exit, cannot return. MPLAB C30 knows this automatically. Some programs define their own functions that never return. You can declare them noreturn to tell the compiler this fact. For example:
void fatal (int i) __attribute__ ((noreturn)); void fatal (int i) { /* Print error message. */ exit (1); }
The noreturn keyword tells the compiler to assume that fatal cannot return. It can then optimize without regard to what would happen if fatal ever did return. This makes slightly better code. Also, it helps avoid spurious warnings of uninitialized variables. It does not make sense for a noreturn function to have a return type other than void.
section ("section-name")
Normally, the compiler places the code it generates in the .text section. Sometimes, however, you need additional sections, or you need certain functions to appear in special sections. The section attribute specifies that a function lives in a particular section. For example, consider the declaration:
extern void foobar (void) __attribute__ ((section (".libtext")));
This puts the function foobar in the .libtext section. The section attribute conflicts with the address attribute. The section name will be ignored with a warning.
secure
This attribute directs the compiler to allocate a function in the secure segment of program Flash. For example, to declare a protected function:
void __attribute__((secure)) func();
An optional argument can be used to specify a protected access entry point within the secure segment. The argument may be a literal integer in the range 0 to 31 (except 16), or the word unused. Integer arguments correspond to 32 instruction slots in the segment access area, which occupies the lowest address range of each secure segment. The value 16 is excluded because access entry 16 is reserved for the secure segment interrupt vector. The value unused is used to specify a function for all of the unused slots in the access area.
DS51284F-page 24
To specify a secure interrupt handler, use the secure attribute in combination with the interrupt attribute:
void __attribute__((secure,interrupt)) secure_interrupts();
When an access entry point is specified for an external secure function, that function need not be included in the project for a successful link. All references to that function will be resolved to a fixed location in Flash, depending on the security model selected at link time. When an access entry point is specified for a locally defined function, the linker will insert a branch instruction into the secure segment access area. The exception is for access entry 16, which is represented as a vector (i.e, an instruction address) rather than an instruction. The actual function definition will be located beyond the access area; therefore the access area will contain a jump table through which control can be transferred from another security segment to functions with defined entry points. Auto Variables: Automatic variables (variables defined within a function) are subject to different rules than file scope variables. Automatic variables are owned by the enclosing function and do not need the boot or secure attribute. They may be assigned initial values, as shown:
void __attribute__((boot)) chuck_cookies() { int hurl; int them = 55; char *where = "far"; splat(where); /* ... */ }
Note that the initial value of where is based on a string literal which is allocated in the PSV constant section .boot_const. The compiler will set PSVPAG to the correct value upon entrance to the function. If necessary, the compiler will also restore PSVPAG after the call to splat().
shadow
The shadow attribute causes the compiler to use the shadow registers rather than the software stack for saving registers. This attribute is usually used in conjunction with the interrupt attribute.
void __attribute__ ((interrupt, shadow)) _T1Interrupt (void);
unused
This attribute, attached to a function, means that the function is meant to be possibly unused. MPLAB C30 will not produce an unused function warning for this function.
DS51284F-page 25
2.3.3
Inline Functions
By declaring a function inline, you can direct MPLAB C30 to integrate that functions code into the code for its callers. This usually makes execution faster by eliminating the function-call overhead. In addition, if any of the actual argument values are constant, their known values may permit simplifications at compile time, so that not all of the inline functions code needs to be included. The effect on code size is less predictable. Machine code may be larger or smaller with inline functions, depending on the particular case. Note: Function inlining will only take place when the functions definition is visible (not just the prototype). In order to have a function inlined into more than one source file, the function definition may be placed into a header file that is included by each of the source files.
To declare a function inline, use the inline keyword in its declaration, like this:
inline int inc (int *a) { (*a)++; }
(If you are using the -traditional option or the -ansi option, write __inline__ instead of inline.) You can also make all simple enough functions inline with the command-line option -finline-functions. The compiler heuristically decides which functions are simple enough to be worth integrating in this way, based on an estimate of the functions size. Note: The inline keyword will only be recognized with -finline or optimizations enabled.
Certain usages in a function definition can make it unsuitable for inline substitution. Among these usages are: use of varargs, use of alloca, use of variable-sized data, use of computed goto and use of nonlocal goto. Using the command-line option -Winline will warn when a function marked inline could not be substituted, and will give the reason for the failure. In MPLAB C30 syntax, the inline keyword does not affect the linkage of the function. When a function is both inline and static, if all calls to the function are integrated into the caller and the functions address is never used, then the functions own assembler code is never referenced. In this case, MPLAB C30 does not actually output assembler code for the function, unless you specify the command-line option -fkeep-inline-functions. Some calls cannot be integrated for various reasons (in particular, calls that precede the functions definition cannot be integrated and neither can recursive calls within the definition). If there is a nonintegrated call, then the function is compiled to assembler code as usual. The function must also be compiled as usual if the program refers to its address, because that cant be inlined. The compiler will only eliminate inline functions if they are declared to be static and if the function definition precedes all uses of the function.
DS51284F-page 26
2.3.4
MPLAB C30 allows you to put a few global variables into specified hardware registers. Note: Using too many registers, in particular register W0, may impair MPLAB C30s ability to compile.
You can also specify the register in which an ordinary register variable should be allocated. Global register variables reserve registers throughout the program. This may be useful in programs such as programming language interpreters which have a couple of global variables that are accessed very often. Local register variables in specific registers do not reserve the registers. The compilers data flow analysis is capable of determining where the specified registers contain live values, and where they are available for other uses. Stores into local register variables may be deleted when they appear to be unused. References to local register variables may be deleted, moved or simplified. These local variables are sometimes convenient for use with the extended inline assembly (see Chapter 8. Mixing Assembly Language and C Modules), if you want to write one output of the assembler instruction directly into a particular register. (This will work provided the register you specify fits the constraints specified for that operand in the inline assembly statement). 2.3.4.1 DEFINING GLOBAL REGISTER VARIABLES
You can define a global register variable in MPLAB C30 like this:
register int *foo asm ("w8");
Here w8 is the name of the register which should be used. Choose a register that is normally saved and restored by function calls (W8-W13), so that library routines will not clobber it. Defining a global register variable in a certain register reserves that register entirely for this use, at least within the current compilation. The register will not be allocated for any other purpose in the functions in the current compilation. The register will not be saved and restored by these functions. Stores into this register are never deleted even if they would appear to be dead, but references may be deleted, moved or simplified. It is not safe to access the global register variables from signal handlers, or from more than one thread of control, because the system library routines may temporarily use the register for other things (unless you recompile them especially for the task at hand).
DS51284F-page 27
You can define a local register variable with a specified register like this:
register int *foo asm ("w8");
Here w8 is the name of the register that should be used. Note that this is the same syntax used for defining global register variables, but for a local variable it would appear within a function. Defining such a register variable does not reserve the register; it remains available for other uses in places where flow control determines the variables value is not live. Using this feature may leave the compiler too few available registers to compile certain functions. This option does not ensure that MPLAB C30 will generate code that has this variable in the register you specify at all times. You may not code an explicit reference to this register in an asm statement and assume it will always refer to this variable. Assignments to local register variables may be deleted when they appear to be unused. References to local register variables may be deleted, moved or simplified.
2.3.5
Complex Numbers
MPLAB C30 supports complex data types. You can declare both complex integer types and complex floating types, using the keyword __complex__. For example, __complex__ float x; declares x as a variable whose real part and imaginary part are both of type float. __complex__ short int y; declares y to have real and imaginary parts of type short int. To write a constant with a complex data type, use the suffix 'i' or 'j' (either one; they are equivalent). For example, 2.5fi has type __complex__ float and 3i has type __complex__ int. Such a constant is a purely imaginary value, but you can form any complex value you like by adding one to a real constant.
DS51284F-page 28
The operator '~' performs complex conjugation when used on a value with a complex type. MPLAB C30 can allocate complex automatic variables in a noncontiguous fashion; its even possible for the real part to be in a register while the imaginary part is on the stack (or vice-versa). The debugging information format has no way to represent noncontiguous allocations like these, so MPLAB C30 describes noncontiguous complex variables as two separate variables of noncomplex type. If the variables actual name is foo, the two fictitious variables are named foo$real and foo$imag.
2.3.6
Double-Word Integers
MPLAB C30 supports data types for integers that are twice as long as long int. Simply write long long int for a signed integer, or unsigned long long int for an unsigned integer. To make an integer constant of type long long int, add the suffix LL to the integer. To make an integer constant of type unsigned long long int, add the suffix ULL to the integer. You can use these types in arithmetic like any other integer types. Addition, subtraction and bitwise boolean operations on these types are open-coded, but division and shifts are not open-coded. The operations that are not open-coded use special library routines that come with MPLAB C30.
2.3.7
Another way to refer to the type of an expression is with the typeof keyword. The syntax for using this keyword looks like sizeof, but the construct acts semantically like a type name defined with typedef. There are two ways of writing the argument to typeof: with an expression or with a type. Here is an example with an expression:
typeof (x[0](1))
This assumes that x is an array of functions; the type described is that of the values of the functions. Here is an example with a typename as the argument:
typeof (int *)
Here the type described is a pointer to int. If you are writing a header file that must work when included in ANSI C programs, write __typeof__ instead of typeof.
DS51284F-page 29
Thus, array (pointer (char), 4) is the type of arrays of four pointers to char.
2.4
STATEMENT DIFFERENCES
This section describes the statement differences between plain ANSI C and the C accepted by MPLAB C30. The statement differences are part of the base GCC implementation, and the discussion in the section is based on the standard GCC documentation, tailored for the specific syntax and semantics of the MPLAB C30 port of GCC. Labels as Values Conditionals with Omitted Operands Case Ranges
2.4.1
Labels as Values
You can get the address of a label defined in the current function (or a containing function) with the unary operator '&&'. The value has type void *. This value is a constant and can be used wherever a constant of that type is valid. For example:
void *ptr; ... ptr = &&foo;
To use these values, you need to be able to jump to one. This is done with the computed goto statement, goto *exp;. For example:
goto *ptr;
Any expression of type void * is allowed. One way of using these constants is in initializing a static array that will serve as a jump table:
static void *array[] = { &&foo, &&bar, &&hack };
Note:
This does not check whether the subscript is in bounds. (Array indexing in C never does.)
DS51284F-page 30
2.4.2
The middle operand in a conditional expression may be omitted. Then if the first operand is nonzero, its value is the value of the conditional expression. Therefore, the expression:
x ? : y
has the value of x if that is nonzero; otherwise, the value of y. This example is perfectly equivalent to:
x ? x : y
In this simple case, the ability to omit the middle operand is not especially useful. When it becomes useful is when the first operand does, or may (if it is a macro argument), contain a side effect. Then repeating the operand in the middle would perform the side effect twice. Omitting the middle operand uses the value already computed without the undesirable effects of recomputing it.
2.4.3
Case Ranges
You can specify a range of consecutive values in a single case label, like this:
case low ... high:
This has the same effect as the proper number of individual case labels, one for each integer value from low to high, inclusive. This feature is especially useful for ranges of ASCII character codes:
case 'A' ... 'Z':
Be careful: Write spaces around the ..., otherwise it may be parsed incorrectly when you use it with integer values. For example, write this:
case 1 ... 5:
2.5
EXPRESSION DIFFERENCES
This section describes the expression differences between plain ANSI C and the C accepted by MPLAB C30.
2.5.1
Binary Constants
A sequence of binary digits preceded by 0b or 0B (the numeral '0' followed by the letter 'b' or 'B') is taken to be a binary integer. The binary digits consist of the numerals '0' and '1'. For example, the (decimal) number 255 can be written as 0b11111111. Like other integer constants, a binary constant may be suffixed by the letter 'u' or 'U', to specify that it is unsigned. A binary constant may also be suffixed by the letter 'l' or 'L', to specify that it is long. Similarly, the suffix 'll' or 'LL' denotes a long long binary constant.
DS51284F-page 31
DS51284F-page 32
3.2
HIGHLIGHTS
Items discussed in this chapter are: Overview File Naming Conventions Options Environment Variables Predefined Constants Compiling a Single File on the Command Line Compiling Multiple Files on the Command Line
3.3
OVERVIEW
The compilation driver program (pic30-gcc) compiles, assembles and links C and assembly language modules and library archives. Most of the compiler command-line options are common to all implementations of the GCC toolset. A few are specific to the MPLAB C30 compiler. The basic form of the compiler command line is:
pic30-gcc [options] files
Note:
The available options are described in Section 3.5 Options. For example, to compile, assemble and link the C source file hello.c, creating the absolute executable hello.exe.
pic30-gcc -o hello.exe hello.c
DS51284F-page 33
FILE NAMES
Definition A C source file that must be preprocessed. A header file (not to be compiled or linked). A C source file that should not be preprocessed. An object file. A pre procedural-abstraction assembly language file. Assembler code. Assembler code that must be preprocessed. A file to be passed to the linker.
3.5
OPTIONS
MPLAB C30 has many options for controlling compilation, all of which are case-sensitive. Options Specific to dsPIC DSC Devices Options for Controlling the Kind of Output Options for Controlling the C Dialect Options for Controlling Warnings and Errors Options for Debugging Options for Controlling Optimization Options for Controlling the Preprocessor Options for Assembling Options for Linking Options for Directory Search Options for Code Generation Conventions
DS51284F-page 34
For more information on the memory models, see Section 4.7 Memory Models. TABLE 3-2:
Option -mconst-in-code -mconst-in-data -merrata= id[,id]*
-mlarge-code
-mpa(1)
-mpa=n(1)
-mno-pa(1)
Note 1:
The procedure abstractor behaves as the inverse of inlining functions. The pass is designed to extract common code sequences from multiple sites throughout a translation unit and place them into a common area of code. Although this option generally does not improve the run-time performance of the generated code, it can reduce the code size significantly. Programs compiled with -mpa can be harder to debug; it is not recommended that this option be used while debugging using the COFF object format. The procedure abstractor is invoked as a separate phase of compilation, after the production of an assembly file. This phase does not optimize across translation units. When the procedure-optimizing phase is enabled, inline assembly code must be limited to valid machine instructions. Invalid machine instructions or instruction sequences, or assembler directives (sectioning directives, macros, include files, etc.) must not be used, or the procedure abstraction phase will fail, inhibiting the creation of an output file.
DS51284F-page 35
-momf=omf
-msmall-code -msmall-data
-msmall-scalar
-mtext=name
-msmart-io [=0|1|2]
Note 1:
The procedure abstractor behaves as the inverse of inlining functions. The pass is designed to extract common code sequences from multiple sites throughout a translation unit and place them into a common area of code. Although this option generally does not improve the run-time performance of the generated code, it can reduce the code size significantly. Programs compiled with -mpa can be harder to debug; it is not recommended that this option be used while debugging using the COFF object format. The procedure abstractor is invoked as a separate phase of compilation, after the production of an assembly file. This phase does not optimize across translation units. When the procedure-optimizing phase is enabled, inline assembly code must be limited to valid machine instructions. Invalid machine instructions or instruction sequences, or assembler directives (sectioning directives, macros, include files, etc.) must not be used, or the procedure abstraction phase will fail, inhibiting the creation of an output file.
DS51284F-page 36
The following options control the kind of output produced by the compiler. TABLE 3-3:
Option -c -E -o file -S -v -x
DS51284F-page 37
The following options define the kind of C dialect used by the compiler. TABLE 3-4:
-ffreestanding
-fno-asm
__builtin_ as prefix.
Let the type char be signed, like signed char. (This is the default.) These options control whether a bit field is signed or unsigned, when the declaration does not use either signed or unsigned. By default, such a bit field is signed, unless -traditional is used, in which case bit fields are always unsigned. Let the type char be unsigned, like unsigned char. Store strings in the writable data segment and dont make them unique.
DS51284F-page 38
-Werror-implicitfunction-declaration -Wformat
-Wmissing-braces
DS51284F-page 39
-Wparentheses
-Wreturn-type
-Wsequence-point
DS51284F-page 40
Option
-Wsystem-headers
-Wtrigraphs -Wuninitialized
-Wunknown-pragmas
-Wunused
-Wunused-function -Wunused-label
DS51284F-page 41
-Wunused-variable
-Wunused-value
The following -W options are not implied by -Wall. Some of them warn about constructions that users generally do not consider questionable, but which occasionally you might wish to check for. Others warn about constructions that are necessary or hard to avoid in some cases, and there is no simple way to modify the code to suppress the warning.
DS51284F-page 42
Option
-Wcast-qual
DS51284F-page 43
Option
-Werror -Winline
-Wmissing-declarations Warn if a global function is defined without a previous declaration. Do so even if the definition itself provides a prototype. -Wmissingformat-attribute If -Wformat is enabled, also warn about functions that might be candidates for format attributes. Note these are only possible candidates, not absolute ones. This option has no effect unless -Wformat is enabled. Warn about functions that might be candidates for attribute noreturn. These are only possible candidates, not absolute ones. Care should be taken to manually verify functions. Actually, do not ever return before adding the noreturn attribute; otherwise subtle code generation bugs could be introduced. Warn if a global function is defined without a previous prototype declaration. This warning is issued even if the definition itself provides a prototype. (This option can be used to detect global functions that are not declared in header files.) Warn if an extern declaration is encountered within a function. Do not warn about uses of functions, variables and types marked as deprecated by using the deprecated attribute. Warn if padding is included in a structure, either to align an element of the structure or to align the whole structure. Warn about anything that depends on the size of a function type or of void. MPLAB C30 assigns these types a size of 1, for convenience in calculations with void * pointers and pointers to functions. Warn if anything is declared more than once in the same scope, even in cases where multiple declaration is valid and changes nothing. Warn whenever a local variable shadows another local variable.
-Wmissing-noreturn
-Wmissing-prototypes
-Wredundant-decls
-Wshadow
DS51284F-page 44
-Wstrict-prototypes
-Wtraditional
-Wundef -Wunreachable-code
-Wwrite-strings
DS51284F-page 45
-Q
-save-temps
3.5.6
-O -O1
DS51284F-page 46
Option
-O3
-Os
The following options control specific optimizations. The -O2 option turns on all of these optimizations except -funroll-loops, -funroll-all-loops and -fstrict-aliasing. You can use the following flags in the rare cases when fine-tuning of optimizations to be performed is desired. TABLE 3-9: SPECIFIC OPTIMIZATION OPTIONS
Definition Align the start of functions to the next power-of-two greater than n, skipping up to n bytes. For instance, -falign-functions=32 aligns functions to the next 32-byte boundary, but -falign-functions=24 would align to the next 32-byte boundary only if this can be done by skipping 23 bytes or less. -fno-align-functions and -falign-functions=1 are equivalent and mean that functions will not be aligned. The assembler only supports this flag when n is a power of two; so n is rounded up. If n is not specified, use a machine-dependent default. Align all branch targets to a power-of-two boundary, skipping up to n bytes like -falign-functions. This option can easily make code slower, because it must insert dummy operations for when the branch target is reached in the usual flow of the code. If -falign-loops or -falign-jumps are applicable and are greater than this value, then their values are used instead. If n is not specified, use a machine-dependent default which is very likely to be 1, meaning no alignment. Align loops to a power-of-two boundary, skipping up to n bytes like -falign-functions. The hope is that the loop will be executed many times, which will make up for any execution of the dummy operations. If n is not specified, use a machine-dependent default. Enable values to be allocated in registers that will be clobbered by function calls, by emitting extra instructions to save and restore the registers around such calls. Such allocation is done only when it seems to result in better code than would otherwise be produced. Option -falign-functions -falign-functions=n
-falign-labels -falign-labels=n
-falign-loops -falign-loops=n
-fcaller-saves
DS51284F-page 47
-fcse-skip-blocks
-fgcse
-fgcse-lm
-fgcse-sm
-fmove-all-movables -fno-defer-pop
-fno-peephole -fno-peephole2
-foptimizeregister-move -fregmove
DS51284F-page 48
-frename-registers
-fschedule-insns2
-fstrength-reduce -fstrict-aliasing
DS51284F-page 49
-funroll-loops
-funroll-all-loops
Options of the form -fflag specify machine-independent flags. Most flags have both positive and negative forms; the negative form of -ffoo would be -fno-foo. In the table below, only one of the forms is listed (the one that is not the default.) TABLE 3-10:
-fforce-mem
Option
-finline-functions
-finline-limit=n
DS51284F-page 50
-fkeep-static-consts
-fno-function-cse
-fno-inline
-fomit-frame-pointer
-foptimize-sibling-calls
3.5.7
-A -predicate =answer Cancel an assertion with the predicate predicate and answer answer. -A predicate =answer Make an assertion with the predicate predicate and answer answer. This form is preferred to the older form -A predicate(answer), which is still supported, because it does not use shell special characters.
DS51284F-page 51
Option
-dN -fno-show-column
-H -I-
-Idir
-idirafter dir
-imacros file
DS51284F-page 52
-iwithprefix dir
-iwithprefixbefore dir -M
-MD
-MF file
-MG
-MM
-MMD
DS51284F-page 53
Option
-MQ
-MT target
-nostdinc
-P
3.5.8
3.5.9
DS51284F-page 54
LINKING OPTIONS
Definition Add directory dir to the list of directories to be searched for libraries specified by the command-line option -l. Search the library named library when linking. The linker searches a standard list of directories for the library, which is actually a file named liblibrary.a. The linker then uses this file as if it had been specified precisely by name. It makes a difference where in the command you write this option; the linker processes libraries and object files in the order they are specified. Thus, foo.o -lz bar.o searches library z after file foo.o but before bar.o. If bar.o refers to functions in libz.a, those functions may not be loaded. The directories searched include several standard system directories, plus any that you specify with -L. Normally the files found this way are library files (archive files whose members are object files). The linker handles an archive file by scanning through it for members which define symbols that have so far been referenced but not defined. But if the file that is found is an ordinary object file, it is linked in the usual fashion. The only difference between using an -l option (e.g., -lmylib) and specifying a file name (e.g., libmylib.a) is that -l searches several directories, as specified. By default the linker is directed to search: <install-path>\lib for libraries specified with the -l option. For a compiler installed into the default location, this would be: c:\Program Files\Microchip\MPLAB C30\lib This behavior can be overridden using the environment variables defined in Section 3.6 Environment Variables. Do not use the standard system libraries when linking. Only the libraries you specify will be passed to the linker. The compiler may generate calls to memcmp, memset and memcpy. These entries are usually resolved by entries in the standard compiler libraries. These entry points should be supplied through some other mechanism when this option is specified. Do not use the standard system startup files or libraries when linking. No startup files and only the libraries you specify will be passed to the linker. The compiler may generate calls to memcmp, memset and memcpy. These entries are usually resolved by entries in standard compiler libraries. These entry points should be supplied through some other mechanism when this option is specified. Remove all symbol table and relocation information from the executable. Pretend symbol is undefined to force linking of library modules to define the symbol. It is legitimate to use -u multiple times with different symbols to force loading of additional library modules. Pass option as an option to the linker. If option contains commas, it is split into multiple options at the commas.
-nodefaultlibs
-nostdlib
-s -u symbol
-Wl,option
-Xlinker option Pass option as an option to the linker. You can use this to supply system-specific linker options that MPLAB C30 does not know how to recognize.
DS51284F-page 55
-specs=file
3.5.11
Options of the form -fflag specify machine-independent flags. Most flags have both positive and negative forms; the negative form of -ffoo would be -fno-foo. In the table below, only one of the forms is listed (the one that is not the default.) TABLE 3-15:
Option -fargument-alias -fargument-noalias -fargumentnoalias-global
DS51284F-page 56
-fcall-used-reg
-ffixed-reg
-finstrumentfunctions
-fno-ident
DS51284F-page 57
-fpcc-structreturn
-fno-short-double
-fshort-enums
-fverbose-asm -fno-verbose-asm
DS51284F-page 58
PIC30_C_INCLUDE_ This variable's value is a semicolon-separated list of directories, much PATH like PATH. When MPLAB C30 searches for header files, it tries the directories listed in the variable, after the directories specified with -I but before the standard header file directories. If the environment variable is undefined, the preprocessor chooses an appropriate value based on the standard installation. By default, the following directories are searched for include files: <install-path>\include and <install-path>\support\h PIC30_COMPILER_ PATH The value of PIC30_COMPILER_PATH is a semicolon-separated list of directories, much like PATH. MPLAB C30 tries the directories thus specified when searching for subprograms, if it cant find the subprograms using PIC30_EXEC_PREFIX. If PIC30_EXEC_PREFIX is set, it specifies a prefix to use in the names of subprograms executed by the compiler. No directory delimiter is added when this prefix is combined with the name of a subprogram, but you can specify a prefix that ends with a slash if you wish. If MPLAB C30 cannot find the subprogram using the specified prefix, it tries looking in your PATH environment variable. If the PIC30_EXEC_PREFIX environment variable is unset or set to an empty value, the compiler driver chooses an appropriate value based on the standard installation. If the installation has not been modified, this will result in the driver being able to locate the required subprograms. Other prefixes specified with the -B command line option take precedence over the user- or driver-defined value of PIC30_EXEC_PREFIX. Under normal circumstances it is best to leave this value undefined and let the driver locate subprograms itself. This variable's value is a semicolon-separated list of directories, much like PATH. This variable specifies a list of directories to be passed to the linker. The driver's default evaluation of this variable is: <install-path>\lib; <install-path>\support\gld. Specifies the OMF (Object Module Format) to be used by MPLAB C30. By default, the tools create COFF object files. If the environment variable PIC30_OMF has the value elf, the tools will create ELF object files. If TMPDIR is set, it specifies the directory to use for temporary files. MPLAB C30 uses temporary files to hold the output of one stage of compilation that is to be used as input to the next stage: for example, the output of the preprocessor, which is the input to the compiler proper.
PIC30_EXEC_ PREFIX
PIC30_LIBRARY_ PATH
PIC30_OMF
TMPDIR
DS51284F-page 59
3.7.1
Constants
The following preprocessing symbols are defined by the compiler being used.
Compiler MPLAB C30 C30 Symbol Defined with -ansi command-line option? No Yes Yes No Yes Yes No Yes Yes
__C30 __C30__
ELF-specific C30ELF
__C30ELF __C30ELF__
COFF-specific C30COFF
In addition, the compiler defines a symbol based on the target device set with -mcpu=. For example, -mcpu=30F6014, which defines the symbol __dsPIC30F6014__. The compiler will define the constant __C30_VERSION__, giving a numeric value to the version identifier. This can be used to take advantage of new compiler features while still remaining backward compatible with older versions. The value is based upon the major and minor version numbers of the current release. For example, release version 2.00 will have a __C30_VERSION__ definition of 200. This macro can be used, in conjunction with standard preprocessor comparison statements, to conditionally include/exclude various code constructs. The current definition of __C30_VERSION__ can be discovered by adding --version to the command line, or by inspecting the README.TXT file that came with the release.
3.7.2
Deprecated Constants
Constants that have been deprecated may be found in Appendix E. Deprecated Features.
3.8
DS51284F-page 60
The first line of the program includes the header file p30f2010.h, which provides definitions for all special function registers on that part. For more information on header files, see Chapter 6. Device Support Files. Compile the program by typing the following at a DOS prompt:
C:\> pic30-gcc -o ex1.o ex1.c
The command-line option -o ex1.o names the output COFF executable file (if the -o option is not specified, then the output file is named a.exe). The COFF executable file may be loaded into the MPLAB IDE. If a hex file is required, for example to load into a device programmer, then use the following command:
C:\> pic30-bin2hex ex1.o
3.9
DS51284F-page 61
This command compiles the modules ex1.c and add.c. The compiled modules are linked with the compiler libraries and the executable file ex1.o is created.
DS51284F-page 62
MPLAB C30 USERS GUIDE Chapter 4. MPLAB C30 C Compiler Runtime Environment
4.1 INTRODUCTION
This section discusses the MPLAB C30 C Compiler runtime environment.
4.2
HIGHLIGHTS
Items discussed in this chapter are: Address Spaces Code and Data Sections Startup and Initialization Memory Spaces Memory Models Locating Code and Data Software Stack The C Stack Usage The C Heap Usage Function Call Conventions Register Conventions Bit Reversed and Modulo Addressing Program Space Visibility (PSV) Usage
4.3
ADDRESS SPACES
The dsPIC Digital Signal Controller (DSC) devices are a combination of traditional PIC Microcontroller (MCU) features (peripherals, Harvard architecture, RISC) and new DSP capabilities. The dsPIC DSC devices have two distinct memory regions: Program Memory (Figure 4-1) contains executable code and optionally constant data. Data Memory (Figure 4-2) contains external variables, static variables, the system stack and file registers. Data memory consists of near data, which is memory in the first 8 KB of the data memory space, and far data, which is in the upper 56 KB of data memory space. Although the program and data memory regions are distinctly separate, the compiler can access constant data in program memory through the program space visibility window.
DS51284F-page 63
GENERAL
.const .dinit
NEAR
008000
.text .handle
General Program Storage Far Code Handles Reset and Exception Vectors
FIGURE 4-2:
DATA SPACE MEMORY MAP FFFF .const Program Space Visibility Data Window (PSV) Stack (Grows Up) Heap (Optional) .ybss, .ydata 2000 .bss, .data .nbss, .ndata .xbss, .xdata 0 General Data Memory X Data Memory Memory Mapped SFRs Y Data Memory
GENERAL
8000
NEAR
DS51284F-page 64
Each default section and a description of the type of information stored into that section is listed below.
.text
Executable code is allocated into the .text section.
.data
Initialized variables with the far attribute are allocated into the .data section. When the large data memory model is selected (i.e., when using the -mlarge-data command-line option), this is the default location for initialized variables.
.ndata
Initialized variables with the near attribute are allocated into the .ndata section. When the small data memory model is selected (i.e., when using the default -msmall-data command-line option), this is the default location for initialized variables.
.const
Constant values, such as string constants and const-qualified variables, are allocated into the .const section when using the default -mconst-in-code command-line option. This section is intended to be located in program memory and accessed using the PSV window. Variables may also be placed into the .const section by using the section attribute:
int i __attribute__((space(auto_psv)));
DS51284F-page 65
.ndconst
Constant values, such as string constants and const-qualified variables, are allocated into the .ndconst section when using the default -msmall-data command-line option without using the -mconst-in-code command-line option. Unless the linker option --no-data-init is specified, the MPLAB C30 startup code will initialize this section by copying data from the .dinit section. The .dinit section is created by the linker and located in program memory.
.bss
Uninitialized variables with the far attribute are allocated into the .bss section. When the large data memory model is selected (i.e., when using the -mlarge-data command-line option), this is the default location for uninitialized variables.
.nbss
Uninitialized variables with the near attribute are allocated into the .nbss section. When the small data memory model is selected (i.e., when using the default -msmall-data command-line option), this is the default location for initialized variables.
To take advantage of persistent data storage, the main() function should begin with a test to determine what type of reset has occurred. Various bits in the RCON reset control register can be tested to determine the reset source. See Section 8 in the dsPIC30F Family Reference Manual (DS70046) for more information.
DS51284F-page 66
4. The function main is called with no parameters. 5. If main returns, the processor will reset. The alternate startup module (crt1.o) is linked when the -Wl, --no-data-init option is specified. It performs the same operations, except for step (3), which is omitted. The alternate startup module is smaller than the primary module, and can be selected to conserve program memory if data initialization is not required. Source code (in dsPIC DSC assembly language) for both modules is provided in the c:\Program Files\Microchip\MPLAB C30\src directory. The startup modules may be modified if necessary. For example, if an application requires main to be called with parameters, a conditional assembly directive may be changed to provide this support.
DS51284F-page 67
data
General data space. Variables in general data space can be accessed using ordinary C statements. This is the default allocation.
prog
General program space, which is normally reserved for executable code. Variables in program space can not be accessed using ordinary C statements. They must be explicitly accessed by the programmer, usually using table-access inline assembly instructions, or using the program space visibility window.
const
A compiler-managed area in program space, designated for program space visibility window access. Variables in const space can be read (but not written) using ordinary C statements, and are subject to a maximum of 32K total space allocated.
psv
Program space, designated for program space visibility window access. Variables in PSV space are not managed by the compiler and can not be accessed using ordinary C statements. They must be explicitly accessed by the programmer, usually using table-access inline assembly instructions, or using the program space visibility window. Variables in PSV space can be accessed using a single setting of the PSVPAG register.
DS51284F-page 68
-mlarge-code
-mconst-in-data -mconst-in-code
The command-line options apply globally to the modules being compiled. Individual variables and functions can be declared as near or far to better control the code generation. For information on setting individual variable or function attributes, see Section 2.3.1 Specifying Attributes of Variables and Section 2.3.2 Specifying Attributes of Functions.
4.7.1
If variables are allocated in the near data section, the compiler is often able to generate better (more compact) code than if the variables are not allocated in the near data section. If all variables for an application can fit within the 8 KB of near data, then the compiler can be requested to place them there by using the default -msmall-data command line option when compiling each module. If the amount of data consumed by scalar types (no arrays or structures) totals less than 8 KB, the default -msmall-scalar may be used. This requests that the compiler arrange to have just the scalars for an application allocated in the near data section. If neither of these global options is suitable, then the following alternatives are available.
DS51284F-page 69
4.7.2
Functions that are near (within a radius of 32 Kwords of each other) may call each other more efficiently that those which are not. If it is known that all functions in an application are near, then the default -msmall-code command line option can be used when compiling each module to direct the compiler to use a more efficient form of the function call. If this default option is not suitable, then the following alternatives are available: 1. It is possible to compile some modules of an application using the -msmall-code command line option. In this case, only function calls in those modules will use a more efficient form of the function call. 2. If the -msmall-code command-line option has been used, then the compiler may be directed to use the long form of the function call for an individual function by tagging it with the far attribute. 3. Instead of using command-line options, which have module scope, the compiler may be directed to call individual functions using a more efficient form of the function call by tagging their declaration and definition with the near attribute. The -msmall-code command-line option differs from the -msmall-data command-line option in that in the former case, the compiler does nothing special to ensure that functions are allocated near one another, whereas in the latter case, the compiler will allocate variables in a special section. The linker will produce an error message if the function declared to be near cannot be reached by one of its callers using a more efficient form of the function call.
DS51284F-page 70
Another way to locate code or data is by placing the function or variable into a user-defined section, and specifying the starting address of that section in a custom linker script. This is done as follows: 1. Modify the code or data declaration in the C source to specify a user-defined section. 2. Add the user-defined section to a custom linker script file to specify the starting address of the section. For example, to locate the function PrintString at address 0x8000 in program memory, first declare the function as follows in the C source: int __attribute__((__section__(".myTextSection"))) PrintString(const char *s); The section attribute specifies that the function should be placed in a section named .myTextSection, rather than the default .text section. It does not specify where the user-defined section is to be located. That must be done in a custom linker script, as follows. Using the device-specific linker script as a base, add the following section definition: .myTextSection 0x8000 : { *(.myTextSection); } >program This specifies that the output file should contain a section named .myTextSection starting at location 0x8000 and containing all input sections named.myTextSection. Since, in this example, there is a single function PrintString in that section, then the function will be located at address 0x8000 in program memory. Similarly, to locate the variable Mabonga at address 0x1000 in data memory, first declare the variable as follows in the C source: int __attribute__((__section__(".myDataSection"))) Mabonga = 1;
DS51284F-page 71
4.9
SOFTWARE STACK
The dsPIC DSC device dedicates register W15 for use as a software Stack Pointer. All processor stack operations, including function calls, interrupts and exceptions, use the software stack. The stack grows upward, towards higher memory addresses. The dsPIC DSC device also supports stack overflow detection. If the Stack Pointer Limit register, SPLIM, is initialized, the device will test for overflow on all stack operations. If an overflow should occur, the processor will initiate a stack error exception. By default, this will result in a processor reset. Applications may also install a stack error exception handler by defining an interrupt function named _StackError. See Chapter 7. Interrupts for details. The C runtime startup module initializes the Stack Pointer (W15) and the Stack Pointer Limit register during the startup and initialization sequence. The initial values are normally provided by the linker, which allocates the largest stack possible from unused data memory. The location of the stack is reported in the link map output file. Applications can ensure that at least a minimum-sized stack is available with the --stack linker command-line option. See the MPLAB ASM30, MPLAB LINK30 and Utilities Users Guide (DS51317) for details. Alternatively, the stack of specific size may be allocated with a user-defined section in a custom linker script. In the following example, 0x100 bytes of data memory are reserved for the stack. Two symbols are declared, __SP_init and __SPLIM_init, for use by the C runtime startup module: .stack : { __SP_init = .; . += 0x100 __SPLIM_init = .; . += 8 } >data __SP_init defines the initial value for the Stack Pointer (W15) and __SPLIM_init defines the initial value for the Stack Pointer Limit register (SPLIM). The value of __SPLIM_init should be at least 8 bytes less than the physical stack limit, to allow for stack error exception processing. This value should be decreased further to account for stack usage by the interrupt handler itself, if a stack error interrupt handler is installed. The default interrupt handler does not require additional stack usage.
DS51284F-page 72
The runtime stack grows upward from lower addresses to higher addresses. The compiler uses two working registers to manage the stack: W15 This is the Stack Pointer (SP). It points to the top of stack which is defined to be the first unused location on the stack. W14 This is the Frame Pointer (FP). It points to the current functions frame. Each function, if required, creates a new frame at the top of the stack from which automatic and temporary variables are allocated. The compiler option -fomit-frame-pointer can be used to restrict the use of the FP. FIGURE 4-3: STACK AND FRAME POINTERS Stack grows toward greater addresses SP (W15) Function Frame FP (W14)
The C runtime startup modules (crt0.o and crt1.o in libpic30.a) initialize the Stack Pointer W15 to point to the bottom of the stack and initialize the Stack Pointer Limit register to point to the top of the stack. The stack grows up and if it should grow beyond the value in the Stack Pointer Limit register, then a stack error trap will be taken. The user may initialize the Stack Pointer Limit register to further restrict stack growth. The following diagrams illustrate the steps involved in calling a function. Executing a CALL or RCALL instruction pushes the return address onto the software stack. See Figure 4-4.
DS51284F-page 73
The called function (callee) can now allocate space for its local context (Figure 4-5). FIGURE 4-5: CALLEE SPACE ALLOCATION SP (W15) Local Variables and Temporaries Previous FP Return addr [23:16] Stack grows toward greater addresses Return addr [15:0] Parameter 1 : Parameter n-1 Parameter n Callers Frame FP (W14)
DS51284F-page 74
[W14+n] accesses local context FP (W14) [W14-n] accesses stack-based function parameters
4.11
DS51284F-page 75
REGISTERS REQUIRED
Number of Registers Required
Parameters are placed in the first aligned contiguous register(s) that are available. The calling function must preserve the parameters, if required. Structures do not have any alignment restrictions; a structure parameter will occupy registers if there are enough registers to hold the entire structure. Function results are stored in consecutive registers, beginning with W0.
4.12.1
Function Parameters
The first eight working registers (W0-W7) are used for function parameters.Parameters are allocated to registers in left-to-right order, and a parameter is assigned to the first available register that is suitably aligned. In the following example, all parameters are passed in registers, although not in the order that they appear in the declaration. This format allows the MPLAB C30 compiler to make the most efficient use of the available parameter registers. EXAMPLE 4-1: FUNCTION CALL MODEL
void params0(short p0, long p1, int p2, char p3, float p4, void *p5) { /* ** W0 p0 ** W1 p2 ** W3:W2 p1 ** W4 p3 ** W5 p5 ** W7:W6 p4 */ ... }
The next example demonstrates how structures are passed to functions. If the complete structure can fit in the available registers, then the structure is passed via registers; otherwise the structure argument will be placed onto the stack.
DS51284F-page 76
Parameters corresponding to the ellipses (...) of a variable-length argument list are not allocated to registers. Any parameter not allocated to registers is pushed onto the stack, in right-to-left order. In the next example, the structure parameter cannot be placed in registers because it is too large. However, this does not prevent the next parameter from using a register spot. EXAMPLE 4-3: FUNCTION CALL MODEL, STACK BASED ARGUMENTS
typedef struct bar { double d,e; } bar; void params2(int i, bar b, int j) { /* ** W0 i ** stack b ** W1 j */ }
Accessing arguments that have been placed onto the stack depends upon whether or not a Frame Pointer has been created. Generally the compiler will produce a Frame Pointer (unless otherwise told not to do so), and stack-based parameters will be accessed via the Frame Pointer register (W14). The above example, b will be accessed from W14-22. The Frame Pointer offset of negative 22 has been calculated (refer to Figure 4-6) by removing 2 bytes for the previous FP, 4 bytes for the return address, followed by 16 bytes for b. When no Frame Pointer is used, the assembly programmer must know how much stack space has been used since entry to the procedure. If no further stack space is used, the calculation is similar to the above. b would be accessed via W15-20; 4 bytes for the return address and 16 bytes to access the start of b.
4.12.2
Return Value
Function return values are returned in W0 for 8- or 16-bit scalars, W1:W0 for 32-bit scalars, and W3:W2:W1:W0 for 64-bit scalars. Aggregates are returned indirectly through W0, which is set up by the function caller to contain the address of the aggregate value.
DS51284F-page 77
4.13
REGISTER CONVENTIONS
Specific registers play specific roles in the C runtime environment. Register variables use one or more working registers, as shown in Table 4-4. TABLE 4-4: REGISTER CONVENTIONS
Variable Working Register
char, signed char, unsigned char W0-W13, and W14 if not used as a Frame Pointer. short, signed short, unsigned short int, signed int,unsigned int void * (or any pointer) W0-W13, and W14 if not used as a Frame Pointer. W0-W13, and W14 if not used as a Frame Pointer. W0-W13, and W14 if not used as a Frame Pointer.
long, signed long, unsigned long A pair of contiguous registers, the first of which is a register from the set {W0, W2, W4, W6, W8, W10, W12}. The lower-numbered register contains the least significant 16-bits of the value. long long, signed long long, unsigned long long A quadruplet of contiguous registers, the first of which is a register from the set {W0, W4, W8}. The lower-numbered register contains the least significant 16-bits of the value. Successively higher-numbered registers contain successively more significant bits. A pair of contiguous registers, the first of which is a register from the set {W0, W2, W4, W6, W8, W10, W12}. The lower-numbered register contains the least significant 16-bits of the significant. A pair of contiguous registers, the first of which is a register from the set {W0, W2, W4, W6, W8, W10, W12}. The lower-numbered register contains the least significant 16-bits of the significant. A quadruplet of contiguous registers, the first of which is a register from the set {W0, W4, W8}. The lower-numbered register contains the least significant 16-bits of the significant.
float
double*
long double
DS51284F-page 78
4.15
4.15.1
Two new psv constant sections will be defined: .boot_const and .secure_const. These sections are analogous to the generic section .const, except that the compiler uses them independently of the user-selectable constants memory model. Regardless of whether you have selected the constants-in-code or constants-in-data memory model, the compiler will create and manage psv constant sections as needed for secure segments. Consequently, PSVPAG and CORCONbits. PSV must become compiler managed resources. Support for user-managed PSV sections is maintained through an object compatibility model explained below. Upon entrance to a boot or secure function, PSVPAG will be set to the correct value. This value will be restored after any external function call.
4.15.2
In addition to being used as initializers, string literals may also be used as function arguments. For example:
myputs("Enter the Dragon code:\n");
DS51284F-page 79
4.15.3
const-qualified variables with initializers can be supported in secure Flash segments using PSV constant sections managed by the compiler. For example:
const int __attribute__((boot)) time_delay = 55;
If the const qualifier was omitted from the definition of time_delay, this statement would be rejected with an error message. (Initialized variables in secure RAM are not supported). Since the const qualifier has been specified, variable time_delay can be allocated in a PSV constant section that is owned by the boot segment. It is also possible to specify the PSV constant section explicitly with the space(auto_psv) attribute:
int __attribute__((boot,space(auto_psv))) bebop = 20;
Pointer variables initialized with string literals require special processing. For example:
char * const foo __attribute__((boot)) = "eek";
The compiler will recognize that string literal "eek" must be allocated in the same PSV constant section as pointer variable foo. The logic for making that association is already supported in the compiler for named PSV sections.
4.15.4
Since functions in secure segments set PSVPAG to their respective psv constant sections, a convention must be established for managing multiple values of the PSVPAG register. In previous versions of C30, a single value of PSVPAG was set during program startup if the default constants-in-code memory model was selected. The compiler relied upon that preset value for accessing const variables and string literals, as well as any variables specifically nominated with space(auto_psv). C30 v3.0 will provide automatic support for multiple values of PSVPAG. Variables declared with space(auto_psv) may be combined with secure segment constant variables and/or managed psv pointer variables in the same source file. Precompiled objects that assume a single, pre-set value of PSVPAG will be link-compatible with objects that define secure segment psv constants or managed psv variables. Even though PSVPAG is now considered to be a compiler-managed resource, there is no change to the function calling conventions. Objects and libraries created with earlier versions are compatible with 3.0 objects, with the exception of some Interrupt Service Routines as noted in Section 7.10 PSV Usage with Interrupt Service Routines.
DS51284F-page 80
5.2
HIGHLIGHTS
Items discussed in this chapter are: Data Representation Integer Floating Point Pointers
5.3
DATA REPRESENTATION
Multibyte quantities are stored in little endian format, which means: The least significant byte is stored at the lowest address The least significant bit is stored at the lowest-numbered bit position As an example, the long value of 0x12345678 is stored at address 0x100 as follows: 0x100
0x78
0x101
0x56
0x102
0x34
0X103
0x12
As another example, the long value of 0x12345678 is stored in registers w4 and w5: w4
0x5678
w5
0x1234
5.4
INTEGER
Table 5-1 shows integer data types are supported in MPLAB C30. TABLE 5-1: INTEGER DATA TYPES
Type char, signed char unsigned char short, signed short unsigned short int, signed int unsigned int long, signed long unsigned long long long**, signed long long** unsigned long long** ** ANSI-89 extension Bits 8 8 16 16 16 16 32 32 64 64 Min -128 0 -32768 0 -32768 0 -231 0 -2
63
Max 127 255 32767 65535 32767 65535 231 - 1 232 - 1 263 - 1 264 - 1
DS51284F-page 81
5.5
FLOATING POINT
MPLAB C30 uses the IEEE-754 format. Table 5-2 shows floating point data types are supported. TABLE 5-2:
Type float double* long double
2-126
-1022
For information on implementation-defined behavior of floating point numbers, see section Section A.8 Floating Point.
5.6
POINTERS
All MPLAB C30 pointers are 16-bits wide. This is sufficient for full data space access (64 KB) and the small code model (32 Kwords of code.) In the large code model (>32 Kwords of code), pointers may resolve to handles; that is, the pointer is the address of a GOTO instruction which is located in the first 32 Kwords of program space.
DS51284F-page 82
6.2
HIGHLIGHTS
Items discussed in this chapter are: Processor Header Files Register Definition Files Using SFRs Using Macros Accessing EEDATA from C Code - dsPIC30F dSCs only
6.3
where xxxx corresponds to the device part number. The C header files are distributed in the support\h directory. Inclusion of the header file is necessary in order to use SFR names (e.g., CORCONbits). For example, the following module, compiled for the dsPIC30F2010 part, includes two functions: one for enabling the PSV window, and another for disabling the PSV window.
#include <p30f2010.h> void EnablePSV(void) { CORCONbits.PSV = 1; } void DisablePSV(void) { CORCONbits.PSV = 0; }
DS51284F-page 83
Note:
The symbols CORCON and CORCONbits refer to the same register and will resolve to the same address at link time.
6.4
where xxxx corresponds to the device part number. For example, assuming that there exists a file named app2010.c, which contains an application for the dsPIC30F2010 part, then it may be compiled and linked using the following command line:
pic30-gcc -o app2010.o -T p30f2010.gld app2010.c
The -o command-line option names the output COFF executable file, and the -T option gives the name for the dsPIC30F2010 part. If p30f2010.gld is not found in the current directory, the linker searches in its known library paths. For the default installation, the linker scripts are included in the PIC30_LIBRARAY_PATH. For reference see Section 3.6 Environment Variables.
DS51284F-page 84
DS51284F-page 85
*/
/* /* /* /* /* /*
clear timer1 register set period1 register set internal clock source set priority level clear interrupt flag enable interrupts
*/ */ */ */ */ */
} void __attribute__((__interrupt__)) _T1Interrupt(void) { static int sticks=0; if (RTclock.timer > 0) RTclock.timer -= 1; RTclock.ticks++; if (sticks++ > 1000) { sticks = 0; RTclock.seconds++; } IFS0bits.T1IF = 0; return; } /* if countdown timer is active */ /* decrement it */ /* increment ticks counter */ /* if time to rollover clear seconds ticks and increment seconds */ */ */
/* /*
*/
DS51284F-page 86
6.6.1
Macros are provided that can be used to set configuration bits. For example, to set the FOSC bit using a macro, the following line of code can be inserted before the beginning of your C source code:
_FOSC(CSW_FSCM_ON & EC_PLL16);
This would enable the external clock with the PLL set to 16x and enable clock switching and fail-safe clock monitoring. Similarly, to set the FBORPOR bit:
_FBORPOR(PBOR_ON & BORV_27 & PWRT_ON_64 & MCLR_DIS);
This would enable Brown-out Reset at 2.7 Volts and initialize the Power-up timer to 64 milliseconds and configure the use of the MCLR pin for I/O. For a complete list of settings valid for each configuration bit, refer to the processor header file.
6.6.2
#define #define #define #define
6.6.3
Macros that may be used to allocate space in data memory are discussed below. There are two types: those that require an argument and those that do not. The following macros require an argument N that specifies alignment. N must be a power of two, with a minimum value of 2.
#define #define #define #define #define _XBSS(N) _XDATA(N) _YBSS(N) _YDATA(N) _EEDATA(N)
For example, to declare an uninitialized array in X memory that is aligned to a 32-byte address:
int _XBSS(32) xbuf[16];
The following macros do not require an argument. They can be used to locate a variable in persistent data memory or in near data memory.
#define _PERSISTENT __attribute__((persistent)) #define _NEAR __attribute__((near))
DS51284F-page 87
6.6.4
The following macros can be used to declare Interrupt Service Routines (ISRs):
#define _ISR __attribute__((interrupt)) #define _ISRFAST __attribute__((interrupt, shadow))
To declare an ISR for the SPI1 interrupt with fast context save:
void _ISRFAST _SPI1Interrupt(void);
Note:
ISRs will be installed into the interrupt vector tables automatically if the reserved names listed in Section 7.4 Writing the Interrupt Vector are used.
6.7
user_data will be placed in the EE data space reserving 10 words with the given initial values. The dsPIC DSC device provides two ways for programmers to access this area of memory. The first is via the program space visibility window. The second is by using special machine instructions (TBLRDx). Accessing EEDATA via the PSV Accessing EEDATA using TBLRDx instructions Additional Sources of Information
6.7.1
The compiler normally manages the PSV window to access constants stored in program memory. If this is not the case, the PSV window can be used to access EEDATA memory. To use the PSV window: The PSVPAG register must be set to the appropriate address for the program memory to be accessed. For EE data this will be 0xFF, but it is best to use the __builtin_psvpage() function. The PSV window should also be enabled by setting the PSV bit in the CORCON register. If this bit is not set, uses of the PSV window will always read 0x0000.
DS51284F-page 88
These steps need only be done once. Unless PSVPAG is changed, variables in EE data space may be read by referring to them as normal C variables, as shown in the example. Note: This access model is not compatible with the compiler-managed PSV (-mconst-in-code) model. You should be careful to prevent conflict.
6.7.2
The TBLRDx instructions are not directly supported by the compiler, but they can be used via inline assembly. Like PSV accesses, a 23-bit address is formed from an SFR value and the address encoded as part of the instruction. To access the same memory as given in the previous example, the following code may be used: To use the TBLRDx instructions: The TBLPAG register must be set to the appropriate address for the program memory to be accessed. For EE data, this will be 0x7F, but it is best to use the __builtin_tblpage() function. The TBLRDx instruction can only be accessed from an __asm__ statement; refer to the dsPIC30F/33F Programmers Reference Manual (DS70157) for information on this instruction. EXAMPLE 6-3: EEDATA ACCESS VIA TABLE READ
#include <p30fxxxx.h> #define eedata_read(src, dest) { register int eedata_addr; register int eedata_val;
int main(void) { int value; TBLPAG = __builtin_tblpage(&user_data); eedata_read(user_data[2], value); if (value) ; /* do something */ }
DS51284F-page 89
DS51284F-page 90
7.2
HIGHLIGHTS
Items discussed in this chapter are: Writing an Interrupt Service Routine You can designate one or more C functions as Interrupt Service Routines (ISRs) to be invoked by the occurrence of an interrupt. For best performance in general, place lengthy calculations or operations that require library calls in the main application. This strategy optimizes performance and minimizes the possibility of losing information when interrupt events occur rapidly. Writing the Interrupt Vector The dsPIC30F devices use interrupt vectors to transfer application control when an interrupt occurs. An interrupt vector is a dedicated location in program memory that specifies the address of an ISR. Applications must contain valid function addresses in these locations to use interrupts. Interrupt Service Routine Context Saving To handle returning from an interrupt to code in the same conditional state as before the interrupt, context information from specific registers must be saved. Latency The time between when an interrupt is called and when the first ISR instruction is executed is the latency of the interrupt. Nesting Interrupts MPLAB C30 supports nested interrupts. Enabling/Disabling Interrupts Enabling and disabling interrupt sources occurs at two levels: globally and individually. Sharing Memory Between Interrupt Service Routines and Mainline Code How to mitigate potential hazards when this technique is used. PSV Usage with Interrupt Service Routines Using ISRs with managed psv pointers and CodeGuard Security psv constant sections.
DS51284F-page 91
7.3.1
The guidelines for writing ISRs are: declare ISRs with no parameters and a void return type (mandatory) do not let ISRs be called by main line code (mandatory) do not let ISRs call other functions (recommended) An MPLAB C30 ISR is like any other C function in that it can have local variables and access global variables. However, an ISR needs to be declared with no parameters and no return value. This is necessary because the ISR, in response to a hardware interrupt or trap, is invoked asynchronously to the mainline C program (that is, it is not called in the normal way, so parameters and return values dont apply). ISRs should only be invoked through a hardware interrupt or trap and not from other C functions. An ISR uses the return from interrupt (RETFIE) instruction to exit from the function rather than the normal RETURN instruction. Using a RETFIE instruction out of context can corrupt processor resources, such as the Status register. Finally, ISRs should not call other functions. This is recommended because of latency issues. See Section 7.6 Latency for more information.
7.3.2
To declare a C function as an interrupt handler, tag the function with the interrupt attribute (see 2.3 for a description of the __attribute__ keyword). The syntax of the interrupt attribute is: __attribute__((interrupt [(
[ save(symbol-list)] [, irq(irqid)] [, altirq(altirqid)] [, preprologue(asm)] )] ))
The interrupt attribute name and the parameter names may be written with a pair of underscore characters before and after the name. Thus, interrupt and __interrupt__ are equivalent, as are save and __save__. The optional save parameter names a list of one or more variables that are to be saved and restored on entry to and exit from the ISR. The list of names is written inside parentheses, with the names separated by commas. You should arrange to save global variables that may be modified in an ISR if you do not want the value to be exported. Global variables modified by an ISR should be qualified volatile. The optional irq parameter allows you to place an interrupt vector at a specific interrupt, and the optional altirq parameter allows you to place an interrupt vector at a specified alternate interrupt. Each parameter requires a parenthesized interrupt ID number. (See Section 7.4 Writing the Interrupt Vector for a list of interrupt IDs.) The optional preprologue parameter allows you to insert assembly-language statements into the generated code immediately before the compiler-generated function prologue.
DS51284F-page 92
Interrupts
When using the interrupt attribute, please specify either auto_psv or no_auto_psv. If none is specified a warning will be produced and auto_psv will be assumed.
7.3.3
Coding ISRs
As this prototype indicates, interrupt functions must not take parameters nor may they return a value. The compiler arranges for all working registers to be preserved, as well as the Status register and the Repeat Count register, if necessary. Other variables may be saved by naming them as parameters of the interrupt attribute. For example, to have the compiler automatically save and restore the variables, var1 and var2, use the following prototype:
void __attribute__((__interrupt__(__save__(var1,var2)))) isr0(void);
To request the compiler to use the fast context save (using the push.s and pop.s instructions), tag the function with the shadow attribute (see Section 2.3.2 Specifying Attributes of Functions). For example:
void __attribute__((__interrupt__, __shadow__)) isr0(void);
7.3.4
If an interrupt handler does not require any of the optional parameters of the interrupt attribute, then a simplified syntax may be used. The following macros are defined in the device-specific header files:
#define _ISR __attribute__((interrupt)) #define _ISRFAST __attribute__((interrupt, shadow))
To declare an interrupt handler for the SPI1 interrupt with fast context save:
#include <p30fxxxx.h> void _ISRFAST _SPI1Interrupt(void);
DS51284F-page 93
Table 7-1 Interrupt Vectors dsPIC30F DSCs (non-SMPS) Table 7-2 Interrupt Vectors - dsPIC30F DSCs (SMPS) Table 7-3 Interrupt Vectors - PIC24F MCUs Table 7-4 Interrupt Vectors - dsPIC33F DSCs/PIC24H MCUs INTERRUPT VECTORS dsPIC30F DSCs (NON-SMPS)
Alternate Name _AltReservedTrap0 _AltOscillatorFail _AltAddressError _AltStackError _AltMathError _AltReservedTrap5 _AltReservedTrap6 _AltReservedTrap7 _AltINT0Interrupt _AltIC1Interrupt _AltOC1Interrupt _AltT1Interrupt _AltIC2Interrupt _AltOC2Interrupt _AltT2Interrupt _AltT3Interrupt _AltSPI1Interrupt _AltU1RXInterrupt _AltU1TXInterrupt _AltADCInterrupt _AltNVMInterrupt _AltSI2CInterrupt _AltMI2CInterrupt _AltCNInterrupt _AltINT1Interrupt _AltIC7Interrupt _AltIC8Interrupt _AltOC3Interrupt Vector Function Reserved Oscillator fail trap Address error trap Stack error trap Math error trap Reserved Reserved Reserved INT0 External interrupt 0 IC1 Input capture 1 OC1 Output compare 1 TMR1 Timer 1 expired IC2 Input capture 2 OC2 Output compare 2 TMR2 Timer 2 expired TMR3 Timer 3 expired SPI1 Serial peripheral interface 1 UART1RX Uart 1 Receiver UART1TX Uart 1 Transmitter ADC convert completed NMM NVM write completed Slave I2C interrupt Master I2C interrupt CN Input change interrupt INT1 External interrupt 0 IC7 Input capture 7 IC8 Input capture 8 OC3 Output compare 3
TABLE 7-1:
IRQ# N/A N/A N/A N/A N/A N/A N/A N/A 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
Primary Name _ReservedTrap0 _OscillatorFail _AddressError _StackError _MathError _ReservedTrap5 _ReservedTrap6 _ReservedTrap7 _INT0Interrupt _IC1Interrupt _OC1Interrupt _T1Interrupt _IC2Interrupt _OC2Interrupt _T2Interrupt _T3Interrupt _SPI1Interrupt _U1RXInterrupt _U1TXInterrupt _ADCInterrupt _NVMInterrupt _SI2CInterrupt _MI2CInterrupt _CNInterrupt _INT1Interrupt _IC7Interrupt _IC8Interrupt _OC3Interrupt
DS51284F-page 94
Interrupts
TABLE 7-1:
IRQ# 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53
Primary Name _OC4Interrupt _T4Interrupt _T5Interrupt _INT2Interrupt _U2RXInterrupt _U2TXInterrupt _SPI2Interrupt _C1Interrupt _IC3Interrupt _IC4Interrupt _IC5Interrupt _IC6Interrupt _OC5Interrupt _OC6Interrupt _OC7Interrupt _OC8Interrupt _INT3Interrupt _INT4Interrupt _C2Interrupt _PWMInterrupt _QEIInterrupt _DCIInterrupt _LVDInterrupt _FLTAInterrupt _FLTBInterrupt _Interrupt45 _Interrupt46 _Interrupt47 _Interrupt48 _Interrupt49 _Interrupt50 _Interrupt51 _Interrupt52 _Interrupt53
TABLE 7-2:
IRQ# N/A N/A N/A N/A N/A N/A N/A N/A
Primary Name _ReservedTrap0 _OscillatorFail _AddressError _StackError _MathError _ReservedTrap5 _ReservedTrap6 _ReservedTrap7
DS51284F-page 95
Primary Name _INT0Interrupt _IC1Interrupt _OC1Interrupt _T1Interrupt _Interrupt4 _OC2Interrupt _T2Interrupt _T3Interrupt _SPI1Interrupt _U1RXInterrupt _U1TXInterrupt _ADCInterrupt _NVMInterrupt _SI2CInterrupt _MI2CInterrupt _Interrupt15 _INT1Interrupt _INT2Interrupt _PWMSpEvent MatchInterrupt _PWM1Interrupt _PWM2Interrupt _PWM3Interrupt _PWM4Interrupt _Interrupt23 _Interrupt24 _Interrupt25 _Interrupt26 _CNInterrupt _Interrupt28 _CMP1Interrupt _CMP2Interrupt _CMP3Interrupt _CMP4Interrupt _Interrupt33 _Interrupt34 _Interrupt35 _Interrupt36 _ADCP0Interrupt _ADCP1Interrupt _ADCP2Interrupt _ADCP3Interrupt _ADCP4Interrupt _ADCP5Interrupt _Interrupt43
DS51284F-page 96
Interrupts
TABLE 7-2:
IRQ# 44 45 46 47 48 49 50 51 52 53
Primary Name _Interrupt44 _Interrupt45 _Interrupt46 _Interrupt47 _Interrupt48 _Interrupt49 _Interrupt50 _Interrupt51 _Interrupt52 _Interrupt53
TABLE 7-3:
IRQ# N/A N/A N/A N/A N/A N/A N/A N/A 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23
Primary Name _ReservedTrap0 _OscillatorFail _AddressError _StackError _MathError _ReservedTrap5 _ReservedTrap6 _ReservedTrap7 _INT0Interrupt _IC1Interrupt _OC1Interrupt _T1Interrupt _Interrupt4 _IC2Interrupt _OC2Interrupt _T2Interrupt _T3Interrupt _SPI1ErrInterrupt _SPI1Interrupt _U1RXInterrupt _U1TXInterrupt _ADC1Interrupt _Interrupt14 _Interrupt15 _SI2C1Interrupt _MI2C1Interrupt _CompInterrupt _CNInterrupt _INT1Interrupt _Interrupt21 _Interrupt22 _Interrupt23
DS51284F-page 97
Primary Name _Interrupt24 _OC3Interrupt _OC4Interrupt _T4Interrupt _T5Interrupt _INT2Interrupt _U2RXInterrupt _U2TXInterrupt _SPI2ErrInterrupt _SPI2Interrupt _Interrupt34 _Interrupt35 _Interrupt36 _IC3Interrupt _IC4Interrupt _IC5Interrupt _Interrupt40 _OC5Interrupt _Interrupt42 _Interrupt43 _Interrupt44 _PMPInterrupt _Interrupt46 _Interrupt47 _Interrupt48 _SI2C2Interrupt _MI2C2Interrupt _Interrupt51 _Interrupt52 _INT3Interrupt _INT4Interrupt _Interrupt55 _Interrupt56 _Interrupt57 _Interrupt58 _Interrupt59 _Interrupt60 _Interrupt61 _RTCCInterrupt _Interrupt63 _Interrupt64 _U1EInterrupt _U2EInterrupt _CRCInterrupt _Interrupt68
DS51284F-page 98
Interrupts
TABLE 7-3:
IRQ# 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113
Primary Name _Interrupt69 _Interrupt70 _Interrupt71 _Interrupt72 _Interrupt73 _Interrupt74 _Interrupt75 _Interrupt76 _Interrupt77 _Interrupt78 _Interrupt79 _Interrupt80 _Interrupt81 _Interrupt82 _Interrupt83 _Interrupt84 _Interrupt85 _Interrupt86 _Interrupt87 _Interrupt88 _Interrupt89 _Interrupt90 _Interrupt91 _Interrupt92 _Interrupt93 _Interrupt94 _Interrupt95 _Interrupt96 _Interrupt97 _Interrupt98 _Interrupt99 _Interrupt100 _Interrupt101 _Interrupt102 _Interrupt103 _Interrupt104 _Interrupt105 _Interrupt106 _Interrupt107 _Interrupt108 _Interrupt109 _Interrupt110 _Interrupt111 _Interrupt112 _Interrupt113
DS51284F-page 99
TABLE 7-4:
IRQ# N/A N/A N/A N/A N/A N/A N/A N/A 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29
Primary Name _ReservedTrap0 _OscillatorFail _AddressError _StackError _MathError _DMACError _ReservedTrap6 _ReservedTrap7 _INT0Interrupt _IC1Interrupt _OC1Interrupt _T1Interrupt _DMA0Interrupt _IC2Interrupt _OC2Interrupt _T2Interrupt _T3Interrupt _SPI1ErrInterrupt _SPI1Interrupt _U1RXInterrupt _U1TXInterrupt _ADC1Interrupt _DMA1Interrupt _Interrupt15 _SI2C1Interrupt _MI2C1Interrupt _Interrupt18 _CNInterrupt _INT1Interrupt _ADC2Interrupt _IC7Interrupt _IC8Interrupt _DMA2Interrupt _OC3Interrupt _OC4Interrupt _T4Interrupt _T5Interrupt _INT2Interrupt
DS51284F-page 100
Interrupts
TABLE 7-4:
IRQ# 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74
Primary Name _U2RXInterrupt _U2TXInterrupt _SPI2ErrInterrupt _SPI2Interrupt _C1RxRdyInterrupt _C1Interrupt _DMA3Interrupt _IC3Interrupt _IC4Interrupt _IC5Interrupt _IC6Interrupt _OC5Interrupt _OC6Interrupt _OC7Interrupt _OC8Interrupt _Interrupt45 _DMA4Interrupt _T6Interrupt _T7Interrupt _SI2C2Interrupt _MI2C2Interrupt _T8Interrupt _T9Interrupt _INT3Interrupt _INT4Interrupt _C2RxRdyInterrupt _C2Interrupt _PWMInterrupt _QEIInterrupt _DCIErrInterrupt _DCIInterrupt _DMA5Interrupt _Interrupt62 _FLTAInterrupt _FLTBInterrupt _U1ErrInterrupt _U2ErrInterrupt _Interrupt67 _DMA6Interrupt _DMA7Interrupt _C1TxReqInterrupt _C2TxReqInterrupt _Interrupt72 _Interrupt73 _Interrupt74
DS51284F-page 101
Primary Name _Interrupt75 _Interrupt76 _Interrupt77 _Interrupt78 _Interrupt79 _Interrupt80 _Interrupt81 _Interrupt82 _Interrupt83 _Interrupt84 _Interrupt85 _Interrupt86 _Interrupt87 _Interrupt88 _Interrupt89 _Interrupt90 _Interrupt91 _Interrupt92 _Interrupt93 _Interrupt94 _Interrupt95 _Interrupt96 _Interrupt97 _Interrupt98 _Interrupt99 _Interrupt100 _Interrupt101 _Interrupt102 _Interrupt103 _Interrupt104 _Interrupt105 _Interrupt106 _Interrupt107 _Interrupt108 _Interrupt109 _Interrupt110 _Interrupt111 _Interrupt112 _Interrupt113 _Interrupt114 _Interrupt115 _Interrupt116 _Interrupt117
DS51284F-page 102
Interrupts
To field an interrupt, a functions address must be placed at the appropriate address in one of the vector tables, and the function must preserve any system resources that it uses. It must return to the foreground task using a RETFIE processor instruction. Interrupt functions may be written in C. When a C function is designated as an interrupt handler, the compiler arranges to preserve all the system resources which the compiler uses, and to return from the function using the appropriate instruction. The compiler can optionally arrange for the interrupt vector table to be populated with the interrupt functions address. To arrange for the compiler to fill in the interrupt vector to point to the interrupt function, name the function as denoted in the preceding table. For example, the stack error vector will automatically be filled if the following function is defined:
void __attribute__((__interrupt__)) _StackError(void);
Note the use of the leading underscore. Similarly, the alternate stack error vector will automatically be filled if the following function is defined:
void __attribute__((__interrupt__)) _AltStackError(void);
Again, note the use of the leading underscore. For all interrupt vectors without specific handlers, a default interrupt handler will be installed. The default interrupt handler is supplied by the linker and simply resets the device. An application may also provide a default interrupt handler by declaring an interrupt function with the name _DefaultInterrupt. The last nine interrupt vectors in each table do not have predefined hardware functions. The vectors for these interrupts may be filled by using the names indicated in the preceding table, or, names more appropriate to the application may be used, while still filling the appropriate vector entry by using the irq or altirq parameter of the interrupt attribute. For example, to specify that a function should use primary interrupt vector fifty-two, use the following:
void __attribute__((__interrupt__(__irq__(52)))) MyIRQ(void);
Similarly, to specify that a function should use alternate interrupt vector fifty-two, use the following:
void __attribute__((__interrupt__(__altirq__(52)))) MyAltIRQ(void);
The irq/altirq number can be one of the interrupt request numbers 45 to 53. If the irq parameter of the interrupt attribute is used, the compiler creates the external symbol name __Interruptn, where n is the vector number. Therefore, the C identifiers _Interrupt45 through _Interrupt53 are reserved by the compiler. In the same way, if the altirq parameter of the interrupt attribute is used, the compiler creates the external symbol name __AltInterruptn, where n is the vector number. Therefore, the C identifiers _AltInterrupt45 through _AltInterrupt53 are reserved by the compiler.
DS51284F-page 103
7.6
LATENCY
There are two elements that affect the number of cycles between the time the interrupt source occurs and the execution of the first instruction of your ISR code. These are: Processor Servicing of Interrupt The amount of time it takes the processor to recognize the interrupt and branch to the first address of the interrupt vector. To determine this value refer to the processor data sheet for the specific processor and interrupt source being used. ISR Code MPLAB C30 saves the registers that it uses in the ISR. This includes the working registers and the RCOUNT special function register. Moreover, if the ISR calls an ordinary function, then the compiler will save all the working registers and RCOUNT, even if they are not all used explicitly in the ISR itself. This must be done, because the compiler cannot know, in general, which resources are used by the called function.
7.7
NESTING INTERRUPTS
The dsPIC30F devices support nested interrupts. Since processor resources are saved on the stack in an ISR, nested ISRs are coded in just the same way as non-nested ones. Nested interrupts are enabled by clearing the NSTDIS (nested interrupt disable) bit in the INTCON1 register. Note that this is the default condition as the dsPIC30F device comes out of reset with nested interrupts enabled. Each interrupt source is assigned a priority in the Interrupt Priority Control registers (IPCn). If there is a pending Interrupt Request (IRQ) with a priority level equal to or greater than the current processor priority level in the Processor Status register (CPUPRI field in the ST register), an interrupt will be presented to the processor.
DS51284F-page 104
Interrupts
7.8 ENABLING/DISABLING INTERRUPTS
Each interrupt source can be individually enabled or disabled. One interrupt enable bit for each IRQ is allocated in the Interrupt Enable Control registers (IECn). Setting an interrupt enable bit to one (1) enables the corresponding interrupt; clearing the interrupt enable bit to zero (0) disables the corresponding interrupt. When the device comes out of reset, all interrupt enable bits are cleared to zero. In addition, the processor has a disable interrupt instruction (DISI) that can disable all interrupts for a specified number of instruction cycles. Note: Traps, such as the address error trap, cannot be disabled. Only IRQs can be disabled.
The DISI instruction can be used in a C program through inline assembly. For example, the inline assembly statement: __asm__ volatile ("disi #16"); will emit the specified DISI instruction at the point it appears in the source program. A disadvantage of using DISI in this way is that the C programmer cannot always be sure how the C compiler will translate C source to machine instructions, so it may be difficult to determine the cycle count for the DISI instruction. It is possible to get around this difficulty by bracketing the code that is to be protected from interrupts by DISI instructions, the first of which sets the cycle count to the maximum value, and the second of which sets the cycle count to zero. For example, __asm__ volatile("disi #0x3FFF"); /* disable interrupts */ /* ... protected C code ... */ __asm__ volatile("disi #0x0000"); /* enable interrupts */ An alternative approach is to write directly to the DISICNT register to enable interrupts. The DISICNT register may be modified only after a DISI instruction has been issued and if the contents of the DISICNT register are not zero. __asm__ volatile("disi #0x3FFF"); /* disable interrupts */ /* ... protected C code ... */ DISICNT = 0x0000; /* enable interrupts */ For some applications, it may be necessary to disable level 7 interrupts as well. These can only be disabled through the modification of the COROCON IPL field. The provided support files contain some useful preprocessor macro functions to help you safely modify the IPL value. These macros are:
SET_CPU_IPL(ipl) SET_AND_SAVE_CPU_IPL(save_to, ipl) RESTORE_CPU_IPL(saved_to)
For example, you may wish to protect a section of code from interrupt. The following code will adjust the current IPL setting and restore the IPL to its previous value.
void foo(void) { int current_cpu_ipl; SET_AND_SAVE_CPU_IPL(current_cpu_ipl, 7); /* protected code here */ RESTORE_CPU_IPL(current_cpu_ipl); } /* disable interrupts */
DS51284F-page 105
The operator (op) may or may not be atomic, based on device architecture. In any event, the compiler may not be able to generate the atomic operation in all instances this will very much depend upon several factors: the availability of an appropriate atomic machine instruction the resource availability - special registers or other constraints the optimization level, and other options that affect data/code placement Without knowledge of the architecture, it is reasonable to assume that the general expression requires two reads, one for each operand and one write to store the result. Several difficulties may arise in the presence of interrupt sequences; they very much depend on the particular application.
7.9.1
Development Issues
Here are some examples: EXAMPLE 7-1: BAR MUST MATCH BAZ
If it is required that bar and baz match, (i.e., are updated synchronously with each other), there is a possible hazard if either bar or baz can be updated within a higher priority interrupt expression. Here are some sample flow sequences: 1. Safe: read bar read baz perform operation write back result to foo
DS51284F-page 106
Interrupts
2. Unsafe: read bar interrupt modifies baz read baz perform operation write back result to foo 3. Safe: read bar read baz interrupt modifies bar or baz perform operation write back result to foo The first is safe because any interrupt falls outside the boundaries of the expression. The second is unsafe because the application demands that bar and baz be updated synchronously with each other. The third is probably safe; foo will possibly have an old value, but the value will be consistent with the data that was available at the start of the expression. EXAMPLE 7-2: TYPE OF FOO, BAR AND BAZ
Another variation depends upon the type of foo, bar and baz. The operations, "read bar", "read baz", or "write back result to foo", may not be atomic, depending upon the architecture of the target processor. For example, dsPIC DSC devices can read or write an 8-bit, 16-bit, or 32-bit quantity in 1 (atomic) instruction. But, a 32-bit quantity may require two instructions depending upon instruction selection (which in turn will depend upon optimization and memory model settings). Assume that the types are long and the compiler is unable to choose atomic operations for accessing the data. Then the access becomes: read lsw bar read msw bar read lsw baz read msw baz perform operation (on lsw and on msw) perform operation write back lsw result to foo write back msw result to foo Now there are more possibilities for an update of bar or baz to cause unexpected data. EXAMPLE 7-3: BIT FIELDS
A third cause for concern are bit fields. C allows memory to be allocated at the bit level, but does not define any bit operations. In the purest sense, any operation on a bit will be treated as an operation on the underlying type of the bit field and will usually require some operations to extract the field from bar and baz or to insert the field into foo. The important consideration to note is that (again depending upon instruction architecture, optimization levels and memory settings) an interrupted routine that writes to any portion of the bit field where foo resides may be corruptible. This is particularly apparent in the case where one of the operands is also the destination. The dsPIC DSC instruction set can operate on 1 bit atomically. The compiler may select these instructions depending upon optimization level, memory settings and resource availability.
DS51284F-page 107
7.9.2
Development Solutions
Here are some strategies to remove potential hazards: Design the software system such that the conflicting event cannot occur. Do not share memory between ISRs and other functions. Make ISRs as simple as possible and move the real work to main code. Use care when sharing memory and, if possible, avoid sharing bit fields which contain multiple bits. Protect non-atomic updates of shared memory from interrupts as you would protect critical sections of code. The following macro can be used for this purpose:
#define INTERRUPT_PROTECT(x) { char saved_ipl; SET_AND_SAVE_CPU_IPL(saved_ipl,7); x; RESTORE_CPU_IPL(saved_ipl); } (void) 0; \ \ \ \ \
This macro disables interrupts by increasing the current priority level to 7, performing the desired statement and then restoring the previous priority level.
7.9.3
Application Example
The following example highlights some of the points discussed in this section:
void __attribute__((interrupt)) HigherPriorityInterrupt(void) { /* User Code Here */ LATGbits.LATG15 = 1; /* Set LATG bit 15 */ IPC0bits.INT0IP = 2; /* Set Interrupt 0 priority (multiple bits involved) to 2 */ } int main(void) { /* More User Code */ LATGbits.LATG10 ^= 1;
/* Potential HAZARD First reads LATG into a W reg, implements XOR operation, then writes result to LATG */ /* No problem, this is a write only assignment operation */ /* No problem likely, this is an assignment of a single bit and will use a single instruction bit set operation */
LATG = 0x1238;
LATGbits.LATG5 = 1;
DS51284F-page 108
Interrupts
LATGbits.LATG2 = 0; /* No problem likely, single instruction bit clear operation probably used */ /* Potential HAZARD First reads LATG into a W reg, implements add operation, then writes result to LATG */ /* HAZARD Assigning a multiple bitfield can generate a multiple instruction sequence */
LATG += 0x0001;
IPC0bits.T1IP = 5;
A statement can be protected from interrupt using the INTERRUPT_PROTECT macro provided above. For this example:
INTERRUPT_PROTECT(LATGbits.LATG15 ^= 1); /* Not interruptible by level 1-7 interrupt requests and safe at any optimization level */
7.10
The no_auto_psv attribute is used to indicate that an ISR does not reference the auto_psv constants section. If neither attribute is specified, the compiler will assume auto_psv and will insert the necessary instructions to ensure correct operation at runtime. A warning diagnostic message will also be issued. The warning will help alert customers to the migration issue, and to the possibility of reducing interrupt latency by specifying the no_auto_psv attribute.
DS51284F-page 109
DS51284F-page 110
MPLAB C30 USERS GUIDE Chapter 8. Mixing Assembly Language and C Modules
8.1 INTRODUCTION
This section describes how to use assembly language and C modules together. It gives examples of using C variables and functions in assembly code and examples of using assembly language variables and functions in C.
8.2
HIGHLIGHTS
Items discussed in this chapter are: Mixing Assembly Language and C Variables and Functions Separate assembly language modules may be assembled, then linked with compiled C modules. Using Inline Assembly Language Assembly language instructions may be embedded directly into the C code. The inline assembler supports both simple (non-parameterized) assembly language statement, as well as extended (parameterized) statements, where C variables can be accessed as operands of an assembler instruction.
8.3
DS51284F-page 111
The file ex2.s defines asmFunction and asmVariable as required for use in a linked application. The assembly file also shows how to call a C function, foo, and how to access a C defined variable, cVariable.
; ; ; file: ex2.s
.text .global _asmFunction _asmFunction: mov #0,w0 mov w0,_cVariable return .global _begin _main: call _foo return .bss .global _asmVariable .align 2 _asmVariable: .space 2 .end
In the C file, ex1.c, external references to symbols declared in an assembly file are declared using the standard extern keyword; note that asmFunction, or _asmFunction in the assembly source, is a void function and is declared accordingly. In the assembly file, ex1.s, the symbols _asmFunction, _main and _asmVariable are made globally visible through the use of the .global assembler directive and can be accessed by any other source file. The symbol _main is only referenced and not declared; therefore, the assembler takes this to be an external reference. The following MPLAB C30 example shows how to call an assembly function with two parameters. The C function main in call1.c calls the asmFunction in call2.s with two parameters.
DS51284F-page 112
The assembly-language function sums its two parameters and returns the result.
; ; file: call2.s ; .global _asmFunction _asmFunction: add w0,w1,w0 return .end
Parameter passing in C is detailed in Section 4.12.2 Return Value. In the preceding example, the two integer arguments are passed in the W0 and W1 registers. The integer return result is transferred via register W0. More complicated parameter lists may require different registers and care should be taken in the hand-written assembly to follow the guidelines.
8.4
where instruction is a valid assembly-language construct. If you are writing inline assembly in ANSI C programs, write __asm__ instead of asm. Note: Only a single string can be passed to the simple form of inline assembly.
In an extended assembler instruction using asm, the operands of the instruction are specified using C expressions. The extended syntax is:
asm("template" [ : [ "constraint"(output-operand) [ , ... ] ] [ : [ "constraint"(input-operand) [ , ... ] ] [ "clobber" [ , ... ] ] ] ]);
You must specify an assembler instruction template, plus an operand constraint string for each operand. The template specifies the instruction mnemonic, and optionally placeholders for the operands. The constraint strings specify operand constraints, for example, that an operand must be in a register (the usual case), or that an operand must be an immediate value. Constraint letters and modifiers supported by MPLAB C30 are listed in Table 8-1 and Table 8-2 respectively.
DS51284F-page 113
T U
TABLE 8-2:
Letter = + &
d q t
EXAMPLE 8-3:
PASSING C VARIABLES
This example demonstrates how to use the swap instruction (which the compiler does not generally use):
asm ("swap %0" : "+r"(var));
Here var is the C expression for the operand, which is both an input and an output operand. The operand is constrained to be of type r, which denotes a register operand. The + in +r indicates that the operand is both an input and output operand. Each operand is described by an operand-constraint string followed by the C expression in parentheses. A colon separates the assembler template from the first output operand, and another separates the last output operand from the first input, if any. Commas separate output operands and separate inputs.
DS51284F-page 114
Some instructions clobber specific hard registers. To describe this, write a third colon after the input operands, followed by the names of the clobbered hard registers (given as strings separated by commas). Here is an example:
asm volatile ("mul.b %0" : /* no outputs */ : "U" (nvar) : "w2");
In this case, the operand nvar is a character variable declared in near data space, as specified by the U constraint. If the assembler instruction can alter the flags (condition code) register, add cc to the list of clobbered registers. If the assembler instruction modifies memory in an unpredictable fashion, add memory to the list of clobbered registers. This will cause MPLAB C30 to not keep memory values cached in registers across the assembler instruction. EXAMPLE 8-5: USING MULTIPLE ASSEMBLER INSTRUCTIONS
You can put multiple assembler instructions together in a single asm template, separated with newlines (written as \n). The input operands and the output operands addresses are ensured not to use any of the clobbered registers, so you can read and write the clobbered registers as many times as you like. Here is an example of multiple instructions in a template; it assumes that the subroutine _foo accepts arguments in registers W0 and W1:
asm ("mov %0,w0\nmov %1,W1\ncall _foo" : /* no outputs */ : "g" (a), "g" (b) : "W0", "W1");
DS51284F-page 115
The intention is to compute the value (a + b) << a. However, as written, the value computed may or may not be this value. The correct coding informs the compiler that the operand c is modified before the asm instruction is finished using the input operands, as follows:
int exprgood(int a, int b) { int c;
EXAMPLE 8-7:
MATCHING OPERANDS
When the assembler instruction has a read-write operand, or an operand in which only some of the bits are to be changed, you must logically split its function into two separate operands: one input operand and one write-only output operand. The connection between them is expressed by constraints that say they need to be in the same location when the instruction executes. You can use the same C expression for both operands or different expressions. For example, here is the add instruction with bar as its read-only source operand and foo as its read-write destination:
asm ("add %2,%1,%0" : "=r" (foo) : "0" (foo), "r" (bar));
The constraint 0 for operand 1 says that it must occupy the same location as operand 0. A digit in constraint is allowed only in an input operand and must refer to an output operand. Only a digit in the constraint can ensure that one operand will be in the same place as another. The mere fact that foo is the value of both operands is not enough to ensure that they will be in the same place in the generated assembler code. The following would not work:
asm ("add %2,%1,%0" : "=r" (foo) : "r" (foo), "r" (bar));
DS51284F-page 116
It is also possible to specify input and output operands using symbolic names that can be referenced within the assembler code template. These names are specified inside square brackets preceding the constraint string, and can be referenced inside the assembler code template using %[name] instead of a percentage sign followed by the operand number. Using named operands, the above example could be coded as follows:
asm ("add %[foo],%[bar],%[foo]" : [foo] "=r" (foo) : "0" (foo), [bar] "r" (bar));
EXAMPLE 8-9:
You can prevent an asm instruction from being deleted, moved significantly, or combined, by writing the keyword volatile after the asm. For example:
#define disi(n) \ asm volatile ("disi #%0" \ : /* no outputs */ \ : "i" (n))
In this case, the constraint letter i denotes an immediate operand, as required by the disi instruction. EXAMPLE 8-10: MAKING CONTROL FLOW CHANGES
There are special precautions that must be taken when making control flow changes within inline assembly statements. There is no way, for example, to tell the compiler that an inline asm statement may result in a change of control flow. The control should enter the asm statement and always proceed to the next statement. Good control flow:
asm("call _foo" : /* outputs */ : /* inputs */ : "w0", "w1", "w2", "w3", "w4", "w5", "w6", "w7"); /* next statement */
This is acceptable because after calling foo, the next statement will be executed. The code tells the compiler that some registers do not survive this statement; these represent the registers that will not be preserved by foo. Bad control flow:
asm("bra OV, error"); /* next statement */ return 0; asm("error: "); return 1;
This is unacceptable as the compiler will assume that the next statement, return 0, is executed when it may not be. In this case, the asm("error: ") and following statements will be deleted because they are unreachable. See further information regarding labels in asm statements.
DS51284F-page 117
This is acceptable, but may not function as expected, (i.e., the next statement is always executed, regardless of any branch inside the asm statement). See further information regarding labels in asm statements. Note that the code indicates that the status flags are no longer valid in this statement by identifying cc as clobbered. Lables and Control Flow: Additionally, labels inside assembly statements can behave unexpectedly with certain optimization options. The inliner may cause labels within asm statements to be defined multiple times. Also the procedural aggragator tool (-mpa) does not accept the local label syntax. See the following example:
inline void foo() { asm("do #6, loopend"); /* some C code */ asm("loopend: "); return; }
This is bad for a number of reasons. First, the asm statements introduce an implied control flow that the compiler does not know about. Second, if foo() is inlined the label loopend will be defined many times. Third, the C code could be badly optimized because the compiler cannot see the loop structure. This example breaks the rule that the asm statement should not interfere with the program flow; asm("loopend:") will not always flow to the next statement. A solution would be to use the local label syntax as described in the MPLAB ASM30, MPLAB LINK30 and Utilties User's Guide (DS51317), as in the following example:
inline void foo() { asm("do #6, 0f"); /* some C code */ asm("0: "); return; }
The above form is slightly better; at least it will fix the multiply-defined label issue. However the procedural aggregator tool (-mpa) does not accept the 0: form of label.
DS51284F-page 118
in1 = some_input1; in2 = some_input2; __asm__ volatile ("funky_instruction %2,%3,%0; = %1" : /* outputs */ "=r"(out1), "=r"(out2) : /* inputs */ "r"(in1), "r"(in2)); /* use out1 and out2 in normal C */ }
In this example, funky_instruction has one explicit output, out1, and one implicit output, out2. Both have been placed in the asm template so that the compiler can track the register usage properly (though the implicit output is in a comment statement). The input shown is normal. Otherwise, the extended register declarator syntax is used to nominate particular hard registers which satisfy the constraints of our fictitious funky_instruction. EXAMPLE 8-12: HANDLING VALUES LARGER THAN INT
Constraint letters and modifiers may be used to identify various entities with which it is acceptable to replace a particular operand, such as %0 in:
asm("mov %1, %0" : "r"(foo) : "r"(bar));
This example indicates that the value stored in foo should be moved into bar. The example code performs this task unless foo or bar are larger than an int. By default, %0 represents the first register for the operand (0). To access the second, third, or fourth register, use a modifier letter specified in Table 8-2.
DS51284F-page 119
DS51284F-page 120
A.2
HIGHLIGHTS
Items discussed in this chapter are: Translation Environment Identifiers Characters Integers Floating Point Arrays and Pointers Registers Structures, Unions, Enumerations and Bit fields Qualifiers Declarators Statements Preprocessing Directives Library Functions Signals Streams and Files tmpfile errno Memory abort exit getenv system strerror
DS51284F-page 121
A.4
ENVIRONMENT
Implementation-Defined Behavior for Environment is covered in section G.3.2 of the ANSI C Standard. What library facilities are available to a freestanding program? (ISO 5.1.2.1) All of the facilities of the standard C library are available, provided that a small set of functions is customized for the environment, as described in the Runtime Libraries" section. Describe program termination in a freestanding environment. (ISO 5.1.2.1) If the function main returns or the function exit is called, a HALT instruction is executed in an infinite loop. This behavior is customizable. Describe the arguments (parameters) passed to the function main? (ISO 5.1.2.2.1) No parameters are passed to main. Which of the following is a valid interactive device: (ISO 5.1.2.3) Asynchronous terminalNo Paired display and keyboardNo Inter program connectionNo Other, please describe?None
DS51284F-page 122
Implementation-Defined Behavior
A.5 IDENTIFIERS
Implementation-Defined Behavior for Identifiers is covered in section G.3.3 of the ANSI C Standard. How many characters beyond thirty-one (31) are significant in an identifier without external linkage? (ISO 6.1.2) All characters are significant. How many characters beyond six (6) are significant in an identifier with external linkage? (ISO 6.1.2) All characters are significant. Is case significant in an identifier with external linkage? (ISO 6.1.2) Yes.
A.6
CHARACTERS
Implementation-Defined Behavior for Characters is covered in section G.3.4 of the ANSI C Standard. Detail any source and execution characters which are not explicitly specified by the Standard? (ISO 5.2.1) None. List escape sequence value produced for listed sequences. (ISO 5.2.2)
TABLE A-1:
How many bits are in a character in the execution character set? (ISO 5.2.4.2) 8. What is the mapping of members of the source character sets (in character and string literals) to members of the execution character set? (ISO 6.1.3.4) The identity function. What is the equivalent type of a plain char? (ISO 6.2.1.1) Either (user defined). The default is signed char. A compiler command-line option may be used to make the default unsigned char.
DS51284F-page 123
INTEGER TYPES
Size (bits) 8 8 8 16 16 16 16 16 16 32 32 32 -128 127 -128 127 0 255 -32768 32767 -32768 32767 0 65535 -32768 32767 -32768 32767 0 65535 -2147483648 2147438647 -2147483648 2147438647 0 4294867295 Range
Designation
What is the result of converting an integer to a shorter signed integer, or the result of converting an unsigned integer to a signed integer of equal length, if the value cannot be represented? (ISO 6.2.1.2) There is a loss of significance. No error is signaled. What are the results of bitwise operations on signed integers? (ISO 6.3) Shift operators retain the sign. Other operators act as if the operand(s) are unsigned integers. What is the sign of the remainder on integer division? (ISO 6.3.5) + What is the result of a right shift of a negative-valued signed integral type? (ISO 6.3.7) The sign is retained.
A.8
FLOATING POINT
Implementation-Defined Behavior for Floating Point is covered in section G.3.6 of the ANSI C Standard. Is the scaled value of a floating constant that is in the range of the representable value for its type, the nearest representable value, or the larger representable value immediately adjacent to the nearest representable value, or the smallest representable value immediately adjacent to the nearest representable value? (ISO 6.1.3.1) The nearest representable value.
DS51284F-page 124
Implementation-Defined Behavior
The following table describes the amount of storage and range of various types of floating point numbers: (ISO 6.1.2.5) TABLE A-3:
float double* long double
FLOATING-POINT TYPES
Size (bits) 32 32 64 Range 1.175494e-38 3.40282346e+38 1.175494e-38 3.40282346e+38 2.22507385e-308 1.79769313e+308
Designation
What is the direction of truncation, when an integral number is converted to a floating-point number, that cannot exactly represent the original value? (ISO 6.2.1.3) Down. What is the direction of truncation, or rounding, when a floating-point number is converted to a narrower floating-point number? (ISO 6.2.1.4) Down.
A.9
A.10 REGISTERS
Implementation-Defined Behavior for Registers is covered in section G.3.8 of the ANSI C Standard. To what extent does the storage class specifier register actually effect the storage of objects in registers? (ISO 6.5.1) If optimization is disabled, an attempt will be made to honor the register storage class; otherwise, it is ignored.
DS51284F-page 125
A.12 QUALIFIERS
Implementation-Defined Behavior for Qualifiers is covered in section G.3.10 of the ANSI C Standard. Describe what action constitutes an access to an object that has volatile-qualified type? (ISO 6.5.3) If an object is named in an expression, it has been accessed.
A.13 DECLARATORS
Implementation-Defined Behavior for Declarators is covered in section G.3.11 of the ANSI C Standard. What is the maximum number of declarators that may modify an arithmetic, structure, or union type? (ISO 6.5.4) No limit.
A.14 STATEMENTS
Implementation-Defined Behavior for Statements is covered in section G.3.12 of the ANSI C Standard. What is the maximum number of case values in a switch statement? (ISO 6.6.4.2) No limit.
DS51284F-page 126
Implementation-Defined Behavior
A.15 PREPROCESSING DIRECTIVES
Implementation-Defined Behavior for Preprocessing Directives is covered in section G.3.13 of the ANSI C Standard. Does the value of a single-character character constant in a constant expression, that controls conditional inclusion, match the value of the same character constant in the execution character set? (ISO 6.8.1) Yes. Can such a character constant have a negative value? (ISO 6.8.1) Yes. What method is used for locating includable source files? (ISO 6.8.2) The preprocessor searches the current directory, followed by directories named using command-line options. How are headers identified, or the places specified? (ISO 6.8.2) The headers are identified on the #include directive, enclosed between < and > delimiters, or between and delimiters. The places are specified using command-line options. Are quoted names supported for includable source files? (ISO 6.8.2) Yes. What is the mapping between delimited character sequences and external source file names? (ISO 6.8.2) The identity function. Describe the behavior of each recognized #pragma directive. (ISO 6.8.6) TABLE A-4: #PRAGMA BEHAVIOR
Pragma #pragma code section-name #pragma code #pragma idata section-name #pragma idata #pragma udata section-name #pragma udata #pragma interrupt function-name Behavior Names the code section. Resets the name of the code section to its default (viz., .text). Names the initialized data section. Resets the name of the initialized data section to its default value (viz., .data). Names the uninitialized data section. Resets the name of the uninitialized data section to its default value (viz., .bss). Designates function-name as an interrupt function.
What are the definitions for __ DATE __ and __ TIME __ respectively, when the date and time of translation are not available? (ISO 6.8.8) Not applicable. The compiler is not supported in environments where these functions are not available.
DS51284F-page 127
What values are returned by the mathematics functions after a domain errors? (ISO 7.5.1) NaN. Do the mathematics functions set the integer expression errno to the value of the macro ERANGE on underflow range errors? (ISO 7.5.1) Yes. Do you get a domain error or is zero returned when the fmod function has a second argument of zero? (ISO 7.5.6.4) Domain error.
DS51284F-page 128
Implementation-Defined Behavior
A.17 SIGNALS
What is the set of signals for the signal function? (ISO 7.7.1.1) TABLE A-6:
SIGABRT SIGINT SIGILL SIGFPE SIGSEGV SIGTERM
SIGNAL FUNCTION
Description Abnormal termination. Receipt of an interactive attention signal. Detection of an invalid function image. An erroneous arithmetic operation. An invalid access to storage. A termination request sent to the program.
Name
Describe the parameters and the usage of each signal recognized by the signal function. (ISO 7.7.1.1) Application defined. Describe the default handling and the handling at program startup for each signal recognized by the signal function? (ISO 7.7.1.1) None. If the equivalent of signal (sig,SIG_DFL) is not executed prior to the call of a signal handler, what blocking of the signal is performed? (ISO 7.7.1.1) None. Is the default handling reset if a SIGILL signal is received by a handler specified to the signal function? (ISO 7.7.1.1) No.
DS51284F-page 129
A.19 TMPFILE
Is an open temporary file removed if the program terminates abnormally? (ISO 7.9.4.3) Yes.
A.20 ERRNO
What value is the macro errno set to by the fgetpos or ftell function on failure? (ISO 7.9.9.1, (ISO 7.9.9.4) Application defined. What is the format of the messages generated by the perror function? (ISO 7.9.10.4) The argument to perror, followed by a colon, followed by a text description of the value of errno.
A.21 MEMORY
What is the behavior of the calloc, malloc or realloc function if the size requested is zero? (ISO 7.10.3) A block of zero length is allocated.
A.22 ABORT
What happens to open and temporary files when the abort function is called? (ISO 7.10.4.1) Nothing.
A.23 EXIT
What is the status returned by the exit function if the value of the argument is other than zero, EXIT_SUCCESS, or EXIT_FAILURE? (ISO 7.10.4.3) The value of the argument.
DS51284F-page 130
Implementation-Defined Behavior
A.24 GETENV
What limitations are there on environment names? (ISO 7.10.4.4) Application defined. Describe the method used to alter the environment list obtained by a call to the getenv function. (ISO 7.10.4.4) Application defined.
A.25 SYSTEM
Describe the format of the string that is passed to the system function. (ISO 7.10.4.5) Application defined. What mode of execution is performed by the system function? (ISO 7.10.4.5) Application defined.
A.26 STRERROR
Describe the format of the error message output by the strerror function. (ISO 7.11.6.2) A plain character string. List the contents of the error message strings returned by a call to the strerror function. (ISO 7.11.6.2) TABLE A-7:
Errno 0 EDOM ERANGE EFPOS EFOPEN nnn no error domain error range error file positioning error file open error error #nnn
DS51284F-page 131
DS51284F-page 132
DS51284F-page 133
Prototype: Argument: Return Value: Assembler Operator / Machine Instruction: Error Messages
__builtin_add Description: Add value to the accumulator specified by result with a shift specified by literal shift. For example: register int result asm("A"); int value; result = __builtin_add(value,0); If value is held in w0, the following will be generated: add w0, #0, A int __builtin_add(int value, const int shift); value shift add Integer number to add to accumulator value. Amount to shift resultant accumulator value.
Prototype: Argument: Return Value: Assembler Operator / Machine Instruction: Error Messages
An error message will be displayed if: the result is not an accumulator register the shift value is not a literal within range
DS51284F-page 134
An error message will be displayed if the parameter values are not within range
__builtin_clr Description: Clear the specified accumulator. For example: register int result asm("A"); result = __builtin_clr(); will generate: clr A int __builtin_clr(void); None Returns the cleared value result to an accumulator.
DS51284F-page 135
(Continued)
clr
__builtin_clr_prefetch Description: Clear an accumulator and prefetch data ready for a future MAC operation. xptr may be null to signify no X prefetch to be performed, in which case the values of xincr and xval are ignored, but required. yptr may be null to signify no Y prefetch to be performed, in which case the values of yincr and yval are ignored, but required. xval and yval nominate the address of a C variable where the prefetched value will be stored. xincr and yincr may be the literal values: -6, -4, -2, 0, 2, 4, 6 or an integer value. If AWB is non null, the other accumulator will be written back into the referenced variable. For example: register int result asm("A"); int x_memory_buffer[256] __attribute__((space(xmemory))); int y_memory_buffer[256] __attribute__((space(ymemory))); int *xmemory; int *ymemory; int awb; int xVal, yVal; xmemory = x_memory_buffer; ymemory = y_memory_buffer; result = __builtin_clr(&xmemory, &xVal, 2, &ymemory, &yVal, 2, &awb); might generate: clr A, [w8]+=2, w4, [w10]+=2, w5, w13 The compiler may need to spill w13 to ensure that it is available for the write-back. It may be recommended to users that the register be claimed for this purpose. After this instruction: result will be cleared xVal will contain x_memory_buffer[0] yVal will contain y_memory_buffer[0] xmemory and ymemory will be incremented by 2, ready for the next mac operation Prototype: int __builtin_clr_prefetch( int **xptr, int *xval, int xincr, int **yptr, int *yval, int yincr, int *AWB);
DS51284F-page 136
(Continued)
Integer pointer to x prefetch. Integer value of x prefetch. Integer increment value of x prefetch. Integer pointer to y prefetch. Integer value of y prefetch. Integer increment value of y prefetch. Accumulator selection.
An error message will be displayed if: the result is not an accumulator register xval is a null value but xptr is not null yval is a null value but yptr is not null
__builtin_divmodsd Description: Issues the 16-bit architecture's native signed divide support with the same restrictions given in the dsPIC30F/33F Programmers Reference Manual (DS70157). Notably, if the quotient does not fit into a 16-bit result, the results (including remainder) are unexpected. This form of the builtin function will capture both the quotient and remainder. signed int __builtin_divmodsd( signed long dividend, signed int divisor, signed int *remainder); dividend divisor remainder divmodsd number to be divided number to divide by pointer to remainder
Prototype:
Argument:
None.
__builtin_divmodud Description: Issues the 16-bit architecture's native unsigned divide support with the same restrictions given in the dsPIC30F/33F Programmers Reference Manual (DS70157). Notably, if the quotient does not fit into a 16-bit result, the results (including remainder) are unexpected. This form of the builtin function will capture both the quotient and remainder. unsigned int __builtin_divmodud( unsigned long dividend, unsigned int divisor, unsigned int *remainder); dividend divisor remainder divmodud number to be divided number to divide by pointer to remainder
Prototype:
Argument:
DS51284F-page 137
(Continued)
__builtin_divsd Description: Computes the quotient num / den. A math error exception occurs if den is zero. Function arguments are signed, as is the function result. The command-line option -Wconversions can be used to detect unexpected sign conversions. int __builtin_divsd(const long num, const int den); num numerator den denominator Returns the signed integer value of the quotient num / den. div.sd
__builtin_divud Description: Computes the quotient num / den. A math error exception occurs if den is zero. Function arguments are unsigned, as is the function result. The command-line option -Wconversions can be used to detect unexpected sign conversions. unsigned int __builtin_divud(const unsigned long num, const unsigned int den); num numerator den denominator Returns the unsigned integer value of the quotient num / den. div.ud
__builtin_dmaoffset Description: Obtains the offset of a symbol within DMA memory. For example: unsigned int result; char buffer[256] __attribute__((space(dma))); result = __builtin_dmaoffset(&buffer); Might generate: mov #dmaoffset(buffer), w0 Prototype: Argument: Return Value: Assembler Operator / Machine Instruction: Error Messages unsigned int __builtin_dmaoffset(const void *p); *p pointer to DMA address value Returns the offset to an accumulator. dmaoffset
DS51284F-page 138
An error message will be displayed if: the result is not an accumulator register xptr is null yptr is null distance is null
__builtin_edac Description: Squares sqr and sums with the nominated accumulator register, returning it as the result. Also prefetchs data for future square operation by computing **xptr - **yptr and storing the result in *distance. xincr and yincr may be the literal values: -6, -4, -2, 0, 2, 4, 6 or an integer value. For example: register int result asm("A"); int *xmemory, *ymemory; int distance; result = __builtin_ed(distance, &xmemory, 2, &ymemory, 2, &distance); might generate: ed w4*w4, A, [w8]+=2, [W10]+=2, w4
DS51284F-page 139
(Continued)
int __builtin_edac(int sqr, int **xptr, int xincr, int **yptr, int yincr, int *distance); sqr xptr xincr yptr yincr distance edac Integer squared value. Integer pointer to pointer to x prefetch. Integer increment value of x prefetch. Integer pointer to pointer to y prefetch. Integer increment value of y prefetch. Integer pointer to distance.
An error message will be displayed if: the result is not an accumulator register xptr is null yptr is null distance is null
__builtin_fbcl Description: Finds the first bit change from left in value. This is useful for dynamic scaling of fixed-point data. For example: int result, value; result = __builtin_fbcl(value); might generate: fbcl w4, w5 Prototype: Argument: Return Value: Assembler Operator / Machine Instruction: Error Messages int __builtin_fbcl(int value); value fbcl Integer number of first bit change. Returns the shifted addition result to an accumulator.
__builtin_lac Description: Shifts value by shift (a literal between -8 and 7) and returns the value to be stored into the accumulator register. For example: register int result asm("A"); int value; result = __builtin_lac(value,3); Might generate: lac w4, #3, A Prototype: Argument: Return Value: int __builtin_lac(int value, int shift); value shift Integer number to be shifted. Literal amount to shift.
DS51284F-page 140
(Continued)
lac
An error message will be displayed if: the result is not an accumulator register the shift value is not a literal within range
__builtin_mac Description: Computes a x b and sums with accumulator; also prefetchs data ready for a future MAC operation. xptr may be null to signify no X prefetch to be performed, in which case the values of xincr and xval are ignored, but required. yptr may be null to signify no Y prefetch to be performed, in which case the values of yincr and yval are ignored, but required. xval and yval nominate the address of a C variable where the prefetched value will be stored. xincr and yincr may be the literal values: -6, -4, -2, 0, 2, 4, 6 or an integer value. If AWB is non null, the other accumulator will be written back into the referenced variable. For example: register int result asm("A"); int *xmemory; int *ymemory; int xVal, yVal; result = __builtin_mac(xVal, yVal, &xmemory, &xVal, 2, &ymemory, &yVal, 2, 0); might generate: mac w4*w5, A, [w8]+=2, w4, [w10]+=2, w5 Prototype: int __builtin_mac(int a, int b, int **xptr, int *xval, int xincr, int **yptr, int *yval, int yincr, int *AWB); a b xptr xval xincr yptr yval yincr AWB mac Integer multiplicand. Integer multiplier. Integer pointer to pointer to x prefetch. Integer pointer to value of x prefetch. Integer increment value of x prefetch. Integer pointer to pointer to y prefetch. Integer pointer to value of y prefetch. Integer increment value of y prefetch. Integer pointer to accumulator selection.
Argument:
An error message will be displayed if: the result is not an accumulator register xval is a null value but xptr is not null yval is a null value but yptr is not null
DS51284F-page 141
Prototype: Argument: Return Value: Assembler Operator / Machine Instruction: Error Messages
None.
__builtin_modud Description: Issues the 16-bit architecture's native unsigned divide support with the same restrictions given in the dsPIC30F/33F Programmers Reference Manual (DS70157). Notably, if the quotient does not fit into a 16-bit result, the results (including remainder) are unexpected. This form of the builtin function will capture only the remainder. unsigned int __builtin_modud(unsigned long dividend, unsigned int divisor); dividend divisor Remainder. modud number to be divided number to divide by
Prototype: Argument: Return Value: Assembler Operator / Machine Instruction: Error Messages
None.
DS51284F-page 142
Argument:
An error message will be displayed if: the result is not an accumulator register xval is a null value but xptr is not null yval is a null value but yptr is not null
DS51284F-page 143
Argument:
An error message will be displayed if: the result is not an accumulator register xval is a null value but xptr is not null yval is a null value but yptr is not null
DS51284F-page 144
Argument:
An error message will be displayed if: the result is not an accumulator register xval is a null value but xptr is not null yval is a null value but yptr is not null
DS51284F-page 145
Argument:
An error message will be displayed if: the result is not an accumulator register xval is a null value but xptr is not null yval is a null value but yptr is not null
__builtin_mulss Description: Computes the product p0 x p1. Function arguments are signed integers, and the function result is a signed long integer. The command-line option -Wconversions can be used to detect unexpected sign conversions. signed long __builtin_mulss(const signed int p0, const signed int p1);
Prototype:
DS51284F-page 146
(Continued)
p0 p1 multiplicand multiplier
Returns the signed long integer value of the product p0 x p1. mul.ss
__builtin_mulsu Description: Computes the product p0 x p1. Function arguments are integers with mixed signs, and the function result is a signed long integer. The command-line option -Wconversions can be used to detect unexpected sign conversions. This function supports the full range of addressing modes of the instruction, including immediate mode for operand p1. signed long __builtin_mulsu(const signed int p0, const unsigned int p1); p0 p1 multiplicand multiplier
Returns the signed long integer value of the product p0 x p1. mul.su
__builtin_mulus Description: Computes the product p0 x p1. Function arguments are integers with mixed signs, and the function result is a signed long integer. The command-line option -Wconversions can be used to detect unexpected sign conversions. This function supports the full range of addressing modes of the instruction. signed long __builtin_mulus(const unsigned int p0, const signed int p1); p0 p1 multiplicand multiplier
Returns the signed long integer value of the product p0 x p1. mul.us
__builtin_muluu Description: Computes the product p0 x p1. Function arguments are unsigned integers, and the function result is an unsigned long integer. The command-line option -Wconversions can be used to detect unexpected sign conversions. This function supports the full range of addressing modes of the instruction, including immediate mode for operand p1. unsigned long __builtin_muluu(const unsigned int p0, const unsigned int p1); p0 p1 multiplicand multiplier
DS51284F-page 147
(Continued)
mul.uu
__builtin_nop Description: Prototype: Argument: Return Value: Assembler Operator / Machine Instruction: Generates a nop instruction. void __builtin_nop(void); None. Returns a no operation (nop). nop
__builtin_psvpage Description: Returns the psv page number of the object whose address is given as a parameter. The argument p must be the address of an object in an EE data, PSV or executable memory space; otherwise an error message is produced and the compilation fails. See the space attribute in the MPLAB C30 C Compiler Users Guide (DS51284). unsigned int __builtin_psvpage(const void *p); p object address Returns the psv page number of the object whose address is given as a parameter. psvpage
Prototype: Argument: Return Value: Assembler Operator / Machine Instruction: Error Messages
The following error message is produced when this function is used incorrectly: Argument to __builtin_psvpage() is not the address of an object in code, psv, or eedata section. The argument must be an explicit object address. For example, if obj is object in an executable or read-only section, the following syntax is valid: unsigned page = __builtin_psvpage(&obj);
__builtin_psvoffset Description: Returns the psv page offset of the object whose address is given as a parameter. The argument p must be the address of an object in an EE data, PSV or executable memory space; otherwise an error message is produced and the compilation fails. See the space attribute in the MPLAB C30 C Compiler Users Guide (DS51284) unsigned int __builtin_psvoffset(const void *p); p object address Returns the psv page number offset of the object whose address is given as a parameter. psvoffset
DS51284F-page 148
(Continued)
The following error message is produced when this function is used incorrectly: Argument to __builtin_psvoffset() is not the address of an object in code, psv, or eedata section. The argument must be an explicit object address. For example, if obj is object in an executable or read-only section, the following syntax is valid: unsigned page = __builtin_psvoffset(&obj);
__builtin_readsfr Description: Prototype: Argument: Return Value: Assembler Operator / Machine Instruction: Error Messages Reads the SFR. unsigned int __builtin_readsfr(const void *p); p object address Returns the SFR. readsfr
The following error message is produced when this function is used incorrectly:
__builtin_return_address Description: Returns the return address of the current function, or of one of its callers. For the level argument, a value of 0 yields the return address of the current function, a value of 1 yields the return address of the caller of the current function, and so forth. When level exceeds the current stack depth, 0 will be returned. This function should only be used with a non-zero argument for debugging purposes. int __builtin_return_address (const int level); level Number of frames to scan up the call stack. Returns the return address of the current function, or of one of its callers. return_address
__builtin_sac Description: Shifts value by shift (a literal between -8 and 7) and returns the value. For example: register int value asm("A"); int result; result = __builtin_sac(value,3); Might generate: sac A, #3, w0 Prototype: Argument: Return Value: int __builtin_sac(int value, int shift); value shift Integer number to be shifted. Literal amount to shift.
DS51284F-page 149
(Continued)
sac
An error message will be displayed if: the result is not an accumulator register the shift value is not a literal within range
__builtin_sacr Description: Shifts value by shift (a literal between -8 and 7) and returns the value which is rounded using the rounding mode determined by the CORCONbits.RND control bit. For example: register int value asm("A"); int result; result = __builtin_sac(value,3); Might generate: sac.r A, #3, w0 Prototype: Argument: Return Value: Assembler Operator / Machine Instruction: Error Messages int __builtin_sacr(int value, int shift); value shift sacr Integer number to be shifted. Literal amount to shift.
An error message will be displayed if: the result is not an accumulator register the shift value is not a literal within range
__builtin_sftac Description: Shifts accumulator by shift. The valid shift range is -16 to 16. For example: register int result asm("A"); int i; result = __builtin_sftac(i); Might generate: sftac A, w0 Prototype: Argument: Return Value: Assembler Operator / Machine Instruction: Error Messages int __builtin_sftac(int shift); shift sftac Literal amount to shift. Returns the shifted result to an accumulator.
An error message will be displayed if: the result is not an accumulator register the shift value is not a literal within range
DS51284F-page 150
Prototype: Argument: Return Value: Assembler Operator / Machine Instruction: Error Messages
__builtin_tblpage Description: Returns the table page number of the object whose address is given as a parameter. The argument p must be the address of an object in an EE data, PSV or executable memory space; otherwise an error message is produced and the compilation fails. See the space attribute in the MPLAB C30 C Compiler Users Guide (DS51284). unsigned int __builtin_tblpage(const void *p); p object address Returns the table page number of the object whose address is given as a parameter. tblpage
Prototype: Argument: Return Value: Assembler Operator / Machine Instruction: Error Messages
The following error message is produced when this function is used incorrectly: Argument to __builtin_tblpage() is not the address of an object in code, psv, or eedata section. The argument must be an explicit object address. For example, if obj is object in an executable or read-only section, the following syntax is valid: unsigned page = __builtin_tblpage(&obj);
__builtin_tbloffset Description: Returns the table page offset of the object whose address is given as a parameter. The argument p must be the address of an object in an EE data, PSV or executable memory space; otherwise an error message is produced and the compilation fails. See the space attribute in the MPLAB C30 C Compiler Users Guide (DS51284). unsigned int __builtin_tbloffset(const void *p); p object address Returns the table page number offset of the object whose address is given as a parameter.
DS51284F-page 151
(Continued)
tbloffset
The following error message is produced when this function is used incorrectly: Argument to __builtin_tbloffset() is not the address of an object in code, psv, or eedata section. The argument must be an explicit object address. For example, if obj is object in an executable or read-only section, the following syntax is valid: unsigned page = __builtin_tbloffset(&obj);
__builtin_tblrdh Description: Issues the tblrdh.w instruction to read a word from Flash or EEDATA memory. You must set up the TBLPAG to point to the appropriate page. To do this, you may make use of __builtin_tbloffset() and __builtin_tblpage(). Please refer to the data sheet or dsPIC Family Reference Manual for complete details regarding reading and writing program Flash. unsigned int __builtin_tblrdh(unsigned int offset); offset None. tblrdh desired memory offset
Prototype: Argument: Return Value: Assembler Operator / Machine Instruction: Error Messages
None.
__builtin_tblrdl Description: Issues the tblrdl.w instruction to read a word from Flash or EEDATA memory. You must set up the TBLPAG to point to the appropriate page. To do this, you may make use of __builtin_tbloffset() and__builtin_tblpage(). Please refer to the data sheet or dsPIC30F Family Reference Manual (DS70046) for complete details regarding reading and writing program Flash. unsigned int __builtin_tblrdl(unsigned int offset); offset None. tblrdl desired memory offset
Prototype: Argument: Return Value: Assembler Operator / Machine Instruction: Error Messages
None.
DS51284F-page 152
Prototype: Argument: Return Value: Assembler Operator / Machine Instruction: Error Messages
None.
__builtin_tblwtl Description: Issues the tblrdl.w instruction to write a word to Flash or EEDATA memory. You must set up the TBLPAG to point to the appropriate page. To do this, you may make use of __builtin_tbloffset() and __builtin_tblpage(). Please refer to the data sheet or dsPIC30F Family Reference Manual (DS70046) for complete details regarding reading and writing program Flash. void __builtin_tblwtl(unsigned int offset unsigned int data); offset data None. tblwtl desired memory offset data to be written
Prototype: Argument: Return Value: Assembler Operator / Machine Instruction: Error Messages
None.
__builtin_write_NVM Description: Prototype: Argument: Return Value: Assembler Operator / Machine Instruction: Enables the Flash for writing by issuing the correct unlock sequence and enabling the WRite bit of the NVMCON register. void __builtin_write_NVM(void); None. None. mov #0x55, Wn mov Wn, _NVMKEY mov #0xAA, Wn mov Wn, _NVMKEY bset _NVMVON, #15 nop nop None.
Error Messages
DS51284F-page 153
Error Messages
__builtin_write_OSCCONH Description: Prototype: Argument: Return Value: Assembler Operator / Machine Instruction*: Unlocks and writes its argument to OSCCONH. void __builtin_write_OSCCONH(unsigned char value); value None. mov #0x78, w0 mov #0x9A, w1 mov #_OSCCON+1, w2 mov.b w0, [w2] mov.b w1, [w2] mov.b value, [w2] None. character to be written
Error Messages
DS51284F-page 154
C.2
ERRORS
Symbols
\x used with no following HEX digits The escape sequence \x should be followed by hex digits. '&' constraint used with no register class The asm statement is invalid. '%' constraint used with last operand The asm statement is invalid. #elif after #else In a preprocessor conditional, the #else clause must appear after any #elif clauses. #elif without #if In a preprocessor conditional, the #if must be used before using the #elif. #else after #else In a preprocessor conditional, the #else clause must appear only once. #else without #if In a preprocessor conditional, the #if must be used before using the #else.
DS51284F-page 155
A
a parameter list with an ellipsis can't match an empty parameter name list declaration The declaration and definition of a function must be consistent. symbol after #line is not a positive integer #line is expecting a source line number which must be positive. aggregate value used where a complex was expected Do not use aggregate values where complex values are expected. aggregate value used where a float was expected Do not use aggregate values where floating-point values are expected. aggregate value used where an integer was expected Do not use aggregate values where integer values are expected. alias arg not a string The argument to the alias attribute must be a string that names the target for which the current identifier is an alias. alignment may not be specified for 'identifier' The aligned attribute may only be used with a variable. '__alignof' applied to a bit-field The '__alignof' operator may not be applied to a bit-field. alternate interrupt vector is not a constant The interrupt vector number must be an integer constant. alternate interrupt vector number n is not valid A valid interrupt vector number is required.
DS51284F-page 156
DS51284F-page 157
C
called object is not a function Only functions may be called in C. cannot convert to a pointer type The expression cannot be converted to a pointer type. cannot put object with volatile field into register It is not legal to put an object with a volatile field into a register. cannot reload integer constant operand in 'asm' The asm statement is invalid. cannot specify both near and far attributes The attributes near and far are mutually exclusive, only one may be used for a function or variable. cannot take address of bit-field 'identifier' It is not legal to attempt to take address of a bit-field. can't open 'file' for writing The system cannot open the specified 'file'. Possible causes are not enough disk space to open the file, the directory does not exist, or there is no write permission in the destination directory. can't set 'attribute' attribute after definition The 'attribute' attribute must be used when the symbol is defined. case label does not reduce to an integer constant Case labels must be compile-time integer constants. case label not within a switch statement Case labels must be within a switch statement. cast specifies array type It is not permissible for a cast to specify an array type.
DS51284F-page 158
D
data type of 'name' isn't suitable for a register The data type does not fit into the requested register. declaration for parameter 'identifier' but no such parameter Only parameters in the parameter list may be declared. declaration of 'identifier' as array of functions It is not legal to have an array of functions. declaration of 'identifier' as array of voids It is not legal to have an array of voids. 'identifier' declared as function returning a function Functions may not return functions. 'identifier' declared as function returning an array Functions may not return arrays. decrement of pointer to unknown structure Do not decrement a pointer to an unknown structure. 'default' label not within a switch statement Default case labels must be within a switch statement. 'symbol' defined both normally and as an alias A 'symbol' can not be used as an alias for another symbol if it has already been defined. 'defined' cannot be used as a macro name The macro name cannot be called 'defined'. dereferencing pointer to incomplete type A dereferenced pointer must be a pointer to an incomplete type. division by zero in #if Division by zero is not computable.
DS51284F-page 159
E
elements of array 'identifier' have incomplete type Array elements should have complete types. empty character constant Empty character constants are not legal. empty file name in '#keyword' The filename specified as an argument of the specified #keyword is empty. empty index range in initializer Do not use empty index ranges in initializers empty scalar initializer Scalar initializers must not be empty. enumerator value for 'identifier' not integer constant Enumerator values must be integer constants. error closing 'file' The system cannot close the specified 'file'. Possible causes are not enough disk space to write to the file or the file is too big. error writing to 'file' The system cannot write to the specified 'file'. Possible causes are not enough disk space to write to the file or the file is too big. excess elements in char array initializer There are more elements in the list than the initializer value states. excess elements in struct initializer Do not use excess elements in structure initializers. expression statement has incomplete type The type of the expression is incomplete. extra brace group at end of initializer Do not place extra brace groups at the end of initializers. extraneous argument to 'option' option There are too many arguments to the specified command-line option.
DS51284F-page 160
DS51284F-page 161
H
'identifier' has an incomplete type It is not legal to have an incomplete type for the specified 'identifier'. 'identifier' has both 'extern' and initializer A variable declared 'extern' cannot be initialized. hexadecimal floating constants require an exponent Hexadecimal floating constants must have exponents.
I
implicit declaration of function 'identifier' The function identifier is used without a preceding prototype declaration or function definition. impossible register constraint in 'asm' The asm statement is invalid. incompatible type for argument n of 'identifier' When calling functions in C, ensure that actual argument types match the formal parameter types. incompatible type for argument n of indirect function call When calling functions in C, ensure that actual argument types match the formal parameter types. incompatible types in operation The types used in operation must be compatible. incomplete 'name' option The option to the command-line parameter name is incomplete. inconsistent operand constraints in an 'asm' The asm statement is invalid. increment of pointer to unknown structure Do not increment a pointer to an unknown structure. initializer element is not computable at load time Initializer elements must be computable at load time. initializer element is not constant Initializer elements must be constant. initializer fails to determine size of 'identifier' An array initializer fails to determine its size.
DS51284F-page 162
DS51284F-page 163
DS51284F-page 164
L
label label referenced outside of any function Labels may only be referenced inside functions. label 'label' used but not defined The specified label is used but is not defined. language 'name' not recognized Permissible languages include: c assembler none. filename: linker input file unused because linking not done The specified filename was specified on the command line, and it was taken to be a linker input file (since it was not recognized as anything else). However, the link step was not run. Therefore, this file was ignored. long long long is too long for GCC MPLAB C30 supports integers no longer than long long. long or short specified with char for 'identifier' The long and short qualifiers cannot be used with the char type. long or short specified with floating type for 'identifier' The long and short qualifiers cannot be used with the float type. long, short, signed or unsigned invalid for 'identifier' The long, short and signed qualifiers may only be used with integral types.
M
macro names must be identifiers Macro names must start with a letter or underscore followed by more letters, numbers or underscores. macro parameters must be comma-separated Commas are required between parameters in a list of parameters. macro 'name' passed n arguments, but takes just n Too many arguments were passed to macro 'name'.
DS51284F-page 165
DS51284F-page 166
O
operand constraint contains incorrectly positioned '+' or '='. The asm statement is invalid. operand constraints for 'asm' differ in number of alternatives The asm statement is invalid. operator defined requires an identifier defined is expecting an identifier. operator 'symbol' has no right operand Preprocessor operator 'symbol' requires an operand on the right side. output number n not directly addressable The asm statement is invalid. output operand constraint lacks '=' The asm statement is invalid. output operand is constant in 'asm' The asm statement is invalid. overflow in enumeration values Enumeration values must be in the range of 'int'.
DS51284F-page 167
DS51284F-page 168
S
save variable 'name' index not constant The subscript of the array 'name' is not a constant integer. save variable 'name' is not word aligned The object being saved must be word aligned save variable 'name' size is not even The object being saved must be evenly sized. save variable 'name' size is not known The object being saved must have a known size.
DS51284F-page 169
DS51284F-page 170
T
the only valid combination is 'long double' The long qualifier is the only qualifier that may be used with the double type. this built-in requires a frame pointer __builtin_return_address requires a frame pointer. Do not use the -fomit-frame-pointer option. this is a previous declaration If a label is duplicated, this message identifies the line number of a preceding declaration. too few arguments to function When calling a function in C, do not specify fewer arguments than the function requires. Nor should you specify too many. too few arguments to function 'identifier' When calling a function in C, do not specify fewer arguments than the function requires. Nor should you specify too many. too many alternatives in 'asm' The asm statement is invalid. too many arguments to function When calling a function in C, do not specify more arguments than the function requires. Nor should you specify too few. too many arguments to function 'identifier' When calling a function in C, do not specify more arguments than the function requires. Nor should you specify too few. too many decimal points in number Expecting only one decimal point. top-level declaration of 'identifier' specifies 'auto' Auto variables can only be declared inside functions. two or more data types in declaration of 'identifier' Each identifier may have only a single data type. two types specified in one empty declaration No more that one type should be specified. type of formal parameter n is incomplete Specify a complete type for the indicated parameter. type mismatch in conditional expression Types in conditional expressions must not be mismatched. typedef 'identifier' is initialized It is not legal to initialize typedef's. Use __typeof__ instead.
2007 Microchip Technology Inc.
DS51284F-page 171
V
'va_start' used in function with fixed args 'va_start' should be used only in functions with variable argument lists. variable 'identifier' has initializer but incomplete type It is not legal to initialize variables with incomplete types. variable or field 'identifier' declared void Neither variables nor fields may be declared void. variable-sized object may not be initialized It is not legal to initialize a variable-sized object. virtual memory exhausted Not enough memory left to write error message.
DS51284F-page 172
W
warning: -pipe ignored because -save-temps specified The -pipe option cannot be used with the -save-temps option. warning: -pipe ignored because -time specified The -pipe option cannot be used with the -time option. warning: '-x spec' after last input file has no effect The '-x' command line option affects only those files named after its on the command line; if there are no such files, then this option has no effect. weak declaration of 'name' must be public Weak symbols must be externally visible. weak declaration of 'name' must precede definition 'name' was defined and then declared weak. wrong number of arguments specified for attribute attribute There are too few or too many arguments given for the attribute named 'attribute'. wrong type argument to bit-complement Do not use the wrong type of argument to this operator. wrong type argument to decrement Do not use the wrong type of argument to this operator. wrong type argument to increment Do not use the wrong type of argument to this operator. wrong type argument to unary exclamation mark Do not use the wrong type of argument to this operator. wrong type argument to unary minus Do not use the wrong type of argument to this operator. wrong type argument to unary plus Do not use the wrong type of argument to this operator.
Z
zero width for bit-field 'identifier' Bit-fields may not have zero width.
DS51284F-page 173
Symbols
'/*' within comment A comment mark was found within a comment. '$' character(s) in identifier or number Dollar signs in identifier names are an extension to the standard. #'directive' is a GCC extension #warning, #include_next, #ident, #import, #assert and #unassert directives are GCC extensions and are not of ISO C89. #import is obsolete, use an #ifndef wrapper in the header file The #import directive is obsolete. #import was used to include a file if it hadn't already been included. Use the #ifndef directive instead. #include_next in primary source file #include_next starts searching the list of header file directories after the directory in which the current file was found. In this case, there were no previous header files so it is starting in the primary source file. #pragma pack (pop) encountered without matching #pragma pack (push, <n>) The pack(pop) pragma must be paired with a pack(push) pragma, which must precede it in the source file. #pragma pack (pop, identifier) encountered without matching #pragma pack (push, identifier, <n>) The pack(pop) pragma must be paired with a pack(push) pragma, which must precede it in the source file. #warning: message The directive #warning causes the preprocessor to issue a warning and continue preprocessing. The tokens following #warning are used as the warning message.
A
absolute address specification ignored Ignoring the absolute address specification for the code section in the #pragma statement because it is not supported in MPLAB C30. Addresses must be specified in the linker script and code sections can be defined with the keyword __attribute__. address of register variable 'name' requested The register specifier prevents taking the address of a variable. alignment must be a small power of two, not n The alignment parameter of the pack pragma must be a small power of two. anonymous enum declared inside parameter list An anonymous enum is declared inside a function parameter list. It is usually better programming practice to declare enums outside parameter lists, since they can never become complete types when defined inside parameter lists. anonymous struct declared inside parameter list An anonymous struct is declared inside a function parameter list. It is usually better programming practice to declare structs outside parameter lists, since they can never become complete types when defined inside parameter lists.
DS51284F-page 174
B
backslash and newline separated by space While processing for escape sequences, a backslash and newline were found separated by a space. backslash-newline at end of file While processing for escape sequences, a backslash and newline were found at the end of the file. bit-field 'identifier' type invalid in ISO C The type used on the specified identifier is not valid in ISO C. braces around scalar initializer A redundant set of braces around an initializer is supplied.
DS51284F-page 175
C
C++ style comments are not allowed in ISO C89 Use C style comments '/*' and '*/' instead of C++ style comments '//'. call-clobbered register used for global register variable Choose a register that is normally saved and restored by function calls (W8-W13), so that library routines will not clobber it. cannot inline function 'main' The function 'main' is declared with the inline attribute. This is not supported, since main must be called from the C start-up code, which is compiled separately. can't inline call to 'identifier' called from here The compiler was unable to inline the call to the specified function. case value 'n' not in enumerated type The controlling expression of a switch statement is an enumeration type, yet a case expression has the value n, which does not correspond to any of the enumeration values. case value 'value' not in enumerated type 'name' 'value' is an extra switch case that is not an element of the enumerated type 'name'. cast does not match function type The return type of a function is cast to a type that does not match the function's type. cast from pointer to integer of different size A pointer is cast to an integer that is not 16-bits wide. cast increases required alignment of target type When compiling with the -Wcast-align command-line option, the compiler verifies that casts do not increase the required alignment of the target type. For example, this warning message will be given if a pointer to char is cast as a pointer to int, since the aligned for char (byte alignment) is less than the alignment requirement for int (word alignment). character constant too long Character constants must not be too long. comma at end of enumerator list Unnecessary comma at the end of the enumerator list. comma operator in operand of #if Not expecting a comma operator in the #if directive. comparing floating point with == or != is unsafe Floating-point values can be approximations to infinitely precise real numbers. Instead of testing for equality, use relational operators to see whether the two values have ranges that overlap. comparison between pointer and integer A pointer type is being compared to an integer type.
DS51284F-page 176
DS51284F-page 177
D
data definition has no type or storage class A data definition was detected that lacked a type and storage class. data qualifier 'qualifier' ignored Data qualifiers, which include 'access', 'shared' and 'overlay', are not used in MPLAB C30, but are there for compatibility with MPLAB C17 and C18. declaration of 'identifier' has 'extern' and is initialized Externs should not be initialized. declaration of 'identifier' shadows a parameter The specified identifier declaration shadows a parameter, making the parameter inaccessible. declaration of 'identifier' shadows a symbol from the parameter list The specified identifier declaration shadows a symbol from the parameter list, making the symbol inaccessible. declaration of 'identifier' shadows global declaration The specified identifier declaration shadows a global declaration, making the global inaccessible. 'identifier' declared inline after being called The specified function was declared inline after it was called. 'identifier' declared inline after its definition The specified function was declared inline after it was defined. 'identifier' declared 'static' but never defined The specified function was declared static, but was never defined. decrement of read-only member 'name' The member 'name' was declared as const and cannot be modified by decrementing. decrement of read-only variable 'name' 'name' was declared as const and cannot be modified by decrementing. 'identifier' defined but not used The specified function was defined, but was never used. deprecated use of label at end of compound statement A label should not be at the end of a statement. It should be followed by a statement. dereferencing 'void *' pointer It is not correct to dereference a 'void *' pointer. Cast it to a pointer of the appropriate type before dereferencing the pointer. division by zero Compile-time division by zero has been detected.
DS51284F-page 178
E
embedded '\0' in format When checking the argument list of a call to printf, scanf, etc., the compiler found that the format string contains an embedded '\0' (zero), which can cause early termination of format string processing. empty body in an else-statement An else statement is empty. empty body in an if-statement An if statement is empty. empty declaration The declaration contains no names to declare. empty range specified The range of values in a case range is empty, that is, the value of the low expression is greater than the value of the high expression. Recall that the syntax for case ranges is case low ... high:. 'enum identifier' declared inside parameter list The specified enum is declared inside a function parameter list. It is usually better programming practice to declare enums outside parameter lists, since they can never become complete types when defined inside parameter lists. enum defined inside parms An enum is defined inside a function parameter list. enumeration value 'identifier' not handled in switch The controlling expression of a switch statement is an enumeration type, yet not all enumeration values have case expressions. enumeration values exceed range of largest integer Enumeration values are represented as integers. The compiler detected that an enumeration range cannot be represented in any of the MPLAB C30 integer formats, including the largest such format. excess elements in array initializer There are more elements in the initializer list than the array was declared with. excess elements in scalar initializer"); There should be only one initializer for a scalar variable. excess elements in struct initializer There are more elements in the initializer list than the structure was declared with. excess elements in union initializer There are more elements in the initializer list than the union was declared with.
DS51284F-page 179
F
-ffunction-sections may affect debugging on some targets You may have problems with debugging if you specify both the -g option and the -ffunction-sections option. first argument of 'identifier' should be 'int' Expecting declaration of first argument of specified identifier to be of type int. floating constant exceeds range of 'double' A floating-point constant is too large or too small (in magnitude) to be represented as a 'double'. floating constant exceeds range of 'float' A floating-point constant is too large or too small (in magnitude) to be represented as a 'float'. floating constant exceeds range of 'long double' A floating-point constant is too large or too small (in magnitude) to be represented as a 'long double'. floating point overflow in expression When folding a floating-point constant expression, the compiler found that the expression overflowed, that is, it could not be represented as float. 'type1' format, 'type2' arg (arg 'num') The format is of type 'type1', but the argument being passed is of type 'type2'. The argument in question is the 'num' argument. format argument is not a pointer (arg n) When checking the argument list of a call to printf, scanf, etc., the compiler found that the specified argument number n was not a pointer, san the format specifier indicated it should be. format argument is not a pointer to a pointer (arg n) When checking the argument list of a call to printf, scanf, etc., the compiler found that the specified argument number n was not a pointer san the format specifier indicated it should be. fprefetch-loop-arrays not supported for this target The option to generate instructions to prefetch memory is not supported for this target. function call has aggregate value The return value of a function is an aggregate. function declaration isn't a prototype When compiling with the -Wstrict-prototypes command-line option, the compiler ensures that function prototypes are specified for all functions. In this case, a function definition was encountered without a preceding function prototype. function declared 'noreturn' has a 'return' statement A function was declared with the noreturn attribute-indicating that the function does not return-yet the function contains a return statement. This is inconsistent.
DS51284F-page 180
G
GCC does not yet properly implement '[*]' array declarators Variable length arrays are not currently supported by the compiler.
H
hex escape sequence out of range The hex sequence must be less than 100 in hex (256 in decimal).
I
ignoring asm-specifier for non-static local variable 'identifier' The asm-specifier is ignored when it is used with an ordinary, non-register local variable. ignoring invalid multibyte character When parsing a multibyte character, the compiler determined that it was invalid. The invalid character is ignored. ignoring option 'option' due to invalid debug level specification A debug option was used with a debug level that is not a valid debug level. ignoring #pragma identifier The specified pragma is not supported by the MPLAB C30 compiler, and is ignored. imaginary constants are a GCC extention ISO C does not allow imaginary numeric constants. implicit declaration of function 'identifier' The specified function has no previous explicit declaration (definition or function prototype), so the compiler makes assumptions about its return type and parameters.
DS51284F-page 181
DS51284F-page 182
DS51284F-page 183
L
label 'identifier' defined but not used The specified label was defined, but not referenced. large integer implicitly truncated to unsigned type An integer constant value appears in the source code without an explicit unsigned modifier, yet the number cannot be represented as a signed int; therefore, the compiler automatically treats it as an unsigned int. left-hand operand of comma expression has no effect One of the operands of a comparison is a promoted ~unsigned, while the other is unsigned. left shift count >= width of type Shift counts should be less than the number of bits in the type being shifted. Otherwise, the shift is meaningless, and the result is undefined. left shift count is negative Shift counts should be positive. A negative left shift count does not mean shift right; it is meaningless.
DS51284F-page 184
M
'main' is usually a function The identifier main is usually used for the name of the main entry point of an application. The compiler detected that it was being used in some other way, for example, as the name of a variable. 'operation' makes integer from pointer without a cast A pointer has been implicitly converted to an integer. 'operation' makes pointer from integer without a cast An integer has been implicitly converted to a pointer. malformed '#pragma pack-ignored' The syntax of the pack pragma is incorrect. malformed '#pragma pack(pop[,id])-ignored' The syntax of the pack pragma is incorrect. malformed '#pragma pack(push[,id],<n>)-ignored' The syntax of the pack pragma is incorrect. malformed '#pragma weak-ignored' The syntax of the weak pragma is incorrect. 'identifier' might be used uninitialized in this function The compiler detected a control path though a function which might use the specified identifier before it has been initialized. missing braces around initializer A required set of braces around an initializer is missing. missing initializer An initializer is missing. modification by 'asm' of read-only variable 'identifier' A const variable is the left-hand-side of an assignment in an 'asm' statement. multi-character character constant A character constant contains more than one character.
DS51284F-page 185
O
octal escape sequence out of range The octal sequence must be less than 400 in octal (256 in decimal). output constraint 'constraint' for operand n is not at the beginning Output constraints in extended asm should be at the beginning. overflow in constant expression The constant expression has exceeded the range of representable values for its type. overflow in implicit constant conversion An implicit constant conversion resulted in a number that cannot be represented as a signed int; therefore, the compiler automatically treats it as an unsigned int.
DS51284F-page 186
DS51284F-page 187
S
second argument of 'identifier' should be 'char **' Expecting second argument of specified identifier to be of type 'char **'. second parameter of 'va_start' not last named argument The second parameter of 'va_start' must be the last named argument. shadowing built-in function 'identifier' The specified function has the same name as a built-in function, and consequently shadows the built-in function. shadowing library function 'identifier' The specified function has the same name as a library function, and consequently shadows the library function.
DS51284F-page 188
DS51284F-page 189
T
'identifier' takes only zero or two arguments Expecting zero or two arguments only. the meaning of '\a' is different in traditional C When the -wtraditional option is used, the escape sequence '\a' is not recognized as a meta-sequence: its value is just 'a'. In non-traditional compilation, '\a' represents the ASCII BEL character. the meaning of '\x' is different in traditional C When the -wtraditional option is used, the escape sequence '\x' is not recognized as a meta-sequence: its value is just 'x'. In non-traditional compilation, '\x' introduces a hexadecimal escape sequence. third argument of 'identifier' should probably be 'char **' Expecting third argument of specified identifier to be of type 'char **'. this function may return with or without a value All exit paths from non-void function should return an appropriate value. The compiler detected a case where a non-void function terminates, sometimes with and sometimes without an explicit return value. Therefore, the return value might be unpredictable. this target machine does not have delayed branches The -fdelayed-branch option is not supported. too few arguments for format When checking the argument list of a call to printf, scanf, etc., the compiler found that the number of actual arguments was fewer than that required by the format string.
DS51284F-page 190
trigraph ??char ignored Trigraph sequence is being ignored. char can be (, ), <, >, =, /, ', !, or type defaults to 'int' in declaration of 'identifier' In the absence of an explicit type declaration for the specified identifier, the compiler assumes that its type is int. type mismatch with previous external decl previous external decl of 'identifier' The type of the specified identifier does not match the previous declaration. type mismatch with previous implicit declaration An explicit declaration conflicts with a previous implicit declaration. type of 'identifier' defaults to 'int' In the absence of an explicit type declaration, the compiler assumes that identifier's type is int. type qualifiers ignored on function return type The type qualifier being used with the function return type is ignored.
U
undefining 'defined' 'defined' cannot be used as a macro name and should not be undefined. undefining 'name' The #undef directive was used on a previously defined macro name 'name'. union cannot be made transparent The transparent_union attribute was applied to a union, but the specified variable does not satisfy the requirements of that attribute. 'union identifier' declared inside parameter list The specified union is declared inside a function parameter list. It is usually better programming practice to declare unions outside parameter lists, since they can never become complete types when defined inside parameter lists.
DS51284F-page 191
DS51284F-page 192
W
-Wformat-extra-args ignored without -Wformat -Wformat must be specified to use -Wformat-extra-args. -Wformat-nonliteral ignored without -Wformat -Wformat must be specified to use -Wformat-nonliteral. -Wformat-security ignored without -Wformat -Wformat must be specified to use -Wformat-security. -Wformat-y2k ignored without -Wformat -Wformat must be specified to use. -Wid-clash-LEN is no longer supported The option -Wid-clash-LEN is no longer supported. -Wmissing-format-attribute ignored without -Wformat -Wformat must be specified to use -Wmissing-format-attribute. -Wuninitialized is not supported without -O Optimization must be on to use the -Wuninitialized option. 'identifier' was declared 'extern' and later 'static' The specified identifier was previously declared 'extern' and is now being declared as static. 'identifier' was declared implicitly 'extern' and later 'static' The specified identifier was previously declared implicitly 'extern' and is now being declared as static. 'identifier' was previously implicitly declared to return 'int' There is a mismatch against the previous implicit declaration.
DS51284F-page 193
Z
zero-length identifier format string When checking the argument list of a call to printf, scanf, etc., the compiler found that the format string was empty ().
DS51284F-page 194
MPLAB C30 USERS GUIDE Appendix D. MPLAB C18 vs. MPLAB C30 C Compiler
D.1 INTRODUCTION
The purpose of this chapter is to highlight the differences between the MPLAB C18 and MPLAB C30 C compilers. For more details on the MPLAB C18 compiler, please refer to the MPLAB C18 C Compiler Users Guide (DS51288).
D.2
HIGHLIGHTS
This chapter discusses the following areas of difference between the two compilers: Data Formats Pointers Storage Classes Stack Usage Storage Qualifiers Predefined Macro Names Integer Promotions String Constants Access Memory Inline Assembly Pragmas Memory Models Calling Conventions Startup Code Compiler-Managed Resources Optimizations Object Module Format Implementation-Defined Behavior Bit fields
DS51284F-page 195
Data Format
MPLAB C18 uses its own data format, which is similar to IEEE-754 format, but with the top nine bits rotated (see Table D-2). MPLAB C30 uses IEEE-754 format. See Section 5.5 Floating Point.
TABLE D-2:
Standard MPLAB C30 MPLAB C18
D.4
POINTERS
TABLE D-3: NUMBER OF BITS USED FOR POINTERS
MPLAB C18 16 24 16 MPLAB C30 16 16 16
Memory Type Program Memory - Near Program Memory - Far Data Memory
D.5
STORAGE CLASSES
MPLAB C18 allows the non-ANSI storage class specifiers overlay for variables and auto or static for function arguments. MPLAB C30 does not allow these specifiers.
D.6
STACK USAGE
TABLE D-4: TYPE OF STACK USED
MPLAB C18 hardware software MPLAB C30 software software
DS51284F-page 196
EXAMPLE D-2:
C18 C30
EXAMPLE D-3:
C18 C30
D.8
D.9
INTEGER PROMOTIONS
MPLAB C18 performs integer promotions at the size of the largest operand even if both operands are smaller than an int. MPLAB C18 provides the -Oi+ option to conform to the standard. MPLAB C30 performs integer promotions at int precision or greater as mandated by ISO.
DS51284F-page 197
Pragma (MPLAB C18) #pragma udata [name] #pragma idata [name] #pragma romdata [name] #pragma code [name] #pragma interruptlow #pragma interrupt #pragma varlocate bank #pragma varlocate name
((section ("name"))) ((section ("name"))) ((space (prog))) ((section ("name"))), ((space (prog))) ((interrupt)) ((interrupt, shadow))
EXAMPLE D-4:
C18 C30
EXAMPLE D-5:
C18 C30
EXAMPLE D-6:
C18
#pragma romdata const_table const rom char my_const_array[10] = {0,1,2,3,4,5,6,7,8,9}; const __attribute__((space(auto_psv))) char my_const_array[10] = {0,1,2,3,4,5,6,7,8,9};
C30
Note:
The MPLAB C30 compiler does not directly support accessing variables in program space. Variables so allocated must be explicitly accessed by the programmer, usually using table-access inline assembly instructions, or using the program space visibility window. See Section 4.15 Program Space Visibility (PSV) Usage for more on the PSV window.
DS51284F-page 198
#pragma code myTextSection=0x8000; int PrintString(const char *s){...}; int __attribute__((address(0x8000))) PrintString (const char *s) {...};
EXAMPLE D-8:
C18
COMPILER AUTOMATICALLY SAVES AND RESTORES THE VARIABLES VAR1 AND VAR2
#pragma interrupt isr0 save=var1, var2 void isr0(void) { /* perform interrupt function here */ } void __attribute__((__interrupt__(__save__(var1,var2)))) isr0(void) { /* perform interrupt function here */ }
C30
DS51284F-page 199
-fwritable-strings N/A Banking not used All registers are automatically tracked Procedural Abstraction(-mpa)
In MPLAB C30, these optimization settings will satisfy most needs. Additional flags may be used for fine-tuning". See Section 3.5.6 Options for Controlling Optimization for more information.
DS51284F-page 200
struct foo will have a size of 10 bytes using MPLAB C30. i will be allocated at bit offset 0 (through 39). There will be 8 bits of padding before j, allocated at bit offset 48. If j were allocated at the next available bit offset, 40, it would cross a storage boundary for a 16 bit integer. k will be allocated after j, at bit offset 64. The structure will contain 8 bits of padding at the end to maintain the required alignment in the case of an array. The alignment is 2 bytes because the largest alignment in the structure is 2 bytes. struct bar will have a size of 8 bytes using MPLAB C30. I will be allocated at bit offset 0 (through 39). There is no need to pad before J because it will not cross a storage boundary for a char. J is allocated at bit offset 40. K can be allocated starting at bit offset 48, completing the structure without wasting any space.
DS51284F-page 201
DS51284F-page 202
E.2
HIGHLIGHTS
Deprecated features covered are: Predefined Constants
E.3
PREDEFINED CONSTANTS
The following preprocessing symbols are defined by the MPLAB C30 compiler.
Symbol dsPIC30 Defined with -ansi command-line option? No Yes Yes
__dsPIC30 __dsPIC30__
The ELF-specific version of the compiler defines the following preprocessing symbols.
Symbol dsPIC30ELF Defined with -ansi command-line option? No Yes Yes
__dsPIC30ELF __dsPIC30ELF__
The COFF-specific version of the compiler defines the following preprocessing symbols.
Symbol dsPIC30COFF Defined with -ansi command-line option? No Yes Yes
__dsPIC30COFF __dsPIC30COFF__
For the most current information, see Section 3.7 Predefined Constants.
DS51284F-page 203
DS51284F-page 204
DS51284F-page 205
DS51284F-page 206
G.1
PREAMBLE
The purpose of this License is to make a manual, textbook, or other functional and useful document free in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or non commercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others. This License is a kind of copyleft, which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software. We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference.
G.2
DS51284F-page 207
DS51284F-page 208
G.3
VERBATIM COPYING
You may copy and distribute the Document in any medium, either commercially or non-commercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3. You may also lend copies, under the same conditions stated above, and you may publicly display copies.
G.4
COPYING IN QUANTITY
If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document's license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects. If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages. If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public. It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document.
G.5
MODIFICATIONS
You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version: a) Use in the Title Page (and on the covers, if any) a title distinct from that of the Document, and from those of previous versions (which should, if there were any, be listed in the History section of the Document). You may use the same title as
DS51284F-page 209
DS51284F-page 210
includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one. The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version.
G.6
COMBINING DOCUMENTS
You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers. The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work. In the combination, you must combine any sections Entitled History in the various original documents, forming one section Entitled History; likewise combine any sections Entitled Acknowledgements, and any sections Entitled Dedications. You must delete all sections Entitled Endorsements.
G.7
COLLECTIONS OF DOCUMENTS
You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects. You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document.
G.8
DS51284F-page 211
G.10 TERMINATION
You may not copy, modify, sublicense, or distribute the Document except as expressly provided for under this License. Any other attempt to copy, modify, sublicense or distribute the Document is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
G.11
DS51284F-page 212
DS51284F-page 213
DS51284F-page 214
Glossary
Breakpoint, Software An address where execution of the firmware will halt. Usually achieved by a special break instruction. Build Compile and link all the source files for an application. C A general-purpose programming language which features economy of expression, modern control flow and data structures and a rich set of operators. Calibration Memory A special function register or registers used to hold values for calibration of a PIC microcontroller on-board RC oscillator or other device peripherals.
DS51284F-page 215
DS51284F-page 216
Glossary
DSP See Digital Signal Processor. EEPROM Electrically Erasable Programmable Read Only Memory. A special type of PROM that can be erased electrically. Data is written or erased one byte at a time. EEPROM retains its contents even when power is turned off. Emulation The process of executing software loaded into emulation memory as if it were firmware residing on a microcontroller device. Emulation Memory Program memory contained within the emulator. Emulator Hardware that performs emulation. Emulator System The MPLAB ICE 2000 and 4000 emulator systems include the pod, processor module, device adapter, cables, and MPLAB IDE software. Endianess Describes order of bytes in a multi-byte object. Epilogue A portion of compiler-generated code that is responsible for deallocating stack space, restoring registers and performing any other machine-specific requirement specified in the runtime model. This code executes after any user code for a given function, immediately prior to the function return. EPROM Erasable Programmable Read Only Memory. A programmable read-only memory that can be erased usually by exposure to ultraviolet radiation. Errors Errors report problems that make it impossible to continue processing your program. When possible, errors identify the source file name and line number where the problem is apparent. Event A description of a bus cycle which may include address, data, pass count, external input, cycle type (fetch, R/W), and time stamp. Events are used to describe triggers, breakpoints and interrupts. Executable Code Software that is ready to be loaded for execution. Export Send data out of the MPLAB IDE in a standardized format. Expressions Combinations of constants and/or symbols separated by arithmetic or logical operators. Extended Microcontroller Mode In extended microcontroller mode, on-chip program memory as well as external memory is available. Execution automatically switches to external if the program memory address is greater than the internal memory space of the PIC17CXXX or PIC18CXXX device.
2007 Microchip Technology Inc.
DS51284F-page 217
DS51284F-page 218
Glossary
File Registers On-chip data memory, including General Purpose Registers (GPRs) and Special Function Registers (SFRs). Flash A type of EEPROM where data is written or erased in blocks instead of bytes. FNOP Forced No Operation. A forced NOP cycle is the second cycle of a two-cycle instruction. Since the PIC microcontroller architecture is pipelined, it prefetches the next instruction in the physical address space while it is executing the current instruction. However, if the current instruction changes the program counter, this prefetched instruction is explicitly ignored, causing a forced NOP cycle. Frame Pointer A pointer that references the location on the stack that separates the stack-based arguments from the stack-based local variables. Provides a convenient base from which to access local variables and other values for the current function. Free-Standing A C compiler implementation that accepts any strictly conforming program that does not use complex types and in which the use of the features specified in the ISO library clause is confined to the contents of the standard headers <float.h>, <iso646.h>, <limits.h>, <stddef.h> and <stdint.h>. GPR General Purpose Register. The portion of device data memory (RAM) available for general use. Halt A stop of program execution. Executing Halt is the same as stopping at a breakpoint. Heap An area of memory used for dynamic memory allocation where blocks of memory are allocated and freed in an arbitrary order determined at runtime. Hex Code Executable instructions stored in a hexadecimal format code. Hex code is contained in a hex file. Hex File An ASCII file containing hexadecimal addresses and values (hex code) suitable for programming a device. High Level Language A language for writing programs that is further removed from the processor than assembly. ICD In-Circuit Debugger. MPLAB ICD and MPLAB ICD 2 are Microchips in-circuit debuggers for PIC16F87X and PIC18FXXX devices, respectively. These ICDs work with MPLAB IDE. ICE In-Circuit Emulator. MPLAB ICE 2000 and 4000 are Microchips in-circuit emulators that work with MPLAB IDE. IDE
DS51284F-page 219
DS51284F-page 220
Glossary
International Organization for Standardization An organization that sets standards in many businesses and technologies, including computing and communications. Interrupt A signal to the CPU that suspends the execution of a running application and transfers control to an Interrupt Service Routine (ISR) so that the event may be processed. Interrupt Handler A routine that processes special code when an interrupt occurs. Interrupt Request An event which causes the processor to temporarily suspend normal instruction execution and to start executing an interrupt handler routine. Some processors have several interrupt request events allowing different priority interrupts. Interrupt Service Routine A function that is invoked when an interrupt occurs. Interrupt Service Routine User-generated code that is entered when an interrupt occurs. The location of the code in program memory will usually depend on the type of interrupt that has occurred. IRQ See Interrupt Request. ISO See International Organization for Standardization. ISR See Interrupt Service Routine. L-value An expression that refers to an object that can be examined and/or modified. An l-value expression is used on the left-hand side of an assignment. Latency The time between an event and its response. Librarian See Archiver. Library See Archive. Linker A language tool that combines object files and libraries to create executable code, resolving references from one module to another. Linker Script Files Linker script files are the command files of a linker. They define linker options and describe available memory on the target platform. Listing Directives Listing directives are those directives that control the assembler listing file format. They allow the specification of titles, pagination and other listing control. Listing File
DS51284F-page 221
DS51284F-page 222
Glossary
Logic Probes Up to 14 logic probes can be connected to some Microchip emulators. The logic probes provide external trace inputs, trigger output signal, +5V, and a common ground. Machine Code The representation of a computer program that is actually read and interpreted by the processor. A program in binary machine code consists of a sequence of machine instructions (possibly interspersed with data). The collection of all possible instructions for a particular processor is known as its instruction set.
DS51284F-page 223
DS51284F-page 224
Glossary
Microchips in-circuit debugger for PIC16F87X, PIC18FXXX and dsPIC30FXXXX devices. The ICD works with MPLAB IDE. The main component of each ICD is the module. A complete system consists of a module, header, demo board, cables and MPLAB IDE Software. MPLAB ICE 2000 Microchips in-circuit emulator for PIC MCUs that works with MPLAB IDE. MPLAB ICE 4000 Microchips in-circuit emulator for dsPIC DSCs that works with MPLAB IDE. MPLAB IDE Microchips Integrated Development Environment. MPLAB LIB30 MPLAB LIB30 archiver/librarian is an object librarian for use with COFF object modules created using either MPLAB ASM30 or MPLAB C30 C compiler. MPLAB LINK30 MPLAB LINK30 is an object linker for the Microchip MPLAB ASM30 assembler and the Microchip MPLAB C30 C compiler. MPLAB SIM Microchips simulator that works with MPLAB IDE in support of PIC MCU devices. MPLAB SIM30 Microchips simulator that works with MPLAB IDE in support of dsPIC DSC devices. MPLIB Object Librarian MPLIB librarian is an object librarian for use with COFF object modules created using either MPASM assembler (mpasm or mpasmwin v2.0) or MPLAB C1X C compilers. MPLINK Object Linker MPLINK linker is an object linker for the Microchip MPASM assembler and the Microchip MPLAB C17 or C18 C compilers. MPLINK linker also may be used with the Microchip MPLIB librarian. MPLINK linker is designed to be used with MPLAB IDE, though it does not have to be. MRU Most Recently Used. Refers to files and windows available to be selected from MPLAB IDE main pull down menus. Nesting Depth The maximum level to which macros can include other macros. Node MPLAB IDE project component. Non Real-Time Refers to the processor at a breakpoint or executing single step instructions or MPLAB IDE being run in simulator mode. Non-Volatile Storage A storage device whose contents are preserved when its power is off. NOP No Operation. An instruction that has no effect when executed except to advance the program counter. Object Code The machine code generated by an assembler or compiler.
2007 Microchip Technology Inc.
DS51284F-page 225
DS51284F-page 226
Glossary
Pragma A directive that has meaning to a specific compiler. Often a pragma is used to convey implementation-defined information to the compiler. MPLAB C30 uses attributes to convey this information. Precedence Rules that define the order of evaluation in expressions. PRO MATE II A device programmer from Microchip. Programs all PIC microcontrollers and most memory and Keeloq devices. Can be used with MPLAB IDE or stand-alone. Program Counter The location that contains the address of the instruction that is currently executing. Program Memory The memory area in a device where instructions are stored. Also, the memory in the emulator or simulator containing the downloaded target application firmware. Program Memory The memory area in a device where instructions are stored. Project A set of source files and instructions to build the object and executable code for an application. Prologue A portion of compiler-generated code that is responsible for allocating stack space, preserving registers and performing any other machine-specific requirement specified in the runtime model. This code executes before any user code for a given function. Prototype System A term referring to a user's target application, or target board. PWM Signals Pulse Width Modulation Signals. Certain PIC MCU devices have a PWM peripheral. Qualifier An address or an address range used by the Pass Counter or as an event before another operation in a complex trigger. Radix The number base, hex or decimal, used in specifying an address. RAM Random Access Memory (Data Memory). Memory in which information can be accessed in any order. Raw Data The binary representation of code or data associated with a section. Real-Time When released from the halt state in the emulator or MPLAB ICD mode, the processor runs in real-time mode and behaves exactly as the normal chip would behave. In real-time mode, the real-time trace buffer of MPLAB ICE is enabled and constantly captures all selected cycles, and all break logic is enabled. In the emulator or MPLAB ICD, the processor executes in real-time until a valid breakpoint causes a halt, or until the user halts the emulator. In the simulator, real-time simply means execution of the microcontroller instructions as fast as they can be simulated by the host CPU.
DS51284F-page 227
DS51284F-page 228
Glossary
When a hardware breakpoint is used to halt the processor, one or more additional instructions may be executed before the processor halts. The number of extra instructions executed after the intended breakpoint is referred to as the skid. Source Code The form in which a computer program is written by the programmer. Source code is written in some formal programming language which can be translated into machine code or executed by an interpreter. Source File An ASCII text file containing source code. Special Function Registers The portion of data memory (RAM) dedicated to registers that control I/O processor functions, I/O status, timers or other modes or peripherals. Stack, Hardware Locations in PIC microcontroller where the return address is stored when a function call is made. Stack, Software Memory used by an application for storing return addresses, function parameters and local variables. This memory is typically managed by the compiler when developing code in a high-level language. Static RAM or SRAM Static Random Access Memory. Program memory you can Read/Write on the target board that does not need refreshing frequently. Status Bar The Status Bar is located on the bottom of the MPLAB IDE window and indicates such current information as cursor position, development mode and device, and active tool bar. Step Into This command is the same as Single Step. Step Into (as opposed to Step Over) follows a CALL instruction into a subroutine. Step Over Step Over allows you to debug code without stepping into subroutines. When stepping over a CALL instruction, the next breakpoint will be set at the instruction after the CALL. If for some reason the subroutine gets into an endless loop or does not return properly, the next breakpoint will never be reached. The Step Over command is the same as Single Step except for its handling of CALL instructions. Stimulus Input to the simulator, (i.e., data generated to exercise the response of simulation to external signals). Often the data is put into the form of a list of actions in a text file. Stimulus may be asynchronous, synchronous (pin), clocked and register. Stopwatch A counter for measuring execution cycles. Storage Class Determines the lifetime of an object. Storage Qualifier Indicates special properties of an object (e.g., volatile). Symbol
DS51284F-page 229
DS51284F-page 230
Glossary
The memory locations from which an application starts execution when a specific event occurs, such as a reset or interrupt. Warning An alert that is provided to warn you of a situation that would cause physical damage to a device, software file, or equipment. Warning Warnings report conditions that may indicate a problem, but do not halt processing. In MPLAB C30, warning messages report the source file name and line number, but include the text warning: to distinguish them from error messages.
DS51284F-page 231
DS51284F-page 232
A
-A.............................................................................. 51 abort ................................................................. 24, 130 Access Memory...................................................... 197 address Attribute ................................................ 12, 20 Address Spaces ....................................................... 63 alias Attribute ........................................................... 20 aligned Attribute ....................................................... 13 Alignment ..............................................13, 15, 76, 126 -ansi ..............................................................26, 38, 54 ANSI C Standard........................................................ 9 ANSI C, Differences with MPLAB C30 ..................... 11 ANSI C, Strict ........................................................... 39 ANSI Standard Library Support.................................. 9 ANSI-89 extension ................................................... 81 Archiver ...................................................................... 8 Arrays and Pointers................................................ 125 ASCII Character Set............................................... 205 asm ...........................................................13, 113, 197 Assembler .................................................................. 8 Assembly Options .................................................... 54 -Wa ................................................................... 54 Assembly, Inline ............................................. 113, 197 Assembly, Mixing with C ........................................ 111 Atomic Operation ................................................... 106 attribute .......................................................12, 20, 198 Attribute, Function .................................................... 20 address ............................................................. 20 alias................................................................... 20 boot ................................................................... 21 const ................................................................. 22 deprecated ........................................................ 22 far ...................................................................... 22 format ................................................................ 22 format_arg......................................................... 23 interrupt................................................23, 93, 104 near ................................................................... 23 no_instrument_function............................... 23, 57 noload ............................................................... 24
DS51284F-page 233
C
-C.............................................................................. 52 -c ........................................................................ 37, 55 C Dialect Control Options ......................................... 38 -ansi .................................................................. 38 -aux-info ............................................................ 38 -ffreestanding .................................................... 38 -fno-asm ............................................................ 38 -fno-builtin ......................................................... 38 -fno-signed-bitfields........................................... 38 -fno-unsigned-bitfields....................................... 38 -fsigned-bitfields ................................................ 38 -fsigned-char ..................................................... 38 -funsigned-bitfields ............................................ 38 -funsigned-char ................................................. 38 -fwritable-strings........................................ 38, 200 -traditional ......................................................... 26 C Heap Usage.......................................................... 75 C Stack Usage ......................................................... 73 C, Mixing with Assembly ........................................ 111 Calling Conventions ............................................... 199 Case Ranges............................................................ 31 Cast .............................................................. 41, 43, 44 char ............................................. 14, 38, 39, 76, 78, 81 Characters.............................................................. 123 Code and Data Sections .......................................... 65 Code Generation Conventions Options.................... 56 -fargument-alias ................................................ 56 -fargument-noalias ............................................ 56 -fargument-noalias-global ................................. 56 -fcall-saved........................................................ 57 -fcall-used.......................................................... 57 -ffixed ................................................................ 57 -finstrument-functions........................................ 57 -fno-ident ........................................................... 57 -fno-short-double............................................... 58 -fno-verbose-asm .............................................. 58 -fpack-struct ...................................................... 58 -fpcc-struct-return.............................................. 58 -fshort-enums .................................................... 58
B
-B........................................................................ 56, 59 Binary Radix ............................................................. 31 Bit Fields ...................................................38, 126, 201 Bit fields.................................................................. 107 Bit Reversed and Modulo Addressing ...................... 79 boot Attribute ...................................................... 13, 21 Built-In Functions __builtin_add................................................... 134 __builtin_addab............................................... 134 __builtin_btg.................................................... 135 __builtin_clr ..................................................... 135 __builtin_clr_prefect ........................................ 136 __builtin_divmodsd ......................................... 137 __builtin_divmodud ......................................... 137 __builtin_divsd ................................................ 138 __builtin_divud ................................................ 138 __builtin_dmaoffset ......................................... 138 __builtin_ed..................................................... 139 __builtin_edac ................................................. 139 __builtin_fbcl ................................................... 140 __builtin_lac .................................................... 140 __builtin_mac .................................................. 141 __builtin_modsd .............................................. 142 __builtin_modud.............................................. 142 __builtin_movsac ............................................ 143 __builtin_mpy .................................................. 144 __builtin_mpyn ................................................ 145 __builtin_msc .................................................. 146 __builtin_mulss ............................................... 146 __builtin_mulsu ............................................... 147
DS51284F-page 234
Index
-fverbose-asm ................................................... 58 -fvolatile ............................................................ 58 -fvolatile-global.................................................. 58 -fvolatile-static ................................................... 58 Code Size, Reduce .......................................35, 46, 47 Coding ISRs ............................................................ 93 COFF .................................................. 7, 8, 61, 84, 200 Command-Line Compiler ......................................... 33 Command-Line Options ........................................... 34 Command-Line Simulator ...................................7, 8, 9 Comments...........................................................39, 52 Common Subexpression Elimination ...... 22, 48, 49, 50 Common Subexpressions ........................................ 50 Compiler..................................................................... 8 Command-Line ................................................. 33 Driver ............................................. 8, 9, 33, 56, 61 Overview ............................................................. 7 Compiler-Managed Resources .............................. 199 Compiling Multiple Files ........................................... 61 Complex Data Types ....................................................... 28 Floating Types .................................................. 28 Integer Types .................................................... 28 Numbers ........................................................... 28 complex.................................................................... 28 Conditional Expression ............................................ 31 Conditionals with Omitted Operands........................ 31 Configuration Bits Setup .......................................... 87 const Attribute .......................................................... 22 Constants Binary................................................................ 31 Predefined .................................................60, 203 String .............................................................. 197 CORCON ......................................................67, 83, 84 Customer Notification Service.................................... 6 Customer Support ...................................................... 6 Differences Between MPLAB C18 and MPLAB C30 ........................ 195 MPLAB C30 and ANSI C .................................. 11 Directories .....................................................52, 53, 54 Directory Search Options ......................................... 56 -B ................................................................ 56, 59 -specs= ............................................................. 56 -dM ........................................................................... 52 -dN ........................................................................... 52 Documentation Conventions ........................................................ 3 Layout ................................................................. 2 double ............................................. 58, 76, 78, 82, 196 Double-Word Integers .............................................. 29 dsPIC DSC-Specific Options.................................... 35 dsPIC-Specific Options -mconst-in-code ................................................ 35 -mconst-in-data ................................................. 35 -mcpu ................................................................ 35 -merrata ............................................................ 35 -mlarge-code..................................................... 35 -mlarge-data...................................................... 35 -mno-isr-warn.................................................... 36 -mno-pa............................................................. 35 -momf=.............................................................. 36 -mpa.................................................................. 35 -mpa=................................................................ 35 -msmall-code .................................................... 36 -msmall-data ..................................................... 36 -msmall-scalar................................................... 36 -msmart-io......................................................... 36 -mtext= .............................................................. 36 DWARF .................................................................... 36
E
-E....................................................... 37, 52, 53, 54, 55 EEDATA............................................................. 87, 88 EEPROM, data......................................................... 87 ELF....................................................................... 7, 36 Enabling/Disabling Interrupts ................................. 105 endian ...................................................................... 81 Enumerations ......................................................... 126 Environment ........................................................... 122 Environment Variables ............................................. 59 PIC30_C_INCLUDE_PATH .............................. 59 PIC30_COMPILER_PATH................................ 59 PIC30_EXEC_PREFIX ..................................... 59 PIC30_LIBRARY_ PATH .................................. 59 PIC30_OMF ...................................................... 59 TMPDIR ............................................................ 59 errno....................................................................... 130 Error Control Options -pedantic-errors................................................. 39 -Werror.............................................................. 44 -Werror-implicit-function-declaration ................. 39 Errors ..................................................................... 155 Escape Sequences ................................................ 123 Exception Vectors .............................................. 64, 94 Executables.............................................................. 61 exit.......................................................................... 130 Extensions................................................................ 53
D
-D ........................................................................52, 54 Data Formats ......................................................... 196 Data Memory Allocation ........................................... 87 Data Memory Space ............................... 35, 36, 64, 75 Data Memory Space, Near....................................... 14 Data Representation ................................................ 81 Data Type ...........................................................14, 81 Complex............................................................ 28 Floating Point .................................................... 82 Integer............................................................... 81 Pointers............................................................. 82 -dD ........................................................................... 52 Debugging Information............................................. 46 Debugging Options .................................................. 46 -g....................................................................... 46 -Q ...................................................................... 46 -save-temps ...................................................... 46 Declarators............................................................. 126 Defining Global Register Variables .......................... 27 deprecated Attribute......................................13, 22, 44 Development Tools .................................................... 7 Device Support Files ................................................ 83 Diagnostics ............................................................ 155
DS51284F-page 235
F
-falign-functions ........................................................ 47 -falign-labels ............................................................. 47 -falign-loops.............................................................. 47 far Attribute........................ 14, 22, 65, 66, 70, 114, 197 Far Data Space ........................................................ 70 -fargument-alias ....................................................... 56 -fargument-noalias ................................................... 56 -fargument-noalias-global......................................... 56 -fcaller-saves ............................................................ 47 -fcall-saved ............................................................... 57 -fcall-used................................................................. 57 -fcse-follow-jumps .................................................... 48 -fcse-skip-blocks....................................................... 48 -fdata-sections.......................................................... 48 -fdefer-pop. See -fno-defer Feature Set ................................................................ 9 -fexpensive-optimizations......................................... 48 -ffixed ................................................................. 28, 57 -fforce-mem ........................................................ 47, 50 -ffreestanding ........................................................... 38 -ffunction-sections .................................................... 48 -fgcse ....................................................................... 48 -fgcse-lm .................................................................. 48 -fgcse-sm ................................................................. 48 File Extensions ......................................................... 34 File Naming Convention ........................................... 34 Files........................................................................ 129 -finline-functions ......................................26, 44, 47, 50 -finline-limit ............................................................... 50 -finstrument-functions......................................... 23, 57 -fkeep-inline-functions ........................................ 26, 51 -fkeep-static-consts .................................................. 51 Flags, Positive and Negative.............................. 50, 56 float ................................................... 14, 58, 76, 78, 82 Floating .................................................................... 82 Floating Point ................................................... 82, 124 Floating Types, Complex.......................................... 28 -fmove-all-movables ................................................. 48 -fno ..................................................................... 50, 56 -fno-asm ................................................................... 38 -fno-builtin ................................................................ 38 -fno-defer-pop .......................................................... 48 -fno-function-cse ...................................................... 51 -fno-ident .................................................................. 57 -fno-inline ................................................................. 51 -fno-keep-static-consts ............................................. 51 -fno-peephole ........................................................... 48 -fno-peephole2 ......................................................... 48 -fno-short-double ...................................................... 58 -fno-show-column..................................................... 52 -fno-signed-bitfields .................................................. 38 -fno-unsigned-bitfields .............................................. 38 -fno-verbose-asm ..................................................... 58 -fomit-frame-pointer.......................................46, 47, 51 -foptimize-register-move........................................... 48 -foptimize-sibling-calls .............................................. 51 format Attribute......................................................... 22
G
-g .............................................................................. 46 general registers..................................................... 114 getenv..................................................................... 131 Global Register Variables......................................... 27 Guidelines for Writing ISRs ..................................... 92
H
-H.............................................................................. 52 Header Files ...................................... 34, 52, 53, 54, 59 Processor .................................................... 83, 85 Heap......................................................................... 64 --heap ....................................................................... 75 Heap, C Usage......................................................... 75 --help ........................................................................ 37 Hex File .................................................................... 61 High-Priority Interrupts ..................................... 91, 106
DS51284F-page 236
Index
I
-I ....................................................................52, 54, 59 -I-.........................................................................52, 54 Identifiers ............................................................... 123 -idirafter .................................................................... 52 IEEE 754................................................................ 196 -imacros ..............................................................52, 54 imag ......................................................................... 29 Implementation-Defined Behavior...................121, 200 Include ................................................................60, 61 -include ...............................................................53, 54 Include Files ............................................................. 56 Inhibit Warnings ....................................................... 39 Initialized Variables .................................................. 65 Inline ............................................. 44, 47, 50, 113, 197 inline..............................................................26, 51, 57 Inline Assembly Usage ............................................ 87 Inline Functions ........................................................ 26 int ............................................................ 14, 76, 78, 81 Integer ...............................................................81, 114 Behavior.......................................................... 124 Double-Word..................................................... 29 Promotions...................................................... 197 Types, Complex ................................................ 28 Internet Address, Microchip ....................................... 5 Interrupt Enabling/Disabling .......................................... 105 Functions ........................................................ 111 Handling.......................................................... 111 High Priority ...............................................91, 106 Latency ........................................................... 104 Low Priority ................................................91, 106 Nesting............................................................ 104 Priority............................................................. 104 Protection From .............................................. 108 Request ............................................................ 94 Service Routine Context Saving ..................... 104 Vectors.............................................................. 94 Vectors, Writing ................................................ 94 interrupt Attribute .......................... 23, 25, 93, 104, 198 -iprefix ...................................................................... 53 IRQ........................................................................... 94 ISR Coding .............................................................. 93 Declaration........................................................ 88 Guidelines for Writing ....................................... 92 Syntax for Writing ............................................. 92 Writing............................................................... 92 -isystem...............................................................53, 56 -iwithprefix ................................................................ 53 -iwithprefixbefore...................................................... 53 Latency................................................................... 104 Librarian ..................................................................... 8 Library ................................................................ 55, 61 ANSI Standard .................................................... 9 Functions ........................................................ 128 Linker ................................................................... 8, 55 Linker Script ............................................ 61, 72, 84, 85 Linking Options ........................................................ 54 -L................................................................. 55, 56 -l ........................................................................ 55 -nodefaultlibs..................................................... 55 -nostdlib ............................................................ 55 -s ....................................................................... 55 -u....................................................................... 55 -Wl..................................................................... 55 -Xlinker.............................................................. 55 little endian ............................................................... 81 LL, Suffix .................................................................. 29 Local Register Variables .................................... 27, 28 Locating Code and Data .......................................... 71 long ......................................................... 14, 76, 78, 81 long double........................................ 14, 58, 76, 78, 82 long long.......................................... 14, 44, 78, 81, 196 long long int.............................................................. 29 Loop Optimization .................................................... 22 Loop Optimizer......................................................... 49 Loop Unrolling .......................................................... 50 Low-Priority Interrupts ...................................... 91, 106
M
-M ............................................................................. 53 Mabonga .......................................................... 71, 198 macro ............................................................27, 52, 54 Macro Names, Predefined ..................................... 197 Macros ..................................................................... 87 Configuration Bits Setup ................................... 87 Inline Assembly Usage ..................................... 87 ISR Declaration................................................. 88 MacrosData Memory Allocation ............................... 87 MATH_DATA ......................................................... 199 -mconst-in-code ................................ 35, 65, 66, 67, 69 -mconst-in-data .................................................. 35, 69 -mcpu ....................................................................... 35 -MD .......................................................................... 53 Memory .................................................................. 130 Memory Models.............................................9, 69, 199 -mconst-in-code ................................................ 69 -mconst-in-data ................................................. 69 -mlarge-code..................................................... 69 -mlarge-data...................................................... 69 -msmall-code .................................................... 69 -msmall-data ..................................................... 69 -msmall-scalar................................................... 69 Memory Spaces ....................................................... 68 Memory, Access..................................................... 197 -merrata.................................................................... 35 -MF........................................................................... 53 -MG .......................................................................... 53 Mixing Assembly Language and C Variables and Functions .................................................................... 111 -mlarge-code ...................................................... 35, 69
K
Keyword Differences ................................................ 11
L
-L.........................................................................55, 56 -l ............................................................................... 55 Labels as Values...................................................... 30 Large Code Model ..............................................35, 82 Large Data Model .........................................35, 65, 66
DS51284F-page 237
N
Near and Far Code .................................................. 70 Near and Far Data ................................................... 69 near Attribute..................... 14, 23, 65, 66, 70, 114, 197 Near Data Section .................................................... 69 Near Data Space.................................................... 115 Nesting Interrupts ................................................... 104 no_instrument_function Attribute........................ 23, 57 -nodefaultlibs ............................................................ 55 noload Attribute .................................................. 14, 24 noreturn Attribute ............................................... 24, 44 -nostdinc............................................................. 52, 54 -nostdlib.................................................................... 55
O
-O ............................................................................. 46 -o ........................................................................ 37, 61 -O0 ........................................................................... 46 -O1 ........................................................................... 46 -O2 ..................................................................... 47, 50 -O3 ........................................................................... 47 Object File ................................. 7, 8, 48, 53, 55, 61, 65 Object Module Format............................................ 200 Omitted Operands .................................................... 31 Optimization ....................................................... 9, 200 Optimization Control Options ................................... 46 -falign-functions................................................. 47 -falign-labels...................................................... 47 -falign-loops ...................................................... 47 -fcaller-saves..................................................... 47 -fcse-follow-jumps ............................................. 48 -fcse-skip-blocks ............................................... 48 -fdata-sections .................................................. 48 -fexpensive-optimizations.................................. 48 -fforce-mem....................................................... 50 -ffunction-sections ............................................. 48 -fgcse ................................................................ 48 -fgcse-lm ........................................................... 48
DS51284F-page 238
Index
P
-P ............................................................................. 54 packed Attribute ..................................................15, 58 Parameters, Function............................................... 76 PATH ....................................................................... 61 PC .......................................................................... 199 -pedantic .............................................................39, 44 -pedantic-errors........................................................ 39 Peephole Optimization ............................................. 48 persistent Attribute ................................................... 15 persistent data ............................................67, 87, 199 PIC30_C_INCLUDE_PATH ..........................59, 60, 61 PIC30_COMPILER_PATH....................................... 59 PIC30_EXEC_PREFIX .......................................56, 59 PIC30_LIBRARY_ PATH ......................................... 59 PIC30_OMF ............................................................. 59 pic30-gcc.................................................................. 33 pointer .................................................................76, 78 Pointers .......................................................44, 82, 196 Frame ..........................................................51, 57 Function ............................................................ 69 Stack ................................................................. 57 Pragmas................................................................. 198 Predefined Constants .......................................60, 203 Predefined Macro Names ...................................... 197 prefix ...................................................................53, 56 Preprocessing Directives ....................................... 127 Preprocessor............................................................ 56 Preprocessor Control Options.................................. 51 -A ...................................................................... 51 -C ...................................................................... 52 -D ...................................................................... 52 -dD .................................................................... 52 -dM.................................................................... 52 -dN .................................................................... 52 -fno-show-column ............................................. 52 -H ...................................................................... 52 -I........................................................................ 52 -I- ...................................................................... 52 -idirafter............................................................. 52 -imacros ............................................................ 52 -include ............................................................. 53 -iprefix ............................................................... 53 -isystem ............................................................ 53 -iwithprefix......................................................... 53 -iwithprefixbefore .............................................. 53 -M...................................................................... 53 -MD ................................................................... 53 -MF ................................................................... 53 -MG ................................................................... 53 -MM................................................................... 53 -MMD ................................................................ 53 -MQ ................................................................... 54 -MT ................................................................... 54 -nostdinc ........................................................... 54 -P ...................................................................... 54 -trigraphs........................................................... 54 -U ...................................................................... 54 -undef................................................................ 54 Preserving Registers Across Function Calls ............ 78 Procedural Abstraction..................................... 35, 200 Processor Header Files...................................... 83, 85 Processor ID ............................................................ 35 PROD..................................................................... 199 Program Memory Pointers ....................................... 69 Program Memory Space .......................................... 64 Program Space Visibility Window. See PSV Window PSV Usage......................................................... 79, 88 PSV Window ............................... 64, 65, 69, 79, 83, 88
Q
-Q ............................................................................. 46 Qualifiers ................................................................ 126
R
RAW Dependency.................................................... 49 RCOUNT................................................................ 199 Reading, Recommended ........................................... 4 real ........................................................................... 29 Reduce Code Size ........................................35, 46, 47 Register Behavior.......................................................... 125 Conventions ...................................................... 78 Definition Files .................................................. 84 register ............................................................... 27, 28 Reset.........................................................94, 104, 105 Reset Vectors........................................................... 64 Return Type ............................................................. 40 Return Value ............................................................ 77 reverse Attribute....................................................... 15 Runtime Environment............................................... 63
S
-S........................................................................ 37, 55 -s .............................................................................. 55 -save-temps ............................................................. 46 Scalars ..................................................................... 69 Scheduling ............................................................... 49 section.........................................................48, 65, 199 section Attribute .............................. 16, 24, 65, 71, 198 Sections, Code and Data ......................................... 65 secure Attribute .................................................. 16, 24 SFR ............................................... 9, 61, 64, 83, 84, 85 sfr Attribute............................................................... 17 shadow Attribute .........................................25, 93, 198 short ..............................................................76, 78, 81 short long ............................................................... 196 Signals ................................................................... 129 signed char............................................................... 81 signed int.................................................................. 81 signed long............................................................... 81 signed long long ....................................................... 81 signed short.............................................................. 81 Simulator, Command-Line ..................................7, 8, 9 Small Code Model...........................................9, 36, 82 Small Data Model...................................... 9, 36, 65, 66 Software Stack ..............................................25, 72, 73 space Attribute ..........................................17, 197, 198 Special Function Registers .........................61, 83, 104 Specifying Registers for Local Variables.................. 28 -specs=..................................................................... 56
DS51284F-page 239
V
-v .............................................................................. 37 Variable Attributes .................................................... 12 Variables in Specified Registers............................... 27 Vectors, Reset and Exception .................................. 64 void........................................................................... 78 volatile ...................................................................... 58
W
-W.............................................. 39, 41, 42, 43, 45, 155 -w.............................................................................. 39 W Registers...................................................... 76, 111 W14 .................................................................. 73, 199 W15 .................................................................. 73, 199 -Wa........................................................................... 54 -Waggregate-return .................................................. 43 -Wall .................................................. 39, 41, 42, 43, 45 Warnings ................................................................ 174 Warnings and Errors Control Options ...................... 39 -fsyntax-only...................................................... 39 -pedantic ........................................................... 39 -pedantic-errors................................................. 39 -W...................................................................... 43 -w ...................................................................... 39 -Waggregate-return........................................... 43 -Wall .................................................................. 39 -Wbad-function-cast .......................................... 43 -Wcast-align ...................................................... 43 -Wcast-qual ....................................................... 43 -Wchar-subscripts ............................................. 39 -Wcomment....................................................... 39 -Wconversion .................................................... 44 -Wdiv-by-zero.................................................... 39 -Werror .............................................................. 44 -Werror-implicit-function-declaration ................. 39 -Wformat ........................................................... 39 -Wimplicit........................................................... 39 -Wimplicit-function-declaration .......................... 39 -Wimplicit-int...................................................... 39 -Winline ............................................................. 44 -Wlarger-than- ................................................... 44 -Wlong-long....................................................... 44 -Wmain.............................................................. 39 -Wmissing-braces ............................................. 39 -Wmissing-declarations..................................... 44
T
-T .............................................................................. 84 TABLAT.................................................................. 199 TBLPTR ................................................................. 199 TBLRD ..................................................................... 89 TMPDIR ................................................................... 59 tmpfile..................................................................... 130 -traditional .......................................................... 26, 38 Traditional C ............................................................. 45 Translation ............................................................. 122 transparent_union Attribute ...................................... 18 Trigraphs ............................................................ 41, 54 -trigraphs .................................................................. 54 Type Conversion ...................................................... 44 typeof ....................................................................... 29
U
-U ....................................................................... 52, 54 -u .............................................................................. 55 ULL, Suffix................................................................ 29 -undef ....................................................................... 54 Underscore....................................................... 92, 111 Uninitialized Variables .............................................. 66 Unions .................................................................... 126 unordered Attribute .................................................. 18
DS51284F-page 240
Index
-Wmissing-format-attribute................................ 44 -Wmissing-noreturn .......................................... 44 -Wmissing-prototypes ....................................... 44 -Wmultichar....................................................... 40 -Wnested-externs ............................................. 44 -Wno-long-long ................................................. 44 -Wno-multichar ................................................. 40 -Wno-sign-compare .......................................... 45 -Wpadded ......................................................... 44 -Wparentheses ................................................. 40 -Wpointer-arith .................................................. 44 -Wredundant-decls ........................................... 44 -Wreturn-type .................................................... 40 -Wsequence-point............................................. 40 -Wshadow ......................................................... 44 -Wsign-compare ............................................... 45 -Wstrict-prototypes............................................ 45 -Wswitch ........................................................... 41 -Wsystem-headers............................................ 41 -Wtraditional...................................................... 45 -Wtrigraphs ....................................................... 41 -Wundef ............................................................ 45 -Wuninitialized .................................................. 41 -Wunknown-pragmas........................................ 41 -Wunreachable-code ........................................ 45 -Wunused ......................................................... 41 -Wunused-function............................................ 41 -Wunused-label................................................. 41 -Wunused-parameter ........................................ 42 -Wunused-value................................................ 42 -Wunused-variable............................................ 42 -Wwrite-strings .................................................. 45 Warnings, Inhibit ...................................................... 39 -Wbad-function-cast ................................................. 43 -Wcast-align ............................................................. 43 -Wcast-qual .............................................................. 43 -Wchar-subscripts .................................................... 39 -Wcomment.............................................................. 39 -Wconversion ........................................................... 44 -Wdiv-by-zero........................................................... 39 weak Attribute .....................................................18, 26 Web Site, Microchip ................................................... 5 -Werror ..................................................................... 44 -Werror-implicit-function-declaration ........................ 39 -Wformat .......................................................23, 39, 44 -Wimplicit ................................................................. 39 -Wimplicit-function-declaration ................................. 39 -Wimplicit-int............................................................. 39 -Winline ...............................................................26, 44 -Wl............................................................................ 55 -Wlarger-than- .......................................................... 44 -Wlong-long.............................................................. 44 -Wmain..................................................................... 39 -Wmissing-braces .................................................... 39 -Wmissing-declarations............................................ 44 -Wmissing-format-attribute....................................... 44 -Wmissing-noreturn.................................................. 44 -Wmissing-prototypes .............................................. 44 -Wmultichar .............................................................. 40 -Wnested-externs..................................................... 44 -Wno- ....................................................................... 39 -Wno-deprecated-declarations................................. 44 -Wno-div-by-zero...................................................... 39 -Wno-long-long......................................................... 44 -Wno-multichar......................................................... 40 -Wno-sign-compare............................................ 43, 45 -Wpadded................................................................. 44 -Wparentheses......................................................... 40 -Wpointer-arith ......................................................... 44 -Wredundant-decls................................................... 44 WREG .................................................................... 199 -Wreturn-type ........................................................... 40 Writing an Interrupt Service Routine ........................ 92 Writing the Interrupt Vector ...................................... 94 -Wsequence-point .................................................... 40 -Wshadow ................................................................ 44 -Wsign-compare....................................................... 45 -Wstrict-prototypes ................................................... 45 -Wswitch................................................................... 41 -Wsystem-headers ................................................... 41 -Wtraditional ............................................................. 45 -Wtrigraphs............................................................... 41 -Wundef.................................................................... 45 -Wuninitialized.......................................................... 41 -Wunknown-pragmas ............................................... 41 -Wunreachable-code................................................ 45 -Wunused........................................................... 41, 43 -Wunused-function ................................................... 41 -Wunused-label ........................................................ 41 -Wunused-parameter ............................................... 42 -Wunused-value ....................................................... 42 -Wunused-variable ................................................... 42 -Wwrite-strings ......................................................... 45
X
-x .............................................................................. 37 -Xlinker ..................................................................... 55
DS51284F-page 241
ASIA/PACIFIC
Asia Pacific Office Suites 3707-14, 37th Floor Tower 6, The Gateway Habour City, Kowloon Hong Kong Tel: 852-2401-1200 Fax: 852-2401-3431 Australia - Sydney Tel: 61-2-9868-6733 Fax: 61-2-9868-6755 China - Beijing Tel: 86-10-8528-2100 Fax: 86-10-8528-2104 China - Chengdu Tel: 86-28-8665-5511 Fax: 86-28-8665-7889 China - Fuzhou Tel: 86-591-8750-3506 Fax: 86-591-8750-3521 China - Hong Kong SAR Tel: 852-2401-1200 Fax: 852-2401-3431 China - Qingdao Tel: 86-532-8502-7355 Fax: 86-532-8502-7205 China - Shanghai Tel: 86-21-5407-5533 Fax: 86-21-5407-5066 China - Shenyang Tel: 86-24-2334-2829 Fax: 86-24-2334-2393 China - Shenzhen Tel: 86-755-8203-2660 Fax: 86-755-8203-1760 China - Shunde Tel: 86-757-2839-5507 Fax: 86-757-2839-5571 China - Wuhan Tel: 86-27-5980-5300 Fax: 86-27-5980-5118 China - Xian Tel: 86-29-8833-7250 Fax: 86-29-8833-7256
ASIA/PACIFIC
India - Bangalore Tel: 91-80-4182-8400 Fax: 91-80-4182-8422 India - New Delhi Tel: 91-11-4160-8631 Fax: 91-11-4160-8632 India - Pune Tel: 91-20-2566-1512 Fax: 91-20-2566-1513 Japan - Yokohama Tel: 81-45-471- 6166 Fax: 81-45-471-6122 Korea - Gumi Tel: 82-54-473-4301 Fax: 82-54-473-4302 Korea - Seoul Tel: 82-2-554-7200 Fax: 82-2-558-5932 or 82-2-558-5934 Malaysia - Penang Tel: 60-4-646-8870 Fax: 60-4-646-5086 Philippines - Manila Tel: 63-2-634-9065 Fax: 63-2-634-9069 Singapore Tel: 65-6334-8870 Fax: 65-6334-8850 Taiwan - Hsin Chu Tel: 886-3-572-9526 Fax: 886-3-572-6459 Taiwan - Kaohsiung Tel: 886-7-536-4818 Fax: 886-7-536-4803 Taiwan - Taipei Tel: 886-2-2500-6610 Fax: 886-2-2508-0102 Thailand - Bangkok Tel: 66-2-694-1351 Fax: 66-2-694-1350
EUROPE
Austria - Wels Tel: 43-7242-2244-39 Fax: 43-7242-2244-393 Denmark - Copenhagen Tel: 45-4450-2828 Fax: 45-4485-2829 France - Paris Tel: 33-1-69-53-63-20 Fax: 33-1-69-30-90-79 Germany - Munich Tel: 49-89-627-144-0 Fax: 49-89-627-144-44 Italy - Milan Tel: 39-0331-742611 Fax: 39-0331-466781 Netherlands - Drunen Tel: 31-416-690399 Fax: 31-416-690340 Spain - Madrid Tel: 34-91-708-08-90 Fax: 34-91-708-08-91 UK - Wokingham Tel: 44-118-921-5869 Fax: 44-118-921-5820
12/08/06
DS51284F-page 242