blob: f00f1ea69c1ac13237feff1e162279eafaf076f3 [file] [log] [blame]
Reid Spencer5f016e22007-07-11 17:01:13 +00001//===--- Preprocess.cpp - C Language Family Preprocessor Implementation ---===//
2//
3// The LLVM Compiler Infrastructure
4//
Chris Lattner0bc735f2007-12-29 19:59:25 +00005// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
Reid Spencer5f016e22007-07-11 17:01:13 +00007//
8//===----------------------------------------------------------------------===//
9//
10// This file implements the Preprocessor interface.
11//
12//===----------------------------------------------------------------------===//
13//
14// Options to support:
15// -H - Print the name of each header file used.
16// -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//
26//===----------------------------------------------------------------------===//
27
28#include "clang/Lex/Preprocessor.h"
29#include "clang/Lex/HeaderSearch.h"
30#include "clang/Lex/MacroInfo.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000031#include "clang/Lex/Pragma.h"
32#include "clang/Lex/ScratchBuffer.h"
33#include "clang/Basic/Diagnostic.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000034#include "clang/Basic/SourceManager.h"
35#include "clang/Basic/TargetInfo.h"
Chris Lattner2db78dd2008-10-05 20:40:30 +000036#include "llvm/ADT/APFloat.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000037#include "llvm/ADT/SmallVector.h"
Chris Lattner97ba77c2007-07-16 06:48:38 +000038#include "llvm/Support/MemoryBuffer.h"
Ted Kremenekbdd30c22008-01-14 16:44:48 +000039#include "llvm/Support/Streams.h"
Reid Spencer5f016e22007-07-11 17:01:13 +000040using namespace clang;
41
42//===----------------------------------------------------------------------===//
43
Ted Kremenekec6c5742008-04-17 21:23:07 +000044PreprocessorFactory::~PreprocessorFactory() {}
45
Reid Spencer5f016e22007-07-11 17:01:13 +000046Preprocessor::Preprocessor(Diagnostic &diags, const LangOptions &opts,
47 TargetInfo &target, SourceManager &SM,
48 HeaderSearch &Headers)
49 : Diags(diags), Features(opts), Target(target), FileMgr(Headers.getFileMgr()),
50 SourceMgr(SM), HeaderInfo(Headers), Identifiers(opts),
Chris Lattner6cfe7592008-03-09 02:26:03 +000051 CurLexer(0), CurDirLookup(0), CurTokenLexer(0), Callbacks(0) {
Reid Spencer5f016e22007-07-11 17:01:13 +000052 ScratchBuf = new ScratchBuffer(SourceMgr);
Chris Lattner9594acf2007-07-15 00:25:26 +000053
Reid Spencer5f016e22007-07-11 17:01:13 +000054 // Clear stats.
55 NumDirectives = NumDefined = NumUndefined = NumPragma = 0;
56 NumIf = NumElse = NumEndif = 0;
57 NumEnteredSourceFiles = 0;
58 NumMacroExpanded = NumFnMacroExpanded = NumBuiltinMacroExpanded = 0;
59 NumFastMacroExpanded = NumTokenPaste = NumFastTokenPaste = 0;
60 MaxIncludeStackDepth = 0;
61 NumSkipped = 0;
62
63 // Default to discarding comments.
64 KeepComments = false;
65 KeepMacroComments = false;
66
67 // Macro expansion is enabled.
68 DisableMacroExpansion = false;
69 InMacroArgs = false;
Chris Lattner6cfe7592008-03-09 02:26:03 +000070 NumCachedTokenLexers = 0;
Reid Spencer5f016e22007-07-11 17:01:13 +000071
Argyrios Kyrtzidis03db1b32008-08-10 13:15:22 +000072 CacheTokens = false;
73 CachedLexPos = 0;
74
Reid Spencer5f016e22007-07-11 17:01:13 +000075 // "Poison" __VA_ARGS__, which can only appear in the expansion of a macro.
76 // This gets unpoisoned where it is allowed.
77 (Ident__VA_ARGS__ = getIdentifierInfo("__VA_ARGS__"))->setIsPoisoned();
78
79 // Initialize the pragma handlers.
80 PragmaHandlers = new PragmaNamespace(0);
81 RegisterBuiltinPragmas();
82
83 // Initialize builtin macros like __LINE__ and friends.
84 RegisterBuiltinMacros();
85}
86
87Preprocessor::~Preprocessor() {
Argyrios Kyrtzidis2174a4f2008-08-23 12:12:06 +000088 assert(BacktrackPositions.empty() && "EnableBacktrack/Backtrack imbalance!");
89
Reid Spencer5f016e22007-07-11 17:01:13 +000090 // Free any active lexers.
91 delete CurLexer;
92
93 while (!IncludeMacroStack.empty()) {
94 delete IncludeMacroStack.back().TheLexer;
Chris Lattner6cfe7592008-03-09 02:26:03 +000095 delete IncludeMacroStack.back().TheTokenLexer;
Reid Spencer5f016e22007-07-11 17:01:13 +000096 IncludeMacroStack.pop_back();
97 }
Chris Lattnercc1a8752007-10-07 08:44:20 +000098
99 // Free any macro definitions.
100 for (llvm::DenseMap<IdentifierInfo*, MacroInfo*>::iterator I =
101 Macros.begin(), E = Macros.end(); I != E; ++I) {
102 // Free the macro definition.
103 delete I->second;
104 I->second = 0;
105 I->first->setHasMacroDefinition(false);
106 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000107
Chris Lattner9594acf2007-07-15 00:25:26 +0000108 // Free any cached macro expanders.
Chris Lattner6cfe7592008-03-09 02:26:03 +0000109 for (unsigned i = 0, e = NumCachedTokenLexers; i != e; ++i)
110 delete TokenLexerCache[i];
Chris Lattner9594acf2007-07-15 00:25:26 +0000111
Reid Spencer5f016e22007-07-11 17:01:13 +0000112 // Release pragma information.
113 delete PragmaHandlers;
114
115 // Delete the scratch buffer info.
116 delete ScratchBuf;
Chris Lattnereb50ed82008-03-14 06:07:05 +0000117
118 delete Callbacks;
Reid Spencer5f016e22007-07-11 17:01:13 +0000119}
120
Reid Spencer5f016e22007-07-11 17:01:13 +0000121/// Diag - Forwarding function for diagnostics. This emits a diagnostic at
Chris Lattnerd2177732007-07-20 16:59:19 +0000122/// the specified Token's location, translating the token's start
Reid Spencer5f016e22007-07-11 17:01:13 +0000123/// position in the current buffer into a SourcePosition object for rendering.
124void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID) {
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000125 Diags.Report(getFullLoc(Loc), DiagID);
Reid Spencer5f016e22007-07-11 17:01:13 +0000126}
127
128void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
129 const std::string &Msg) {
Ted Kremenek9c728dc2007-12-12 22:39:36 +0000130 Diags.Report(getFullLoc(Loc), DiagID, &Msg, 1);
Reid Spencer5f016e22007-07-11 17:01:13 +0000131}
132
Chris Lattner8ed30442008-05-05 06:45:50 +0000133void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
134 const std::string &Msg,
135 const SourceRange &R1, const SourceRange &R2) {
136 SourceRange R[] = {R1, R2};
137 Diags.Report(getFullLoc(Loc), DiagID, &Msg, 1, R, 2);
138}
139
140
141void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
142 const SourceRange &R) {
143 Diags.Report(getFullLoc(Loc), DiagID, 0, 0, &R, 1);
144}
145
146void Preprocessor::Diag(SourceLocation Loc, unsigned DiagID,
147 const SourceRange &R1, const SourceRange &R2) {
148 SourceRange R[] = {R1, R2};
149 Diags.Report(getFullLoc(Loc), DiagID, 0, 0, R, 2);
150}
151
152
Chris Lattnerd2177732007-07-20 16:59:19 +0000153void Preprocessor::DumpToken(const Token &Tok, bool DumpFlags) const {
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000154 llvm::cerr << tok::getTokenName(Tok.getKind()) << " '"
155 << getSpelling(Tok) << "'";
Reid Spencer5f016e22007-07-11 17:01:13 +0000156
157 if (!DumpFlags) return;
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000158
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000159 llvm::cerr << "\t";
Reid Spencer5f016e22007-07-11 17:01:13 +0000160 if (Tok.isAtStartOfLine())
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000161 llvm::cerr << " [StartOfLine]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000162 if (Tok.hasLeadingSpace())
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000163 llvm::cerr << " [LeadingSpace]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000164 if (Tok.isExpandDisabled())
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000165 llvm::cerr << " [ExpandDisabled]";
Reid Spencer5f016e22007-07-11 17:01:13 +0000166 if (Tok.needsCleaning()) {
167 const char *Start = SourceMgr.getCharacterData(Tok.getLocation());
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000168 llvm::cerr << " [UnClean='" << std::string(Start, Start+Tok.getLength())
169 << "']";
Reid Spencer5f016e22007-07-11 17:01:13 +0000170 }
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000171
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000172 llvm::cerr << "\tLoc=<";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000173 DumpLocation(Tok.getLocation());
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000174 llvm::cerr << ">";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000175}
176
177void Preprocessor::DumpLocation(SourceLocation Loc) const {
178 SourceLocation LogLoc = SourceMgr.getLogicalLoc(Loc);
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000179 llvm::cerr << SourceMgr.getSourceName(LogLoc) << ':'
180 << SourceMgr.getLineNumber(LogLoc) << ':'
Ted Kremenek109949a2008-07-19 19:10:04 +0000181 << SourceMgr.getColumnNumber(LogLoc);
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000182
183 SourceLocation PhysLoc = SourceMgr.getPhysicalLoc(Loc);
184 if (PhysLoc != LogLoc) {
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000185 llvm::cerr << " <PhysLoc=";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000186 DumpLocation(PhysLoc);
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000187 llvm::cerr << ">";
Chris Lattnerc3d8d572007-12-09 20:31:55 +0000188 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000189}
190
191void Preprocessor::DumpMacro(const MacroInfo &MI) const {
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000192 llvm::cerr << "MACRO: ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000193 for (unsigned i = 0, e = MI.getNumTokens(); i != e; ++i) {
194 DumpToken(MI.getReplacementToken(i));
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000195 llvm::cerr << " ";
Reid Spencer5f016e22007-07-11 17:01:13 +0000196 }
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000197 llvm::cerr << "\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000198}
199
200void Preprocessor::PrintStats() {
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000201 llvm::cerr << "\n*** Preprocessor Stats:\n";
202 llvm::cerr << NumDirectives << " directives found:\n";
203 llvm::cerr << " " << NumDefined << " #define.\n";
204 llvm::cerr << " " << NumUndefined << " #undef.\n";
205 llvm::cerr << " #include/#include_next/#import:\n";
206 llvm::cerr << " " << NumEnteredSourceFiles << " source files entered.\n";
207 llvm::cerr << " " << MaxIncludeStackDepth << " max include stack depth\n";
208 llvm::cerr << " " << NumIf << " #if/#ifndef/#ifdef.\n";
209 llvm::cerr << " " << NumElse << " #else/#elif.\n";
210 llvm::cerr << " " << NumEndif << " #endif.\n";
211 llvm::cerr << " " << NumPragma << " #pragma.\n";
212 llvm::cerr << NumSkipped << " #if/#ifndef#ifdef regions skipped\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000213
Ted Kremenekbdd30c22008-01-14 16:44:48 +0000214 llvm::cerr << NumMacroExpanded << "/" << NumFnMacroExpanded << "/"
215 << NumBuiltinMacroExpanded << " obj/fn/builtin macros expanded, "
216 << NumFastMacroExpanded << " on the fast path.\n";
217 llvm::cerr << (NumFastTokenPaste+NumTokenPaste)
218 << " token paste (##) operations performed, "
219 << NumFastTokenPaste << " on the fast path.\n";
Reid Spencer5f016e22007-07-11 17:01:13 +0000220}
221
222//===----------------------------------------------------------------------===//
223// Token Spelling
224//===----------------------------------------------------------------------===//
225
226
227/// getSpelling() - Return the 'spelling' of this token. The spelling of a
228/// token are the characters used to represent the token in the source file
229/// after trigraph expansion and escaped-newline folding. In particular, this
230/// wants to get the true, uncanonicalized, spelling of things like digraphs
231/// UCNs, etc.
Chris Lattnerd2177732007-07-20 16:59:19 +0000232std::string Preprocessor::getSpelling(const Token &Tok) const {
Reid Spencer5f016e22007-07-11 17:01:13 +0000233 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
234
235 // If this token contains nothing interesting, return it directly.
236 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
237 if (!Tok.needsCleaning())
238 return std::string(TokStart, TokStart+Tok.getLength());
239
240 std::string Result;
241 Result.reserve(Tok.getLength());
242
243 // Otherwise, hard case, relex the characters into the string.
244 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
245 Ptr != End; ) {
246 unsigned CharSize;
247 Result.push_back(Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features));
248 Ptr += CharSize;
249 }
250 assert(Result.size() != unsigned(Tok.getLength()) &&
251 "NeedsCleaning flag set on something that didn't need cleaning!");
252 return Result;
253}
254
255/// getSpelling - This method is used to get the spelling of a token into a
256/// preallocated buffer, instead of as an std::string. The caller is required
257/// to allocate enough space for the token, which is guaranteed to be at least
258/// Tok.getLength() bytes long. The actual length of the token is returned.
259///
260/// Note that this method may do two possible things: it may either fill in
261/// the buffer specified with characters, or it may *change the input pointer*
262/// to point to a constant buffer with the data already in it (avoiding a
263/// copy). The caller is not allowed to modify the returned buffer pointer
264/// if an internal buffer is returned.
Chris Lattnerd2177732007-07-20 16:59:19 +0000265unsigned Preprocessor::getSpelling(const Token &Tok,
Reid Spencer5f016e22007-07-11 17:01:13 +0000266 const char *&Buffer) const {
267 assert((int)Tok.getLength() >= 0 && "Token character range is bogus!");
268
269 // If this token is an identifier, just return the string from the identifier
270 // table, which is very quick.
271 if (const IdentifierInfo *II = Tok.getIdentifierInfo()) {
272 Buffer = II->getName();
Chris Lattner0f670322007-07-22 22:50:09 +0000273
274 // Return the length of the token. If the token needed cleaning, don't
275 // include the size of the newlines or trigraphs in it.
276 if (!Tok.needsCleaning())
277 return Tok.getLength();
278 else
279 return strlen(Buffer);
Reid Spencer5f016e22007-07-11 17:01:13 +0000280 }
281
282 // Otherwise, compute the start of the token in the input lexer buffer.
283 const char *TokStart = SourceMgr.getCharacterData(Tok.getLocation());
284
285 // If this token contains nothing interesting, return it directly.
286 if (!Tok.needsCleaning()) {
287 Buffer = TokStart;
288 return Tok.getLength();
289 }
290 // Otherwise, hard case, relex the characters into the string.
291 char *OutBuf = const_cast<char*>(Buffer);
292 for (const char *Ptr = TokStart, *End = TokStart+Tok.getLength();
293 Ptr != End; ) {
294 unsigned CharSize;
295 *OutBuf++ = Lexer::getCharAndSizeNoWarn(Ptr, CharSize, Features);
296 Ptr += CharSize;
297 }
298 assert(unsigned(OutBuf-Buffer) != Tok.getLength() &&
299 "NeedsCleaning flag set on something that didn't need cleaning!");
300
301 return OutBuf-Buffer;
302}
303
304
305/// CreateString - Plop the specified string into a scratch buffer and return a
306/// location for it. If specified, the source location provides a source
307/// location for the token.
308SourceLocation Preprocessor::
309CreateString(const char *Buf, unsigned Len, SourceLocation SLoc) {
310 if (SLoc.isValid())
311 return ScratchBuf->getToken(Buf, Len, SLoc);
312 return ScratchBuf->getToken(Buf, Len);
313}
314
315
Chris Lattner97ba77c2007-07-16 06:48:38 +0000316/// AdvanceToTokenCharacter - Given a location that specifies the start of a
317/// token, return a new location that specifies a character within the token.
318SourceLocation Preprocessor::AdvanceToTokenCharacter(SourceLocation TokStart,
319 unsigned CharNo) {
Chris Lattner9dc1f532007-07-20 16:37:10 +0000320 // If they request the first char of the token, we're trivially done. If this
321 // is a macro expansion, it doesn't make sense to point to a character within
322 // the instantiation point (the name). We could point to the source
323 // character, but without also pointing to instantiation info, this is
324 // confusing.
325 if (CharNo == 0 || TokStart.isMacroID()) return TokStart;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000326
327 // Figure out how many physical characters away the specified logical
328 // character is. This needs to take into consideration newlines and
329 // trigraphs.
Chris Lattner9dc1f532007-07-20 16:37:10 +0000330 const char *TokPtr = SourceMgr.getCharacterData(TokStart);
331 unsigned PhysOffset = 0;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000332
333 // The usual case is that tokens don't contain anything interesting. Skip
334 // over the uninteresting characters. If a token only consists of simple
335 // chars, this method is extremely fast.
336 while (CharNo && Lexer::isObviouslySimpleCharacter(*TokPtr))
Chris Lattner9dc1f532007-07-20 16:37:10 +0000337 ++TokPtr, --CharNo, ++PhysOffset;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000338
339 // If we have a character that may be a trigraph or escaped newline, create a
340 // lexer to parse it correctly.
Chris Lattner97ba77c2007-07-16 06:48:38 +0000341 if (CharNo != 0) {
342 // Create a lexer starting at this token position.
Chris Lattner25bdb512007-07-20 16:52:03 +0000343 Lexer TheLexer(TokStart, *this, TokPtr);
Chris Lattnerd2177732007-07-20 16:59:19 +0000344 Token Tok;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000345 // Skip over characters the remaining characters.
Chris Lattner9dc1f532007-07-20 16:37:10 +0000346 const char *TokStartPtr = TokPtr;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000347 for (; CharNo; --CharNo)
348 TheLexer.getAndAdvanceChar(TokPtr, Tok);
Chris Lattner9dc1f532007-07-20 16:37:10 +0000349
350 PhysOffset += TokPtr-TokStartPtr;
Chris Lattner97ba77c2007-07-16 06:48:38 +0000351 }
Chris Lattner9dc1f532007-07-20 16:37:10 +0000352
353 return TokStart.getFileLocWithOffset(PhysOffset);
Chris Lattner97ba77c2007-07-16 06:48:38 +0000354}
355
356
Chris Lattner53b0dab2007-10-09 22:10:18 +0000357//===----------------------------------------------------------------------===//
358// Preprocessor Initialization Methods
359//===----------------------------------------------------------------------===//
360
361// Append a #define line to Buf for Macro. Macro should be of the form XXX,
362// in which case we emit "#define XXX 1" or "XXX=Y z W" in which case we emit
363// "#define XXX Y z W". To get a #define with no value, use "XXX=".
364static void DefineBuiltinMacro(std::vector<char> &Buf, const char *Macro,
365 const char *Command = "#define ") {
366 Buf.insert(Buf.end(), Command, Command+strlen(Command));
367 if (const char *Equal = strchr(Macro, '=')) {
368 // Turn the = into ' '.
369 Buf.insert(Buf.end(), Macro, Equal);
370 Buf.push_back(' ');
371 Buf.insert(Buf.end(), Equal+1, Equal+strlen(Equal));
372 } else {
373 // Push "macroname 1".
374 Buf.insert(Buf.end(), Macro, Macro+strlen(Macro));
375 Buf.push_back(' ');
376 Buf.push_back('1');
377 }
378 Buf.push_back('\n');
379}
380
Chris Lattner2db78dd2008-10-05 20:40:30 +0000381/// PickFP - This is used to pick a value based on the FP semantics of the
382/// specified FP model.
383template <typename T>
384static T PickFP(const llvm::fltSemantics *Sem, T IEEESingleVal,
385 T IEEEDoubleVal, T X87DoubleExtendedVal, T PPCDoubleDoubleVal) {
386 if (Sem == &llvm::APFloat::IEEEsingle)
387 return IEEESingleVal;
388 if (Sem == &llvm::APFloat::IEEEdouble)
389 return IEEEDoubleVal;
390 if (Sem == &llvm::APFloat::x87DoubleExtended)
391 return X87DoubleExtendedVal;
392 assert(Sem == &llvm::APFloat::PPCDoubleDouble);
393 return PPCDoubleDoubleVal;
394}
395
396static void DefineFloatMacros(std::vector<char> &Buf, const char *Prefix,
397 const llvm::fltSemantics *Sem) {
398 const char *DenormMin = PickFP(Sem, "1.40129846e-45F",
399 "4.9406564584124654e-324",
400 "3.64519953188247460253e-4951L",
401 "4.94065645841246544176568792868221e-324L");
402
403 char MacroBuf[60];
404 sprintf(MacroBuf, "__%s_DENORM_MIN__=%s", Prefix, DenormMin);
405 DefineBuiltinMacro(Buf, MacroBuf);
406}
407
Chris Lattner53b0dab2007-10-09 22:10:18 +0000408
409static void InitializePredefinedMacros(Preprocessor &PP,
410 std::vector<char> &Buf) {
Chris Lattner62213d92008-10-05 19:32:22 +0000411 // Compiler version introspection macros.
412 DefineBuiltinMacro(Buf, "__llvm__=1"); // LLVM Backend
413 DefineBuiltinMacro(Buf, "__clang__=1"); // Clang Frontend
414
415 // Currently claim to be compatible with GCC 4.2.1-5621.
416 DefineBuiltinMacro(Buf, "__APPLE_CC__=5621");
417 DefineBuiltinMacro(Buf, "__GNUC_MINOR__=2");
418 DefineBuiltinMacro(Buf, "__GNUC_PATCHLEVEL__=1");
419 DefineBuiltinMacro(Buf, "__GNUC__=4");
420 DefineBuiltinMacro(Buf, "__GXX_ABI_VERSION=1002");
421 DefineBuiltinMacro(Buf, "__VERSION__=\"4.2.1 (Apple Computer, Inc. "
422 "build 5621) (dot 3)\"");
423
424
425 // Initialize language-specific preprocessor defines.
426
Chris Lattner53b0dab2007-10-09 22:10:18 +0000427 // FIXME: Implement magic like cpp_init_builtins for things like __STDC__
428 // and __DATE__ etc.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000429 // These should all be defined in the preprocessor according to the
430 // current language configuration.
431 DefineBuiltinMacro(Buf, "__STDC__=1");
432 //DefineBuiltinMacro(Buf, "__ASSEMBLER__=1");
433 if (PP.getLangOptions().C99 && !PP.getLangOptions().CPlusPlus)
434 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199901L");
435 else if (0) // STDC94 ?
436 DefineBuiltinMacro(Buf, "__STDC_VERSION__=199409L");
437
438 DefineBuiltinMacro(Buf, "__STDC_HOSTED__=1");
Daniel Dunbarfba5cb12008-08-12 00:21:46 +0000439 if (PP.getLangOptions().ObjC1) {
Chris Lattner53b0dab2007-10-09 22:10:18 +0000440 DefineBuiltinMacro(Buf, "__OBJC__=1");
Daniel Dunbarfba5cb12008-08-12 00:21:46 +0000441
442 if (PP.getLangOptions().getGCMode() == LangOptions::NonGC) {
443 DefineBuiltinMacro(Buf, "__weak=");
444 DefineBuiltinMacro(Buf, "__strong=");
445 } else {
446 DefineBuiltinMacro(Buf, "__weak=__attribute__((objc_gc(weak)))");
447 DefineBuiltinMacro(Buf, "__strong=__attribute__((objc_gc(strong)))");
448 DefineBuiltinMacro(Buf, "__OBJC_GC__=1");
449 }
450
451 if (PP.getLangOptions().NeXTRuntime)
452 DefineBuiltinMacro(Buf, "__NEXT_RUNTIME__=1");
453
454 // darwin_constant_cfstrings controls this. This is also dependent
455 // on other things like the runtime I believe.
456 DefineBuiltinMacro(Buf, "__CONSTANT_CFSTRINGS__=1");
457 }
Chris Lattner9b533162008-10-05 19:44:25 +0000458
Steve Naroff73b17cd2008-05-15 21:12:10 +0000459 if (PP.getLangOptions().ObjC2)
460 DefineBuiltinMacro(Buf, "OBJC_NEW_PROPERTIES");
Steve Naroff8ee529b2007-10-31 18:42:27 +0000461
Chris Lattner048dd942008-09-30 00:48:48 +0000462 if (PP.getLangOptions().PascalStrings)
463 DefineBuiltinMacro(Buf, "__PASCAL_STRINGS__");
464
Chris Lattner62213d92008-10-05 19:32:22 +0000465 if (PP.getLangOptions().Blocks) {
466 DefineBuiltinMacro(Buf, "__block=__attribute__((__blocks__(byref)))");
467 DefineBuiltinMacro(Buf, "__BLOCKS__=1");
Chris Lattner2b43ad92008-10-05 19:32:52 +0000468 }
Chris Lattner62213d92008-10-05 19:32:22 +0000469
470 if (PP.getLangOptions().CPlusPlus) {
471 DefineBuiltinMacro(Buf, "__DEPRECATED=1");
472 DefineBuiltinMacro(Buf, "__EXCEPTIONS=1");
473 DefineBuiltinMacro(Buf, "__GNUG__=4");
474 DefineBuiltinMacro(Buf, "__GXX_WEAK__=1");
475 DefineBuiltinMacro(Buf, "__cplusplus=1");
476 DefineBuiltinMacro(Buf, "__private_extern__=extern");
477 }
478
479 // Filter out some microsoft extensions when trying to parse in ms-compat
480 // mode.
481 if (PP.getLangOptions().Microsoft) {
482 DefineBuiltinMacro(Buf, "__stdcall=");
483 DefineBuiltinMacro(Buf, "__cdecl=");
484 DefineBuiltinMacro(Buf, "_cdecl=");
485 DefineBuiltinMacro(Buf, "__ptr64=");
486 DefineBuiltinMacro(Buf, "__w64=");
487 DefineBuiltinMacro(Buf, "__forceinline=");
488 DefineBuiltinMacro(Buf, "__int8=char");
489 DefineBuiltinMacro(Buf, "__int16=short");
490 DefineBuiltinMacro(Buf, "__int32=int");
491 DefineBuiltinMacro(Buf, "__int64=long long");
492 DefineBuiltinMacro(Buf, "__declspec(X)=");
493 }
494
495
496 // Initialize target-specific preprocessor defines.
Chris Lattner9b533162008-10-05 19:44:25 +0000497 const TargetInfo &TI = PP.getTargetInfo();
498
499 // Define type sizing macros based on the target properties.
500 assert(TI.getCharWidth() == 8 && "Only support 8-bit char so far");
501 DefineBuiltinMacro(Buf, "__CHAR_BIT__=8");
502 DefineBuiltinMacro(Buf, "__SCHAR_MAX__=127");
Chris Lattner2db78dd2008-10-05 20:40:30 +0000503
504 assert(TI.getWCharWidth() == 32 && "Only support 32-bit wchar so far");
505 DefineBuiltinMacro(Buf, "__WCHAR_MAX__=2147483647");
506 DefineBuiltinMacro(Buf, "__WCHAR_TYPE__=int");
507 DefineBuiltinMacro(Buf, "__WINT_TYPE__=int");
Chris Lattner9b533162008-10-05 19:44:25 +0000508
509 assert(TI.getShortWidth() == 16 && "Only support 16-bit short so far");
Chris Lattner9b533162008-10-05 19:44:25 +0000510 DefineBuiltinMacro(Buf, "__SHRT_MAX__=32767");
511
Chris Lattner0e5d4ef2008-10-05 20:06:37 +0000512 if (TI.getIntWidth() == 32)
513 DefineBuiltinMacro(Buf, "__INT_MAX__=2147483647");
514 else if (TI.getIntWidth() == 16)
515 DefineBuiltinMacro(Buf, "__INT_MAX__=32767");
516 else
517 assert(0 && "Unknown integer size");
Chris Lattner9b533162008-10-05 19:44:25 +0000518
519 assert(TI.getLongLongWidth() == 64 && "Only support 64-bit long long so far");
520 DefineBuiltinMacro(Buf, "__LONG_LONG_MAX__=9223372036854775807LL");
521
Chris Lattner0e5d4ef2008-10-05 20:06:37 +0000522 if (TI.getLongWidth() == 32)
523 DefineBuiltinMacro(Buf, "__LONG_MAX__=2147483647L");
524 else if (TI.getLongWidth() == 64)
525 DefineBuiltinMacro(Buf, "__LONG_MAX__=9223372036854775807L");
526 else if (TI.getLongWidth() == 16)
527 DefineBuiltinMacro(Buf, "__LONG_MAX__=32767L");
528 else
529 assert(0 && "Unknown long size");
530
531 // For "32-bit" targets, GCC generally defines intmax to be 'long long' and
532 // ptrdiff_t to be 'int'. On "64-bit" targets, it defines intmax to be long,
533 // and ptrdiff_t to be 'long int'. This sort of stuff shouldn't matter in
534 // theory, but can affect C++ overloading, stringizing, etc.
535 if (TI.getPointerWidth(0) == TI.getLongLongWidth()) {
536 // If sizeof(void*) == sizeof(long long) assume we have an LP64 target,
537 // because we assume sizeof(long) always is sizeof(void*) currently.
538 assert(TI.getPointerWidth(0) == TI.getLongWidth() &&
539 TI.getLongWidth() == 64 &&
540 TI.getIntWidth() == 32 && "Not I32 LP64?");
Chris Lattner2db78dd2008-10-05 20:40:30 +0000541 assert(TI.getIntMaxTWidth() == 64);
Chris Lattner0e5d4ef2008-10-05 20:06:37 +0000542 DefineBuiltinMacro(Buf, "__INTMAX_MAX__=9223372036854775807L");
543 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=long int");
544 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=long int");
545 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=long unsigned int");
546 } else {
547 // Otherwise we know that the pointer is smaller than long long. We continue
548 // to assume that sizeof(void*) == sizeof(long).
549 assert(TI.getPointerWidth(0) < TI.getLongLongWidth() &&
550 TI.getPointerWidth(0) == TI.getLongWidth() &&
551 "Unexpected target sizes");
552 // We currently only support targets where long is 32-bit. This can be
553 // easily generalized in the future.
Chris Lattner2db78dd2008-10-05 20:40:30 +0000554 assert(TI.getIntMaxTWidth() == 64);
Chris Lattner0e5d4ef2008-10-05 20:06:37 +0000555 DefineBuiltinMacro(Buf, "__INTMAX_MAX__=9223372036854775807LL");
556 DefineBuiltinMacro(Buf, "__INTMAX_TYPE__=long long int");
557 DefineBuiltinMacro(Buf, "__PTRDIFF_TYPE__=int");
558 DefineBuiltinMacro(Buf, "__UINTMAX_TYPE__=long long unsigned int");
559 }
560
561 // All of our current targets have sizeof(long) == sizeof(void*).
562 assert(TI.getPointerWidth(0) == TI.getLongWidth());
563 DefineBuiltinMacro(Buf, "__SIZE_TYPE__=long unsigned int");
564
Chris Lattner2db78dd2008-10-05 20:40:30 +0000565 DefineFloatMacros(Buf, "FLT", &TI.getFloatFormat());
566 DefineFloatMacros(Buf, "DBL", &TI.getDoubleFormat());
567 DefineFloatMacros(Buf, "LDBL", &TI.getLongDoubleFormat());
Chris Lattner0e5d4ef2008-10-05 20:06:37 +0000568
Chris Lattner048dd942008-09-30 00:48:48 +0000569
Chris Lattnerd19144b2007-10-10 17:48:53 +0000570 // Add __builtin_va_list typedef.
571 {
Chris Lattner9b533162008-10-05 19:44:25 +0000572 const char *VAList = TI.getVAListDeclaration();
Chris Lattnerd19144b2007-10-10 17:48:53 +0000573 Buf.insert(Buf.end(), VAList, VAList+strlen(VAList));
574 Buf.push_back('\n');
575 }
Chris Lattner53b0dab2007-10-09 22:10:18 +0000576
Chris Lattner9b533162008-10-05 19:44:25 +0000577 if (const char *Prefix = TI.getUserLabelPrefix()) {
Chris Lattner3fdf4672008-10-05 19:22:37 +0000578 llvm::SmallString<20> TmpStr;
579 TmpStr += "__USER_LABEL_PREFIX__=";
580 TmpStr += Prefix;
581 DefineBuiltinMacro(Buf, TmpStr.c_str());
582 }
583
Chris Lattner9b533162008-10-05 19:44:25 +0000584 // Build configuration options. FIXME: these should be controlled by
585 // command line options or something.
Chris Lattner53b0dab2007-10-09 22:10:18 +0000586 DefineBuiltinMacro(Buf, "__DYNAMIC__=1");
587 DefineBuiltinMacro(Buf, "__FINITE_MATH_ONLY__=0");
588 DefineBuiltinMacro(Buf, "__NO_INLINE__=1");
589 DefineBuiltinMacro(Buf, "__PIC__=1");
Chris Lattner9b533162008-10-05 19:44:25 +0000590
591 // Get other target #defines.
592 TI.getTargetDefines(Buf);
Chris Lattner53b0dab2007-10-09 22:10:18 +0000593
Chris Lattner53b0dab2007-10-09 22:10:18 +0000594 // FIXME: Should emit a #line directive here.
595}
596
597
598/// EnterMainSourceFile - Enter the specified FileID as the main source file,
Nate Begeman6b616022008-01-07 04:01:26 +0000599/// which implicitly adds the builtin defines etc.
Ted Kremenek95041a22007-12-19 22:51:13 +0000600void Preprocessor::EnterMainSourceFile() {
601
602 unsigned MainFileID = SourceMgr.getMainFileID();
603
Chris Lattner53b0dab2007-10-09 22:10:18 +0000604 // Enter the main file source buffer.
605 EnterSourceFile(MainFileID, 0);
606
Chris Lattnerb2832982007-11-15 19:07:47 +0000607 // Tell the header info that the main file was entered. If the file is later
608 // #imported, it won't be re-entered.
609 if (const FileEntry *FE =
610 SourceMgr.getFileEntryForLoc(SourceLocation::getFileLoc(MainFileID, 0)))
611 HeaderInfo.IncrementIncludeCount(FE);
612
Chris Lattner53b0dab2007-10-09 22:10:18 +0000613 std::vector<char> PrologFile;
614 PrologFile.reserve(4080);
615
616 // Install things like __POWERPC__, __GNUC__, etc into the macro table.
617 InitializePredefinedMacros(*this, PrologFile);
618
619 // Add on the predefines from the driver.
Chris Lattneraa391972008-04-19 23:09:31 +0000620 PrologFile.insert(PrologFile.end(), Predefines.begin(), Predefines.end());
Chris Lattner53b0dab2007-10-09 22:10:18 +0000621
622 // Memory buffer must end with a null byte!
623 PrologFile.push_back(0);
624
625 // Now that we have emitted the predefined macros, #includes, etc into
626 // PrologFile, preprocess it to populate the initial preprocessor state.
627 llvm::MemoryBuffer *SB =
628 llvm::MemoryBuffer::getMemBufferCopy(&PrologFile.front(),&PrologFile.back(),
629 "<predefines>");
630 assert(SB && "Cannot fail to create predefined source buffer");
631 unsigned FileID = SourceMgr.createFileIDForMemBuffer(SB);
632 assert(FileID && "Could not create FileID for predefines?");
633
634 // Start parsing the predefines.
635 EnterSourceFile(FileID, 0);
636}
Chris Lattner97ba77c2007-07-16 06:48:38 +0000637
Reid Spencer5f016e22007-07-11 17:01:13 +0000638
639//===----------------------------------------------------------------------===//
640// Lexer Event Handling.
641//===----------------------------------------------------------------------===//
642
643/// LookUpIdentifierInfo - Given a tok::identifier token, look up the
644/// identifier information for the token and install it into the token.
Chris Lattnerd2177732007-07-20 16:59:19 +0000645IdentifierInfo *Preprocessor::LookUpIdentifierInfo(Token &Identifier,
Reid Spencer5f016e22007-07-11 17:01:13 +0000646 const char *BufPtr) {
Chris Lattner22f6bbc2007-10-09 18:02:16 +0000647 assert(Identifier.is(tok::identifier) && "Not an identifier!");
Reid Spencer5f016e22007-07-11 17:01:13 +0000648 assert(Identifier.getIdentifierInfo() == 0 && "Identinfo already exists!");
649
650 // Look up this token, see if it is a macro, or if it is a language keyword.
651 IdentifierInfo *II;
652 if (BufPtr && !Identifier.needsCleaning()) {
653 // No cleaning needed, just use the characters from the lexed buffer.
654 II = getIdentifierInfo(BufPtr, BufPtr+Identifier.getLength());
655 } else {
656 // Cleaning needed, alloca a buffer, clean into it, then use the buffer.
Chris Lattnerc35717a2007-07-13 17:10:38 +0000657 llvm::SmallVector<char, 64> IdentifierBuffer;
658 IdentifierBuffer.resize(Identifier.getLength());
659 const char *TmpBuf = &IdentifierBuffer[0];
Reid Spencer5f016e22007-07-11 17:01:13 +0000660 unsigned Size = getSpelling(Identifier, TmpBuf);
661 II = getIdentifierInfo(TmpBuf, TmpBuf+Size);
662 }
663 Identifier.setIdentifierInfo(II);
664 return II;
665}
666
667
668/// HandleIdentifier - This callback is invoked when the lexer reads an
669/// identifier. This callback looks up the identifier in the map and/or
670/// potentially macro expands it or turns it into a named token (like 'for').
Chris Lattnerd2177732007-07-20 16:59:19 +0000671void Preprocessor::HandleIdentifier(Token &Identifier) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000672 assert(Identifier.getIdentifierInfo() &&
673 "Can't handle identifiers without identifier info!");
674
675 IdentifierInfo &II = *Identifier.getIdentifierInfo();
676
677 // If this identifier was poisoned, and if it was not produced from a macro
678 // expansion, emit an error.
679 if (II.isPoisoned() && CurLexer) {
680 if (&II != Ident__VA_ARGS__) // We warn about __VA_ARGS__ with poisoning.
681 Diag(Identifier, diag::err_pp_used_poisoned_id);
682 else
683 Diag(Identifier, diag::ext_pp_bad_vaargs_use);
684 }
685
686 // If this is a macro to be expanded, do it.
Chris Lattnercc1a8752007-10-07 08:44:20 +0000687 if (MacroInfo *MI = getMacroInfo(&II)) {
Reid Spencer5f016e22007-07-11 17:01:13 +0000688 if (!DisableMacroExpansion && !Identifier.isExpandDisabled()) {
689 if (MI->isEnabled()) {
690 if (!HandleMacroExpandedIdentifier(Identifier, MI))
691 return;
692 } else {
693 // C99 6.10.3.4p2 says that a disabled macro may never again be
694 // expanded, even if it's in a context where it could be expanded in the
695 // future.
Chris Lattnerd2177732007-07-20 16:59:19 +0000696 Identifier.setFlag(Token::DisableExpand);
Reid Spencer5f016e22007-07-11 17:01:13 +0000697 }
698 }
Reid Spencer5f016e22007-07-11 17:01:13 +0000699 }
700
701 // C++ 2.11p2: If this is an alternative representation of a C++ operator,
702 // then we act as if it is the actual operator and not the textual
703 // representation of it.
704 if (II.isCPlusPlusOperatorKeyword())
705 Identifier.setIdentifierInfo(0);
706
707 // Change the kind of this identifier to the appropriate token kind, e.g.
708 // turning "for" into a keyword.
709 Identifier.setKind(II.getTokenID());
710
711 // If this is an extension token, diagnose its use.
Steve Naroffb4eaf9c2008-09-02 18:50:17 +0000712 // We avoid diagnosing tokens that originate from macro definitions.
713 if (II.isExtensionToken() && Features.C99 && !DisableMacroExpansion)
Reid Spencer5f016e22007-07-11 17:01:13 +0000714 Diag(Identifier, diag::ext_token_used);
715}