/* CPP Library - lexical analysis. Copyright (C) 2000-2020 Free Software Foundation, Inc. Contributed by Per Bothner, 1994-95. Based on CCCP program by Paul Rubin, June 1986 Adapted to ANSI C, Richard Stallman, Jan 1987 Broken out to separate file, Zack Weinberg, Mar 2000 This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 3, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program; see the file COPYING3. If not see . */ #include "config.h" #include "system.h" #include "cpplib.h" #include "internal.h" enum spell_type { SPELL_OPERATOR = 0, SPELL_IDENT, SPELL_LITERAL, SPELL_NONE }; struct token_spelling { enum spell_type category; const unsigned char *name; }; static const unsigned char *const digraph_spellings[] = { UC"%:", UC"%:%:", UC"<:", UC":>", UC"<%", UC"%>" }; #define OP(e, s) { SPELL_OPERATOR, UC s }, #define TK(e, s) { SPELL_ ## s, UC #e }, static const struct token_spelling token_spellings[N_TTYPES] = { TTYPE_TABLE }; #undef OP #undef TK #define TOKEN_SPELL(token) (token_spellings[(token)->type].category) #define TOKEN_NAME(token) (token_spellings[(token)->type].name) static void add_line_note (cpp_buffer *, const uchar *, unsigned int); static int skip_line_comment (cpp_reader *); static void skip_whitespace (cpp_reader *, cppchar_t); static void lex_string (cpp_reader *, cpp_token *, const uchar *); static void save_comment (cpp_reader *, cpp_token *, const uchar *, cppchar_t); static void store_comment (cpp_reader *, cpp_token *); static void create_literal (cpp_reader *, cpp_token *, const uchar *, unsigned int, enum cpp_ttype); static bool warn_in_comment (cpp_reader *, _cpp_line_note *); static int name_p (cpp_reader *, const cpp_string *); static tokenrun *next_tokenrun (tokenrun *); static _cpp_buff *new_buff (size_t); /* Utility routine: Compares, the token TOKEN to the NUL-terminated string STRING. TOKEN must be a CPP_NAME. Returns 1 for equal, 0 for unequal. */ int cpp_ideq (const cpp_token *token, const char *string) { if (token->type != CPP_NAME) return 0; return !ustrcmp (NODE_NAME (token->val.node.node), (const uchar *) string); } /* Record a note TYPE at byte POS into the current cleaned logical line. */ static void add_line_note (cpp_buffer *buffer, const uchar *pos, unsigned int type) { if (buffer->notes_used == buffer->notes_cap) { buffer->notes_cap = buffer->notes_cap * 2 + 200; buffer->notes = XRESIZEVEC (_cpp_line_note, buffer->notes, buffer->notes_cap); } buffer->notes[buffer->notes_used].pos = pos; buffer->notes[buffer->notes_used].type = type; buffer->notes_used++; } /* Fast path to find line special characters using optimized character scanning algorithms. Anything complicated falls back to the slow path below. Since this loop is very hot it's worth doing these kinds of optimizations. One of the paths through the ifdefs should provide const uchar *search_line_fast (const uchar *s, const uchar *end); Between S and END, search for \n, \r, \\, ?. Return a pointer to the found character. Note that the last character of the buffer is *always* a newline, as forced by _cpp_convert_input. This fact can be used to avoid explicitly looking for the end of the buffer. */ /* Configure gives us an ifdef test. */ #ifndef WORDS_BIGENDIAN #define WORDS_BIGENDIAN 0 #endif /* We'd like the largest integer that fits into a register. There's nothing in that gives us that. For most hosts this is unsigned long, but MS decided on an LLP64 model. Thankfully when building with GCC we can get the "real" word size. */ #ifdef __GNUC__ typedef unsigned int word_type __attribute__((__mode__(__word__))); #else typedef unsigned long word_type; #endif /* The code below is only expecting sizes 4 or 8. Die at compile-time if this expectation is violated. */ typedef char check_word_type_size [(sizeof(word_type) == 8 || sizeof(word_type) == 4) * 2 - 1]; /* Return X with the first N bytes forced to values that won't match one of the interesting characters. Note that NUL is not interesting. */ static inline word_type acc_char_mask_misalign (word_type val, unsigned int n) { word_type mask = -1; if (WORDS_BIGENDIAN) mask >>= n * 8; else mask <<= n * 8; return val & mask; } /* Return X replicated to all byte positions within WORD_TYPE. */ static inline word_type acc_char_replicate (uchar x) { word_type ret; ret = (x << 24) | (x << 16) | (x << 8) | x; if (sizeof(word_type) == 8) ret = (ret << 16 << 16) | ret; return ret; } /* Return non-zero if some byte of VAL is (probably) C. */ static inline word_type acc_char_cmp (word_type val, word_type c) { #if defined(__GNUC__) && defined(__alpha__) /* We can get exact results using a compare-bytes instruction. Get (val == c) via (0 >= (val ^ c)). */ return __builtin_alpha_cmpbge (0, val ^ c); #else word_type magic = 0x7efefefeU; if (sizeof(word_type) == 8) magic = (magic << 16 << 16) | 0xfefefefeU; magic |= 1; val ^= c; return ((val + magic) ^ ~val) & ~magic; #endif } /* Given the result of acc_char_cmp is non-zero, return the index of the found character. If this was a false positive, return -1. */ static inline int acc_char_index (word_type cmp ATTRIBUTE_UNUSED, word_type val ATTRIBUTE_UNUSED) { #if defined(__GNUC__) && defined(__alpha__) && !WORDS_BIGENDIAN /* The cmpbge instruction sets *bits* of the result corresponding to matches in the bytes with no false positives. */ return __builtin_ctzl (cmp); #else unsigned int i; /* ??? It would be nice to force unrolling here, and have all of these constants folded. */ for (i = 0; i < sizeof(word_type); ++i) { uchar c; if (WORDS_BIGENDIAN) c = (val >> (sizeof(word_type) - i - 1) * 8) & 0xff; else c = (val >> i * 8) & 0xff; if (c == '\n' || c == '\r' || c == '\\' || c == '?') return i; } return -1; #endif } /* A version of the fast scanner using bit fiddling techniques. For 32-bit words, one would normally perform 16 comparisons and 16 branches. With this algorithm one performs 24 arithmetic operations and one branch. Whether this is faster with a 32-bit word size is going to be somewhat system dependent. For 64-bit words, we eliminate twice the number of comparisons and branches without increasing the number of arithmetic operations. It's almost certainly going to be a win with 64-bit word size. */ static const uchar * search_line_acc_char (const uchar *, const uchar *) ATTRIBUTE_UNUSED; static const uchar * search_line_acc_char (const uchar *s, const uchar *end ATTRIBUTE_UNUSED) { const word_type repl_nl = acc_char_replicate ('\n'); const word_type repl_cr = acc_char_replicate ('\r'); const word_type repl_bs = acc_char_replicate ('\\'); const word_type repl_qm = acc_char_replicate ('?'); unsigned int misalign; const word_type *p; word_type val, t; /* Align the buffer. Mask out any bytes from before the beginning. */ p = (word_type *)((uintptr_t)s & -sizeof(word_type)); val = *p; misalign = (uintptr_t)s & (sizeof(word_type) - 1); if (misalign) val = acc_char_mask_misalign (val, misalign); /* Main loop. */ while (1) { t = acc_char_cmp (val, repl_nl); t |= acc_char_cmp (val, repl_cr); t |= acc_char_cmp (val, repl_bs); t |= acc_char_cmp (val, repl_qm); if (__builtin_expect (t != 0, 0)) { int i = acc_char_index (t, val); if (i >= 0) return (const uchar *)p + i; } val = *++p; } } /* Disable on Solaris 2/x86 until the following problem can be properly autoconfed: The Solaris 10+ assembler tags objects with the instruction set extensions used, so SSE4.2 executables cannot run on machines that don't support that extension. */ #if (GCC_VERSION >= 4005) && (__GNUC__ >= 5 || !defined(__PIC__)) && (defined(__i386__) || defined(__x86_64__)) && !(defined(__sun__) && defined(__svr4__)) /* Replicated character data to be shared between implementations. Recall that outside of a context with vector support we can't define compatible vector types, therefore these are all defined in terms of raw characters. */ static const char repl_chars[4][16] __attribute__((aligned(16))) = { { '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n' }, { '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r' }, { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' }, { '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?' }, }; /* A version of the fast scanner using MMX vectorized byte compare insns. This uses the PMOVMSKB instruction which was introduced with "MMX2", which was packaged into SSE1; it is also present in the AMD MMX extension. Mark the function as using "sse" so that we emit a real "emms" instruction, rather than the 3dNOW "femms" instruction. */ static const uchar * #ifndef __SSE__ __attribute__((__target__("sse"))) #endif search_line_mmx (const uchar *s, const uchar *end ATTRIBUTE_UNUSED) { typedef char v8qi __attribute__ ((__vector_size__ (8))); typedef int __m64 __attribute__ ((__vector_size__ (8), __may_alias__)); const v8qi repl_nl = *(const v8qi *)repl_chars[0]; const v8qi repl_cr = *(const v8qi *)repl_chars[1]; const v8qi repl_bs = *(const v8qi *)repl_chars[2]; const v8qi repl_qm = *(const v8qi *)repl_chars[3]; unsigned int misalign, found, mask; const v8qi *p; v8qi data, t, c; /* Align the source pointer. While MMX doesn't generate unaligned data faults, this allows us to safely scan to the end of the buffer without reading beyond the end of the last page. */ misalign = (uintptr_t)s & 7; p = (const v8qi *)((uintptr_t)s & -8); data = *p; /* Create a mask for the bytes that are valid within the first 16-byte block. The Idea here is that the AND with the mask within the loop is "free", since we need some AND or TEST insn in order to set the flags for the branch anyway. */ mask = -1u << misalign; /* Main loop processing 8 bytes at a time. */ goto start; do { data = *++p; mask = -1; start: t = __builtin_ia32_pcmpeqb(data, repl_nl); c = __builtin_ia32_pcmpeqb(data, repl_cr); t = (v8qi) __builtin_ia32_por ((__m64)t, (__m64)c); c = __builtin_ia32_pcmpeqb(data, repl_bs); t = (v8qi) __builtin_ia32_por ((__m64)t, (__m64)c); c = __builtin_ia32_pcmpeqb(data, repl_qm); t = (v8qi) __builtin_ia32_por ((__m64)t, (__m64)c); found = __builtin_ia32_pmovmskb (t); found &= mask; } while (!found); __builtin_ia32_emms (); /* FOUND contains 1 in bits for which we matched a relevant character. Conversion to the byte index is trivial. */ found = __builtin_ctz(found); return (const uchar *)p + found; } /* A version of the fast scanner using SSE2 vectorized byte compare insns. */ static const uchar * #ifndef __SSE2__ __attribute__((__target__("sse2"))) #endif search_line_sse2 (const uchar *s, const uchar *end ATTRIBUTE_UNUSED) { typedef char v16qi __attribute__ ((__vector_size__ (16))); const v16qi repl_nl = *(const v16qi *)repl_chars[0]; const v16qi repl_cr = *(const v16qi *)repl_chars[1]; const v16qi repl_bs = *(const v16qi *)repl_chars[2]; const v16qi repl_qm = *(const v16qi *)repl_chars[3]; unsigned int misalign, found, mask; const v16qi *p; v16qi data, t; /* Align the source pointer. */ misalign = (uintptr_t)s & 15; p = (const v16qi *)((uintptr_t)s & -16); data = *p; /* Create a mask for the bytes that are valid within the first 16-byte block. The Idea here is that the AND with the mask within the loop is "free", since we need some AND or TEST insn in order to set the flags for the branch anyway. */ mask = -1u << misalign; /* Main loop processing 16 bytes at a time. */ goto start; do { data = *++p; mask = -1; start: t = __builtin_ia32_pcmpeqb128(data, repl_nl); t |= __builtin_ia32_pcmpeqb128(data, repl_cr); t |= __builtin_ia32_pcmpeqb128(data, repl_bs); t |= __builtin_ia32_pcmpeqb128(data, repl_qm); found = __builtin_ia32_pmovmskb128 (t); found &= mask; } while (!found); /* FOUND contains 1 in bits for which we matched a relevant character. Conversion to the byte index is trivial. */ found = __builtin_ctz(found); return (const uchar *)p + found; } #ifdef HAVE_SSE4 /* A version of the fast scanner using SSE 4.2 vectorized string insns. */ static const uchar * #ifndef __SSE4_2__ __attribute__((__target__("sse4.2"))) #endif search_line_sse42 (const uchar *s, const uchar *end) { typedef char v16qi __attribute__ ((__vector_size__ (16))); static const v16qi search = { '\n', '\r', '?', '\\' }; uintptr_t si = (uintptr_t)s; uintptr_t index; /* Check for unaligned input. */ if (si & 15) { v16qi sv; if (__builtin_expect (end - s < 16, 0) && __builtin_expect ((si & 0xfff) > 0xff0, 0)) { /* There are less than 16 bytes left in the buffer, and less than 16 bytes left on the page. Reading 16 bytes at this point might generate a spurious page fault. Defer to the SSE2 implementation, which already handles alignment. */ return search_line_sse2 (s, end); } /* ??? The builtin doesn't understand that the PCMPESTRI read from memory need not be aligned. */ sv = __builtin_ia32_loaddqu ((const char *) s); index = __builtin_ia32_pcmpestri128 (search, 4, sv, 16, 0); if (__builtin_expect (index < 16, 0)) goto found; /* Advance the pointer to an aligned address. We will re-scan a few bytes, but we no longer need care for reading past the end of a page, since we're guaranteed a match. */ s = (const uchar *)((si + 15) & -16); } /* Main loop, processing 16 bytes at a time. */ #ifdef __GCC_ASM_FLAG_OUTPUTS__ while (1) { char f; /* By using inline assembly instead of the builtin, we can use the result, as well as the flags set. */ __asm ("%vpcmpestri\t$0, %2, %3" : "=c"(index), "=@ccc"(f) : "m"(*s), "x"(search), "a"(4), "d"(16)); if (f) break; s += 16; } #else s -= 16; /* By doing the whole loop in inline assembly, we can make proper use of the flags set. */ __asm ( ".balign 16\n" "0: add $16, %1\n" " %vpcmpestri\t$0, (%1), %2\n" " jnc 0b" : "=&c"(index), "+r"(s) : "x"(search), "a"(4), "d"(16)); #endif found: return s + index; } #else /* Work around out-dated assemblers without sse4 support. */ #define search_line_sse42 search_line_sse2 #endif /* Check the CPU capabilities. */ #include "../gcc/config/i386/cpuid.h" typedef const uchar * (*search_line_fast_type) (const uchar *, const uchar *); static search_line_fast_type search_line_fast; #define HAVE_init_vectorized_lexer 1 static inline void init_vectorized_lexer (void) { unsigned dummy, ecx = 0, edx = 0; search_line_fast_type impl = search_line_acc_char; int minimum = 0; #if defined(__SSE4_2__) minimum = 3; #elif defined(__SSE2__) minimum = 2; #elif defined(__SSE__) minimum = 1; #endif if (minimum == 3) impl = search_line_sse42; else if (__get_cpuid (1, &dummy, &dummy, &ecx, &edx) || minimum == 2) { if (minimum == 3 || (ecx & bit_SSE4_2)) impl = search_line_sse42; else if (minimum == 2 || (edx & bit_SSE2)) impl = search_line_sse2; else if (minimum == 1 || (edx & bit_SSE)) impl = search_line_mmx; } else if (__get_cpuid (0x80000001, &dummy, &dummy, &dummy, &edx)) { if (minimum == 1 || (edx & (bit_MMXEXT | bit_CMOV)) == (bit_MMXEXT | bit_CMOV)) impl = search_line_mmx; } search_line_fast = impl; } #elif defined(_ARCH_PWR8) && defined(__ALTIVEC__) /* A vection of the fast scanner using AltiVec vectorized byte compares and VSX unaligned loads (when VSX is available). This is otherwise the same as the pre-GCC 5 version. */ ATTRIBUTE_NO_SANITIZE_UNDEFINED static const uchar * search_line_fast (const uchar *s, const uchar *end ATTRIBUTE_UNUSED) { typedef __attribute__((altivec(vector))) unsigned char vc; const vc repl_nl = { '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n' }; const vc repl_cr = { '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r' }; const vc repl_bs = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' }; const vc repl_qm = { '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', }; const vc zero = { 0 }; vc data, t; /* Main loop processing 16 bytes at a time. */ do { vc m_nl, m_cr, m_bs, m_qm; data = __builtin_vec_vsx_ld (0, s); s += 16; m_nl = (vc) __builtin_vec_cmpeq(data, repl_nl); m_cr = (vc) __builtin_vec_cmpeq(data, repl_cr); m_bs = (vc) __builtin_vec_cmpeq(data, repl_bs); m_qm = (vc) __builtin_vec_cmpeq(data, repl_qm); t = (m_nl | m_cr) | (m_bs | m_qm); /* T now contains 0xff in bytes for which we matched one of the relevant characters. We want to exit the loop if any byte in T is non-zero. Below is the expansion of vec_any_ne(t, zero). */ } while (!__builtin_vec_vcmpeq_p(/*__CR6_LT_REV*/3, t, zero)); /* Restore s to to point to the 16 bytes we just processed. */ s -= 16; { #define N (sizeof(vc) / sizeof(long)) union { vc v; /* Statically assert that N is 2 or 4. */ unsigned long l[(N == 2 || N == 4) ? N : -1]; } u; unsigned long l, i = 0; u.v = t; /* Find the first word of T that is non-zero. */ switch (N) { case 4: l = u.l[i++]; if (l != 0) break; s += sizeof(unsigned long); l = u.l[i++]; if (l != 0) break; s += sizeof(unsigned long); /* FALLTHRU */ case 2: l = u.l[i++]; if (l != 0) break; s += sizeof(unsigned long); l = u.l[i]; } /* L now contains 0xff in bytes for which we matched one of the relevant characters. We can find the byte index by finding its bit index and dividing by 8. */ #ifdef __BIG_ENDIAN__ l = __builtin_clzl(l) >> 3; #else l = __builtin_ctzl(l) >> 3; #endif return s + l; #undef N } } #elif (GCC_VERSION >= 4005) && defined(__ALTIVEC__) && defined (__BIG_ENDIAN__) /* A vection of the fast scanner using AltiVec vectorized byte compares. This cannot be used for little endian because vec_lvsl/lvsr are deprecated for little endian and the code won't work properly. */ /* ??? Unfortunately, attribute(target("altivec")) is not yet supported, so we can't compile this function without -maltivec on the command line (or implied by some other switch). */ static const uchar * search_line_fast (const uchar *s, const uchar *end ATTRIBUTE_UNUSED) { typedef __attribute__((altivec(vector))) unsigned char vc; const vc repl_nl = { '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n', '\n' }; const vc repl_cr = { '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r', '\r' }; const vc repl_bs = { '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\', '\\' }; const vc repl_qm = { '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', '?', }; const vc ones = { -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, -1, }; const vc zero = { 0 }; vc data, mask, t; /* Altivec loads automatically mask addresses with -16. This lets us issue the first load as early as possible. */ data = __builtin_vec_ld(0, (const vc *)s); /* Discard bytes before the beginning of the buffer. Do this by beginning with all ones and shifting in zeros according to the mis-alignment. The LVSR instruction pulls the exact shift we want from the address. */ mask = __builtin_vec_lvsr(0, s); mask = __builtin_vec_perm(zero, ones, mask); data &= mask; /* While altivec loads mask addresses, we still need to align S so that the offset we compute at the end is correct. */ s = (const uchar *)((uintptr_t)s & -16); /* Main loop processing 16 bytes at a time. */ goto start; do { vc m_nl, m_cr, m_bs, m_qm; s += 16; data = __builtin_vec_ld(0, (const vc *)s); start: m_nl = (vc) __builtin_vec_cmpeq(data, repl_nl); m_cr = (vc) __builtin_vec_cmpeq(data, repl_cr); m_bs = (vc) __builtin_vec_cmpeq(data, repl_bs); m_qm = (vc) __builtin_vec_cmpeq(data, repl_qm); t = (m_nl | m_cr) | (m_bs | m_qm); /* T now contains 0xff in bytes for which we matched one of the relevant characters. We want to exit the loop if any byte in T is non-zero. Below is the expansion of vec_any_ne(t, zero). */ } while (!__builtin_vec_vcmpeq_p(/*__CR6_LT_REV*/3, t, zero)); { #define N (sizeof(vc) / sizeof(long)) union { vc v; /* Statically assert that N is 2 or 4. */ unsigned long l[(N == 2 || N == 4) ? N : -1]; } u; unsigned long l, i = 0; u.v = t; /* Find the first word of T that is non-zero. */ switch (N) { case 4: l = u.l[i++]; if (l != 0) break; s += sizeof(unsigned long); l = u.l[i++]; if (l != 0) break; s += sizeof(unsigned long); /* FALLTHROUGH */ case 2: l = u.l[i++]; if (l != 0) break; s += sizeof(unsigned long); l = u.l[i]; } /* L now contains 0xff in bytes for which we matched one of the relevant characters. We can find the byte index by finding its bit index and dividing by 8. */ l = __builtin_clzl(l) >> 3; return s + l; #undef N } } #elif defined (__ARM_NEON) && defined (__ARM_64BIT_STATE) #include "arm_neon.h" /* This doesn't have to be the exact page size, but no system may use a size smaller than this. ARMv8 requires a minimum page size of 4k. The impact of being conservative here is a small number of cases will take the slightly slower entry path into the main loop. */ #define AARCH64_MIN_PAGE_SIZE 4096 static const uchar * search_line_fast (const uchar *s, const uchar *end ATTRIBUTE_UNUSED) { const uint8x16_t repl_nl = vdupq_n_u8 ('\n'); const uint8x16_t repl_cr = vdupq_n_u8 ('\r'); const uint8x16_t repl_bs = vdupq_n_u8 ('\\'); const uint8x16_t repl_qm = vdupq_n_u8 ('?'); const uint8x16_t xmask = (uint8x16_t) vdupq_n_u64 (0x8040201008040201ULL); #ifdef __ARM_BIG_ENDIAN const int16x8_t shift = {8, 8, 8, 8, 0, 0, 0, 0}; #else const int16x8_t shift = {0, 0, 0, 0, 8, 8, 8, 8}; #endif unsigned int found; const uint8_t *p; uint8x16_t data; uint8x16_t t; uint16x8_t m; uint8x16_t u, v, w; /* Align the source pointer. */ p = (const uint8_t *)((uintptr_t)s & -16); /* Assuming random string start positions, with a 4k page size we'll take the slow path about 0.37% of the time. */ if (__builtin_expect ((AARCH64_MIN_PAGE_SIZE - (((uintptr_t) s) & (AARCH64_MIN_PAGE_SIZE - 1))) < 16, 0)) { /* Slow path: the string starts near a possible page boundary. */ uint32_t misalign, mask; misalign = (uintptr_t)s & 15; mask = (-1u << misalign) & 0xffff; data = vld1q_u8 (p); t = vceqq_u8 (data, repl_nl); u = vceqq_u8 (data, repl_cr); v = vorrq_u8 (t, vceqq_u8 (data, repl_bs)); w = vorrq_u8 (u, vceqq_u8 (data, repl_qm)); t = vorrq_u8 (v, w); t = vandq_u8 (t, xmask); m = vpaddlq_u8 (t); m = vshlq_u16 (m, shift); found = vaddvq_u16 (m); found &= mask; if (found) return (const uchar*)p + __builtin_ctz (found); } else { data = vld1q_u8 ((const uint8_t *) s); t = vceqq_u8 (data, repl_nl); u = vceqq_u8 (data, repl_cr); v = vorrq_u8 (t, vceqq_u8 (data, repl_bs)); w = vorrq_u8 (u, vceqq_u8 (data, repl_qm)); t = vorrq_u8 (v, w); if (__builtin_expect (vpaddd_u64 ((uint64x2_t)t) != 0, 0)) goto done; } do { p += 16; data = vld1q_u8 (p); t = vceqq_u8 (data, repl_nl); u = vceqq_u8 (data, repl_cr); v = vorrq_u8 (t, vceqq_u8 (data, repl_bs)); w = vorrq_u8 (u, vceqq_u8 (data, repl_qm)); t = vorrq_u8 (v, w); } while (!vpaddd_u64 ((uint64x2_t)t)); done: /* Now that we've found the terminating substring, work out precisely where we need to stop. */ t = vandq_u8 (t, xmask); m = vpaddlq_u8 (t); m = vshlq_u16 (m, shift); found = vaddvq_u16 (m); return (((((uintptr_t) p) < (uintptr_t) s) ? s : (const uchar *)p) + __builtin_ctz (found)); } #elif defined (__ARM_NEON) #include "arm_neon.h" static const uchar * search_line_fast (const uchar *s, const uchar *end ATTRIBUTE_UNUSED) { const uint8x16_t repl_nl = vdupq_n_u8 ('\n'); const uint8x16_t repl_cr = vdupq_n_u8 ('\r'); const uint8x16_t repl_bs = vdupq_n_u8 ('\\'); const uint8x16_t repl_qm = vdupq_n_u8 ('?'); const uint8x16_t xmask = (uint8x16_t) vdupq_n_u64 (0x8040201008040201ULL); unsigned int misalign, found, mask; const uint8_t *p; uint8x16_t data; /* Align the source pointer. */ misalign = (uintptr_t)s & 15; p = (const uint8_t *)((uintptr_t)s & -16); data = vld1q_u8 (p); /* Create a mask for the bytes that are valid within the first 16-byte block. The Idea here is that the AND with the mask within the loop is "free", since we need some AND or TEST insn in order to set the flags for the branch anyway. */ mask = (-1u << misalign) & 0xffff; /* Main loop, processing 16 bytes at a time. */ goto start; do { uint8x8_t l; uint16x4_t m; uint32x2_t n; uint8x16_t t, u, v, w; p += 16; data = vld1q_u8 (p); mask = 0xffff; start: t = vceqq_u8 (data, repl_nl); u = vceqq_u8 (data, repl_cr); v = vorrq_u8 (t, vceqq_u8 (data, repl_bs)); w = vorrq_u8 (u, vceqq_u8 (data, repl_qm)); t = vandq_u8 (vorrq_u8 (v, w), xmask); l = vpadd_u8 (vget_low_u8 (t), vget_high_u8 (t)); m = vpaddl_u8 (l); n = vpaddl_u16 (m); found = vget_lane_u32 ((uint32x2_t) vorr_u64 ((uint64x1_t) n, vshr_n_u64 ((uint64x1_t) n, 24)), 0); found &= mask; } while (!found); /* FOUND contains 1 in bits for which we matched a relevant character. Conversion to the byte index is trivial. */ found = __builtin_ctz (found); return (const uchar *)p + found; } #else /* We only have one accelerated alternative. Use a direct call so that we encourage inlining. */ #define search_line_fast search_line_acc_char #endif /* Initialize the lexer if needed. */ void _cpp_init_lexer (void) { #ifdef HAVE_init_vectorized_lexer init_vectorized_lexer (); #endif } /* Returns with a logical line that contains no escaped newlines or trigraphs. This is a time-critical inner loop. */ void _cpp_clean_line (cpp_reader *pfile) { cpp_buffer *buffer; const uchar *s; uchar c, *d, *p; buffer = pfile->buffer; buffer->cur_note = buffer->notes_used = 0; buffer->cur = buffer->line_base = buffer->next_line; buffer->need_line = false; s = buffer->next_line; if (!buffer->from_stage3) { const uchar *pbackslash = NULL; /* Fast path. This is the common case of an un-escaped line with no trigraphs. The primary win here is by not writing any data back to memory until we have to. */ while (1) { /* Perform an optimized search for \n, \r, \\, ?. */ s = search_line_fast (s, buffer->rlimit); c = *s; if (c == '\\') { /* Record the location of the backslash and continue. */ pbackslash = s++; } else if (__builtin_expect (c == '?', 0)) { if (__builtin_expect (s[1] == '?', false) && _cpp_trigraph_map[s[2]]) { /* Have a trigraph. We may or may not have to convert it. Add a line note regardless, for -Wtrigraphs. */ add_line_note (buffer, s, s[2]); if (CPP_OPTION (pfile, trigraphs)) { /* We do, and that means we have to switch to the slow path. */ d = (uchar *) s; *d = _cpp_trigraph_map[s[2]]; s += 2; goto slow_path; } } /* Not a trigraph. Continue on fast-path. */ s++; } else break; } /* This must be \r or \n. We're either done, or we'll be forced to write back to the buffer and continue on the slow path. */ d = (uchar *) s; if (__builtin_expect (s == buffer->rlimit, false)) goto done; /* DOS line ending? */ if (__builtin_expect (c == '\r', false) && s[1] == '\n') { s++; if (s == buffer->rlimit) goto done; } if (__builtin_expect (pbackslash == NULL, true)) goto done; /* Check for escaped newline. */ p = d; while (is_nvspace (p[-1])) p--; if (p - 1 != pbackslash) goto done; /* Have an escaped newline; process it and proceed to the slow path. */ add_line_note (buffer, p - 1, p != d ? ' ' : '\\'); d = p - 2; buffer->next_line = p - 1; slow_path: while (1) { c = *++s; *++d = c; if (c == '\n' || c == '\r') { /* Handle DOS line endings. */ if (c == '\r' && s != buffer->rlimit && s[1] == '\n') s++; if (s == buffer->rlimit) break; /* Escaped? */ p = d; while (p != buffer->next_line && is_nvspace (p[-1])) p--; if (p == buffer->next_line || p[-1] != '\\') break; add_line_note (buffer, p - 1, p != d ? ' ': '\\'); d = p - 2; buffer->next_line = p - 1; } else if (c == '?' && s[1] == '?' && _cpp_trigraph_map[s[2]]) { /* Add a note regardless, for the benefit of -Wtrigraphs. */ add_line_note (buffer, d, s[2]); if (CPP_OPTION (pfile, trigraphs)) { *d = _cpp_trigraph_map[s[2]]; s += 2; } } } } else { while (*s != '\n' && *s != '\r') s++; d = (uchar *) s; /* Handle DOS line endings. */ if (*s == '\r' && s != buffer->rlimit && s[1] == '\n') s++; } done: *d = '\n'; /* A sentinel note that should never be processed. */ add_line_note (buffer, d + 1, '\n'); buffer->next_line = s + 1; } /* Return true if the trigraph indicated by NOTE should be warned about in a comment. */ static bool warn_in_comment (cpp_reader *pfile, _cpp_line_note *note) { const uchar *p; /* Within comments we don't warn about trigraphs, unless the trigraph forms an escaped newline, "iso-b5", "iso-b6", "iso-b7", "iso-b8", "iso-b9", "iso-b10", "jis-b0", "jis-b1", "jis-b2", "jis-b3", "jis-b4", "jis-b5", "jis-b6", "jis-b7", "jis-b8", "jis-b9", "jis-b10", "iso-c0", "iso-c1", "iso-c2", "iso-c3", "iso-c4", "iso-c5", "iso-c6", "iso-c7", "iso-c8", "iso-c9", "iso-c10", "iso-designated-long", "executive", "folio", "invoice", "ledger", "na-letter", "na-legal", "quarto", "a", "b", "c", "d", "e", "na-10x15-envelope", "na-10x14-envelope", "na-10x13-envelope", "na-9x12-envelope", "na-9x11-envelope", "na-7x9-envelope", "na-6x9-envelope", "na-number-9-envelope", "na-number-10-envelope", "na-number-11-envelope", "na-number-12-envelope", "na-number-14-envelope", "invite-envelope", "italy-envelope", "monarch-envelope", "personal-envelope" }; public static final MediaType ISO_4A0 = new MediaType(0); public static final MediaType ISO_2A0 = new MediaType(1); public static final MediaType ISO_A0 = new MediaType(2); public static final MediaType ISO_A1 = new MediaType(3); public static final MediaType ISO_A2 = new MediaType(4); public static final MediaType ISO_A3 = new MediaType(5); public static final MediaType ISO_A4 = new MediaType(6); public static final MediaType ISO_A5 = new MediaType(7); public static final MediaType ISO_A6 = new MediaType(8); public static final MediaType ISO_A7 = new MediaType(9); public static final MediaType ISO_A8 = new MediaType(10); public static final MediaType ISO_A9 = new MediaType(11); public static final MediaType ISO_A10 = new MediaType(12); public static final MediaType ISO_B0 = new MediaType(13); public static final MediaType ISO_B1 = new MediaType(14); public static final MediaType ISO_B2 = new MediaType(15); public static final MediaType ISO_B3 = new MediaType(16); public static final MediaType ISO_B4 = new MediaType(17); public static final MediaType ISO_B5 = new MediaType(18); public static final MediaType ISO_B6 = new MediaType(19); public static final MediaType ISO_B7 = new MediaType(20); public static final MediaType ISO_B8 = new MediaType(21); public static final MediaType ISO_B9 = new MediaType(22); public static final MediaType ISO_B10 = new MediaType(23); public static final MediaType JIS_B0 = new MediaType(24); public static final MediaType JIS_B1 = new MediaType(25); public static final MediaType JIS_B2 = new MediaType(26); public static final MediaType JIS_B3 = new MediaType(27); public static final MediaType JIS_B4 = new MediaType(28); public static final MediaType JIS_B5 = new MediaType(29); public static final MediaType JIS_B6 = new MediaType(30); public static final MediaType JIS_B7 = new MediaType(31); public static final MediaType JIS_B8 = new MediaType(32); public static final MediaType JIS_B9 = new MediaType(33); public static final MediaType JIS_B10 = new MediaType(34); public static final MediaType ISO_C0 = new MediaType(35); public static final MediaType ISO_C1 = new MediaType(36); public static final MediaType ISO_C2 = new MediaType(37); public static final MediaType ISO_C3 = new MediaType(38); public static final MediaType ISO_C4 = new MediaType(39); public static final MediaType ISO_C5 = new MediaType(40); public static final MediaType ISO_C6 = new MediaType(41); public static final MediaType ISO_C7 = new MediaType(42); public static final MediaType ISO_C8 = new MediaType(43); public static final MediaType ISO_C9 = new MediaType(44); public static final MediaType ISO_C10 = new MediaType(45); public static final MediaType ISO_DESIGNATED_LONG = new MediaType(46); public static final MediaType EXECUTIVE = new MediaType(47); public static final MediaType FOLIO = new MediaType(48); public static final MediaType INVOICE = new MediaType(49); public static final MediaType LEDGER = new MediaType(50); public static final MediaType NA_LETTER = new MediaType(51); public static final MediaType NA_LEGAL = new MediaType(52); public static final MediaType QUARTO = new MediaType(53); public static final MediaType A = new MediaType(54); public static final MediaType B = new MediaType(55); public static final MediaType C = new MediaType(56); public static final MediaType D = new MediaType(57); public static final MediaType E = new MediaType(58); public static final MediaType NA_10X15_ENVELOPE = new MediaType(59); public static final MediaType NA_10X14_ENVELOPE = new MediaType(60); public static final MediaType NA_10X13_ENVELOPE = new MediaType(61); public static final MediaType NA_9X12_ENVELOPE = new MediaType(62); public static final MediaType NA_9X11_ENVELOPE = new MediaType(63); public static final MediaType NA_7X9_ENVELOPE = new MediaType(64); public static final MediaType NA_6X9_ENVELOPE = new MediaType(65); public static final MediaType NA_NUMBER_9_ENVELOPE = new MediaType(66); public static final MediaType NA_NUMBER_10_ENVELOPE = new MediaType(67); public static final MediaType NA_NUMBER_11_ENVELOPE = new MediaType(68); public static final MediaType NA_NUMBER_12_ENVELOPE = new MediaType(69); public static final MediaType NA_NUMBER_14_ENVELOPE = new MediaType(70); public static final MediaType INVITE_ENVELOPE = new MediaType(71); public static final MediaType ITALY_ENVELOPE = new MediaType(72); public static final MediaType MONARCH_ENVELOPE = new MediaType(73); public static final MediaType PERSONAL_ENVELOPE = new MediaType(74); public static final MediaType A0 = ISO_A0; public static final MediaType A1 = ISO_A1; public static final MediaType A2 = ISO_A2; public static final MediaType A3 = ISO_A3; public static final MediaType A4 = ISO_A4; public static final MediaType A5 = ISO_A5; public static final MediaType A6 = ISO_A6; public static final MediaType A7 = ISO_A7; public static final MediaType A8 = ISO_A8; public static final MediaType A9 = ISO_A9; public static final MediaType A10 = ISO_A10; public static final MediaType B0 = ISO_B0; public static final MediaType B1 = ISO_B1; public static final MediaType B2 = ISO_B2; public static final MediaType B3 = ISO_B3; public static final MediaType B4 = ISO_B4; public static final MediaType ISO_B4_ENVELOPE = ISO_B4; public static final MediaType B5 = ISO_B5; public static final MediaType ISO_B5_ENVELOPE = ISO_B4; public static final MediaType B6 = ISO_B6; public static final MediaType B7 = ISO_B7; public static final MediaType B8 = ISO_B8; public static final MediaType B9 = ISO_B9; public static final MediaType B10 = ISO_B10; public static final MediaType C0 = ISO_B0; public static final MediaType ISO_C0_ENVELOPE = ISO_C0; public static final MediaType C1 = ISO_C1; public static final MediaType ISO_C1_ENVELOPE = ISO_C1; public static final MediaType C2 = ISO_C2; public static final MediaType ISO_C2_ENVELOPE = ISO_C2; public static final MediaType C3 = ISO_C3; public static final MediaType ISO_C3_ENVELOPE = ISO_C3; public static final MediaType C4 = ISO_C4; public static final MediaType ISO_C4_ENVELOPE = ISO_C4; public static final MediaType C5 = ISO_C5; public static final MediaType ISO_C5_ENVELOPE = ISO_C5; public static final MediaType C6 = ISO_C6; public static final MediaType ISO_C6_ENVELOPE = ISO_C6; public static final MediaType C7 = ISO_C7; public static final MediaType ISO_C7_ENVELOPE = ISO_C7; public static final MediaType C8 = ISO_C8; public static final MediaType ISO_C8_ENVELOPE = ISO_C8; public static final MediaType C9 = ISO_C9; public static final MediaType ISO_C9_ENVELOPE = ISO_C9; public static final MediaType C10 = ISO_C10; public static final MediaType ISO_C10_ENVELOPE = ISO_C10; public static final MediaType ISO_DESIGNATED_LONG_ENVELOPE = ISO_DESIGNATED_LONG; public static final MediaType STATEMENT = INVOICE; public static final MediaType TABLOID = LEDGER; public static final MediaType LETTER = NA_LETTER; public static final MediaType NOTE = NA_LETTER; public static final MediaType LEGAL = NA_LEGAL; public static final MediaType ENV_10X15 = NA_10X15_ENVELOPE; public static final MediaType ENV_10X14 = NA_10X14_ENVELOPE; public static final MediaType ENV_10X13 = NA_10X13_ENVELOPE; public static final MediaType ENV_9X12 = NA_9X12_ENVELOPE; public static final MediaType ENV_9X11 = NA_9X11_ENVELOPE; public static final MediaType ENV_7X9 = NA_7X9_ENVELOPE; public static final MediaType ENV_6X9 = NA_6X9_ENVELOPE; public static final MediaType ENV_9 = NA_NUMBER_9_ENVELOPE; public static final MediaType ENV_10 = NA_NUMBER_10_ENVELOPE; public static final MediaType ENV_11 = NA_NUMBER_11_ENVELOPE; public static final MediaType ENV_12 = NA_NUMBER_12_ENVELOPE; public static final MediaType ENV_14 = NA_NUMBER_14_ENVELOPE; public static final MediaType ENV_INVITE = INVITE_ENVELOPE; public static final MediaType ENV_ITALY = ITALY_ENVELOPE; public static final MediaType ENV_MONARCH = MONARCH_ENVELOPE; public static final MediaType ENV_PERSONAL = PERSONAL_ENVELOPE; public static final MediaType INVITE = INVITE_ENVELOPE; public static final MediaType ITALY = ITALY_ENVELOPE; public static final MediaType MONARCH = MONARCH_ENVELOPE; public static final MediaType PERSONAL = PERSONAL_ENVELOPE; private MediaType(int value) { super(value, NAMES); } } // class MediaType public static final class OrientationRequestedType extends AttributeValue { private static final String[] NAMES = { "portrait", "landscape" }; public static final OrientationRequestedType PORTRAIT = new OrientationRequestedType(0); public static final OrientationRequestedType LANDSCAPE = new OrientationRequestedType(1); private OrientationRequestedType(int value) { super(value, NAMES); } } // class OrientationRequestedType public static final class OriginType extends AttributeValue { private static final String[] NAMES = { "physical", "printable" }; public static final OriginType PHYSICAL = new OriginType(0); public static final OriginType PRINTABLE = new OriginType(1); private OriginType(int value) { super(value, NAMES); } } // class OriginType public static final class PrintQualityType extends AttributeValue { private static final String[] NAMES = { "high", "normal", "draft" }; public static final PrintQualityType HIGH = new PrintQualityType(0); public static final PrintQualityType NORMAL = new PrintQualityType(1); public static final PrintQualityType DRAFT = new PrintQualityType(2); private PrintQualityType(int value) { super(value, NAMES); } } // class PrintQualityType private ColorType color; private MediaType media; private OrientationRequestedType orientation; private OriginType origin; private PrintQualityType quality; private int resolutionX; private int resolutionY; private int resolutionScale; public PageAttributes() { color = ColorType.MONOCHROME; setMediaToDefault(); orientation = OrientationRequestedType.PORTRAIT; origin = OriginType.PHYSICAL; quality = PrintQualityType.NORMAL; setPrinterResolutionToDefault(); } public PageAttributes(PageAttributes attr) { set(attr); } public PageAttributes(ColorType color, MediaType media, OrientationRequestedType orientation, OriginType origin, PrintQualityType quality, int[] resolution) { if (color == null || media == null || orientation == null || origin == null || quality == null) throw new IllegalArgumentException(); setPrinterResolution(resolution); this.color = color; this.media = media; this.orientation = orientation; this.origin = origin; this.quality = quality; } public Object clone() { return new PageAttributes(this); } public void set(PageAttributes attr) { color = attr.color; media = attr.media; orientation = attr.orientation; origin = attr.origin; quality = attr.quality; resolutionX = attr.resolutionX; resolutionY = attr.resolutionY; resolutionScale = attr.resolutionScale; } public ColorType getColor() { return color; } public void setColor(ColorType color) { if (color == null) throw new IllegalArgumentException(); this.color = color; } public MediaType getMedia() { return media; } public void setMedia(MediaType media) { if (media == null) throw new IllegalArgumentException(); this.media = media; } public void setMediaToDefault() { String country = Locale.getDefault().getCountry(); media = ("US".equals(country) || "CA".equals(country)) ? MediaType.LETTER : MediaType.A4; } public OrientationRequestedType getOrientationRequested() { return orientation; } public void setOrientationRequested(OrientationRequestedType orientation) { if (orientation == null) throw new IllegalArgumentException(); this.orientation = orientation; } public void setOrientationRequested(int orientation) { if (orientation == 3) this.orientation = OrientationRequestedType.PORTRAIT; else if (orientation == 4) this.orientation = OrientationRequestedType.LANDSCAPE; else throw new IllegalArgumentException(); } public void setOrientationRequestedToDefault() { orientation = OrientationRequestedType.PORTRAIT; } public OriginType getOrigin() { return origin; } public void setOrigin(OriginType origin) { if (origin == null) throw new IllegalArgumentException(); this.origin = origin; } public PrintQualityType getPrintQuality() { return quality; } public void setPrintQuality(PrintQualityType quality) { if (quality == null) throw new IllegalArgumentException(); this.quality = quality; } public void setPrintQuality(int quality) { if (quality == 3) this.quality = PrintQualityType.DRAFT; else if (quality == 4) this.quality = PrintQualityType.NORMAL; else if (quality == 5) this.quality = PrintQualityType.HIGH; else throw new IllegalArgumentException(); } public void setPrintQualityToDefault() { quality = PrintQualityType.NORMAL; } public int[] getPrinterResolution() { return new int[] { resolutionX, resolutionY, resolutionScale }; } public void setPrinterResolution(int[] resolution) { if (resolution == null || resolution.length != 3 || resolution[0] <= 0 || resolution[1] <= 0 || resolution[2] < 3 || resolution[2] > 4) throw new IllegalArgumentException(); resolutionX = resolution[0]; resolutionY = resolution[1]; resolutionScale = resolution[2]; } public void setPrinterResolution(int resolution) { if (resolution <= 0) throw new IllegalArgumentException(); resolutionX = resolution; resolutionY = resolution; resolutionScale = 3; } public void setPrinterResolutionToDefault() { resolutionX = 72; resolutionY = 72; resolutionScale = 3; } public boolean equals(Object o) { if (this == o) return true; if (! (o instanceof PageAttributes)) return false; PageAttributes pa = (PageAttributes) o; return color == pa.color && media == pa.media && orientation == pa.orientation && origin == pa.origin && quality == pa.quality && resolutionX == pa.resolutionX && resolutionY == pa.resolutionY && resolutionScale == pa.resolutionScale; } public int hashCode() { return (color.value << 31) ^ (media.value << 24) ^ (orientation.value << 23) ^ (origin.value << 22) ^ (quality.value << 20) ^ (resolutionScale << 19) ^ (resolutionY << 10) ^ resolutionX; } public String toString() { return "color=" + color + ",media=" + media + ",orientation-requested=" + orientation + ",origin=" + origin + ",print-quality=" + quality + ",printer-resolution=[" + resolutionX + ',' + resolutionY + ',' + resolutionScale + ']'; } } // class PageAttributes >> ucn_len); for (ucn_len_c = 1; ucn_len_c < ucn_len; ucn_len_c++) { utf32 = (utf32 << 6) | (*++name & 0x3F); /* Ill-formed UTF-8. */ if ((*name & ~0x3F) != 0x80) abort (); } *buffer++ = '\\'; *buffer++ = 'U'; for (j = 7; j >= 0; j--) *buffer++ = "0123456789abcdef"[(utf32 >> (4 * j)) & 0xF]; return ucn_len; } /* Given a token TYPE corresponding to a digraph, return a pointer to the spelling of the digraph. */ static const unsigned char * cpp_digraph2name (enum cpp_ttype type) { return digraph_spellings[(int) type - (int) CPP_FIRST_DIGRAPH]; } /* Write the spelling of an identifier IDENT, using UCNs, to BUFFER. The buffer must already contain the enough space to hold the token's spelling. Returns a pointer to the character after the last character written. */ unsigned char * _cpp_spell_ident_ucns (unsigned char *buffer, cpp_hashnode *ident) { size_t i; const unsigned char *name = NODE_NAME (ident); for (i = 0; i < NODE_LEN (ident); i++) if (name[i] & ~0x7F) { i += utf8_to_ucn (buffer, name + i) - 1; buffer += 10; } else *buffer++ = name[i]; return buffer; } /* Write the spelling of a token TOKEN to BUFFER. The buffer must already contain the enough space to hold the token's spelling. Returns a pointer to the character after the last character written. FORSTRING is true if this is to be the spelling after translation phase 1 (with the original spelling of extended identifiers), false if extended identifiers should always be written using UCNs (there is no option for always writing them in the internal UTF-8 form). FIXME: Would be nice if we didn't need the PFILE argument. */ unsigned char * cpp_spell_token (cpp_reader *pfile, const cpp_token *token, unsigned char *buffer, bool forstring) { switch (TOKEN_SPELL (token)) { case SPELL_OPERATOR: { const unsigned char *spelling; unsigned char c; if (token->flags & DIGRAPH) spelling = cpp_digraph2name (token->type); else if (token->flags & NAMED_OP) goto spell_ident; else spelling = TOKEN_NAME (token); while ((c = *spelling++) != '\0') *buffer++ = c; } break; spell_ident: case SPELL_IDENT: if (forstring) { memcpy (buffer, NODE_NAME (token->val.node.spelling), NODE_LEN (token->val.node.spelling)); buffer += NODE_LEN (token->val.node.spelling); } else buffer = _cpp_spell_ident_ucns (buffer, token->val.node.node); break; case SPELL_LITERAL: memcpy (buffer, token->val.str.text, token->val.str.len); buffer += token->val.str.len; break; case SPELL_NONE: cpp_error (pfile, CPP_DL_ICE, "unspellable token %s", TOKEN_NAME (token)); break; } return buffer; } /* Returns TOKEN spelt as a null-terminated string. The string is freed when the reader is destroyed. Useful for diagnostics. */ unsigned char * cpp_token_as_text (cpp_reader *pfile, const cpp_token *token) { unsigned int len = cpp_token_len (token) + 1; unsigned char *start = _cpp_unaligned_alloc (pfile, len), *end; end = cpp_spell_token (pfile, token, start, false); end[0] = '\0'; return start; } /* Returns a pointer to a string which spells the token defined by TYPE and FLAGS. Used by C front ends, which really should move to using cpp_token_as_text. */ const char * cpp_type2name (enum cpp_ttype type, unsigned char flags) { if (flags & DIGRAPH) return (const char *) cpp_digraph2name (type); else if (flags & NAMED_OP) return cpp_named_operator2name (type); return (const char *) token_spellings[type].name; } /* Writes the spelling of token to FP, without any preceding space. Separated from cpp_spell_token for efficiency - to avoid stdio double-buffering. */ void cpp_output_token (const cpp_token *token, FILE *fp) { switch (TOKEN_SPELL (token)) { case SPELL_OPERATOR: { const unsigned char *spelling; int c; if (token->flags & DIGRAPH) spelling = cpp_digraph2name (token->type); else if (token->flags & NAMED_OP) goto spell_ident; else spelling = TOKEN_NAME (token); c = *spelling; do putc (c, fp); while ((c = *++spelling) != '\0'); } break; spell_ident: case SPELL_IDENT: { size_t i; const unsigned char * name = NODE_NAME (token->val.node.node); for (i = 0; i < NODE_LEN (token->val.node.node); i++) if (name[i] & ~0x7F) { unsigned char buffer[10]; i += utf8_to_ucn (buffer, name + i) - 1; fwrite (buffer, 1, 10, fp); } else fputc (NODE_NAME (token->val.node.node)[i], fp); } break; case SPELL_LITERAL: fwrite (token->val.str.text, 1, token->val.str.len, fp); break; case SPELL_NONE: /* An error, most probably. */ break; } } /* Compare two tokens. */ int _cpp_equiv_tokens (const cpp_token *a, const cpp_token *b) { if (a->type == b->type && a->flags == b->flags) switch (TOKEN_SPELL (a)) { default: /* Keep compiler happy. */ case SPELL_OPERATOR: /* token_no is used to track where multiple consecutive ## tokens were originally located. */ return (a->type != CPP_PASTE || a->val.token_no == b->val.token_no); case SPELL_NONE: return (a->type != CPP_MACRO_ARG || (a->val.macro_arg.arg_no == b->val.macro_arg.arg_no && a->val.macro_arg.spelling == b->val.macro_arg.spelling)); case SPELL_IDENT: return (a->val.node.node == b->val.node.node && a->val.node.spelling == b->val.node.spelling); case SPELL_LITERAL: return (a->val.str.len == b->val.str.len && !memcmp (a->val.str.text, b->val.str.text, a->val.str.len)); } return 0; } /* Returns nonzero if a space should be inserted to avoid an accidental token paste for output. For simplicity, it is conservative, and occasionally advises a space where one is not needed, e.g. "." and ".2". */ int cpp_avoid_paste (cpp_reader *pfile, const cpp_token *token1, const cpp_token *token2) { enum cpp_ttype a = token1->type, b = token2->type; cppchar_t c; if (token1->flags & NAMED_OP) a = CPP_NAME; if (token2->flags & NAMED_OP) b = CPP_NAME; c = EOF; if (token2->flags & DIGRAPH) c = digraph_spellings[(int) b - (int) CPP_FIRST_DIGRAPH][0]; else if (token_spellings[b].category == SPELL_OPERATOR) c = token_spellings[b].name[0]; /* Quickly get everything that can paste with an '='. */ if ((int) a <= (int) CPP_LAST_EQ && c == '=') return 1; switch (a) { case CPP_GREATER: return c == '>'; case CPP_LESS: return c == '<' || c == '%' || c == ':'; case CPP_PLUS: return c == '+'; case CPP_MINUS: return c == '-' || c == '>'; case CPP_DIV: return c == '/' || c == '*'; /* Comments. */ case CPP_MOD: return c == ':' || c == '>'; case CPP_AND: return c == '&'; case CPP_OR: return c == '|'; case CPP_COLON: return c == ':' || c == '>'; case CPP_DEREF: return c == '*'; case CPP_DOT: return c == '.' || c == '%' || b == CPP_NUMBER; case CPP_HASH: return c == '#' || c == '%'; /* Digraph form. */ case CPP_NAME: return ((b == CPP_NUMBER && name_p (pfile, &token2->val.str)) || b == CPP_NAME || b == CPP_CHAR || b == CPP_STRING); /* L */ case CPP_NUMBER: return (b == CPP_NUMBER || b == CPP_NAME || c == '.' || c == '+' || c == '-'); /* UCNs */ case CPP_OTHER: return ((token1->val.str.text[0] == '\\' && b == CPP_NAME) || (CPP_OPTION (pfile, objc) && token1->val.str.text[0] == '@' && (b == CPP_NAME || b == CPP_STRING))); case CPP_LESS_EQ: return c == '>'; case CPP_STRING: case CPP_WSTRING: case CPP_UTF8STRING: case CPP_STRING16: case CPP_STRING32: return (CPP_OPTION (pfile, user_literals) && (b == CPP_NAME || (TOKEN_SPELL (token2) == SPELL_LITERAL && ISIDST (token2->val.str.text[0])))); default: break; } return 0; } /* Output all the remaining tokens on the current line, and a newline character, to FP. Leading whitespace is removed. If there are macros, special token padding is not performed. */ void cpp_output_line (cpp_reader *pfile, FILE *fp) { const cpp_token *token; token = cpp_get_token (pfile); while (token->type != CPP_EOF) { cpp_output_token (token, fp); token = cpp_get_token (pfile); if (token->flags & PREV_WHITE) putc (' ', fp); } putc ('\n', fp); } /* Return a string representation of all the remaining tokens on the current line. The result is allocated using xmalloc and must be freed by the caller. */ unsigned char * cpp_output_line_to_string (cpp_reader *pfile, const unsigned char *dir_name) { const cpp_token *token; unsigned int out = dir_name ? ustrlen (dir_name) : 0; unsigned int alloced = 120 + out; unsigned char *result = (unsigned char *) xmalloc (alloced); /* If DIR_NAME is empty, there are no initial contents. */ if (dir_name) { sprintf ((char *) result, "#%s ", dir_name); out += 2; } token = cpp_get_token (pfile); while (token->type != CPP_EOF) { unsigned char *last; /* Include room for a possible space and the terminating nul. */ unsigned int len = cpp_token_len (token) + 2; if (out + len > alloced) { alloced *= 2; if (out + len > alloced) alloced = out + len; result = (unsigned char *) xrealloc (result, alloced); } last = cpp_spell_token (pfile, token, &result[out], 0); out = last - result; token = cpp_get_token (pfile); if (token->flags & PREV_WHITE) result[out++] = ' '; } result[out] = '\0'; return result; } /* Memory buffers. Changing these three constants can have a dramatic effect on performance. The values here are reasonable defaults, but might be tuned. If you adjust them, be sure to test across a range of uses of cpplib, including heavy nested function-like macro expansion. Also check the change in peak memory usage (NJAMD is a good tool for this). */ #define MIN_BUFF_SIZE 8000 #define BUFF_SIZE_UPPER_BOUND(MIN_SIZE) (MIN_BUFF_SIZE + (MIN_SIZE) * 3 / 2) #define EXTENDED_BUFF_SIZE(BUFF, MIN_EXTRA) \ (MIN_EXTRA + ((BUFF)->limit - (BUFF)->cur) * 2) #if MIN_BUFF_SIZE > BUFF_SIZE_UPPER_BOUND (0) #error BUFF_SIZE_UPPER_BOUND must be at least as large as MIN_BUFF_SIZE! #endif /* Create a new allocation buffer. Place the control block at the end of the buffer, so that buffer overflows will cause immediate chaos. */ static _cpp_buff * new_buff (size_t len) { _cpp_buff *result; unsigned char *base; if (len < MIN_BUFF_SIZE) len = MIN_BUFF_SIZE; len = CPP_ALIGN (len); #ifdef ENABLE_VALGRIND_ANNOTATIONS /* Valgrind warns about uses of interior pointers, so put _cpp_buff struct first. */ size_t slen = CPP_ALIGN2 (sizeof (_cpp_buff), 2 * DEFAULT_ALIGNMENT); base = XNEWVEC (unsigned char, len + slen); result = (_cpp_buff *) base; base += slen; #else base = XNEWVEC (unsigned char, len + sizeof (_cpp_buff)); result = (_cpp_buff *) (base + len); #endif result->base = base; result->cur = base; result->limit = base + len; result->next = NULL; return result; } /* Place a chain of unwanted allocation buffers on the free list. */ void _cpp_release_buff (cpp_reader *pfile, _cpp_buff *buff) { _cpp_buff *end = buff; while (end->next) end = end->next; end->next = pfile->free_buffs; pfile->free_buffs = buff; } /* Return a free buffer of size at least MIN_SIZE. */ _cpp_buff * _cpp_get_buff (cpp_reader *pfile, size_t min_size) { _cpp_buff *result, **p; for (p = &pfile->free_buffs;; p = &(*p)->next) { size_t size; if (*p == NULL) return new_buff (min_size); result = *p; size = result->limit - result->base; /* Return a buffer that's big enough, but don't waste one that's way too big. */ if (size >= min_size && size <= BUFF_SIZE_UPPER_BOUND (min_size)) break; } *p = result->next; result->next = NULL; result->cur = result->base; return result; } /* Creates a new buffer with enough space to hold the uncommitted remaining bytes of BUFF, and at least MIN_EXTRA more bytes. Copies the excess bytes to the new buffer. Chains the new buffer after BUFF, and returns the new buffer. */ _cpp_buff * _cpp_append_extend_buff (cpp_reader *pfile, _cpp_buff *buff, size_t min_extra) { size_t size = EXTENDED_BUFF_SIZE (buff, min_extra); _cpp_buff *new_buff = _cpp_get_buff (pfile, size); buff->next = new_buff; memcpy (new_buff->base, buff->cur, BUFF_ROOM (buff)); return new_buff; } /* Creates a new buffer with enough space to hold the uncommitted remaining bytes of the buffer pointed to by BUFF, and at least MIN_EXTRA more bytes. Copies the excess bytes to the new buffer. Chains the new buffer before the buffer pointed to by BUFF, and updates the pointer to point to the new buffer. */ void _cpp_extend_buff (cpp_reader *pfile, _cpp_buff **pbuff, size_t min_extra) { _cpp_buff *new_buff, *old_buff = *pbuff; size_t size = EXTENDED_BUFF_SIZE (old_buff, min_extra); new_buff = _cpp_get_buff (pfile, size); memcpy (new_buff->base, old_buff->cur, BUFF_ROOM (old_buff)); new_buff->next = old_buff; *pbuff = new_buff; } /* Free a chain of buffers starting at BUFF. */ void _cpp_free_buff (_cpp_buff *buff) { _cpp_buff *next; for (; buff; buff = next) { next = buff->next; #ifdef ENABLE_VALGRIND_ANNOTATIONS free (buff); #else free (buff->base); #endif } } /* Allocate permanent, unaligned storage of length LEN. */ unsigned char * _cpp_unaligned_alloc (cpp_reader *pfile, size_t len) { _cpp_buff *buff = pfile->u_buff; unsigned char *result = buff->cur; if (len > (size_t) (buff->limit - result)) { buff = _cpp_get_buff (pfile, len); buff->next = pfile->u_buff; pfile->u_buff = buff; result = buff->cur; } buff->cur = result + len; return result; } /* Allocate permanent, unaligned storage of length LEN from a_buff. That buffer is used for growing allocations when saving macro replacement lists in a #define, and when parsing an answer to an assertion in #assert, #unassert or #if (and therefore possibly whilst expanding macros). It therefore must not be used by any code that they might call: specifically the lexer and the guts of the macro expander. All existing other uses clearly fit this restriction: storing registered pragmas during initialization. */ unsigned char * _cpp_aligned_alloc (cpp_reader *pfile, size_t len) { _cpp_buff *buff = pfile->a_buff; unsigned char *result = buff->cur; if (len > (size_t) (buff->limit - result)) { buff = _cpp_get_buff (pfile, len); buff->next = pfile->a_buff; pfile->a_buff = buff; result = buff->cur; } buff->cur = result + len; return result; } /* Commit or allocate storage from a buffer. */ void * _cpp_commit_buff (cpp_reader *pfile, size_t size) { void *ptr = BUFF_FRONT (pfile->a_buff); if (pfile->hash_table->alloc_subobject) { void *copy = pfile->hash_table->alloc_subobject (size); memcpy (copy, ptr, size); ptr = copy; } else BUFF_FRONT (pfile->a_buff) += size; return ptr; } /* Say which field of TOK is in use. */ enum cpp_token_fld_kind cpp_token_val_index (const cpp_token *tok) { switch (TOKEN_SPELL (tok)) { case SPELL_IDENT: return CPP_TOKEN_FLD_NODE; case SPELL_LITERAL: return CPP_TOKEN_FLD_STR; case SPELL_OPERATOR: /* Operands which were originally spelled as ident keep around the node for the exact spelling. */ if (tok->flags & NAMED_OP) return CPP_TOKEN_FLD_NODE; else if (tok->type == CPP_PASTE) return CPP_TOKEN_FLD_TOKEN_NO; else return CPP_TOKEN_FLD_NONE; case SPELL_NONE: if (tok->type == CPP_MACRO_ARG) return CPP_TOKEN_FLD_ARG_NO; else if (tok->type == CPP_PADDING) return CPP_TOKEN_FLD_SOURCE; else if (tok->type == CPP_PRAGMA) return CPP_TOKEN_FLD_PRAGMA; /* fall through */ default: return CPP_TOKEN_FLD_NONE; } } /* All tokens lexed in R after calling this function will be forced to have their location_t to be P, until cpp_stop_forcing_token_locations is called for R. */ void cpp_force_token_locations (cpp_reader *r, location_t loc) { r->forced_token_location = loc; } /* Go back to assigning locations naturally for lexed tokens. */ void cpp_stop_forcing_token_locations (cpp_reader *r) { r->forced_token_location = 0; } /* We're looking at \, if it's escaping EOL, look past it. If at LIMIT, don't advance. */ static const unsigned char * do_peek_backslash (const unsigned char *peek, const unsigned char *limit) { const unsigned char *probe = peek; if (__builtin_expect (peek[1] == '\n', true)) { eol: probe += 2; if (__builtin_expect (probe < limit, true)) { peek = probe; if (*peek == '\\') /* The user might be perverse. */ return do_peek_backslash (peek, limit); } } else if (__builtin_expect (peek[1] == '\r', false)) { if (probe[2] == '\n') probe++; goto eol; } return peek; } static const unsigned char * do_peek_next (const unsigned char *peek, const unsigned char *limit) { if (__builtin_expect (*peek == '\\', false)) peek = do_peek_backslash (peek, limit); return peek; } static const unsigned char * do_peek_prev (const unsigned char *peek, const unsigned char *bound) { if (peek == bound) return NULL; unsigned char c = *--peek; if (__builtin_expect (c == '\n', false) || __builtin_expect (c == 'r', false)) { if (peek == bound) return peek; int ix = -1; if (c == '\n' && peek[ix] == '\r') { if (peek + ix == bound) return peek; ix--; } if (peek[ix] == '\\') return do_peek_prev (peek + ix, bound); return peek; } else return peek; } /* Directives-only scanning. Somewhat more relaxed than correct parsing -- some ill-formed programs will not be rejected. */ void cpp_directive_only_process (cpp_reader *pfile, void *data, void (*cb) (cpp_reader *, CPP_DO_task, void *, ...)) { do { restart: /* Buffer initialization, but no line cleaning. */ cpp_buffer *buffer = pfile->buffer; buffer->cur_note = buffer->notes_used = 0; buffer->cur = buffer->line_base = buffer->next_line; buffer->need_line = false; /* Files always end in a newline. We rely on this for character peeking safety. */ gcc_assert (buffer->rlimit[-1] == '\n'); const unsigned char *base = buffer->cur; unsigned line_count = 0; const unsigned char *line_start = base; bool bol = true; bool raw = false; const unsigned char *lwm = base; for (const unsigned char *pos = base, *limit = buffer->rlimit; pos < limit;) { unsigned char c = *pos++; /* This matches the switch in _cpp_lex_direct. */ switch (c) { case ' ': case '\t': case '\f': case '\v': /* Whitespace, do nothing. */ break; case '\r': /* MAC line ending, or Windows \r\n */ if (*pos == '\n') pos++; /* FALLTHROUGH */ case '\n': bol = true; next_line: CPP_INCREMENT_LINE (pfile, 0); line_count++; line_start = pos; break; case '\\': /* is removed, and doesn't undo any preceeding escape or whatnot. */ if (*pos == '\n') { pos++; goto next_line; } else if (*pos == '\r') { if (pos[1] == '\n') pos++; pos++; goto next_line; } goto dflt; case '#': if (bol) { /* Line directive. */ if (pos - 1 > base && !pfile->state.skipping) cb (pfile, CPP_DO_print, data, line_count, base, pos - 1 - base); /* Prep things for directive handling. */ buffer->next_line = pos; buffer->need_line = true; bool ok = _cpp_get_fresh_line (pfile); gcc_checking_assert (ok); /* Ensure proper column numbering for generated error messages. */ buffer->line_base -= pos - line_start; _cpp_handle_directive (pfile, line_start + 1 != pos); /* Sanitize the line settings. Duplicate #include's can mess things up. */ // FIXME: Necessary? pfile->line_table->highest_location = pfile->line_table->highest_line; if (!pfile->state.skipping && pfile->buffer->next_line < pfile->buffer->rlimit) cb (pfile, CPP_DO_location, data, pfile->line_table->highest_line); goto restart; } goto dflt; case '/': { const unsigned char *peek = do_peek_next (pos, limit); if (!(*peek == '/' || *peek == '*')) goto dflt; /* Line or block comment */ bool is_block = *peek == '*'; bool star = false; bool esc = false; location_t sloc = linemap_position_for_column (pfile->line_table, pos - line_start); while (pos < limit) { char c = *pos++; switch (c) { case '\\': esc = true; break; case '\r': if (*pos == '\n') pos++; /* FALLTHROUGH */ case '\n': { CPP_INCREMENT_LINE (pfile, 0); line_count++; line_start = pos; if (!esc && !is_block) { bol = true; goto done_comment; } } if (!esc) star = false; esc = false; break; case '*': if (pos > peek && !esc) star = is_block; esc = false; break; case '/': if (star) goto done_comment; /* FALLTHROUGH */ default: star = false; esc = false; break; } } cpp_error_with_line (pfile, CPP_DL_ERROR, sloc, 0, "unterminated comment"); done_comment: lwm = pos; break; } case '\'': if (!CPP_OPTION (pfile, digit_separators)) goto delimited_string; /* Possibly a number punctuator. */ if (!ISIDNUM (*do_peek_next (pos, limit))) goto delimited_string; goto quote_peek; case '\"': if (!CPP_OPTION (pfile, rliterals)) goto delimited_string; quote_peek: { /* For ' see if it's a number punctuator \.?(| |'|'|[eEpP]|\.)* */ /* For " see if it's a raw string {U,L,u,u8}R. This includes CPP_NUMBER detection, because that could be 0e+R. */ const unsigned char *peek = pos - 1; bool quote_first = c == '"'; bool quote_eight = false; bool maybe_number_start = false; bool want_number = false; while ((peek = do_peek_prev (peek, lwm))) { unsigned char p = *peek; if (quote_first) { if (!raw) { if (p != 'R') break; raw = true; continue; } quote_first = false; if (p == 'L' || p == 'U' || p == 'u') ; else if (p == '8') quote_eight = true; else goto second_raw; } else if (quote_eight) { if (p != 'u') { raw = false; break; } quote_eight = false; } else if (c == '"') { second_raw:; if (!want_number && ISIDNUM (p)) { raw = false; break; } } if (ISDIGIT (p)) maybe_number_start = true; else if (p == '.') want_number = true; else if (ISIDNUM (p)) maybe_number_start = false; else if (p == '+' || p == '-') { if (const unsigned char *peek_prev = do_peek_prev (peek, lwm)) { p = *peek_prev; if (p == 'e' || p == 'E' || p == 'p' || p == 'P') { want_number = true; maybe_number_start = false; } else break; } else break; } else if (p == '\'' || p == '\"') { /* If this is lwm, this must be the end of a previous string. So this is a trailing literal type, (a) if those are allowed, and (b) maybe_start is false. Otherwise this must be a CPP_NUMBER because we've met another ', and we'd have checked that in its own right. */ if (peek == lwm && CPP_OPTION (pfile, uliterals)) { if (!maybe_number_start && !want_number) /* Must be a literal type. */ raw = false; } else if (p == '\'' && CPP_OPTION (pfile, digit_separators)) maybe_number_start = true; break; } else if (c == '\'') break; else if (!quote_first && !quote_eight) break; } if (maybe_number_start) { if (c == '\'') /* A CPP NUMBER. */ goto dflt; raw = false; } goto delimited_string; } delimited_string: { /* (Possibly raw) string or char literal. */ unsigned char end = c; int delim_len = -1; const unsigned char *delim = NULL; location_t sloc = linemap_position_for_column (pfile->line_table, pos - line_start); int esc = 0; if (raw) { /* There can be no line breaks in the delimiter. */ delim = pos; for (delim_len = 0; (c = *pos++) != '('; delim_len++) { if (delim_len == 16) { cpp_error_with_line (pfile, CPP_DL_ERROR, sloc, 0, "raw string delimiter" " longer than %d" " characters", delim_len); raw = false; pos = delim; break; } if (strchr (") \\\t\v\f\n", c)) { cpp_error_with_line (pfile, CPP_DL_ERROR, sloc, 0, "invalid character '%c'" " in raw string" " delimiter", c); raw = false; pos = delim; break; } if (pos >= limit) goto bad_string; } } while (pos < limit) { char c = *pos++; switch (c) { case '\\': if (!raw) esc++; break; case '\r': if (*pos == '\n') pos++; /* FALLTHROUGH */ case '\n': { CPP_INCREMENT_LINE (pfile, 0); line_count++; line_start = pos; } if (esc) esc--; break; case ')': if (raw && pos + delim_len + 1 < limit && pos[delim_len] == end && !memcmp (delim, pos, delim_len)) { pos += delim_len + 1; raw = false; goto done_string; } break; default: if (!raw && !(esc & 1) && c == end) goto done_string; esc = 0; break; } } bad_string: cpp_error_with_line (pfile, CPP_DL_ERROR, sloc, 0, "unterminated literal"); done_string: raw = false; lwm = pos - 1; } goto dflt; default: dflt: bol = false; pfile->mi_valid = false; break; } } if (buffer->rlimit > base && !pfile->state.skipping) cb (pfile, CPP_DO_print, data, line_count, base, buffer->rlimit - base); _cpp_pop_buffer (pfile); } while (pfile->buffer); }