blob: e09ce1312de953c50bc8b2494bcd58d0f386c7bb [file] [log] [blame]
Chris Lattner22eb9722006-06-18 05:43:12 +00001//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner5b12ab82007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Chris Lattner22eb9722006-06-18 05:43:12 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Preprocessor interface.
11//
12//===----------------------------------------------------------------------===//
13//
Chris Lattner22eb9722006-06-18 05:43:12 +000014// Options to support:
15// -H - Print the name of each header file used.
Chris Lattner22eb9722006-06-18 05:43:12 +000016// -d[MDNI] - Dump various things.
17// -fworking-directory - #line's with preprocessor's working dir.
18// -fpreprocessed
19// -dependency-file,-M,-MM,-MF,-MG,-MP,-MT,-MQ,-MD,-MMD
20// -W*
21// -w
22//
23// Messages to emit:
24// "Multiple include guards may be useful for:\n"
25//
Chris Lattner22eb9722006-06-18 05:43:12 +000026//===----------------------------------------------------------------------===//
27
28#include "clang/Lex/Preprocessor.h"
Chris Lattner07b019a2006-10-22 07:28:56 +000029#include "clang/Lex/HeaderSearch.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000030#include "clang/Lex/MacroInfo.h"
Chris Lattnerb8761832006-06-24 21:31:03 +000031#include "clang/Lex/Pragma.h"
Chris Lattner0b8cfc22006-06-28 06:49:17 +000032#include "clang/Lex/ScratchBuffer.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000033#include "clang/Basic/Diagnostic.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000034#include "clang/Basic/SourceManager.h"
Chris Lattner81278c62006-10-14 19:03:49 +000035#include "clang/Basic/TargetInfo.h"
Chris Lattner5cd83512008-10-05 20:40:30 +000036#include "llvm/ADT/APFloat.h"
Chris Lattner7a4af3b2006-07-26 06:26:52 +000037#include "llvm/ADT/SmallVector.h"
Chris Lattner8a7003c2007-07-16 06:48:38 +000038#include "llvm/Support/MemoryBuffer.h"
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +000039#include "llvm/Support/Streams.h"
Chris Lattner22eb9722006-06-18 05:43:12 +000040using namespace clang;
41
42//===----------------------------------------------------------------------===//
43
Ted Kremenek219bab32008-04-17 21:23:07 +000044PreprocessorFactory::~PreprocessorFactory() {}
45
Chris Lattner02dffbd2006-10-14 07:50:21 +000046Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
Chris Lattnerad7cdd32006-11-21 06:08:20 +000047 TargetInfo &target, SourceManager &SM,
Chris Lattner59a9ebd2006-10-18 05:34:33 +000048 HeaderSearch &Headers)
Chris Lattnerad7cdd32006-11-21 06:08:20 +000049 : Diags(diags), Features(opts), Target(target), FileMgr(Headers.getFileMgr()),
50 SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts),
Ted Kremenekc7a36632008-11-19 00:44:06 +000051 CurPPLexer(0), CurDirLookup(0), Callbacks(0) {
Chris Lattner0b8cfc22006-06-28 06:49:17 +000052 ScratchBuf = new ScratchBuffer(SourceMgr);
Chris Lattnerc02c4ab2007-07-15 00:25:26 +000053
Chris Lattner22eb9722006-06-18 05:43:12 +000054 // Clear stats.
Chris Lattner59a9ebd2006-10-18 05:34:33 +000055 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000056 NumIf = NumElse = NumEndif = 0;
Chris Lattner78186052006-07-09 00:45:31 +000057 NumEnteredSourceFiles = 0;
58 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
Chris Lattner510ab612006-07-20 04:47:30 +000059 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
Chris Lattner59a9ebd2006-10-18 05:34:33 +000060 MaxIncludeStackDepth = 0;
Chris Lattner22eb9722006-06-18 05:43:12 +000061 NumSkipped = 0;
Chris Lattnerb352e3e2006-11-21 06:17:10 +000062
63 // Default to discarding comments.
64 KeepComments = false;
65 KeepMacroComments = false;
66
Chris Lattner22eb9722006-06-18 05:43:12 +000067 // Macro expansion is enabled.
68 DisableMacroExpansion = false;
Chris Lattneree8760b2006-07-15 07:42:55 +000069 InMacroArgs = false;
Chris Lattner285c0c12008-03-09 02:26:03 +000070 NumCachedTokenLexers = 0;
Chris Lattner0c885f52006-06-21 06:50:18 +000071
Argyrios Kyrtzidisb3dd1e02008-08-10 13:15:22 +000072 CachedLexPos = 0;
73
Chris Lattner8ff71992006-07-06 05:17:39 +000074 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
75 // This gets unpoisoned where it is allowed.
76 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
77
Chris Lattnerb8761832006-06-24 21:31:03 +000078 // Initialize the pragma handlers.
79 PragmaHandlers = new PragmaNamespace(0);
80 RegisterBuiltinPragmas();
Chris Lattner677757a2006-06-28 05:26:32 +000081
82 // Initialize builtin macros like __LINE__ and friends.
83 RegisterBuiltinMacros();
Chris Lattner22eb9722006-06-18 05:43:12 +000084}
85
86Preprocessor::~Preprocessor() {
Argyrios Kyrtzidis5d240d02008-08-23 12:12:06 +000087 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
88
Chris Lattner69772b02006-07-02 20:34:39 +000089 while (!IncludeMacroStack.empty()) {
90 delete IncludeMacroStack.back().TheLexer;
Chris Lattner285c0c12008-03-09 02:26:03 +000091 delete IncludeMacroStack.back().TheTokenLexer;
Chris Lattner69772b02006-07-02 20:34:39 +000092 IncludeMacroStack.pop_back();
Chris Lattner22eb9722006-06-18 05:43:12 +000093 }
Chris Lattnerc43ddc82007-10-07 08:44:20 +000094
95 // Free any macro definitions.
96 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
97 Macros.begin(), E = Macros.end(); I != E; ++I) {
Ted Kremenek6c7ea112008-12-15 19:56:42 +000098 // We don't need to free the MacroInfo objects directly. These
99 // will be released when the BumpPtrAllocator 'BP' object gets
100 // destroyed.
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000101 I->first->setHasMacroDefinition(false);
102 }
Chris Lattnerb8761832006-06-24 21:31:03 +0000103
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000104 // Free any cached macro expanders.
Chris Lattner285c0c12008-03-09 02:26:03 +0000105 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
106 delete TokenLexerCache[i];
Chris Lattnerc02c4ab2007-07-15 00:25:26 +0000107
Chris Lattnerb8761832006-06-24 21:31:03 +0000108 // Release pragma information.
109 delete PragmaHandlers;
Chris Lattner0b8cfc22006-06-28 06:49:17 +0000110
111 // Delete the scratch buffer info.
112 delete ScratchBuf;
Chris Lattner22192932008-03-14 06:07:05 +0000113
114 delete Callbacks;
Chris Lattner22eb9722006-06-18 05:43:12 +0000115}
116
Chris Lattner146762e2007-07-20 16:59:19 +0000117void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000118 llvm::cerr << tok::getTokenName(Tok.getKind()) << " '"
119 << getSpelling(Tok) << "'";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000120
121 if (!DumpFlags) return;
Chris Lattner615315f2007-12-09 20:31:55 +0000122
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000123 llvm::cerr << "\t";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000124 if (Tok.isAtStartOfLine())
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000125 llvm::cerr << " [StartOfLine]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000126 if (Tok.hasLeadingSpace())
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000127 llvm::cerr << " [LeadingSpace]";
Chris Lattner6e4bf522006-07-27 06:59:25 +0000128 if (Tok.isExpandDisabled())
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000129 llvm::cerr << " [ExpandDisabled]";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000130 if (Tok.needsCleaning()) {
Chris Lattner50b497e2006-06-18 16:32:35 +0000131 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000132 llvm::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
133 << "']";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000134 }
Chris Lattner615315f2007-12-09 20:31:55 +0000135
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000136 llvm::cerr << "\tLoc=<";
Chris Lattner615315f2007-12-09 20:31:55 +0000137 DumpLocation(Tok.getLocation());
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000138 llvm::cerr << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000139}
140
141void Preprocessor::DumpLocation(SourceLocation Loc) const {
142 SourceLocation LogLoc = SourceMgr.getLogicalLoc(Loc);
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000143 llvm::cerr << SourceMgr.getSourceName(LogLoc) << ':'
144 << SourceMgr.getLineNumber(LogLoc) << ':'
Ted Kremenek0fff6d32008-07-19 19:10:04 +0000145 << SourceMgr.getColumnNumber(LogLoc);
Chris Lattner615315f2007-12-09 20:31:55 +0000146
147 SourceLocation PhysLoc = SourceMgr.getPhysicalLoc(Loc);
148 if (PhysLoc != LogLoc) {
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000149 llvm::cerr << " <PhysLoc=";
Chris Lattner615315f2007-12-09 20:31:55 +0000150 DumpLocation(PhysLoc);
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000151 llvm::cerr << ">";
Chris Lattner615315f2007-12-09 20:31:55 +0000152 }
Chris Lattnerd01e2912006-06-18 16:22:51 +0000153}
154
155void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000156 llvm::cerr << "MACRO: ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000157 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
158 DumpToken(MI.getReplacementToken(i));
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000159 llvm::cerr << " ";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000160 }
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000161 llvm::cerr << "\n";
Chris Lattnerd01e2912006-06-18 16:22:51 +0000162}
163
Chris Lattner22eb9722006-06-18 05:43:12 +0000164void Preprocessor::PrintStats() {
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000165 llvm::cerr << "\n*** Preprocessor Stats:\n";
166 llvm::cerr << NumDirectives << " directives found:\n";
167 llvm::cerr << " " << NumDefined << " #define.\n";
168 llvm::cerr << " " << NumUndefined << " #undef.\n";
169 llvm::cerr << " #include/#include_next/#import:\n";
170 llvm::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
171 llvm::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
172 llvm::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
173 llvm::cerr << " " << NumElse << " #else/#elif.\n";
174 llvm::cerr << " " << NumEndif << " #endif.\n";
175 llvm::cerr << " " << NumPragma << " #pragma.\n";
176 llvm::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000177
Ted Kremeneka0a3e9b2008-01-14 16:44:48 +0000178 llvm::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
179 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
180 << NumFastMacroExpanded << " on the fast path.\n";
181 llvm::cerr << (NumFastTokenPaste+NumTokenPaste)
182 << " token paste (##) operations performed, "
183 << NumFastTokenPaste << " on the fast path.\n";
Chris Lattner22eb9722006-06-18 05:43:12 +0000184}
185
186//===----------------------------------------------------------------------===//
Chris Lattnerd01e2912006-06-18 16:22:51 +0000187// Token Spelling
188//===----------------------------------------------------------------------===//
189
190
191/// getSpelling() - Return the 'spelling' of this token. The spelling of a
192/// token are the characters used to represent the token in the source file
193/// after trigraph expansion and escaped-newline folding. In particular, this
194/// wants to get the true, uncanonicalized, spelling of things like digraphs
195/// UCNs, etc.
Chris Lattner146762e2007-07-20 16:59:19 +0000196std::string Preprocessor::getSpelling(const Token &Tok) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000197 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
Ted Kremenekb0b4f742009-01-13 22:05:50 +0000198 const char* TokStart;
199
200 if (PTH) {
201 SourceLocation sloc = SourceMgr.getPhysicalLoc(Tok.getLocation());
Ted Kremeneke9814182009-01-13 23:19:12 +0000202 unsigned fid = SourceMgr.getCanonicalFileID(sloc);
Ted Kremenekb0b4f742009-01-13 22:05:50 +0000203 unsigned fpos = SourceMgr.getFullFilePos(sloc);
204 if (unsigned len = PTH->getSpelling(fid, fpos, TokStart)) {
205 assert(!Tok.needsCleaning());
206 return std::string(TokStart, TokStart+len);
207 }
208 }
Chris Lattnerd01e2912006-06-18 16:22:51 +0000209
210 // If this token contains nothing interesting, return it directly.
Ted Kremenekb0b4f742009-01-13 22:05:50 +0000211 TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000212 if (!Tok.needsCleaning())
213 return std::string(TokStart, TokStart+Tok.getLength());
214
Chris Lattnerd01e2912006-06-18 16:22:51 +0000215 std::string Result;
216 Result.reserve(Tok.getLength());
217
Chris Lattneref9eae12006-07-04 22:33:12 +0000218 // Otherwise, hard case, relex the characters into the string.
Chris Lattnerd01e2912006-06-18 16:22:51 +0000219 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
220 Ptr != End; ) {
221 unsigned CharSize;
222 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
223 Ptr += CharSize;
224 }
225 assert(Result.size() != unsigned(Tok.getLength()) &&
226 "NeedsCleaning flag set on something that didn't need cleaning!");
227 return Result;
228}
229
230/// getSpelling - This method is used to get the spelling of a token into a
231/// preallocated buffer, instead of as an std::string. The caller is required
232/// to allocate enough space for the token, which is guaranteed to be at least
233/// Tok.getLength() bytes long. The actual length of the token is returned.
Chris Lattneref9eae12006-07-04 22:33:12 +0000234///
235/// Note that this method may do two possible things: it may either fill in
236/// the buffer specified with characters, or it may *change the input pointer*
237/// to point to a constant buffer with the data already in it (avoiding a
238/// copy). The caller is not allowed to modify the returned buffer pointer
239/// if an internal buffer is returned.
Chris Lattner146762e2007-07-20 16:59:19 +0000240unsigned Preprocessor::getSpelling(const Token &Tok,
Chris Lattneref9eae12006-07-04 22:33:12 +0000241 const char *&Buffer) const {
Chris Lattnerd01e2912006-06-18 16:22:51 +0000242 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
243
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000244 // If this token is an identifier, just return the string from the identifier
245 // table, which is very quick.
246 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
247 Buffer = II->getName();
Chris Lattner07ebf302009-01-05 19:44:41 +0000248 return II->getLength();
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000249 }
Ted Kremenek884a5582009-01-08 02:47:16 +0000250
251 // If using PTH, try and get the spelling from the PTH file.
Ted Kremenekb0b4f742009-01-13 22:05:50 +0000252 if (PTH) {
253 unsigned len;
Ted Kremenek884a5582009-01-08 02:47:16 +0000254
Ted Kremenekb0b4f742009-01-13 22:05:50 +0000255 if (CurPTHLexer) {
256 // We perform the const_cast<> here because we will only have a PTHLexer
257 // when grabbing a stream of tokens from the PTH file (and thus the
258 // Preprocessor state is allowed to change). The PTHLexer can assume we are
259 // getting token spellings in the order of tokens, and thus can update
260 // its internal state so that it can quickly fetch spellings from the PTH
261 // file.
262 len =
263 const_cast<PTHLexer*>(CurPTHLexer.get())->getSpelling(Tok.getLocation(),
264 Buffer);
265 }
266 else {
267 SourceLocation sloc = SourceMgr.getPhysicalLoc(Tok.getLocation());
Ted Kremeneke9814182009-01-13 23:19:12 +0000268 unsigned fid = SourceMgr.getCanonicalFileID(sloc);
Ted Kremenekb0b4f742009-01-13 22:05:50 +0000269 unsigned fpos = SourceMgr.getFullFilePos(sloc);
270 len = PTH->getSpelling(fid, fpos, Buffer);
271 }
272
Ted Kremenek884a5582009-01-08 02:47:16 +0000273 // Did we find a spelling? If so return its length. Otherwise fall
274 // back to the default behavior for getting the spelling by looking at
Ted Kremenekb0b4f742009-01-13 22:05:50 +0000275 // at the source code.
276 if (len)
277 return len;
Ted Kremenek884a5582009-01-08 02:47:16 +0000278 }
279
Chris Lattnerd3a15f72006-07-04 23:01:03 +0000280 // Otherwise, compute the start of the token in the input lexer buffer.
Chris Lattner50b497e2006-06-18 16:32:35 +0000281 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
Chris Lattnerd01e2912006-06-18 16:22:51 +0000282
283 // If this token contains nothing interesting, return it directly.
284 if (!Tok.needsCleaning()) {
Chris Lattneref9eae12006-07-04 22:33:12 +0000285 Buffer = TokStart;
286 return Tok.getLength();
Chris Lattnerd01e2912006-06-18 16:22:51 +0000287 }
288 // Otherwise, hard case, relex the characters into the string.
Chris Lattneref9eae12006-07-04 22:33:12 +0000289 char *OutBuf = const_cast<char*>(Buffer);
Chris Lattnerd01e2912006-06-18 16:22:51 +0000290 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
291 Ptr != End; ) {
292 unsigned CharSize;
293 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
294 Ptr += CharSize;
295 }
296 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
297 "NeedsCleaning flag set on something that didn't need cleaning!");
298
299 return OutBuf-Buffer;
300}
301
Chris Lattnerb94ec7b2006-07-14 06:54:10 +0000302
303/// CreateString - Plop the specified string into a scratch buffer and return a
304/// location for it. If specified, the source location provides a source
305/// location for the token.
306SourceLocation Preprocessor::
307CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
308 if (SLoc.isValid())
309 return ScratchBuf->getToken(Buf, Len, SLoc);
310 return ScratchBuf->getToken(Buf, Len);
311}
312
313
Chris Lattner8a7003c2007-07-16 06:48:38 +0000314/// AdvanceToTokenCharacter - Given a location that specifies the start of a
315/// token, return a new location that specifies a character within the token.
316SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
317 unsigned CharNo) {
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000318 // If they request the first char of the token, we're trivially done. If this
319 // is a macro expansion, it doesn't make sense to point to a character within
320 // the instantiation point (the name). We could point to the source
321 // character, but without also pointing to instantiation info, this is
322 // confusing.
323 if (CharNo == 0 || TokStart.isMacroID()) return TokStart;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000324
325 // Figure out how many physical characters away the specified logical
326 // character is. This needs to take into consideration newlines and
327 // trigraphs.
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000328 const char *TokPtr = SourceMgr.getCharacterData(TokStart);
329 unsigned PhysOffset = 0;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000330
331 // The usual case is that tokens don't contain anything interesting. Skip
332 // over the uninteresting characters. If a token only consists of simple
333 // chars, this method is extremely fast.
334 while (CharNo && Lexer::isObviouslySimpleCharacter(*TokPtr))
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000335 ++TokPtr, --CharNo, ++PhysOffset;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000336
337 // If we have a character that may be a trigraph or escaped newline, create a
338 // lexer to parse it correctly.
Chris Lattner8a7003c2007-07-16 06:48:38 +0000339 if (CharNo != 0) {
340 // Create a lexer starting at this token position.
Chris Lattner77e9de52007-07-20 16:52:03 +0000341 Lexer TheLexer(TokStart, *this, TokPtr);
Chris Lattner146762e2007-07-20 16:59:19 +0000342 Token Tok;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000343 // Skip over characters the remaining characters.
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000344 const char *TokStartPtr = TokPtr;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000345 for (; CharNo; --CharNo)
346 TheLexer.getAndAdvanceChar(TokPtr, Tok);
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000347
348 PhysOffset += TokPtr-TokStartPtr;
Chris Lattner8a7003c2007-07-16 06:48:38 +0000349 }
Chris Lattnerdc5c0552007-07-20 16:37:10 +0000350
351 return TokStart.getFileLocWithOffset(PhysOffset);
Chris Lattner8a7003c2007-07-16 06:48:38 +0000352}
353
354
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000355//===----------------------------------------------------------------------===//
356// Preprocessor Initialization Methods
357//===----------------------------------------------------------------------===//
358
359// Append a #define line to Buf for Macro. Macro should be of the form XXX,
360// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
361// "#define XXX Y z W". To get a #define with no value, use "XXX=".
362static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
363 const char *Command = "#define ") {
364 Buf.insert(Buf.end(), Command, Command+strlen(Command));
365 if (const char *Equal = strchr(Macro, '=')) {
366 // Turn the = into ' '.
367 Buf.insert(Buf.end(), Macro, Equal);
368 Buf.push_back(' ');
369 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
370 } else {
371 // Push "macroname 1".
372 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
373 Buf.push_back(' ');
374 Buf.push_back('1');
375 }
376 Buf.push_back('\n');
377}
378
Chris Lattner5cd83512008-10-05 20:40:30 +0000379/// PickFP - This is used to pick a value based on the FP semantics of the
380/// specified FP model.
381template <typename T>
382static T PickFP(const llvm::fltSemantics *Sem, T IEEESingleVal,
383 T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal) {
384 if (Sem == &llvm::APFloat::IEEEsingle)
385 return IEEESingleVal;
386 if (Sem == &llvm::APFloat::IEEEdouble)
387 return IEEEDoubleVal;
388 if (Sem == &llvm::APFloat::x87DoubleExtended)
389 return X87DoubleExtendedVal;
390 assert(Sem == &llvm::APFloat::PPCDoubleDouble);
391 return PPCDoubleDoubleVal;
392}
393
394static void DefineFloatMacros(std::vector<char> &Buf, const char *Prefix,
395 const llvm::fltSemantics *Sem) {
Chris Lattner6da2f0d2008-10-05 21:40:58 +0000396 const char *DenormMin, *Epsilon, *Max, *Min;
397 DenormMin = PickFP(Sem, "1.40129846e-45F", "4.9406564584124654e-324",
398 "3.64519953188247460253e-4951L",
399 "4.94065645841246544176568792868221e-324L");
400 int Digits = PickFP(Sem, 6, 15, 18, 31);
401 Epsilon = PickFP(Sem, "1.19209290e-7F", "2.2204460492503131e-16",
402 "1.08420217248550443401e-19L",
403 "4.94065645841246544176568792868221e-324L");
404 int HasInifinity = 1, HasQuietNaN = 1;
405 int MantissaDigits = PickFP(Sem, 24, 53, 64, 106);
406 int Min10Exp = PickFP(Sem, -37, -307, -4931, -291);
407 int Max10Exp = PickFP(Sem, 38, 308, 4932, 308);
408 int MinExp = PickFP(Sem, -125, -1021, -16381, -968);
409 int MaxExp = PickFP(Sem, 128, 1024, 16384, 1024);
410 Min = PickFP(Sem, "1.17549435e-38F", "2.2250738585072014e-308",
411 "3.36210314311209350626e-4932L",
412 "2.00416836000897277799610805135016e-292L");
413 Max = PickFP(Sem, "3.40282347e+38F", "1.7976931348623157e+308",
414 "1.18973149535723176502e+4932L",
415 "1.79769313486231580793728971405301e+308L");
Chris Lattner5cd83512008-10-05 20:40:30 +0000416
417 char MacroBuf[60];
418 sprintf(MacroBuf, "__%s_DENORM_MIN__=%s", Prefix, DenormMin);
419 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattner6da2f0d2008-10-05 21:40:58 +0000420 sprintf(MacroBuf, "__%s_DIG__=%d", Prefix, Digits);
421 DefineBuiltinMacro(Buf, MacroBuf);
422 sprintf(MacroBuf, "__%s_EPSILON__=%s", Prefix, Epsilon);
423 DefineBuiltinMacro(Buf, MacroBuf);
424 sprintf(MacroBuf, "__%s_HAS_INFINITY__=%d", Prefix, HasInifinity);
425 DefineBuiltinMacro(Buf, MacroBuf);
426 sprintf(MacroBuf, "__%s_HAS_QUIET_NAN__=%d", Prefix, HasQuietNaN);
427 DefineBuiltinMacro(Buf, MacroBuf);
428 sprintf(MacroBuf, "__%s_MANT_DIG__=%d", Prefix, MantissaDigits);
429 DefineBuiltinMacro(Buf, MacroBuf);
430 sprintf(MacroBuf, "__%s_MAX_10_EXP__=%d", Prefix, Max10Exp);
431 DefineBuiltinMacro(Buf, MacroBuf);
432 sprintf(MacroBuf, "__%s_MAX_EXP__=%d", Prefix, MaxExp);
433 DefineBuiltinMacro(Buf, MacroBuf);
434 sprintf(MacroBuf, "__%s_MAX__=%s", Prefix, Max);
435 DefineBuiltinMacro(Buf, MacroBuf);
436 sprintf(MacroBuf, "__%s_MIN_10_EXP__=(%d)", Prefix, Min10Exp);
437 DefineBuiltinMacro(Buf, MacroBuf);
438 sprintf(MacroBuf, "__%s_MIN_EXP__=(%d)", Prefix, MinExp);
439 DefineBuiltinMacro(Buf, MacroBuf);
440 sprintf(MacroBuf, "__%s_MIN__=%s", Prefix, Min);
441 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattner5cd83512008-10-05 20:40:30 +0000442}
443
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000444
445static void InitializePredefinedMacros(Preprocessor &PP,
446 std::vector<char> &Buf) {
Chris Lattner1f7e2d542008-10-05 19:32:22 +0000447 // Compiler version introspection macros.
448 DefineBuiltinMacro(Buf, "__llvm__=1"); // LLVM Backend
449 DefineBuiltinMacro(Buf, "__clang__=1"); // Clang Frontend
450
451 // Currently claim to be compatible with GCC 4.2.1-5621.
452 DefineBuiltinMacro(Buf, "__APPLE_CC__=5621");
453 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=2");
454 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
455 DefineBuiltinMacro(Buf, "__GNUC__=4");
456 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
457 DefineBuiltinMacro(Buf, "__VERSION__=\"4.2.1 (Apple Computer, Inc. "
458 "build 5621) (dot 3)\"");
459
460
461 // Initialize language-specific preprocessor defines.
462
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000463 // FIXME: Implement magic like cpp_init_builtins for things like __STDC__
464 // and __DATE__ etc.
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000465 // These should all be defined in the preprocessor according to the
466 // current language configuration.
Steve Naroff1ef21272008-12-18 22:37:25 +0000467 if (!PP.getLangOptions().Microsoft)
468 DefineBuiltinMacro(Buf, "__STDC__=1");
Daniel Dunbar1f3d7842008-12-01 18:55:22 +0000469 if (PP.getLangOptions().AsmPreprocessor)
470 DefineBuiltinMacro(Buf, "__ASSEMBLER__=1");
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000471 if (PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus)
472 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L");
473 else if (0) // STDC94 ?
474 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L");
475
476 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1");
Daniel Dunbar2258aa02008-08-12 00:21:46 +0000477 if (PP.getLangOptions().ObjC1) {
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000478 DefineBuiltinMacro(Buf, "__OBJC__=1");
Daniel Dunbar2258aa02008-08-12 00:21:46 +0000479
480 if (PP.getLangOptions().getGCMode() == LangOptions::NonGC) {
481 DefineBuiltinMacro(Buf, "__weak=");
482 DefineBuiltinMacro(Buf, "__strong=");
483 } else {
484 DefineBuiltinMacro(Buf, "__weak=__attribute__((objc_gc(weak)))");
485 DefineBuiltinMacro(Buf, "__strong=__attribute__((objc_gc(strong)))");
486 DefineBuiltinMacro(Buf, "__OBJC_GC__=1");
487 }
488
489 if (PP.getLangOptions().NeXTRuntime)
490 DefineBuiltinMacro(Buf, "__NEXT_RUNTIME__=1");
Daniel Dunbar2258aa02008-08-12 00:21:46 +0000491 }
Chris Lattner4ecd7532008-10-05 19:44:25 +0000492
Chris Lattner1b0a00a2008-10-06 07:43:09 +0000493 // darwin_constant_cfstrings controls this. This is also dependent
494 // on other things like the runtime I believe. This is set even for C code.
495 DefineBuiltinMacro(Buf, "__CONSTANT_CFSTRINGS__=1");
496
Steve Naroffad918682008-05-15 21:12:10 +0000497 if (PP.getLangOptions().ObjC2)
498 DefineBuiltinMacro(Buf, "OBJC_NEW_PROPERTIES");
Steve Naroff6d40db02007-10-31 18:42:27 +0000499
Chris Lattner7ed32092008-09-30 00:48:48 +0000500 if (PP.getLangOptions().PascalStrings)
501 DefineBuiltinMacro(Buf, "__PASCAL_STRINGS__");
502
Chris Lattner1f7e2d542008-10-05 19:32:22 +0000503 if (PP.getLangOptions().Blocks) {
504 DefineBuiltinMacro(Buf, "__block=__attribute__((__blocks__(byref)))");
505 DefineBuiltinMacro(Buf, "__BLOCKS__=1");
Chris Lattner248d3c42008-10-05 19:32:52 +0000506 }
Chris Lattner1f7e2d542008-10-05 19:32:22 +0000507
508 if (PP.getLangOptions().CPlusPlus) {
509 DefineBuiltinMacro(Buf, "__DEPRECATED=1");
510 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
511 DefineBuiltinMacro(Buf, "__GNUG__=4");
512 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
513 DefineBuiltinMacro(Buf, "__cplusplus=1");
514 DefineBuiltinMacro(Buf, "__private_extern__=extern");
515 }
516
517 // Filter out some microsoft extensions when trying to parse in ms-compat
518 // mode.
519 if (PP.getLangOptions().Microsoft) {
Steve Naroff44ac7772008-12-25 14:16:32 +0000520 DefineBuiltinMacro(Buf, "_cdecl=__cdecl");
Chris Lattner1f7e2d542008-10-05 19:32:22 +0000521 DefineBuiltinMacro(Buf, "__int8=char");
522 DefineBuiltinMacro(Buf, "__int16=short");
523 DefineBuiltinMacro(Buf, "__int32=int");
524 DefineBuiltinMacro(Buf, "__int64=long long");
Chris Lattner1f7e2d542008-10-05 19:32:22 +0000525 }
526
527
528 // Initialize target-specific preprocessor defines.
Chris Lattner4ecd7532008-10-05 19:44:25 +0000529 const TargetInfo &TI = PP.getTargetInfo();
530
531 // Define type sizing macros based on the target properties.
532 assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
533 DefineBuiltinMacro(Buf, "__CHAR_BIT__=8");
534 DefineBuiltinMacro(Buf, "__SCHAR_MAX__=127");
Chris Lattner5cd83512008-10-05 20:40:30 +0000535
536 assert(TI.getWCharWidth() == 32 && "Only support 32-bit wchar so far");
537 DefineBuiltinMacro(Buf, "__WCHAR_MAX__=2147483647");
538 DefineBuiltinMacro(Buf, "__WCHAR_TYPE__=int");
539 DefineBuiltinMacro(Buf, "__WINT_TYPE__=int");
Chris Lattner4ecd7532008-10-05 19:44:25 +0000540
541 assert(TI.getShortWidth() == 16 && "Only support 16-bit short so far");
Chris Lattner4ecd7532008-10-05 19:44:25 +0000542 DefineBuiltinMacro(Buf, "__SHRT_MAX__=32767");
543
Chris Lattner6512a882008-10-05 20:06:37 +0000544 if (TI.getIntWidth() == 32)
545 DefineBuiltinMacro(Buf, "__INT_MAX__=2147483647");
546 else if (TI.getIntWidth() == 16)
547 DefineBuiltinMacro(Buf, "__INT_MAX__=32767");
548 else
549 assert(0 && "Unknown integer size");
Sanjiv Guptad7959242008-10-31 09:52:39 +0000550
551 if (TI.getLongLongWidth() == 64)
552 DefineBuiltinMacro(Buf, "__LONG_LONG_MAX__=9223372036854775807LL");
553 else if (TI.getLongLongWidth() == 32)
554 DefineBuiltinMacro(Buf, "__LONG_LONG_MAX__=2147483647L");
Chris Lattner4ecd7532008-10-05 19:44:25 +0000555
Chris Lattner6512a882008-10-05 20:06:37 +0000556 if (TI.getLongWidth() == 32)
557 DefineBuiltinMacro(Buf, "__LONG_MAX__=2147483647L");
558 else if (TI.getLongWidth() == 64)
559 DefineBuiltinMacro(Buf, "__LONG_MAX__=9223372036854775807L");
560 else if (TI.getLongWidth() == 16)
561 DefineBuiltinMacro(Buf, "__LONG_MAX__=32767L");
562 else
563 assert(0 && "Unknown long size");
Sanjiv Guptad7959242008-10-31 09:52:39 +0000564 char MacroBuf[60];
565 sprintf(MacroBuf, "__INTMAX_MAX__=%lld",
566 (TI.getIntMaxType() == TargetInfo::UnsignedLongLong?
Sanjiv Gupta83b95cc2008-10-31 10:24:31 +0000567 (1LL << (TI.getLongLongWidth() - 1)) :
568 ((1LL << (TI.getLongLongWidth() - 2)) - 1)));
Sanjiv Guptad7959242008-10-31 09:52:39 +0000569 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattner6512a882008-10-05 20:06:37 +0000570
Sanjiv Guptad7959242008-10-31 09:52:39 +0000571 if (TI.getIntMaxType() == TargetInfo::UnsignedLongLong)
572 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=unsigned long long int");
573 else if (TI.getIntMaxType() == TargetInfo::SignedLongLong)
Chris Lattner6512a882008-10-05 20:06:37 +0000574 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=long long int");
Sanjiv Guptad7959242008-10-31 09:52:39 +0000575 else if (TI.getIntMaxType() == TargetInfo::UnsignedLong)
576 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=unsigned long int");
577 else if (TI.getIntMaxType() == TargetInfo::SignedLong)
578 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=long int");
579 else if (TI.getIntMaxType() == TargetInfo::UnsignedInt)
580 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=unsigned int");
581 else
582 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=int");
Chris Lattner6512a882008-10-05 20:06:37 +0000583
Sanjiv Guptad7959242008-10-31 09:52:39 +0000584 if (TI.getUIntMaxType() == TargetInfo::UnsignedLongLong)
585 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=unsigned long long int");
586 else if (TI.getUIntMaxType() == TargetInfo::SignedLongLong)
587 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=long long int");
588 else if (TI.getUIntMaxType() == TargetInfo::UnsignedLong)
589 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=unsigned long int");
590 else if (TI.getUIntMaxType() == TargetInfo::SignedLong)
591 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=long int");
592 else if (TI.getUIntMaxType() == TargetInfo::UnsignedInt)
593 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=unsigned int");
594 else
595 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=int");
596
597 if (TI.getPtrDiffType(0) == TargetInfo::UnsignedLongLong)
598 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=unsigned long long int");
599 else if (TI.getPtrDiffType(0) == TargetInfo::SignedLongLong)
600 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=long long int");
601 else if (TI.getPtrDiffType(0) == TargetInfo::UnsignedLong)
602 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=unsigned long int");
603 else if (TI.getPtrDiffType(0) == TargetInfo::SignedLong)
604 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=long int");
605 else if (TI.getPtrDiffType(0) == TargetInfo::UnsignedInt)
606 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=unsigned int");
607 else
608 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=int");
609
610 if (TI.getSizeType() == TargetInfo::UnsignedLongLong)
611 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=unsigned long long int");
612 else if (TI.getSizeType() == TargetInfo::SignedLongLong)
613 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=long long int");
614 else if (TI.getSizeType() == TargetInfo::UnsignedLong)
615 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=unsigned long int");
616 else if (TI.getSizeType() == TargetInfo::SignedLong)
617 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=long int");
618 else if (TI.getSizeType() == TargetInfo::UnsignedInt)
619 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=unsigned int");
620 else if (TI.getSizeType() == TargetInfo::SignedInt)
621 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=int");
622 else
623 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=unsigned short");
624
Chris Lattner5cd83512008-10-05 20:40:30 +0000625 DefineFloatMacros(Buf, "FLT", &TI.getFloatFormat());
626 DefineFloatMacros(Buf, "DBL", &TI.getDoubleFormat());
627 DefineFloatMacros(Buf, "LDBL", &TI.getLongDoubleFormat());
Chris Lattner6512a882008-10-05 20:06:37 +0000628
Chris Lattner7ed32092008-09-30 00:48:48 +0000629
Chris Lattnered2a9eb2007-10-10 17:48:53 +0000630 // Add __builtin_va_list typedef.
631 {
Chris Lattner4ecd7532008-10-05 19:44:25 +0000632 const char *VAList = TI.getVAListDeclaration();
Chris Lattnered2a9eb2007-10-10 17:48:53 +0000633 Buf.insert(Buf.end(), VAList, VAList+strlen(VAList));
634 Buf.push_back('\n');
635 }
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000636
Chris Lattner4ecd7532008-10-05 19:44:25 +0000637 if (const char *Prefix = TI.getUserLabelPrefix()) {
Chris Lattnerac7ed9a2008-10-05 21:49:27 +0000638 sprintf(MacroBuf, "__USER_LABEL_PREFIX__=%s", Prefix);
639 DefineBuiltinMacro(Buf, MacroBuf);
Chris Lattnerf37bafc2008-10-05 19:22:37 +0000640 }
641
Chris Lattner4ecd7532008-10-05 19:44:25 +0000642 // Build configuration options. FIXME: these should be controlled by
643 // command line options or something.
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000644 DefineBuiltinMacro(Buf, "__DYNAMIC__=1");
645 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
646 DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
647 DefineBuiltinMacro(Buf, "__PIC__=1");
Chris Lattner4ecd7532008-10-05 19:44:25 +0000648
Chris Lattnerac7ed9a2008-10-05 21:49:27 +0000649 // Macros to control C99 numerics and <float.h>
650 DefineBuiltinMacro(Buf, "__FLT_EVAL_METHOD__=0");
651 DefineBuiltinMacro(Buf, "__FLT_RADIX__=2");
652 sprintf(MacroBuf, "__DECIMAL_DIG__=%d",
653 PickFP(&TI.getLongDoubleFormat(), -1/*FIXME*/, 17, 21, 33));
654 DefineBuiltinMacro(Buf, MacroBuf);
655
Chris Lattner4ecd7532008-10-05 19:44:25 +0000656 // Get other target #defines.
657 TI.getTargetDefines(Buf);
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000658
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000659 // FIXME: Should emit a #line directive here.
660}
661
662
663/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begemanf7c3ff62008-01-07 04:01:26 +0000664/// which implicitly adds the builtin defines etc.
Ted Kremenek230bd912007-12-19 22:51:13 +0000665void Preprocessor::EnterMainSourceFile() {
666
667 unsigned MainFileID = SourceMgr.getMainFileID();
668
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000669 // Enter the main file source buffer.
670 EnterSourceFile(MainFileID, 0);
671
Chris Lattner609d4132007-11-15 19:07:47 +0000672 // Tell the header info that the main file was entered. If the file is later
673 // #imported, it won't be re-entered.
674 if (const FileEntry *FE =
675 SourceMgr.getFileEntryForLoc(SourceLocation::getFileLoc(MainFileID, 0)))
676 HeaderInfo.IncrementIncludeCount(FE);
677
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000678 std::vector<char> PrologFile;
679 PrologFile.reserve(4080);
680
681 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
682 InitializePredefinedMacros(*this, PrologFile);
683
684 // Add on the predefines from the driver.
Chris Lattnerba1f37b2008-04-19 23:09:31 +0000685 PrologFile.insert(PrologFile.end(), Predefines.begin(), Predefines.end());
Chris Lattner1f1b0db2007-10-09 22:10:18 +0000686
687 // Memory buffer must end with a null byte!
688 PrologFile.push_back(0);
689
690 // Now that we have emitted the predefined macros, #includes, etc into
691 // PrologFile, preprocess it to populate the initial preprocessor state.
692 llvm::MemoryBuffer *SB =
693 llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(),
694 "<predefines>");
695 assert(SB && "Cannot fail to create predefined source buffer");
696 unsigned FileID = SourceMgr.createFileIDForMemBuffer(SB);
697 assert(FileID && "Could not create FileID for predefines?");
698
699 // Start parsing the predefines.
700 EnterSourceFile(FileID, 0);
701}
Chris Lattner8a7003c2007-07-16 06:48:38 +0000702
Chris Lattner677757a2006-06-28 05:26:32 +0000703
704//===----------------------------------------------------------------------===//
705// Lexer Event Handling.
706//===----------------------------------------------------------------------===//
707
Chris Lattnercefc7682006-07-08 08:28:12 +0000708/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
709/// identifier information for the token and install it into the token.
Chris Lattner146762e2007-07-20 16:59:19 +0000710IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
Chris Lattnercefc7682006-07-08 08:28:12 +0000711 const char *BufPtr) {
Chris Lattner98c1f7c2007-10-09 18:02:16 +0000712 assert(Identifier.is(tok::identifier) && "Not an identifier!");
Chris Lattnercefc7682006-07-08 08:28:12 +0000713 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
714
715 // Look up this token, see if it is a macro, or if it is a language keyword.
716 IdentifierInfo *II;
717 if (BufPtr && !Identifier.needsCleaning()) {
718 // No cleaning needed, just use the characters from the lexed buffer.
719 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
720 } else {
721 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattnerf9aba2c2007-07-13 17:10:38 +0000722 llvm::SmallVector<char, 64> IdentifierBuffer;
723 IdentifierBuffer.resize(Identifier.getLength());
724 const char *TmpBuf = &IdentifierBuffer[0];
Chris Lattnercefc7682006-07-08 08:28:12 +0000725 unsigned Size = getSpelling(Identifier, TmpBuf);
726 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
727 }
Chris Lattner8c204872006-10-14 05:19:21 +0000728 Identifier.setIdentifierInfo(II);
Chris Lattnercefc7682006-07-08 08:28:12 +0000729 return II;
730}
731
732
Chris Lattner677757a2006-06-28 05:26:32 +0000733/// HandleIdentifier - This callback is invoked when the lexer reads an
734/// identifier. This callback looks up the identifier in the map and/or
735/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattner146762e2007-07-20 16:59:19 +0000736void Preprocessor::HandleIdentifier(Token &Identifier) {
Chris Lattner0f1f5052006-07-20 04:16:23 +0000737 assert(Identifier.getIdentifierInfo() &&
738 "Can't handle identifiers without identifier info!");
739
Chris Lattnerc79f6fb2006-07-04 17:53:21 +0000740 IdentifierInfo &II = *Identifier.getIdentifierInfo();
Chris Lattner677757a2006-06-28 05:26:32 +0000741
742 // If this identifier was poisoned, and if it was not produced from a macro
743 // expansion, emit an error.
Ted Kremeneka2c3c8d2008-11-19 22:43:49 +0000744 if (II.isPoisoned() && CurPPLexer) {
Chris Lattner8ff71992006-07-06 05:17:39 +0000745 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
746 Diag(Identifier, diag::err_pp_used_poisoned_id);
747 else
748 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
749 }
Chris Lattner677757a2006-06-28 05:26:32 +0000750
Chris Lattner78186052006-07-09 00:45:31 +0000751 // If this is a macro to be expanded, do it.
Chris Lattnerc43ddc82007-10-07 08:44:20 +0000752 if (MacroInfo *MI = getMacroInfo(&II)) {
Chris Lattner6e4bf522006-07-27 06:59:25 +0000753 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
754 if (MI->isEnabled()) {
755 if (!HandleMacroExpandedIdentifier(Identifier, MI))
756 return;
757 } else {
758 // C99 6.10.3.4p2 says that a disabled macro may never again be
759 // expanded, even if it's in a context where it could be expanded in the
760 // future.
Chris Lattner146762e2007-07-20 16:59:19 +0000761 Identifier.setFlag(Token::DisableExpand);
Chris Lattner6e4bf522006-07-27 06:59:25 +0000762 }
763 }
Chris Lattner063400e2006-10-14 19:54:15 +0000764 }
Chris Lattner677757a2006-06-28 05:26:32 +0000765
Chris Lattner5b9f4892006-11-21 17:23:33 +0000766 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
767 // then we act as if it is the actual operator and not the textual
768 // representation of it.
769 if (II.isCPlusPlusOperatorKeyword())
770 Identifier.setIdentifierInfo(0);
771
Chris Lattner677757a2006-06-28 05:26:32 +0000772 // Change the kind of this identifier to the appropriate token kind, e.g.
773 // turning "for" into a keyword.
Chris Lattner8c204872006-10-14 05:19:21 +0000774 Identifier.setKind(II.getTokenID());
Chris Lattner677757a2006-06-28 05:26:32 +0000775
776 // If this is an extension token, diagnose its use.
Steve Naroffc84e8b72008-09-02 18:50:17 +0000777 // We avoid diagnosing tokens that originate from macro definitions.
778 if (II.isExtensionToken() && Features.C99 && !DisableMacroExpansion)
Chris Lattner53621a52007-06-13 20:44:40 +0000779 Diag(Identifier, diag::ext_token_used);
Chris Lattner677757a2006-06-28 05:26:32 +0000780}