ARM Developer Suite ® Version 1.2 Compilers and Libraries Guide Copyright © 1999-2001 ARM Limited. All rights reserved.
ARM Developer Suite Compilers and Libraries Guide Copyright © 1999-2001 ARM Limited. All rights reserved. Release Information The following changes have been made to this book. Change History Date Issue Change October 1999 A Release 1.0 March 2000 B Release 1.0.1 November 2000 C Release 1.1 November 2001 D Release 1.2 Proprietary Notice Words and logos marked with ® or ™ are registered trademarks or trademarks owned by ARM Limited.
Contents ARM Developer Suite Compilers and Libraries Guide Preface About this book ............................................................................................ viii Feedback ...................................................................................................... xii Chapter 1 Introduction 1.1 1.2 1.3 1.4 Chapter 2 About the C and C++ compilers .................................................................. 2-2 File usage .................................................
Contents Chapter 4 The C and C++ Libraries 4.1 4.2 4.3 4.4 4.5 4.6 4.7 4.8 4.9 4.10 4.11 4.12 4.13 4.14 4.15 Chapter 5 Floating-point Support 5.1 5.2 5.3 5.4 5.5 Appendix A EC++ support ............................................................................................. Integral conversion ..................................................................................... Calling a pure virtual function .....................................................................
Contents Glossary ARM DUI 0067D Copyright © 1999-2001 ARM Limited. All rights reserved.
Contents vi Copyright © 1999-2001 ARM Limited. All rights reserved.
Preface This preface introduces the ARM Developer Suite (ADS) tools and reference documentation. It contains the following sections: • About this book on page viii • Feedback on page xii. ARM DUI 0067D Copyright © 1999-2001 ARM Limited. All rights reserved.
Preface About this book This book provides reference information for ADS. It describes the command-line options to the compilers. The book also gives reference material on the ARM implementation of the C and C++ compilers and the C libraries. Intended audience This book is written for all developers who are producing applications using ADS. It assumes that you are an experienced software developer and that you are familiar with the ARM development tools as described in ADS Getting Started.
Preface Appendix C Standard C++ Implementation Definition Read this appendix for information on the ARM C++ implementation. Appendix D C and C++ Compiler Implementation Limits Read this appendix for implementation limits of the ARM C and C++ compilers. Typographical conventions The following typographical conventions are used in this book: monospace Denotes text that can be entered at the keyboard, such as commands, file and program names, and source code.
Preface ARM publications This book contains reference information that is specific to development tools supplied with ADS.
Preface The following book describes the C++ language: • ISO/IEC 14882:1998(E), C++ Standard. Available from the national standards body. The following books provide general C++ programming information: • Ellis, M.A. and Stroustrup, B., The Annotated C++ Reference Manual (1990). Addison-Wesley Publishing Company, Reading, Massachusetts. ISBN 0-201-51459-1. This is a reference guide to C++. • Stroustrup, B., The Design and Evolution of C++ (1994).
Preface Feedback ARM Limited welcomes feedback on both ADS and the documentation. Feedback on the ARM Developer Suite If you have any problems with ADS, please contact your supplier.
Chapter 1 Introduction This chapter introduces the ARM compilers, libraries, linker, and utility programs provided with ADS. It contains the following sections: • About the compilers and libraries on page 1-2 • The ARM compilers and libraries on page 1-3 • Linking compiled objects on page 1-5 • Related utilities on page 1-6. ARM DUI 0067D Copyright © 1999-2001 ARM Limited. All rights reserved.
Introduction 1.1 About the compilers and libraries ADS consists of a suite of applications, together with supporting documentation and examples, that enable you to write and debug applications for the ARM family of RISC processors. You can use ADS to develop, build, and debug C, C++, and ARM assembly language programs. The ADS toolkit consists of the following major components: • command-line development tools • GUI development tools • utilities • supporting software.
Introduction 1.2 The ARM compilers and libraries This section gives an overview of the ARM C and C++ compilers, and the C and C++ libraries. 1.2.1 The C and C++ compilers ADS provides the following compilers: armcc The ARM C compiler. The compiler is tested against the Plum Hall C Validation Suite for ANSI conformance. It compiles ANSI C source into 32-bit ARM code. armcpp This is the ARM C++ compiler. It compiles ANSI C++ or EC++ source into 32-bit ARM code. tcc The Thumb C compiler.
Introduction 1.2.2 The C and C++ libraries ADS provides the following runtime C and C++ libraries: The ARM C libraries The ARM C libraries provide standard C functions, and helper functions used by the C and C++ libraries. The C libraries also provide target-dependent functions that are used to implement the standard C library functions in a semihosted environment. The C libraries are structured so that you can redefine target-dependent functions in your own code to remove semihosting dependencies.
Introduction 1.3 Linking compiled objects The ARM and Thumb linker combines the contents of one or more object files with selected parts of one or more object libraries to produce an ELF executable image, or a partially linked ELF object. The linker can link ARM code and Thumb code, and automatically generates interworking veneers to switch processor state when required. The linker also automatically generates long branch veneers, where required, to extend the range of branch instructions.
Introduction 1.4 Related utilities This section gives an overview of the utility tools that are provided to support the main development tools, including: • fromELF • armar • armprof. See the ADS Linker and Utilities Guide for detailed information on the utilities. 1.4.1 fromELF fromELF is the ARM image conversion utility.
Chapter 2 C and C++ Compilers This chapter describes the command-line options to the ARM and Thumb, C and C++ compilers. This chapter assumes you are familiar with command-line software development tools such as those provided with ADS. It contains the following sections: • About the C and C++ compilers on page 2-2 • File usage on page 2-4 • Command syntax on page 2-9. ARM DUI 0067D Copyright © 1999-2001 ARM Limited. All rights reserved.
C and C++ Compilers 2.1 About the C and C++ compilers Wherever possible, the compilers adopt widely used command-line options familiar both to users of UNIX and to users of Windows/MS-DOS. The ARM C and C++ compilers compile ANSI C. The ARM C++ compilers expect C++ that conforms to the ISO/IEC 14822 :1998 International Standard for C++. See Appendix C Standard C++ Implementation Definition for a detailed description of ARM C++ language support.
C and C++ Compilers 2.1.2 Source language modes The ARM compilers have three distinct source language modes that you can use to compile several varieties of C and C++ source code: ANSI C In ANSI C mode, the ARM compilers pass release 7.00 of the Plum Hall C Validation Suite (CVS). This suite has been adopted by the British Standards Institute for C compiler validation in Europe. The compiler option -strict is used when running the tests. EC++ This mode applies only to the ARM C++ compilers.
C and C++ Compilers 2.2 File usage This section describes naming conventions and included files. 2.2.1 Naming conventions The ARM compilers use suffix naming (filename-extension) conventions to identify the classes of file involved in compilation and in the linking process. The names used on the command line, and as arguments to preprocessor #include directives, map directly to host file names under UNIX and Windows/MS-DOS.
C and C++ Compilers Filenames are parsed as follows: • a name starting with host-volume-name:/ is a pseudo UNIX filename • a name that does not start with host-volume-name:/ and contains / is a UNIX filename • a name that does not contain a / is a host filename. Filename validity The compilers do not check that filenames are acceptable to the host file system. If a filename is not acceptable, the compiler reports that the file cannot be opened, but the compiler gives no more diagnosis.
C and C++ Compilers 2.2.2 Included files Several factors affect the way the ARM compilers search for #include header files and source files. These include: • the -I and -j compiler options • the -fk and -fd compiler options • the value of the environment variable ARMINC • whether the filename is an absolute filename or a relative filename • whether the filename is between angle brackets or double quotes.
C and C++ Compilers The original current place install_directory\include is restored only when the compiler has finished processing defs.h. You can disable the stacking of current places by using the compiler option -fk. This option makes the compiler use the search rule originally described by Kernighan and Ritchie in The C Programming Language. Under this rule each nonrooted user #include is sought relative to the directory containing the source file that is being compiled.
C and C++ Compilers The search path Table 2-2 shows how the various command-line options affect the search path used by the compiler when it searches for included header and source files. The following conventions are used in the table: :mem The in-memory file system where the ARM compilers store ANSI C and some C++ header files. See The in-memory file system on page 2-6 for more information. ARMINC The list of directories specified by the ARMINC environment variable, if it is set.
C and C++ Compilers 2.3 Command syntax This section describes the command syntax for the ARM C and C++ compilers. You can control many aspects of compiler operation with command-line options. All options are prefixed by a minus – sign, and some options are followed by an argument. In most cases the ARM C and C++ compilers permit space between the option letter and the argument. 2.3.
C and C++ Compilers debug-options This specifies whether or not debug tables are generated, and their format. See Generating debug information on page 2-22 for details. code-generation-options This specifies options such as optimization, byte order, and alignment of data produced by the compiler. See Controlling code generation on page 2-24 for details. warning-options This specifies whether specific warning messages are generated. See Controlling warning messages on page 2-31 details.
C and C++ Compilers Specifying keyboard input Use minus – as the source filename to instruct the compiler to take input from the keyboard. Input is terminated by entering Ctrl-D on UNIX environments or Ctrl-Z on MS Windows environments. An assembly listing for the keyboard input is sent to the output stream after input has been terminated if both of the following are true: • no output file is specified • no preprocessor-only option is specified, for example -E.
C and C++ Compilers 2.3.2 Procedure Call Standard options This section applies to the ARM/Thumb Procedure Call Standard (ATPCS) as used by the ARM compilers. See the ADS Developer Guide for more information on the ARM and Thumb procedure call standards. See Controlling code generation on page 2-24 for other build options.
C and C++ Compilers Position independence qualifiers /noropi This option generates code that is not (read-only) position-independent. This is the default. /nopic is an alias for this option. /ropi This option generates (read-only) position-independent code. /pic is an alias for this option. If this option is selected the compiler: • addresses read-only code and data pc-relative • sets the Position Independent (PI) attribute on read-only output sections.
C and C++ Compilers Stack checking qualifiers 2.3.3 /noswstackcheck This option uses the non software-stack-checking ATPCS variant. This is the default. /swstackcheck This option uses the software-stack-checking ATPCS variant. Setting the source language This section describes options that determine the source language variant accepted by the compiler (see also Controlling code generation on page 2-24).
C and C++ Compilers Compiles normal ANSI standard C (C mode of C++). armcpp -ansi armcpp -ansi -strict Compiles strict ANSI standard C (C mode of C++). armcpp -strict 2.3.4 Compiles strict C++. Specifying search paths The following options specify the directories that are searched for included files. The precise search path varies according to the combination of options selected and whether the include file is enclosed in angle brackets or double quotes.
C and C++ Compilers You can also use the -o option to specify a filefor the preprocessed output. By default, comments are stripped from the output. The preprocessor accepts source files with any extension (for example, .o, .s, and .txt). See also the -C option. This option retains comments in preprocessor output when used in conjunction with -E. This option differs from the -c (lowercase) option that suppresses the link step. See Specifying output format on page 2-17 for a description of the -c option.
C and C++ Compilers 2.3.6 Specifying output format By default, source files are compiled and linked into an executable image. Use the following options to direct the compiler to create unlinked object files, assembly language files, or listing files from C or C++ source files. -asm This option writes a listing of the assembly language generated by the compiler to a file. Object code is generated and, unless the -c option is also used, the link step is performed.
C and C++ Compilers -fi This option is used with -list to list the lines from any files included with directives of the form #include "file". -fj This option is used with -list to list the lines from any files included with directives of the form #include . -fu This option is used with -list to list source that was not preprocessed. By default, if you specify -list, the compiler lists the source text as seen by the compiler after preprocessing.
C and C++ Compilers the current directory, where file.c is the name of the source file stripped of any leading directory names. The default file name can be overridden with the -o option. Note You can use armasm to assemble the output file and produce object code. The compilers add ASSERT directives for command-line options such as ATPCS variants and byte order to ensure that compatible compiler and assembler options are used when reassembling the output.
C and C++ Compilers • Use only a single processor or architecture name with -cpu. You cannot specify both a processor and an architecture. • If -cpu is not specified, the default is -cpu ARM7TDMI. • Specifying a Thumb-aware processor, such as -cpu ARM7TDMI to armcc or armcpp does not make these compilers generate Thumb code. It only allows features of the processor to be used, such as interworking instructions. Use tcc or tcpp to generate Thumb code.
C and C++ Compilers Valid options are: none Selects no floating-point option. No floating-point code is to be used. vfp Selects hardware vector floating-point unit conforming to architecture VFPv1. This is a synonym for -fpu vfpv1. This option is not available for the Thumb compilers. vfpv1 Selects hardware vector floating-point unit conforming to architecture VFPv1, such as the VFP10 rev 0. This option is not available for the Thumb compilers.
C and C++ Compilers 2.3.8 softvfp Selects software floating-point library (FPLib) with pure-endian doubles. This is the default if you do not specify a -fpu option. softfpa Selects software floating-point library with mixed-endian doubles. Generating debug information This section describes options that enable you to specify whether debug tables are generated for the current compilation and, if they are, specify their format.
C and C++ Compilers Debug table format options The following option specifies the format of the debug tables generated by the compilers: -dwarf2 ARM DUI 0067D This option specifies DWARF2 debug table format. This is the default, and is the only available debug table format. Copyright © 1999-2001 ARM Limited. All rights reserved.
C and C++ Compilers 2.3.9 Controlling code generation Use the options described in this section to control aspects of the code generated by the compiler such as optimization. See Pragmas on page 3-2 for information on additional code generation options that are controlled using pragmas.
C and C++ Compilers while (expression) body; as: if (expression) { do body; while (expression); } If you specify neither -Otime or -Ospace, the compiler uses -Ospace. You can compile time-critical parts of your code with -Otime, and the rest with -Ospace. You must not specify both -Otime and -Ospace in the same compiler invocation. -Ono_inline This option disables inlining of functions. Calls to inline functions are not expanded inline. You can use this option to help debug inline functions.
C and C++ Compilers -Oautoinline This option enables automatic inlining. It is off by default for optimization levels -O0 and -O1, and on by default for optimization level -O2. The compiler automatically inlines functions where it is sensible to do so. The -Ospace and -Otime options influence how the compiler automatically inlines functions. -Ono_ldrd This option disables optimizations specific to ARM Architecture v5TE processors. This is the default.
C and C++ Compilers Note Using this option increases code size and decreases performance slightly. This option does not split ARM inline assembly LDM or STM instructions, or VFP FLDM or FSTM instructions, but does split Thumb LDM and STM inline assembly instructions where possible. Using inline Thumb assembly routines, however, is deprecated and generates a warning message. This option has no significant benefit for cached systems, or for processors with a write buffer.
C and C++ Compilers Note This behavior is not in accordance with the ANSI C standard. If the other operand in the expression has type double, a constant of unspecified type is converted to double. A cast of a constant of unspecified type to type T produces a constant of type T (Example 2-1). Example 2-1 Double and float float f1(float x) { return x + 1.0; } // Uses float add and is treated the same // as f2() below, a warning is issued. float f2(float x) { return x + 1.
C and C++ Compilers to place a function at a particular address in memory. If you are using third-party code, you do not have to change the source, but you must recompile (unless the code was already compiled with the -zo option). pragma arm section This pragma specifies the code or data section name used for subsequent functions or objects. This includes definitions of anonymous objects the compiler creates for initializations.
C and C++ Compilers -S22 The memory cannot store halfwords. You can use this to suppress the generation of STRH instructions when generating ARM code for architecture v4 (and later) processors. -L22 The memory cannot load halfwords. You can use this to suppress the generation of LDRH instructions when generating ARM code for architecture v4 (and later) processors. Note Do not use -L22 or -S22 when compiling Thumb code.
C and C++ Compilers 2.3.10 Controlling warning messages The compiler issues warnings about potential portability problems and other hazards. The compiler options enable you to turn off specific warnings. For example, you can turn off warnings if you are in the early stages of porting a program written in old-style C. In general, it is better to check the code than to switch off warnings. The options are on by default, unless specified otherwise.
C and C++ Compilers • -Wd specifying char, short, float, or enum arguments to variadic functions such as va_start(). This option suppresses the warning message: C2215W: Deprecated declaration foo() - give arg types This warning is normally given when a declaration without argument types is encountered in ANSI C mode. In ANSI C, declarations like this are deprecated. However, it is sometimes useful to suppress this warning when porting old code.
C and C++ Compilers C2621W: double constant automatically converted to float These warnings are given when the default type of unqualified floating-point constants is changed by the -auto_float_constants option. This warning is switched on by default. -Wl This option turns off the warning: C2951W: lower precision in wider context when code like the following is found: long x; int y, z; x = y*z where the multiplication yields an int result that is then widened to long.
C and C++ Compilers struct Base { virtual void f(); }; struct Derived : Base { void f(); }; generates the following warning: C2997W: 'Derived::f()' inherits implicit virtual from 'Base::f()' Adding the virtual keyword in the derived class prevents the warning. -Ws This option suppresses warnings generated when the compiler inserts padding in a struct. For example: C2221W: padding inserted in struct 's' This warning is off by default. It can be enabled with -W+s.
C and C++ Compilers By default, unused declaration warnings are given for: • local (within a function) declarations of variables, typedefs, and functions • labels (always within a function) • top-level static functions and static variables. -Wy 2.3.11 This option turns off warnings about deprecated features. Specifying additional checks The options described below give you control over the extent and rigor of the checks. Additional checking is an aid to portability and is good coding practice.
C and C++ Compilers int f(int i) {return (int)i;} // Warning: explicit cast to same type. 2-36 -fv This option reports on all unused declarations (including from standard headers). -fx This option enables all warnings normally suppressed by default, with the exception of the additional checks described in this section. Copyright © 1999-2001 ARM Limited. All rights reserved.
C and C++ Compilers 2.3.12 Controlling error messages The compiler issues errors to indicate serious problems in the code it is attempting to compile. The compiler options described below enable you to: • turn off specific recoverable errors • downgrade specific errors to warnings. Caution These options force the compiler to accept C and C++ source that normally produces errors.
C and C++ Compilers -Ec This option suppresses all implicit cast errors, such as implicit casts of a nonzero int to pointer. C3029E: ’=’: implicit cast of non-0 int to pointer -Ef This option suppresses errors for unclean casts, such as short to pointer. -Ei For C++ only, this option downgrades from error to warning the use of implicit int in constructs such as const i;.
Chapter 3 ARM Compiler Reference This chapter gives information on ARM-specific features of the ARM C and C++ compilers. It contains the following sections: • Compiler-specific features on page 3-2 • Language extensions on page 3-16 • C and C++ implementation details on page 3-21 • Predefined macros on page 3-31.
ARM Compiler Reference 3.1 Compiler-specific features This section describes the ARM-specific aspects of the ARM C and C++ compilers, including: • Pragmas • Function keywords on page 3-6 • Variable declaration keywords on page 3-9. Note Features described here are outside the ANSI specification and might not easily port to other compilers. 3.1.1 Pragmas Pragmas of the following form are recognized by the ARM compiler: #pragma [no_]feature-name Pragmas are listed in Table 3-1.
ARM Compiler Reference Pragmas controlling printf and scanf argument checking The following pragmas control type checking of printf-like and scanf-like arguments: check_printf_formats This pragma marks printf-like functions for type checking against a literal format string, if it exists. If the format is not a literal string, no type checking is done. The format string must be the last fixed argument. For example: #pragma check_printf_formats extern void myprintf(const char * format,...
ARM Compiler Reference Pragmas controlling code generation The following pragmas control how code is generated. Many other code generation options are available from the compiler command line: check_stack This pragma reenables the generation of function entry code that checks for stack limit violation if stack checking has been disabled with #pragma no_check_stack and the -apcs /swst command-line option is used.
ARM Compiler Reference Where name is the name to use for the section and sort_type is one of: • code • rwdata • rodata • zidata. If sort_type is specified but name is not, the section name for sort_type is reset to the default value. Enter #pragma arm section on its own to restore the names of all object sections to their defaults. See Example 3-1. Example 3-1 Section naming int x1 = 5; // in .data (default) int y1[100]; // in .bss (default) int const z1[3] = {1,2,3}; // in .
ARM Compiler Reference 3.1.2 Function keywords Several keywords tell the compiler to give a function special treatment. These are all ARM extensions to the ANSI C specification: Declarations inside functions Declarations inside a function indicate that the following statements are processed differently. The asm keyword does not modify the surrounding function, but it does indicate that the statements following the keyword are different.
ARM Compiler Reference __pure void (*h(void))(void); /* declares 'h' as a (pure?) function that returns a pointer to a (pure?) function. It is ambiguous which of the two function types is pure. */ void (*h1(void) __pure)(void); /* 'h1' is a pure function returning a pointer to a (normal) function */ __softfp This asserts that a function uses software floating-point linkage. Calls to the function pass floating-point arguments in integer registers.
ARM Compiler Reference real_num Is the value passed in r12 to the SWI handler. You can use this feature to implement indirect SWIs. The SWI handler can use r12 to determine the function to perform. For example: int __swi_indirect(0) ioctl(int swino, int fn, void *argp); This SWI can be called as follows: ioctl(IOCTL+4, RESET, NULL); It compiles to a SWI 0 with IOCTL+4 in r12. To use the indirect SWI mechanism, your system SWI handlers must make use of the r12 value to select the required operation.
ARM Compiler Reference __inline int f(int x) {return x*5+1;} int g(int x, int y) {return f(x) + f(y);} The compiler compiles functions inline when __inline is used and the functions are not too large. Large functions are not compiled inline because they can adversely affect code density and performance. See Defining optimization criteria on page 2-24 for information on command-line options that affect inlining.
ARM Compiler Reference Standard keywords These keywords declare a storage class. register Using the ARM compilers, you can declare any number of local objects (auto variables) to have the storage class register. Note Using register is not recommended because the compiler is very effective at optimizing code. The register keyword is regarded by the compiler as a suggestion only. Other variables, not declared with the register keyword, can be kept in registers and register variables can be kept in memory.
ARM Compiler Reference number (for example, r4). In C, global register variables cannot be qualified or initialized at declaration. In C++, any initialization is treated as a dynamic initialization. Valid types are: • any integer type, except long long • any pointer type. For example, to declare a global integer register variable allocated to r5 (the ATPCS register v2), use the following: __global_reg(2) int x; The global register must be specified in all declarations of the same variable.
ARM Compiler Reference • A global register variable maps to a callee-saved register, so its value is saved and restored across a call to a function in a compilation unit that does not use it as a global register variable, such as a library function. • Calls back into a compilation unit that uses a global register variable are dangerous.
ARM Compiler Reference Note The ARM-Thumb Procedure Call Standard requires that the stack is 8-byte aligned at all external interfaces. The ARM compilers and C libraries ensure that 8-byte alignment of the stack is maintained. In addition, the default C library memory model maintains 8-byte alignment of the heap. __packed The __packed qualifier sets the alignment of any valid type to 1.
ARM Compiler Reference Example 3-2 Pointer to packed __packed int *p There are no packed array types. A packed array is an array of objects of packed type. There is no padding in the array. Note On ARM processors, access to unaligned data can take up to seven instructions and three work registers. Data accesses through packed structures must be minimized to avoid increase in code size, and performance loss.
ARM Compiler Reference volatile The standard ANSI qualifier volatile informs the compiler that the qualified type contains data that can be changed from outside the program. The compiler does not attempt to optimize accesses to volatile types.
ARM Compiler Reference 3.2 Language extensions This section describes the language extensions supported by the ARM compilers. 3.2.1 C language extensions The compilers support the ANSI C language extensions described below and in C and C++ language extensions. The extensions are not available if the compiler is restricted to compiling strict ANSI C, for example, by specifying the -strict compiler option. // comments The character sequence // starts a comment.
ARM Compiler Reference Identifiers The $ character is a legal character in identifiers. Void returns and arguments Any void type, including a typedef to void, is permitted as the return type in a function declaration, or the indicator that a function takes no argument.
ARM Compiler Reference Inline assembler The ARM C++ compilers support the syntax in the ISO/IEC C++ standard, with the restriction that the string-literal must be a single string, for example: asm("instruction[;instruction]"); The asm declaration must be inside a C++ function. You cannot include comments in the string literal. The ARM C and C++ compilers also support an extended inline assembler syntax, introduced by the asm keyword (C++), or the __asm keyword (C and C++).
ARM Compiler Reference Hexadecimal floating-point constants ARM implements an extension to the syntax of numeric constants in C to enable explicit specification of floating-point constants as IEEE bit patterns. The syntax is: 0f_n Interpret an 8-digit hex number n as a float. 0d_nn Interpret a 16-digit hex number nn as a double. There must be exactly eight digits for float constants. There must be exactly 16 digits for double constants.
ARM Compiler Reference Example 3-6 Linkage specification extern const int z; /* in read-only segment, cannot */ /* be dynamically initialized */ extern "C++:read/write" const int y; /* in read/write segment */ /* can be dynamically initialized */ extern "C++:read/write" { const int i=5; /* placed in read-only segment, */ /* not extern because implicitly static */ extern const T x=6; /* placed in read/write segment */ struct S { static const T T x; /* placed in read/write segment */ }; } Constant objects
ARM Compiler Reference 3.3 C and C++ implementation details This section describes implementation details for the ARM compilers, including: • Character sets and identifiers • Basic data types on page 3-23 • Operations on basic data types on page 3-24 • Structures, unions, enumerations, and bitfields on page 3-26. 3.3.
ARM Compiler Reference • In C all character constants have type int. In C++ a character constant containing one character has the type char and a character constant containing more than one character has the type int. Up to four characters of the constant are represented in the integer value. The last character in the constant occupies the lowest-order byte of the integer value. Up to three preceding characters are placed at higher-order bytes. Unused bytes are filled with the NULL (\0) character.
ARM Compiler Reference 3.3.2 Basic data types This section gives information about how the basic data types are implemented in ARM C and C++. Size and alignment of basic data types Table 3-3 gives the size and natural alignment of the basic data types. Type alignment varies according to the context. (See Structures, unions, enumerations, and bitfields on page 3-26.) • Local variables are usually kept in registers, but when local variables are spilled onto the stack, they are always word-aligned.
ARM Compiler Reference Float Floating-point quantities are stored in IEEE format: • float values are represented by IEEE single-precision values • double and long double values are represented by IEEE double-precision values. If softvfp, vfp, or softvfp+vfp is selected, for double and long double quantities the word containing the sign, the exponent, and the most significant part of the mantissa is stored with the lower machine address in big-endian mode and at the higher address in little-endian mode.
ARM Compiler Reference • Any quantity that specifies the amount of a shift is treated as an unsigned 8-bit value. • Any value to be shifted is treated as a 32-bit value. • Left shifts of more than 31 give a result of zero. • Right shifts of more than 31 give a result of zero from a shift of an unsigned value or positive signed value. They yield –1 from a shift of a negative signed value. • The remainder on integer division has the same sign as the divisor.
ARM Compiler Reference 3.3.4 • If the pointers point to objects whose size is one, two, or four bytes, the natural alignment of the object ensures that the division is exact, provided the objects are not packed. • For packed or longer types, such as double and struct, both pointers must point to elements of the same array. Structures, unions, enumerations, and bitfields This section describes the implementation of the structured data types union, enum, and struct.
ARM Compiler Reference • all C++ structures and classes not using virtual functions or base classes. Structure alignment The alignment of a nonpacked structure is the maximum alignment required by any of its fields. Field alignment Structures are arranged with the first-named component at the lowest address. Fields are aligned as follows: • A field with a char type is aligned to the next available byte. • A field with a short type is aligned to the next even-addressed byte.
ARM Compiler Reference Packed structures A packed structure is one where the alignment of the structure, and of the fields within it, is always 1. Floating-point types cannot be fields of packed structures. Packed structures are defined with the __packed qualifier. (See ARM-specific keywords on page 3-10.) There is no command-line option to change the default packing of structures. Bitfields In nonpacked structures, the ARM compilers allocate bitfields in containers.
ARM Compiler Reference struct X { int x:10; int y:20; int z:5; }; The compiler pads the remaining two bits for the first container and assigns a new integer container for z. Bitfield containers can overlap each other, for example: struct X { int x:10; char y:2; }; The first declaration creates an integer container and allocates 10 bits to x. These 10 bits occupy the first byte and two bits of the second byte of the integer container.
ARM Compiler Reference struct X { int x:10; char y:8; int z:5; } The compiler allocates an int container starting at the same location as the int x:10 container and allocates a byte-aligned char and 5-bit bitfield (Figure 3-3). Bit number 31 30 29 28 27 26 25 24 23 22 21 20 19 18 17 16 15 14 13 12 11 10 9 8 7 6 5 4 3 2 1 0 free z y padding x Figure 3-3 Bitfield allocation 2 You can explicitly pad a bitfield container by declaring an unnamed bitfield of size zero.
ARM Compiler Reference 3.4 Predefined macros Table 3-4 lists the macro names predefined by the ARM C and C++ compilers. Where the value field is empty, the symbol is only defined. Table 3-4 Predefined macros Name Value When defined __arm – If using armcc, tcc, armcpp, or tcpp. __ARMCC_VERSION ver For giving the version number of the compiler. The value is the same for the ARM and Thumb compilers. It is a decimal number, whose value can be relied on to increase between releases.
ARM Compiler Reference Table 3-4 Predefined macros (continued) Name Value When defined __OPTIMISE_TIME – If -Otime in use. __prettyfunc__ name The unmangled name of the current function. __sizeof_int 4 For sizeof(int), but available in preprocessor expressions. __sizeof_long 4 For sizeof(long), but available in preprocessor expressions. __sizeof_ptr 4 For sizeof(void *), but available in preprocessor expressions. __SOFTFP__ – If compiling to use the software floating-point library.
ARM Compiler Reference Table 3-4 Predefined macros (continued) Name Value When defined __TARGET_FEATURE_HALFWORD – If the target architecture supports halfword and signed byte access instructions, for example v5TE. __TARGET_FEATURE_MULTIPLY – If the target architecture supports the long multiply instructions MULL and MULAL. __TARGET_FEATURE_THUMB – If the target architecture is Thumb-capable (ARM architecture v4T or later).
ARM Compiler Reference 3-34 Copyright © 1999-2001 ARM Limited. All rights reserved.
Chapter 4 The C and C++ Libraries This chapter describes the ARM C and C++ libraries. The libraries support programs written in C or C++.
The C and C++ Libraries 4.1 About the runtime libraries The following runtime libraries are provided to support compiled C and C++: ANSI C C++ The C libraries consist of: • The functions defined by the ISO C library standard. • Target-dependent functions used to implement the C library functions in the semihosted execution environment. You can redefine these functions in your own application. • Helper functions used by the C and C++ compilers.
The C and C++ Libraries 4.1.1 Build options and library variants When you build your application, you must make certain fundamental choices. For example: Byte order Big-endian or little-endian. Floating-point support FPA, VFP, software, or none. Stack limit Checked or unchecked. Position-independence Data can be read/write position-independent or not position-independent. Code can be read-only position-independent or not position-independent.
The C and C++ Libraries 4.1.2 Library directory structure The libraries are installed in two subdirectories within install_directory\lib: armlib This subdirectory contains the variants of the ARM C library, the floating-point arithmetic library, and the math library. The accompanying header files are in install_directory\include. cpplib This subdirectory contains the variants of the Rogue Wave C++ library and supporting C++ functions.
The C and C++ Libraries The following points describe how static data is used by the libraries: • Floating-point arithmetic libraries do not use static data and are always reentrant. • All statically-initialized data in the C libraries is read-only. • All writable static data is uninitialized. • Most C library functions use no writable static data and are reentrant whether built with base build options (-apcs /norwpi) or reentrant (-apcs /rwpi) build options.
The C and C++ Libraries 4.2 Building an application with the C library This section covers creating an application that links with functions from the C or C++ libraries. Functions in the C library are responsible for: • Creating an environment in which a C or C++ program can execute. This includes — creating a stack — creating a heap, if required — initializing the parts of the library the program uses. • Starting execution by calling main(). • Supporting use of ISO-defined functions by the program.
The C and C++ Libraries Using ARMulator The ARM instruction set simulator (ARMulator) supports the semihosting SWI and has a memory map that enables using the library. The ARMulator uses memory in the host machine and this is normally adequate for your application. Using Angel ARM boards running the Angel debug monitor support the semihosting SWI and have memory maps that enable using the library.
The C and C++ Libraries Implementing your own semihosting SWI support It is possible to implement your own semihosting SWI support. The interface is simple and requires a handler for only two SWI numbers. 0x123456 is used in ARM state and 0xab is used in Thumb state. See the semihosting SWI definitions in ADS Debug Target Guide and the include file rt_sys.h 4.2.
The C and C++ Libraries Overview of semihosting dependencies The functions shown in Table 4-2 depend directly on semihosting SWIs. Table 4-2 Direct dependencies Function Description __user_initial_stackheap() Tailoring the runtime memory model on page 4-67. You must reimplement this function if you are using scatter-loading. _sys_exit() Tailoring error signaling, error handling, and program exit on page 4-51. _ttywrch() _sys_command_string() Tailoring the input/output functions on page 4-75.
The C and C++ Libraries The functions listed in Table 4-3 depend indirectly on one or more of the functions listed in Table 4-2 on page 4-9. Table 4-3 Indirect dependencies Function Where used __raise() Catch, handle, or diagnose C library exceptions, without C signal support. See Tailoring error signaling, error handling, and program exit on page 4-51. __default_signal_handler() Catch, handle, or diagnose C library exceptions, with C signal support.
The C and C++ Libraries Use the linker symbol table and cross reference listings to identify functions you have called that directly, or indirectly, use semihosting. You can view this information by using the linker options -map, -xref, and -verbose. Remove, or re-implement semihosted functions, and rebuild the application.
The C and C++ Libraries If you are re-implementing a function that exists in the standard ARM library, the linker uses an object or library from your project rather than the standard ARM library. A library you add to a project does not have to follow the ARM naming convention for libraries. Caution Do not replace or delete libraries supplied by ARM. You must not overwrite the supplied library files. Place your re-implemented functions in a separate library. 4-12 Copyright © 1999-2001 ARM Limited.
The C and C++ Libraries 4.3 Building an application without the C library Creating an application that has a main() function causes the C library initialization functions to be included. If your application does not have a main() function, the C library is not initialized and the following features are not available in your application: • software stack checking • low-level stdio • signal-handling functions, signal() and raise() in signal.h • atexit() • alloca().
The C and C++ Libraries • Ensure that your initialization veneer is executed by, for example, placing it in your reset handler. • Build your application using -fpu none and link it normally. The linker will use the appropriate C library variant to find any needed compiler helper functions. Many library facilities require __user_libspace() for static data.
The C and C++ Libraries Program design The functions you must re-implement depend on how much of the library functionality you require as follows: • If you want only the compiler support functions for division, structure copy, and FP arithmetic, you must provide __rt_raise(). This also enables very simple library functions such as those in errno.h, setjmp.h, and most of string.h to work. • If you call setlocale() explicitly, locale-dependent functions start to work.
The C and C++ Libraries Using high-level functions High-level I/O functions, fprintf() for example, can be used if the low-level functions, fputc() for example, are re-implemented. Most of the formatted output functions also require a call to setlocale(). See Tailoring the input/output functions on page 4-75 for instructions. Anything that uses locale must not be called before first calling setlocale() to initialize it, for example call setlocale(LC_ALL, "C").
The C and C++ Libraries fenv.h Functions in this file work without the requirement for any library initialization and only require the re-implementation of __rt_raise(). float.h This file does not contain any code. The definitions in the file do not require library initialization or function re-implementation. inttypes.h Functions listed in this file require the locale functions. limits.h Functions in this file work without the requirement for any library initialization or function re-implementation.
The C and C++ Libraries math.h Functions in this file work without the requirement for any library initialization and only require the re-implementation of __rt_raise(). You must call _fp_init() to use floating-point functions. setjmp.h Functions in this file work without any library initialization or function re-implementation. signal.h Functions listed in this file are not available without library initialization.
The C and C++ Libraries • The remove() and rename() functions are system-specific and probably not usable in your application. stdlib.h Most functions in this file work without any library initialization or function re-implementation. The following functions are not available, or require implementation of a support function: ato*() Requires locale. strto*() Requires locale. malloc() malloc(), calloc(), realloc(), and free() require heap functions. atexit() Is not available. string.
The C and C++ Libraries 4.4 Tailoring the C library to a new execution environment This section describes how to re-implement functions to produce an application for a different execution environment, for example embedded in ROM or used with an RTOS. Symbols that have a single or double underscore, _ or __, name functions that are used as part of the low-level implementation. You can re-implement some of these functions. Additional information on these library functions is available in the rt_heap.
The C and C++ Libraries 2. Calls __rt_lib_init() to initialize referenced library functions, initialize the locale and, if necessary, set up argc and argv for main(). For C++, calls the constructors for any top-level objects. 3. Calls main(), the user-level root of the application. From main(), your program might call, among other things, library functions. See Library functions called from main() for more information. 4. Calls exit() with the value returned by main().
The C and C++ Libraries 4.4.2 Exiting from the program The program can exit normally at the end of main() or it can exit prematurely because of an error. See also: • __rt_entry • __rt_exit() on page 4-23 • Tailoring error signaling, error handling, and program exit on page 4-51. Exiting from an assert The exit sequence from an assert is: 1. assert() prints a message on stderr. 2. assert() calls abort(). 3. abort() calls __rt_raise(). 4.
The C and C++ Libraries The default implementation of __rt_entry: 1. Sets up the heap and stack. 2. Initializes the C library. 3. Calls main(). 4. Shuts down the C library. 5. Exits. __rt_entry must end with a call to one of the following functions: 4.4.4 exit() To get full atexit() handling and library shut down. __rt_exit() To correctly shut down the library, bypassing atexit() processing. _sys_exit() To exit directly to the execution environment, bypassing atexit().
The C and C++ Libraries Syntax extern value_in_regs unsigned heaptop) struct __argc_argv __rt_lib_init(unsigned heapbase, heapbase Is the start of the heap memory block. heaptop Is the end of the heap memory block. Implementation This is the library initialization function. It is called immediatelyafter __rt_stackheap_init() and passed an initial chunk of memory to use as a heap. This function is the standard ARM library initialization function and must not be re-implemented.
The C and C++ Libraries 4.5 Tailoring static data access This section describes using callouts from the C library to access static data.
The C and C++ Libraries 4.6 Tailoring locale and CTYPE This section describes functions related to locale. Applications use locale when they display or process data that is dependent on the local language or region, for example character order, monetary symbols, decimal point, time, and date. See the rt_locale.h include file for more information on locale-related functions. 4.6.
The C and C++ Libraries Implementation To select an ISO8859-1 (Latin-1 alphabet) locale category, include a call from your application to the functions shown in Table 4-6. Table 4-6 Default locales Function Description __use_iso8859_ctype() Selects the ISO8859-1 (Latin-1) classification of characters (this is essentially 7-bit ASCII, except that the top-bit-set character codes 160-255 represent a selection of useful European punctuation characters, letters, and accented letters).
The C and C++ Libraries 4.6.2 Selecting locale at run time The C library function setlocale() selects a locale at runtime for the locale category, or categories, specified in its arguments. It does this by selecting the requested locale separately in each locale category. In effect, each locale category is a small filing system containing an entry for each locale.
The C and C++ Libraries All locale blocks for a category are collected into a read-only, position-independent, in-memory file system structure. The C library provides a set of macros to create the blocks and the _findlocale() function to search the file system. You can define a set of runtime selectable locales by using the supplied re-implementations as a starting point. Your application will not call _get_lc_category functions directly.
The C and C++ Libraries Using the macros The data blocks for a single locale category must be contiguous and the LC_INDEX_END macro must be the last macro in the sequence. The examples in each locale category use two test macros that are defined as: #define EQI(i,j) assert(i==j) #define EQS(s,t) assert(!strcmp(s,t)) 4.6.4 _get_lc_ctype() The ctype implementation is selected at link time to be either: • The C locale only. This is the default. • The ISO 8859 (Latin-1) locale.
The C and C++ Libraries __C, __C, __C, __C, __C, __C, __C, __C, __C, __C, __C, __C, __C, __C, __C, __C, __C, __C, __B+__S, __P, __P, __P, __P, __P, __P, __P, __P, __P, __P, __P, __P, __P, __P, __P, __N, __N, __N, __N, __N, __N, __N, __N, __N, __N, __P, __P, __P, __P, __P, __P, __P, __U+__X, __U+__X, __U+__X, __U+__X, __U+__X, __U+__X, __U, __U, __U, __U, __U, __U, __U, __U, __U, __U, __U, __U, __U, __U, __U, __U, __U, __U, __U, __U, __P, __P, __P, __P, __P, __P, __L+__X, __L+__X, __L+__X, __L+__X, __L+__X,
The C and C++ Libraries * - 0xc0-0xdf are uppercase chars except * - 0xe0-0xff are lowercase chars except __C,__C,__C,__C,__C,__C,__C,__C, /* __C,__C,__C,__C,__C,__C,__C,__C, /* __C,__C,__C,__C,__C,__C,__C,__C, /* __C,__C,__C,__C,__C,__C,__C,__C, /* __B+__S,__P,__P,__P,__P,__P,__P,__P, /* __P,__P,__P,__P,__P,__P,__P,__P, /* __P,__P,__P,__P,__P,__P,__P,__P, /* __P,__P,__P,__P,__P,__P,__P,__P, /* __U,__U,__U,__U,__U,__U,__U,__U, /* __U,__U,__U,__U,__U,__U,__U,__U, /* __U,__U,__U,__U,__U,__U,__U,__P, /* __U,_
The C and C++ Libraries Each element gives the position in the collation sequence of the character represented by the index of the element. For example, if you want strcoll() to sort strings beginning with Z in between those beginning with A and those beginning with B, you can set up the LC_COLLATE table so that array['A'] < array['Z'] and array['Z'] < array['B']. _get_lc_collate() must return a pointer to a collate structure. Use the macros in Example 4-4 to create the structure.
The C and C++ Libraries 0x9c, /* n - then 1 n variant */ 0x9e, /* o - then 6 o variants */ 0xa5, /* p */ 0xa6, /* q */ 0xa7, /* r */ 0xa8, /* s - then 1 s variant */ 0xaa, /* t */ 0xab, /* u - then 4 u variants */ 0xb0, /* v */ 0xb1, /* w */ 0xb2, /* x */ 0xb3, /* y - then 2 y variants */ 0xb6, /* z - then eth & thorn */ 0xb9, /* { */ 0xba, /* | */ 0xbb, /* } */ 0xbc, /* ~ */ 0xbd, /* del */ /* top bit set control characters */ 0xbe, 0xbf, 0xc0, 0xc1, 0xc2, 0xc3, 0xc4, 0xc5, 0xc6, 0xc7, 0xc8, 0xc9, 0xca, 0
The C and C++ Libraries 0xac, 0xae, 0xb4, 0xb5 /* /* /* /* u u y y grave */ 0xad, /* u acute */ circumflex */ 0xaf, /* u umlaut */ acute */ 0xb8, /* thorn */ umlaut */ }; __LC_INDEX_END(lccollate_dummy) void const *_get_lc_collate(void const *null, char return _findlocale(&lccoll_c_index, name); } void test_lc_collate(void) { char buf[5]; /* test both strxfrm and strcoll here*/ EQS(setlocale(LC_COLLATE, NULL), "C"); EQS((strxfrm(buf, "\xEF", 4), buf), "\xEF"); EQI(strcoll("\xEF", "j") < 0, 0); EQI(!set
The C and C++ Libraries Example 4-6 LC_MONETARY_DEF __LC_MONETARY_DEF(lcmonetary_c, "C", "","","","","","","", 255,255,255,255,255,255,255,255) __LC_MONETARY_DEF(lcmonetary_iso8859_1, "ISO8859-1", "STG ", "\243", ".
The C and C++ Libraries 4.6.7 _get_lc_numeric() _get_lc_numeric() must return a pointer to an __lc_numeric_blk structure. Use the macros in Example 4-7 to create the structure. Example 4-7 LC_NUMERIC_DEF __LC_NUMERIC_DEF(lcnumeric_c, "C",".","","") __LC_NUMERIC_DEF(lcnumeric_iso8859_1, "ISO8859-1", ".", ",", "\3") __LC_NUMERIC_DEF(lcnumeric_fr, "fr", ",", ".
The C and C++ Libraries 4.6.8 _get_lc_time() _get_lc_time() must return a pointer to a __lc_time_blk structure. Use the macros in Example 4-8 to create the structure.
The C and C++ Libraries strftime(timestr, sizeof(timestr), "%c", &tm); EQS(timestr, "jeudi, 12 fevrier 1998, 23:13:13"); EQI(!setlocale(LC_TIME, "C"), 0); /* setlocale should work */ EQS(setlocale(LC_TIME, NULL), "C"); strftime(timestr, sizeof(timestr), "%c", &tm); EQS(timestr, "12 Feb 1998 23:13:13"); } The offset fields are interpreted similarly to __lc_monetary_blk. 4.6.
The C and C++ Libraries 4.6.10 localeconv() localeconv() creates and sets the components of an lconv structure with values appropriate for the formatting of numeric quantities according to the rules of the current locale. Syntax struct lconv* localeconv(void) Implementation The members of the structure with type char are strings, any of which, except decimal_point, can point to "" to indicate that the value is not available in the current locale or is of zero length.
The C and C++ Libraries 4.6.11 setlocale() Selects the appropriate locale as specified by the category and locale arguments. Syntax char* setlocale(int category, const char* locale) Implementation The setlocale() function is used to changeor query part or all of the current locale. The effect of the category argument for each value is described below. A value of "C" for locale specifies the minimal environment for C translation.
The C and C++ Libraries If category is LC_ALL and the most recent successful locale-setting call uses a category other than LC_ALL, a composite string might be returned. The string returned is such that a subsequent call with that string and its associated category restores that part the program locale. The string returned is not modified by the program, but might be overwritten by a subsequent call to setlocale(). 4.6.
The C and C++ Libraries Note Because the compiler optimizes the data segment, it reorders and removes parts of locale definitions, and breaks the data structures. The code examples provided are for informational purposes only. In practice, the definitions require additional pragmas to disable optimizations. 4.6.14 __LC_COLLATE_DEF This macro is used to create collate blocks used when sorting ASCII characters. The definition from rt_locale.
The C and C++ Libraries 4.6.15 __LC_TIME_DEF This macro is used to create blocks used when formatting time or date values. The definition from rt_locale.h and sample code are shown in Example 4-12. For all the macros, the first two arguments are a symbol prefix and a locale name. The resulting locale block is addressed by the expression &symprefix_start, and the index entry by the expression &symprefix_index.
The C and C++ Libraries Usage See _get_lc_time() on page 4-38. See also __LC_CTYPE_DEF on page 4-42 for details of the side-effects of compiler optimizations. ARM DUI 0067D Copyright © 1999-2001 ARM Limited. All rights reserved.
The C and C++ Libraries 4.6.16 __LC_NUMERIC_DEF This macro is used to create blocks used when formatting numbers. The definition from rt_locale.h and sample code are shown in Example 4-13. For all the macros, the first two arguments are a symbol prefix and a locale name. The resulting locale block is addressed by the expression &symprefix_start, and the index entry by the expression &symprefix_index.
The C and C++ Libraries static static static static static static static static static static static static static static static const const const const const const const const const const const const const const const static const static const static static static static static static static const const const const const const const + (~3 & (3 + sizeof(ln)))); \ char sym##_lname[~3 & (3 + sizeof(ln))] = ln; \ int sym##_pname = -4-(~3 & (3 + sizeof(ln))); \ char sym##_start = id; \ char sym##_fdchr = f
The C and C++ Libraries 4.6.18 __LC_INDEX_END This macro is used to declare the end of an index. symprefix is provided to ensure a unique name. The definition from rt_locale.h and sample code are shown in Example 4-15. Example 4-15 LC_INDEX_END #define __LC_INDEX_END(symprefix) 4.6.19 static const int symprefix##_index = 0; The lconv structure The lconv structure contains numeric formatting information. The structure is filled by the functions _get_lconv() and localeconv().
The C and C++ Libraries char *mon_grouping; /* A string whose elements indicate the size of each group of digits */ /* in formatted monetary quantities. See below for more details. */ char *positive_sign; /* The string used to indicate a non-negative-valued formatted */ /* monetary quantity. */ char *negative_sign; /* The string used to indicate a negative-valued formatted monetary */ /* quantity.
The C and C++ Libraries The value of p_sign_posn and n_sign_posn are interpreted as follows: 4-50 0 Parentheses surround the quantity and currency symbol. 1 The sign string precedes the quantity and currency symbol. 2 The sign string is after the quantity and currency symbol. 3 The sign string immediately precedes the currency symbol. 4 The sign string immediately succeeds the currency symbol. Copyright © 1999-2001 ARM Limited. All rights reserved.
The C and C++ Libraries 4.7 Tailoring error signaling, error handling, and program exit All trap or error signals raised by the C library go through the __raise() function. You can re-implement this function or the lower-level functions that it uses. Caution The IEEE 754 standard for floating-point processing states that the default response to an exception is to proceed without a trap. You can modify floating-point error handling by tailoring the functions and definitions in fenv.h.
The C and C++ Libraries 4.7.1 _sys_exit() The library exit function. All exits from the library eventually call _sys_exit(). Syntax void _sys_exit(int return_code) Implementation This function must not return. You can intercept applicationexit at a higher level by either: • Implementing the C library function exit() as part of your application. You lose atexit() processing and library shutdown if you do this. • Implementing the function __rt_exit(int n) as part of your application.
The C and C++ Libraries Returns The default implementation is a veneer on __user_libspace() that returns the address of the status word. A suitable default definition is given in the C library standard headers. 4.7.3 __rt_errno_addr() This function is called to obtain the address of the C library errno variable when the C library attempts to read or write errno. A default implementation is provided by the library. It is unlikely that you will have to re-implement this function.
The C and C++ Libraries 4.7.5 0 The signal was handled. nonzero The calling code must pass that return value to the exit code. The default library implementation calls _sys_exit(rc) if __raise() returns a nonzero return code rc. __rt_raise() This function raises a signal to indicate a runtime anomaly. Syntax void __rt_raise(int signal, int type) signal Is an integer that holds the signal number. type Is an integer or string constant or variable.
The C and C++ Libraries void __default_signal_handler(int signal, int argument) The interface is the same as __raise(), but this function is only called after the C signal handling mechanism has declined to process the signal. A complete list of the defined signals is in signal.h. See Table 4-10 for those signals that are used by the libraries. Note The signals used by the libraries might change in future releases of the product.
The C and C++ Libraries 4.7.7 _ttywrch() This function writes a character to the console. The console might have been redirected. You can use this function as a last resort error handling routine. Syntax void _ttywrch(int ch) Implementation The default implementation of this function uses the semihostingSWI. You can redefine this function, or __raise(), even if there is no other input/output. For example, it might write an error message to a log kept in nonvolatile memory. 4.7.
The C and C++ Libraries 4.8 Tailoring storage management This section describes the functions from rt_heap.h that you can define if you are tailoring memory management. There are also two helper functions that you can call from your heap implementation. See the rt_heap.h and rt_memory.s include files for more information on memory-related functions. Note Users who are developing embedded systems with limited RAM might require a system that does not use the heap or any heap-using functions.
The C and C++ Libraries This implementation has low overheads, but the cost of malloc() or free() grows linearly with the number of free blocks. The smallest block that can be allocated is four bytes and there is an additional overhead of four bytes. If you expect more than 100 unallocated blocks it is recommended that you use Heap2. Heap2: Alternative heap implementation Heap2 provides a compact implementation with the cost of malloc() or free() growing logarithmically with the number of free blocks.
The C and C++ Libraries • your memory model can supply a block of memory at a lower address than the first one supplied. If you know in advance that the address space bounds of your heap are small, you do not have to redefine __user_heap_extent(), but it does speed up the heap algorithms if you do. The input parameters are the default values that are used if this routine is not defined. You can, for example, leave the default base value unchanged and only adjust the size.
The C and C++ Libraries 4.8.2 Creating your own storage-management system You can implement the heap functions in Table 4-11 to create a new storage-management system. Table 4-11 Heap functions 4-60 Function Description __Heap_Descriptor You must define your own implementation of the abstract data type for heap. See __Heap_Descriptor on page 4-61. __Heap_Initialize() Initializes the heap. See __Heap_Initialize() on page 4-62. __Heap_DescSize() Returns the size of the __Heap_Descriptor structure.
The C and C++ Libraries 4.8.3 __Heap_Descriptor You must define your own implementation of the abstract data type for heap. A C header file describing this abstract data type is provided in rt_heap.h. You must provide the interior definition of the structure so that the other functions can find the heap data. Typical contents are given in Example 4-17.
The C and C++ Libraries 4.8.4 __Heap_Initialize() Initializes the heap. Syntax void __Heap_Initialize(struct __Heap_Descriptor*h) Implementation This is called at initialization. You must redefine it toset up the fields in your heap descriptor structure to correct initial values. A typical linked-list heap initializes the first_free_block pointer to NULL to indicate that there are no free blocks in the heap. 4.8.5 __Heap_DescSize() Returns the size of the __Heap_Descriptor structure.
The C and C++ Libraries 4.8.6 __Heap_ProvideMemory() Called to increase the size of the heap. Syntax void __Heap_ProvideMemory(struct __Heap_Descriptor* h, void* base, size_t size) Implementation This is called when the system provides a chunk of memory for use by the heap. The parameters are: • your heap descriptor • a pointer to a new 8-byte aligned block of memory • the size of the block. __Heap_ProvideMemory() can assume that the input block is 8-byte aligned.
The C and C++ Libraries 4.8.8 __Heap_Free() Returns previously allocated space to the heap. Syntax void __Heap_Free(struct __Heap_Descriptor* h, void* _blk) Implementation This is called from free(),and given a pointer that was previously returned from either __Heap_Alloc() or __Heap_Realloc(). It returns the previously allocated space to the collection of free blocks in the heap. 4.8.9 __Heap_Realloc() Adjusts the size of an already allocated block.
The C and C++ Libraries 4.8.10 __Heap_Stats() Called from __heapstats() to print statistics about the state of the heap. Syntax void *__Heap_Stats(__Heap_Descriptor *h, int(*print)(void*, char const *format,...), void *printparam) Implementation It must output its results, using the supplied printf-type print routine,by calls of the form: print(printparam, "%d free blocks\n", nblocks); The format of the statistics data is implementation-defined, so it can do nothing.
The C and C++ Libraries 4.8.12 __Heap_Full() Attempts to acquire a new block of at least size bytes from the system. You must not re-implement this function. Syntax int __Heap_Full(struct __Heap_Descriptor *h, size_t size) Implementation If __Heap_Alloc() or __Heap_Realloc() cannotallocate a block of the required size from the memory owned by the heap, then before giving up and returning NULL, they can try calling this routine. You must provide space for heap housekeeping data.
The C and C++ Libraries 4.9 Tailoring the runtime memory model This section describes: 4.9.1 • the management of writable memory by the C library as static data, heap, and stack • functions that can be redefined to change how writable memory is managed. The memory models You can select either of the following memory models: Single memory region The stack grows downward from the top of the memory region while the heap grows upwards from the bottom of the region. This is the default.
The C and C++ Libraries 4.9.2 Controlling the runtime memory model The behavior of the heap and stack manager can be modified by redefining the functions listed in Table 4-12. Table 4-12 Memory model initialization Function Description __user_initial_stackheap() Returns the location of the initial heap. See __user_initial_stackheap() on page 4-69. __user_heap_extend() Returns the size and base address of a heap extra block. See __user_heap_extend() on page 4-70.
The C and C++ Libraries 4.9.4 __user_initial_stackheap() Returns the locations of the initial stack and heap. Syntax __value_in_regs struct __initial_stackheap__user_initial_stackheap (unsigned R0, unsigned SP, unsigned R2, unsigned SL) Implementation Note If you are using scatter-loading files with the linker, you must reimplement this function. The default implementation uses the value of the symbol Image$$ZI$$Limit.
The C and C++ Libraries Returns The values returned in r0 to r3 depend on whether you are using the one or two region model: One region (r0,r1) is the single stack and heap region. r1 is greater than r0. r2 and r3 are ignored. Two regions (r0, r2) is the initial heap and (r3, r1) is the initial stack. r2 is greater than or equal to r0. r3 is less than r1. 4.9.5 __user_heap_extend() This function can be defined to return extra blocks of memory, separate from the initial one, to be used by the heap.
The C and C++ Libraries Syntax __value_in_regs struct __heap_extent __user_heap_extent(unsigned ignore1, unsigned ignore2) Implementation There is no default implementation of this function. The valuesof the parameters ignore1 and ignore2 are not used by the function. 4.9.7 __user_stack_slop() If defined, this function returns the size of the extra stack your system requires below sl. The extra stack is in addition to the 256 bytes required by ATPCS.
The C and C++ Libraries preserve any other registers. On entry to this function, sp and sl are exactly as they were on entry to the whole application, so a valid stack can be inherited from the execution environment if desired. (sl is only required if stack checking is used.) 4.9.9 __rt_stack_overflow() This function is called if a stack overflow occurs. An incomplete prototype implementation is in rt_memory.
The C and C++ Libraries 4.9.10 __rt_heap_extend() This function returns a new 8-byte aligned block of memory to add to the heap, if possible. If you reimplement the other memory model functions, you must reimplement this function. An incomplete prototype implementation is in rt_memory.s. Implementation The calling convention is ordinary ATPCS. On entry, r0 is the minimum size of the block to add, and r1 holds a pointer to a location to store the base address.
The C and C++ Libraries 4.9.11 __rt_stack_postlongjmp() This function sets sp and sl to correct values after a call to longjmp(). An incomplete prototype implementation in assembler code is in rt_memory.s. Implementation This function is called with r0 containing the pre-setjmp() value for sl, and r1 containing the pre-setjmp() value for sp. If your memory model is used only with non stack-checked ATPCS, you do not have to implement this function.
The C and C++ Libraries 4.10 Tailoring the input/output functions The higher-level input/output functions such as fscanf() and fprintf() are not target-dependent. However, the higher-level functions perform input/output by calling lower-level functions that are target-dependent. To retarget input/output, you can either avoid these higher-level functions or redefine the lower-level functions. See the rt_sys.h include file for more information on I/O functions. 4.10.
The C and C++ Libraries printf family The printf family consists of _printf(), printf(), _fprintf(), fprintf(), vprintf(), and vfprintf(). All these functions use __FILE opaquely and depend only on the functions fputc() and ferror(). The functions _printf() and _fprintf() are identical to printf() and fprintf() except that they cannot format floating-point values. The standard output functions of the form _printf(...) are equivalent to: fprintf(& __stdout, ...) where __stdout has type __FILE.
The C and C++ Libraries { /* Your implementation of ferror */ return EOF; } void test(void) { printf("Hello world\n"); } /* This works ... */ By default, fread() and fwrite() call fast block input/output functions that are part of the ARM stream implementation. If you define your own __FILE structure instead of using the ARM stream implementation, fread() and fwrite() will call fgetc() instead of calling the block input/output functions. See also the implementation in \Examples\Embedded\embed\retarget.c.
The C and C++ Libraries 4.10.2 Target-dependent input/output support functions rt_sys.h defines the type FILEHANDLE. The value of FILEHANDLE is returned by _sys_open() and identifies an open file on the host system. The target-dependent input and output functions and their library members are listed in Table 4-15.
The C and C++ Libraries 4.10.3 _sys_open() This function opens a file. Syntax FILEHANDLE _sys_open(const char *name, int openmode) Implementation The _sys_open function is required by fopen() and freopen().These functions, in turn, are required if any file input/output function is to be used. The openmode parameter is a bitmap, whose bits mostly correspond directly to the ANSI mode specification. See rt_sys.h for details.
The C and C++ Libraries 4.10.5 _sys_read() This function reads the contents of a file into a buffer. Syntax int _sys_read(FILEHANDLE fh, unsigned char *buf, unsigned len, int mode) Implementation The mode argument is abitmap describing the state of the file connected to fh, as for _sys_write(). Returns The return value is one of the following: 4-80 • The number of characters not read (that is, len - result were read). • An error indication. • An EOF indicator.
The C and C++ Libraries 4.10.6 _sys_write() Writes the contents of a buffer to a file previously opened with _sys_open(). Syntax int _sys_write(FILEHANDLE fh, const unsigned char *buf, unsigned len, int mode) Implementation The mode parameter isa bitmap describing the state of the file connected to fh, whether it is a binary file, and how it is buffered.
The C and C++ Libraries 4.10.7 _sys_ensure() This function flushes buffers associated with a file handle. Syntax int _sys_ensure(FILEHANDLE fh) Implementation A call to _sys_ensure() flushes any buffersassociated with file handle fh, and ensures that the file is up to date on the backing store medium. Returns If an error occurs, the result is negative. 4.10.8 _sys_flen() This function returns the current length of a file.
The C and C++ Libraries 4.10.9 _sys_seek() This function puts the file pointer at offset pos from the beginning of the file. Syntax int _sys_seek(FILEHANDLE fh, long pos) Implementation This function sets the current read or write position to thenew location pos relative to the start of the current file fh. Returns The result is non-negative if no error occurs or is negative if an error occurs. 4.10.10 _sys_istty() This function determines if a file handle identifies a terminal.
The C and C++ Libraries 4.10.11 _sys_tmpnam() This function converts the file number fileno for a temporary file to a unique filename, for example tmp0001. Syntax void _sys_tmpnam(char *name, int fileno, unsigned maxlength) Implementation The function must be defined if tmpnam() or tmpfile() isused. Returns Returns the filename in name. 4.10.12 _sys_command_string() This function retrieves the command line used to invoke the current application from the environment that called the application.
The C and C++ Libraries 4.11 Tailoring other C library functions Implementation of the following ANSI standard functions depends entirely on the target operating system. None of the functions listed below is used internally by the library. So if any of these functions are not implemented, only applications calling the function directly will fail. The target-dependent ANSI C library functions are listed in Table 4-16.
The C and C++ Libraries 4.11.1 clock() This is the standard C library clock function from time.h. Syntax clock_tclock(void) Implementation If the units of clock_t() differ from the default of centiseconds you must define __CLK_TCK on the compiler command line or in your own header file. The value in the definition is used for CLK_TCK and CLOCKS_PER_SEC (the default value is 100 for centiseconds). If you re-implement clock() you must also re-implement _clock_init().
The C and C++ Libraries 4.11.3 time() This is the standard C library time() function from time.h. Syntax time_t time(time_t *timer) The return value is an approximation of the current calendartime. Returns The value (time_t*)-1 is returned if the calendar time is not available. If timer is not a NULL pointer, the return value is also assigned to the time_t*. 4.11.4 remove() This is the standard C library remove() function from stdio.h.
The C and C++ Libraries 4.11.5 rename() This is the standard C library rename() function from stdio.h. Syntax int rename(const char *old, const char *new) Implementation rename() causes the file whose name isthe string pointed to by old to be subsequently known by the name given by the string pointed to by new. The file named old is effectively removed. If a file named by the string pointed to by new exists prior to the call of the rename function, the behavior is implementation-defined.
The C and C++ Libraries 4.11.7 getenv() This is the standard C library getenv() function from stdlib.h. Syntax char *getenv(const char *name) Implementation The default implementation returns NULL indicatingthat no environment information is available. You can re-implement getenv() yourself. It depends on no other function and no other function depends on it.
The C and C++ Libraries 4.12 Selecting real-time division The division helper routine supplied with the ARM libraries provides good overall performance. However, the amount of time required to perform a division depends on the input values. A 4-bit quotient requires only 12 cycles, but a 32-bit quotient requires 96 cycles. Some applications require a faster worst-case cycle count at the expense of lower average performance. For this reason, two divide routines are provided with the ARM library.
The C and C++ Libraries 4.13 ISO implementation definition This section describes how the libraries fulfill the requirements of the ANSI specification. 4.13.1 ANSI C library implementation definition The ANSI C library variants are listed in Library naming conventions on page 4-105. The ANSI specification leaves some details to the implementors, but requires their implementation choices to be documented. The implementation details are described in this section.
The C and C++ Libraries Mathematical functions The mathematical functions shown in Table 4-17, when supplied with out-of-range arguments, respond in the way shown.
The C and C++ Libraries Table 4-17 Mathematical functions (continued) Function Condition Returned value Error number sqrt(x) x < 0 QNaN EDOM sin(x) x=Inf QNaN EDOM sinh(x) Overflow +Inf ERANGE tan(x) x=Inf QNaN EDOM atan(x) SNaN SNaN None ceil(x) SNaN SNaN None floor(x) SNaN SNaN None frexp(x) SNaN SNaN None ldexp(x) SNaN SNaN None modf(x) SNaN SNaN None tanh(x) SNaN SNaN None HUGE_VAL is an alias for Inf. Consult the errno variable for the error number.
The C and C++ Libraries Signal function The signals listed in Table 4-18 are supported by the signal() function. See also Table 4-10 on page 4-55 for signals used by the C and C++ libraries.
The C and C++ Libraries signal() returns an error code if you try to register a handler for a signal number greater than SIGUSR2. The default handling of all recognized signals is to print a diagnostic message and call exit(). This default behavior applies at program startup and until you change it. Caution The IEEE 754 standard for floating-point processing states that the default action to an exception is to proceed without a trap.
The C and C++ Libraries • A file can be opened many times for reading, but only once for writing or updating. A file cannot simultaneously be open for reading on one stream, and open for writing or updating on another. • Local time zones and Daylight Saving Time are not implemented. The values returned indicate that the information is not available. For example, the gmtime() function always returns NULL. • The status returned by exit() is the same value that was passed to it.
The C and C++ Libraries The following characteristics, required to be specified in an ANSI-compliant implementation, are unspecified in the ARM C library: • the validity of a filename • whether remove() can remove an open file • the effect of calling the rename() function when the new name already exists • the effect of calling getenv() (the default is to return NULL, no value available) • the effect of calling system() • the value returned by clock(). 4.13.
The C and C++ Libraries Table 4-20 C++ requirements on the C library (continued) File Required function in C library stdlib.h abort(), abs(), atexit(), atof(), atoi(), atol(), bsearch(), calloc(), div(), exit(), free(), getenv(), labs(), ldiv(), malloc(), mblen(), qsort(), rand(), realloc(), srand(), strtod(), strtol(), strtoul(), system() string.
The C and C++ Libraries 4.14 C library extensions This section describes the ARM-specific library extensions and functions defined by the C99 draft standard (ISO/IEC 9899:1999E). The extensions are summarized in Table 4-22. Table 4-22 Extensions 4.14.1 Function Header file definition Extension atoll() stdlib.h C99 draft standard strtoll() on page 4-100 stdlib.h C99 draft standard strtoull() on page 4-100 stdlib.h C99 draft standard snprintf() on page 4-100 stdio.
The C and C++ Libraries 4.14.2 strtoll() The strtoll() function converts a string in an arbitrary base to an integer, similar to the ANSI function strtol(), but returning a long long result. Like strtol(), the parameter endptr can point to a location in which to store a pointer to the end of the translated string, or can be NULL. The parameter base must contain the number base. Setting base to zero indicates that the base is to be selected in the same way as atoll().
The C and C++ Libraries The bufsize parameter specifies the number of characters of buffer that the function can write into, including the terminating null. is an ANSI header file, but the function is not allowed by the ANSI C library standard. It is therefore not available if you use the compilers with the -strict option. Syntax int vsnprintf(char *buffer, 4.14.
The C and C++ Libraries alloca() must not be called through a function pointer. You must take care when using alloca() and setjmp() in the same function, because memory allocated by alloca() between calling setjmp() and longjmp() is deallocated by the call to longjmp(). This function is a common nonstandard extension to many C libraries. Syntax void* alloca(size_t size) 4.14.9 _fisatty() The _fisatty() functiondetermines whether the given stdio stream is attached to a terminal device or a normal file.
The C and C++ Libraries Example 4-20 heapstats output 32272 bytes in 2 free blocks (avge size 16136) 1 blocks 2^12+1 to 2^13 1 blocks 2^13+1 to 2^14 The function outputs its results by calling the output function dprint, which must work like fprintf(). The first parameter passed to dprint is the supplied pointer param. You can pass fprintf() itself, provided you cast it to the right function pointer type. This type is defined as a typedef for convenience. It is called __heapprt.
The C and C++ Libraries 4.14.11 __heapvalid() The __heapvalid() functionperforms a consistency check on the heap. It outputs detailed information about every free block if the verbose parameter is nonzero, and only output errors otherwise. The function outputs its results by calling the output function dprint, which must work like fprintf(). The first parameter passed to dprint is the supplied pointer param. You can pass fprintf() itself, provided you cast it to the right function pointer type.
The C and C++ Libraries 4.15 Library naming conventions The filename identifies how the variant was built as follows: root_.
The C and C++ Libraries c_t__un Thumb, no stack checking, not reentrant (base PCS). The standard FPLIB names are f_{a,t}[fm, vp, _m, _p] f_afm ARM, FPA, mixed-endian double f_avp ARM, VFP, pure-endian double f_a_m ARM, soft FPA, mixed-endian f_a_p ARM, soft VFP, pure-endian f_a ARM, used with -fpu none f_tfm Thumb, FPA, mixed-endian double f_tvp Thumb, VFP, pure-endian double f_t_m Thumb, soft FPA, mixed-endian double f_t_p Thumb, soft FPA, pure-endian double f_t Thumb, used with -fpu none.
The C and C++ Libraries m_t_ps m_t_pu Thumb, soft FPA, pure-endian, stack checking Thumb, soft FPA, pure-endian, no stack checking. See Specifying the target processor or architecture on page 2-19 for details on selecting a specific architecture or processor selection. ARM DUI 0067D Copyright © 1999-2001 ARM Limited. All rights reserved.
The C and C++ Libraries 4-108 Copyright © 1999-2001 ARM Limited. All rights reserved.
Chapter 5 Floating-point Support This chapter describes the ARM support for floating-point computations. It contains the following sections: • About floating-point support on page 5-2 • The software floating-point library, fplib on page 5-3 • Controlling the floating-point environment on page 5-8 • The math library, mathlib on page 5-24 • IEEE 754 arithmetic on page 5-30. ARM DUI 0067D Copyright © 1999-2001 ARM Limited. All rights reserved.
Floating-point Support 5.1 About floating-point support The ARM floating-point environment is an implementation of the IEEE 754 standard for binary floating-point arithmetic. See IEEE 754 arithmetic on page 5-30 for details of the ARM implementation of the standard. An ARM system might have: • a Vector Floating-Point (VFP) coprocessor • a Floating-Point Accelerator (FPA) coprocessor • no floating-point hardware.
Floating-point Support 5.2 The software floating-point library, fplib When programs are compiled to use a floating-point coprocessor, they perform basic floating-point arithmetic (for example addition and multiplication) by means of floating-point machine instructions for the target coprocessor. When programs are compiled to use software floating-point, there is no floating-point instruction set available, and so the ARM libraries have to provide a set of procedure calls to do floating-point arithmetic.
Floating-point Support 5.2.1 Arithmetic on numbers in a particular format The routines in Table 5-1 perform arithmetic on numbers in a particular format. Arguments and results are always in the same format.
Floating-point Support 5.2.2 Conversions between floats, doubles, and ints The routines in Table 5-2 perform conversions between number formats, excluding long longs.
Floating-point Support 5.2.3 Conversions between long longs and other number formats The routines in Table 5-3 perform conversions between long longs and other number formats.
Floating-point Support 5.2.4 Floating-point comparisons The routines in Table 5-4 perform comparisons between floating-point numbers.
Floating-point Support 5.3 Controlling the floating-point environment This section describes the functions you can use to control the ARM floating-point environment. With these functions, you can change the rounding mode, enable and disable trapping of exceptions, and install your own custom exception trap handlers. ARM supplies several different interfaces to the floating-point environment, for compatibility and porting ease. 5.3.
Floating-point Support • Bits 22 and 23 control the rounding mode (Table 5-5). Table 5-5 Rounding mode control Bits Rounding mode 00 Round to nearest 01 Round up 10 Round down 11 Round toward zero • Bit 24 enables FZ (Flush to Zero) mode if it is set. In FZ mode, denormals are forced to zero to speed up processing (because denormals can be difficult to work with and slow down floating-point systems). Setting this bit reduces accuracy but might increase speed. • Bits marked R are reserved.
Floating-point Support To untrap the Inexact Result exception: __ieee_status(FE_IEEE_MASK_INEXACT, 0); To clear the Underflow sticky flag: __ieee_status(FE_IEEE_UNDERFLOW, 0); 5.3.2 The __fp_status function Previous versions of the ARM libraries implemented a function called __fp_status, that manipulated a status word in the floating-point environment. ARM still supports this function, for backwards compatibility. It is defined in stdlib.h.
Floating-point Support The fields in Figure 5-2 on page 5-10 are as follows: • Bits 0 to 4 (values 0x1 to 0x10, respectively) are the sticky flags, or cumulative flags, for each exception. The sticky flag for an exception is set to 1 whenever that exception happens and is not trapped. Sticky flags are never cleared by the system, only by the user.
Floating-point Support __fp_status(_fpsr_IXE | _fpsr_UFE | _fpsr_OFE | _fpsr_DZE | _fpsr_IOE, _fpsr_IOE); To untrap the Inexact Result exception: __fp_status(_fpsr_IXE, 0); To clear the Underflow sticky flag: __fp_status(_fpsr_UFC, 0); 5.3.3 Microsoft compatibility functions The following three functions are implemented for compatibility with Microsoft products, to ease porting of floating-point code to the ARM architecture. They are defined in float.h.
Floating-point Support Table 5-7 _controlfp argument macros (continued) Macro Description _EM_UNDERFLOW Bit describing the Underflow exception _EM_INEXACT Bit describing the Inexact Result exception _MCW_RC Mask for the rounding mode field _RC_CHOP Rounding mode value describing Round Toward Zero _RC_UP Rounding mode value describing Round Up _RC_DOWN Rounding mode value describing Round Down _RC_NEAR Rounding mode value describing Round To Nearest Note It is not guaranteed that the values
Floating-point Support The _statusfp function The function _statusfp returns the current value of the exception sticky flags. The macros given in Table 5-7 on page 5-12, for example _EM_INVALID, _EM_ZERODIVIDE, can be used to test bits of the returned result. _statusfp has the following prototype: unsigned _statusfp(void); 5.3.4 C9X-compatible functions In addition to the above functions, ARM also supports a set of functions defined in the C9X draft standard.
Floating-point Support The exception macros are bit fields. The macro FE_ALL_EXCEPT is the bitwise OR of all of them. Handling exception flags C9X provides three functions to clear, test and raise exceptions: void feclearexcept(int excepts); int fetestexcept(int excepts); void feraiseexcept(int excepts); The feclearexcept function clears the sticky flags for the given exceptions.
Floating-point Support The fegetround function returns the current rounding mode, as one of the macros defined above. The fesetround function sets the current rounding mode to the value provided. fesetround returns zero for success, or nonzero if its argument is not a valid rounding mode.
Floating-point Support Then, if the frob() function raises Underflow, it is cleared again by feclearexcept, and so no trap occurs when feupdateenv is called. However, if frob() raises Invalid Operation, the sticky flag is set when feupdateenv is called, and so the trap handler is invoked. This mechanism is provided by C9X because C9X specifies no way to change exception trapping for individual exceptions.
Floating-point Support __softfp__ieee_value_t myhandler(__ieee_value_t op1, __ieee_value_t op2, __ieee_edata_t edata); The parameters to this function are: • op1 and op2 are used to give the operands, or the intermediate result, for the operation that caused the exception: — For the Invalid Operation and Divide by Zero exceptions, the original operands are supplied. — For the Inexact Result exception, all that is supplied is the ordinary result that would have been returned anyway.
Floating-point Support The flags contained in edata are: • edata & FE_EX_RDIR is nonzero if the intermediate result in Underflow was rounded down, and 0 if it was rounded up or not rounded. (The difference between the last two is given in the Inexact Result bit.) This bit is meaningless for any other type of exception. • edata & FE_EX_exception is nonzero if the given exception (INVALID, DIVBYZERO, OVERFLOW, UNDERFLOW or INEXACT) occurred.
Floating-point Support • edata & FE_EX_OUTTYPE_MASK gives the type of the operands to the function, as one of the type values shown in Table 5-9.
Floating-point Support When the operation is a comparison, the result must be returned as if it were an int, and must be one of the four values shown in Table 5-11. Input and output types are the same for all operations except Compare and Convert.
Floating-point Support /* For all other invalid operations, raise SIGFPE as usual */ raise(SIGFPE); } Install the handler function as follows: fenv_t env; fegetenv(&env); env.statusword |= FE_IEEE_MASK_INVALID; env.invalid_handler = myhandler; fesetenv(&env); After the handler is installed, dividing 0.0 by 0.0 returns 1.0. Exception trap handling by signals If an exception is trapped but the trap handler address is set to NULL, a default trap handler is used.
Floating-point Support __rt_raise is declared in rt_misc.h. ARM DUI 0067D Copyright © 1999-2001 ARM Limited. All rights reserved.
Floating-point Support 5.4 The math library, mathlib Trigonometric functions in mathlib use range reduction to bring large arguments within the range 0 to 2π. ARM provides two different range reduction functions. One is accurate to one unit in the last place for any input values, but is larger and slower than the other. The other is reliable enough for almost all purposes and is faster and smaller. The fast and small range reducer is used by default.
Floating-point Support 5.4.1 Inverse hyperbolic functions (acosh, asinh, atanh) double acosh(double x); double asinh(double x); double atanh(double x); These functions are the inverses of the ANSI-required cosh, sinh and tanh: 5.4.2 • Because cosh is a symmetric function (that is, it returns the same value when applied to x or –x), acosh always has a choice of two return values, one positive and one negative. It chooses the positive result.
Floating-point Support 5.4.5 One less than exp(x) (expm1) double expm1(double x); This function computes e to the power x, minus one. It is better to use expm1(x) than exp(x)-1 if x is very near to zero, because expm1 returns a more accurate value. 5.4.6 Determine if a number is finite (finite) int finite(double x); This function returns 1 if x is finite, and 0 if x is infinite or NaN. It does not cause any errors or exceptions. 5.4.
Floating-point Support 5.4.9 Return the exponent of a number (ilogb) int ilogb(double x); This function returns the exponent of x, without any bias, so ilogb(1.0) would return 0, and ilogb(2.0) would return 1, and so on. When applied to 0, ilogb returns -0x7FFFFFFF. When applied to a NaN or an infinity, ilogb returns +0x7FFFFFFF. ilogb causes no exceptions or errors. 5.4.10 Determine if a number is a NaN (isnan) int isnan(double x); This function returns 1 if x is a NaN, and 0 otherwise.
Floating-point Support 5.4.13 Logarithm of one more than x (log1p) double log1p(double x); This function computes the natural logarithm of x + 1. Like expm1, it is better to use this function than log(x+1) because this function is more accurate when x is near zero. 5.4.14 Return the exponent of a number (logb) double logb(double x); This function is similar to ilogb, but returns its result as a double. It can therefore return special results in special cases. • logb(NaN) is a quiet NaN.
Floating-point Support 5.4.18 Scale a number by a power of two (scalb, scalbn) double scalb(double x, double n); double scalbn(double x, int n); These functions return x times two to the power n. The difference between the functions is whether n is passed in as an int or as a double. scalb is the same function as the Scalb function described in the IEEE 754 Appendix. Its behavior when n is not an integer is undefined. 5.4.
Floating-point Support 5.5 IEEE 754 arithmetic The ARM floating-point environment is an implementation of the IEEE 754 standard for binary floating-point arithmetic. This section contains a summary of the standard as it is implemented by ARM. 5.5.1 Basic data types ARM floating-point values are stored in one of two data types, single precision and double precision. In this document these are called float and double. These are the corresponding C types. Single precision A float value is 32 bits wide.
Floating-point Support Numbers stored in the above form are called normalized numbers. The maximum and minimum exponent values, 0 and 255, are special cases. Exponent 255 is used to represent infinity, and store Not a Number (NaN) values. Infinity can occur as a result of dividing by zero, or as a result of computing a value that is too large to store in this format. NaN values are used for special purposes. Infinity is stored by setting Exp to 255 and Frac to all zeros.
Floating-point Support Sample values Some sample float and double bit patterns, together with their mathematical values, are given in Table 5-12 and Table 5-13 on page 5-33. Table 5-12 Sample single-precision floating-point values Float value S Exp Frac Mathematical value Notes 0x3F800000 0 0x7F 000...000 1.0 - 0xBF800000 1 0x7F 000...000 -1.0 - 0x3F800001 0 0x7F 000...001 1.000 000 119 a 0x3F400000 0 0x7E 100...000 0.75 - 0x00800000 0 0x01 000...000 1.
Floating-point Support Table 5-13 Sample double-precision floating-point values Double value S Exp Frac Mathematical value Notes 0x3FF00000 00000000 0 0x3FF 000...000 1.0 - 0xBFF00000 00000000 1 0x3FF 000...000 -1.0 - 0x3FF00000 00000001 0 0x3FF 000...001 1.000 000 000 000 000 222 a 0x3FE80000 00000000 0 0x3FE 100...000 0.75 - 0x00100000 00000000 0 0x001 000...000 2.23*10-308 b 0x00000000 00000001 0 0x000 000...001 4.94*10-324 c 0x7FEFFFFF FFFFFFFF 0 0x7FE 111..
Floating-point Support 5.5.2 Arithmetic and rounding Arithmetic is generally performed by computing the result of an operation as if it were stored exactly (to infinite precision), and then rounding it to fit in the format. Apart from operations whose result already fits exactly into the format (such as adding 1.0 to 1.0), the correct answer is generally somewhere between two representable numbers in the format. The system then chooses one of these two numbers as the rounded result.
Floating-point Support 5.5.3 Exceptions Floating-point arithmetic operations can run into various problems. For example, the result computed might be either too big or too small to fit into the format, or there might be no way to calculate the result (as in trying to take the square root of a negative number, or trying to divide zero by zero). These are known as exceptions, because they indicate unusual or exceptional situations.
Floating-point Support Types of exception The ARM floating-point environment recognizes five different types of exception: • The Invalid Operation exception happens when there is no sensible result for an operation.
Floating-point Support (For readers familiar with the IEEE 754 specification, the ARM choice of implementation options are to detect tininess after rounding, and to detect loss of accuracy as a denormalization loss.) If Underflow is not trapped, the result is rounded to one of the two nearest representable denormal numbers, according to the current rounding mode. The loss of precision is ignored and the system returns the best result it can.
Floating-point Support 5-38 Copyright © 1999-2001 ARM Limited. All rights reserved.
Appendix A Via File Syntax This appendix describes the syntax of via files accepted by the ARM development tools, such as the ARM compilers, linker, assembler, and fromELF. It contains the following sections: • Overview of via files on page A-2 • Syntax on page A-3. ARM DUI 0067D Copyright © 1999-2001 ARM Limited. All rights reserved.
Via File Syntax A.1 Overview of via files Via files are plain text files that contain command-line arguments and options to ARM development tools. You can use via files with most of the ARM command-line tools, including: • the compilers • the assembler • the linker • the ARM librarian. You can specify a via file either from the command line using the -via tool option, or within the CodeWarrior IDE. See the documentation for the individual tool for more information.
Via File Syntax A.2 Syntax Via files must conform to the following syntax rules: • A via file is a text file containing a sequence of words. Each word in the text file is converted into an argument string and passed to the tool. • Words are separated by white space, or the end of a line, except in delimited strings. For example: -split -ropi -split-ropi • -- Treated as two words -- Treated as one word The end of a line is treated as white space.
Via File Syntax • Lines beginning with a semicolon (;) or a hash (#) character as the first non-whitespace character are comment lines. If a semicolon or hash character appears anywhere else in line, it is not treated as the start of a comment. For example: -o objectname.axf ;this is not a comment A comment ends at the end of a line, or at the end of the file. There are no multi-line comments, and there are no part-line comments. A-4 Copyright © 1999-2001 ARM Limited. All rights reserved.
Appendix B Standard C Implementation Definition This appendix gives information required by the ISO C standard for conforming C implementations. It contains the following sections: • ARM DUI 0067D Implementation definition on page B-2. Copyright © 1999-2001 ARM Limited. All rights reserved.
Standard C Implementation Definition B.1 Implementation definition Appendix G of the ISO C standard (IS/IEC 9899:1990 (E)) collates information about portability issues. Subclause G3 lists the behavior that each implementation must document. Note This appendix does not duplicate information that is part of the compiler-specific implementations. See Compiler-specific features on page 3-2. This section provides references where applicable.
Standard C Implementation Definition B.1.1 Translation Diagnostic messages produced by the compiler are of the form: source-file, line-number: severity: error-code: explanation where severity is one of: Warning This is a helpful message from the compiler relatingto a minor violation of the ANSI specification. Error This is a violation of the ANSI specification but the compiler is able to recover by guessing the intention.
Standard C Implementation Definition Interactive device In an unhosted implementation of the ARM C library, the term interactive device might be meaningless. The generic ARM C library supports a pair of devices, both called :tt, intended to handle keyboard input and VDU screen output.
Standard C Implementation Definition >>& filename This appends both stdout and stderr to filename. File redirection is done only if either: B.1.3 • the invoking operating system supports it • the program reads and writes characters and has not replaced the C library functions fputc() and fgetc(). Identifiers See Character sets and identifiers on page 3-21 for details. B.1.4 Characters See Character sets and identifiers on page 3-21 for details. B.1.
Standard C Implementation Definition • whether a plain int bitfield is treated as a signed int bitfield or as an unsigned int bitfield • the order of allocation of bitfields within a unit • whether a bitfield can straddle a storage-unit boundary • the integer type chosen to represent the values of an enumeration type. These implementation details are documented in the relevant sections of C and C++ implementation details on page 3-21. Unions See Unions on page 3-26 for details.
Standard C Implementation Definition B.1.12 Statements The number of case values in a switch statement is limited only by memory. Expression evaluation The compiler performs the usual arithmetic conversions (promotions) set out in the appropriate C or C++ standard before evaluating an expression. • • • Note The compiler can re-order expressions involving only associative and commutative operators of equal precedence, even in the presence of parentheses.
Standard C Implementation Definition B.1.14 Library functions The ANSI C library variants are listed in About the runtime libraries on page 4-2. The precise nature of each C library is unique to the particular implementation. The generic ARM C library has, or supports, the following features: • The macro NULL expands to the integer constant 0. • If a program redefines a reserved external identifier such as printf, an error might occur when the program is linked with the standard libraries.
Appendix C Standard C++ Implementation Definition The majority of the language features described in the ISO/IEC standard for C++ are supported by the ARM C++ compilers. This appendix lists the C++ language features defined in the standard, and states whether or not that language feature is supported by ARM C++. Note ARM C++ differs from ISO/IEC because the compliance requirements for Embedded C++ (EC++) differ from the requirements for ISO/IEC C++.
Standard C++ Implementation Definition C.1 EC++ support ARM C++ supports all features required by the definition of Embedded C++ except for argument-dependent name lookup (Koenig lookup). C-2 Copyright © 1999-2001 ARM Limited. All rights reserved.
Standard C++ Implementation Definition C.2 Integral conversion During integral conversion, if the destination type is signed, the value is unchanged if it can be represented in the destination type and bitfield width. Otherwise, the value is truncated to fit the size of the destination type. Note This section is related to section 4.7 of the ISO/IEC standard. ARM DUI 0067D Copyright © 1999-2001 ARM Limited. All rights reserved.
Standard C++ Implementation Definition C.3 Calling a pure virtual function If a pure virtual function is called, the signal SIGPVFN is raised. The default signal handler prints an error message and exits. See __default_signal_handler() on page 4-54. C-4 Copyright © 1999-2001 ARM Limited. All rights reserved.
Standard C++ Implementation Definition C.4 Minor features of language support Table C-1 shows the minor features of the language supported by this release of ARM C++. Table C-1 Minor feature support for language Minor feature Support atexit Implemented as defined in The Annotated C++ Reference, Addison-Wesley, 1991. Namespaces No. Runtime type identification (RTTI) Partial. Typeid is supported for static types and expressions with non-polymorphic type. See also the restrictions on new style casts.
Standard C++ Implementation Definition Table C-1 Minor feature support for language (continued) C-6 Minor feature Support typename keyword Yes. Member templates Yes. Partial specialization for class template Yes. Partial ordering of function templates Yes. Universal character names No. Koenig lookup No. Copyright © 1999-2001 ARM Limited. All rights reserved.
Standard C++ Implementation Definition C.5 Major features of language support Table C-2 shows the major features of the language supported by this release of ARM C++.
Standard C++ Implementation Definition C.6 Standard C++ library implementation definition Version 2.01.01 of the Rogue Wave library provides a subset of the library defined in the standard. There are slight differences from the December 1996 version of the ISO/IEC standard. For details of the implementation definition, see Standard C++ library implementation definition on page 4-97. The library can be used with user-defined functions to produce target-dependent applications.
Appendix D C and C++ Compiler Implementation Limits This appendix list the implementation limits for the ARM C and C++ compilers. It contains the following sections: • C++ ISO/IEC standard limits on page D-2 • Internal limits on page D-4 • Limits for integral numbers on page D-5 • Limits for floating-point numbers on page D-6. ARM DUI 0067D Copyright © 1999-2001 ARM Limited. All rights reserved.
C and C++ Compiler Implementation Limits D.1 C++ ISO/IEC standard limits The ISO/IEC C++ standard recommends minimum limits that a conforming compiler must accept. You must be aware of these when porting applications between compilers. A summary is given in Table D-1. A limit of memory indicates that no limit is imposed by the ARM compilers, other than that imposed by the available memory.
C and C++ Compiler Implementation Limits Table D-1 Implementation limits (continued) Description Recommended ARM Case labels for a switch statement, excluding those for any nested switch statements. 16384 memory Data members in a single class, structure, or union.
C and C++ Compiler Implementation Limits D.2 Internal limits In addition to the limits described in Table D-1 on page D-2, the compiler has internal limits as listed in Table D-2. Table D-2 Internal limits Description ARM Maximum number of lines in a C source file. (A file with more lines gives wrapped line numbers in messages because the internal format for line numbers is a 16-bit unsigned short.) 65536 Maximum number of relocatable references in a single translation unit.
C and C++ Compiler Implementation Limits D.3 Limits for integral numbers Table D-3 gives the ranges for integral numbers in ARM C and C++. The third column of the table gives the numerical value of the range endpoint. The fourth column gives the bit pattern (in hexadecimal) that would be interpreted as this value by the ARM compilers. When entering a constant, choose the size and sign with care. Constants are interpreted differently in decimal and hexadecimal/octal.
C and C++ Compiler Implementation Limits D.4 Limits for floating-point numbers Table D-4 and Table D-5 on page D-7 give the characteristics, ranges, and limits for floating-point numbers in ARM and Thumb compilers. Note When a floating-point number is converted to a shorter floating-point number, it is rounded to the nearest representable number. The properties of floating-point arithmetic accord with IEEE 754. Table D-4 Floating-point limits Constant Meaning FLT_MAX Maximum value of float 3.
C and C++ Compiler Implementation Limits Table D-4 Floating-point limits (continued) Constant Meaning Value DBL_MIN_10_EXP Minimum value of base 10 exponent for type double LDBL_MAX_10_EXP Maximum value of base 10 exponent for type long double 308 LDBL_MIN_10_EXP Minimum value of base 10 exponent for type long double –307 –307 Table D-5 Other floating-point characteristics Constant Meaning FLT_RADIX Base (radix) of the ARM floating-point number representation FLT_ROUNDS Rounding mode for f
C and C++ Compiler Implementation Limits D-8 Copyright © 1999-2001 ARM Limited. All rights reserved.
Glossary ADS See ARM Developer Suite. ANSI American National Standards Institute. An organization that specifies standards for, among other things, computer software. API Application Program Interface. Architecture The term used to identify a group of processors that have similar characteristics. ARM Developer Suite A suite of applications, together with supporting documentation and examples, that enable you to write and debug applications for the ARM family of RISC processors.
Glossary Coprocessor An additional processor which is used for certain operations. Usually used for floating-point math calculations, signal processing, or memory management. Current place In compiler terminology, the directory which contains files to be included in the compilation process. Debugger An application that monitors and controls the execution of a second application. Usually used to find errors in the application program flow.
Glossary Inline Functions that are repeated in code each time they are used rather than having a common subroutine. Assembler code placed within a C or C++ program. See also Output sections. Interrupt A change in the normal processing sequence of an application caused by, for example, an external signal. Interworking Producing an application that uses both ARM and Thumb code. Library A collection of assembler or compiler output objects grouped together into a single repository.
Glossary Scatter-loading Assigning the address and grouping of code and data sections individually rather than using single large blocks. Scope The accessibility of a function or variable at a particular point in the application code. Symbols which have global scope are always accessible. Symbols with local or private scope are only accessible to code in the same subroutine or object.
Index A abort() 4-22, 4-91, 4-96 Access control error 2-37 acosh function 5-25 Alignment bitfields, C and C++ 3-30 data types, C and C++ 3-23 field alignment, C and C++ 3-27 structures, C and C++ 3-27 alloca() 4-13, 4-59, 4-101 ANSI C library Angel definitions 4-7 API definitions 4-11 avoiding semihosting 4-10 build options 4-3 dependencies 4-75 directory structure 4-4 error handling 4-51 error handling functions 4-51 execution environment 4-20 FILEHANDLE 4-78 implementation definition 4-91 ARM DUI 0067D
Index B nothrow, new C-5 overlapping of bitfields 3-29 __backspace() 4-10, 4-15, 4-76 pointers, subtraction 3-25 Base classes 3-27 runtime type identification C-5 Berkeley UNIX signals 4-55 search paths 2-6 Standard C++ Bessel functions 5-27, 5-29 and error messages 2-37 Bitfields 3-30 inline assembler 3-18 overlapping, C and C++ 3-29 limits D-2 bool, C++ C-5 static member constants C-5 byte order 2-29 structures, see Structures, C and C++ virtual functions 3-27 wchar_t C-5 wide characters C-5 C calloc()
Index -Wg 2-32 -Wi 2-32 -Wk 2-27 -Wl 2-33 -Wm 2-33 -Wn 2-33 -Wo 2-33 -Wp 2-33 -Wq 2-33 -Wr 2-33 -Ws 2-34 -Wt 2-34 -Wu 2-34 -Wv 2-34 -Wx 2-34 -Wy 2-35 -zas 2-30 -zc 2-30 -zo 2-28 Compilers ANSI standard C 2-14 ANSI standard C++ 2-14 architecture, specifying 2-19 big-endian code 2-29 C and C++ 2-1 code generation 2-24 debug tables 2-22 defining symbols 2-16 EC++ 2-14 errors, redirecting 2-11 header files 2-6 inline assemblers 2-3 invoking 2-9 keyboard input 2-11 language, setting source 2-14 library support
Index F ferror() 4-10, 4-15, 4-76 fgetc() 4-10, 4-15, 4-76 fgets() 4-10, 4-77 Field alignment, C and C++ 3-27 FILEHANDLE 4-78 Files header 2-4 include 2-6 in-memory file system 2-6 naming conventions 2-4 object 2-5 redirecting to 2-11 source 2-4 via options 2-10 _findlocale() 4-29, 4-42 _find_locale() 4-29 _fisatty() 4-102 float type 5-30 Floating-point bit patterns 5-32 chop 5-34 comparison 5-7 constants 3-19 custom trap handlers 5-17 C9X draft standard 5-14, 5-17 denormal 5-32 double precision 5-31 envir
Index __Heap_Stats() 4-65 __Heap_Valid() 4-65 Help compiler option 2-11 Hypotenuse function 5-26 I IEEE format 3-24 IEEE 754 arithmetic 5-30 __ieee_status 5-8 Image size 2-24 Implementation C library 4-91 standards, C and C++ D-1 Implicit constructor warning 2-32 narrowing warning 2-33 return warning 2-34 _init_alloc() 4-16 Inline assemblers 2-3 inline, C and C++ keyword 3-8 In-memory filing system 2-15 mem directory 2-6, 2-15 Internal limits, compilers D-4 Interrupt latency 2-26 Invoking the compiler 2-9
Index Natural alignment, C and C++ 3-23 New array, C++ C-5 New style casts, C++ C-5 nextafter function 5-28 Normalized 5-32 Nothrow new, C++ C-5 O Optimization common sub-expression elimination 3-6 compiler options 2-24 controlling 2-24 packed keyword 3-14 and pure functions 3-6 structure packing 3-12 volatile keyword 3-15 Overlapping, of bitfields, C and C++ 3-29 Overloaded functions, C and C++ argument limits D-2 P Packed structures, C and C++ 3-13, 3-28 packed, C and C++ keyword 3-28 Padding C and C++
Index C++ 2-3 EC++ 2-3 strict 2-14 strict ANSI C 2-14 Specifying additional checks 2-35 function declaration keywords 3-6 preprocessor options 2-15 search paths 2-15 structure alignment 2-30 warning messages 2-31 Speed and structure packing 3-12 sprintf() 4-15 srand() 4-5, 4-15 sscanf() 4-15 Stack checking 3-4 C and C++ 2-12, 2-14 Standard C++ support for C-1 Standard error function 5-25 Standards C and C++ 2-2 C library implementation 4-91 C++ implementation C-1 C++ language support C-1 C++ library implem
Index implicit conversion 2-33 implicit narrowing cast 2-33 implicit return 2-34 implicit virtual 2-33 initialization order 2-33 inventing extern 2-32 lower precision 2-33 non-ANSI include 2-33 padding inserted in structure 2-34 pointer casts 2-32 specifying 2-31 specifying additional checks 2-35 unguarded header 2-32 unused declaration 2-34 unused this 2-34 wchar_t, C++ C-5 Wide characters, C++ C-5 Symbols $ in identifiers 3-17 Index-8 Copyright © 1999-2001 ARM Limited. All rights reserved.