clang 22.0.0git
PPMacroExpansion.cpp
Go to the documentation of this file.
1//===--- PPMacroExpansion.cpp - Top level Macro Expansion -----------------===//
2//
3// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4// See https://llvm.org/LICENSE.txt for license information.
5// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6//
7//===----------------------------------------------------------------------===//
8//
9// This file implements the top level handling of macro expansion for the
10// preprocessor.
11//
12//===----------------------------------------------------------------------===//
13
18#include "clang/Basic/LLVM.h"
28#include "clang/Lex/MacroArgs.h"
29#include "clang/Lex/MacroInfo.h"
33#include "clang/Lex/Token.h"
34#include "llvm/ADT/ArrayRef.h"
35#include "llvm/ADT/DenseMap.h"
36#include "llvm/ADT/DenseSet.h"
37#include "llvm/ADT/FoldingSet.h"
38#include "llvm/ADT/STLExtras.h"
39#include "llvm/ADT/SmallVector.h"
40#include "llvm/ADT/StringRef.h"
41#include "llvm/ADT/StringSwitch.h"
42#include "llvm/Support/ErrorHandling.h"
43#include "llvm/Support/Format.h"
44#include "llvm/Support/Path.h"
45#include "llvm/Support/raw_ostream.h"
46#include <algorithm>
47#include <cassert>
48#include <cstddef>
49#include <cstring>
50#include <ctime>
51#include <iomanip>
52#include <optional>
53#include <sstream>
54#include <string>
55#include <tuple>
56#include <utility>
57
58using namespace clang;
59
62 if (!II->hadMacroDefinition())
63 return nullptr;
64 auto Pos = CurSubmoduleState->Macros.find(II);
65 return Pos == CurSubmoduleState->Macros.end() ? nullptr
66 : Pos->second.getLatest();
67}
68
70 assert(MD && "MacroDirective should be non-zero!");
71 assert(!MD->getPrevious() && "Already attached to a MacroDirective history.");
72
73 MacroState &StoredMD = CurSubmoduleState->Macros[II];
74 auto *OldMD = StoredMD.getLatest();
75 MD->setPrevious(OldMD);
76 StoredMD.setLatest(MD);
77 StoredMD.overrideActiveModuleMacros(*this, II);
78
79 if (needModuleMacros()) {
80 // Track that we created a new macro directive, so we know we should
81 // consider building a ModuleMacro for it when we get to the end of
82 // the module.
83 PendingModuleMacroNames.push_back(II);
84 }
85
86 // Set up the identifier as having associated macro history.
87 II->setHasMacroDefinition(true);
88 if (!MD->isDefined() && !LeafModuleMacros.contains(II))
89 II->setHasMacroDefinition(false);
90 if (II->isFromAST())
92}
93
96 MacroDirective *MD) {
97 // Normally, when a macro is defined, it goes through appendMacroDirective()
98 // above, which chains a macro to previous defines, undefs, etc.
99 // However, in a pch, the whole macro history up to the end of the pch is
100 // stored, so ASTReader goes through this function instead.
101 // However, built-in macros are already registered in the Preprocessor
102 // ctor, and ASTWriter stops writing the macro chain at built-in macros,
103 // so in that case the chain from the pch needs to be spliced to the existing
104 // built-in.
105
106 assert(II && MD);
107 MacroState &StoredMD = CurSubmoduleState->Macros[II];
108
109 if (auto *OldMD = StoredMD.getLatest()) {
110 // shouldIgnoreMacro() in ASTWriter also stops at macros from the
111 // predefines buffer in module builds. However, in module builds, modules
112 // are loaded completely before predefines are processed, so StoredMD
113 // will be nullptr for them when they're loaded. StoredMD should only be
114 // non-nullptr for builtins read from a pch file.
115 assert(OldMD->getMacroInfo()->isBuiltinMacro() &&
116 "only built-ins should have an entry here");
117 assert(!OldMD->getPrevious() && "builtin should only have a single entry");
118 ED->setPrevious(OldMD);
119 StoredMD.setLatest(MD);
120 } else {
121 StoredMD = MD;
122 }
123
124 // Setup the identifier as having associated macro history.
125 II->setHasMacroDefinition(true);
126 if (!MD->isDefined() && !LeafModuleMacros.contains(II))
127 II->setHasMacroDefinition(false);
128
129 if (getLangOpts().Modules) {
130 // When both modules and a PCH are used, we may run into the following
131 // situation:
132 // - the PCH is compiled with macro definitions on the command line.
133 // - the modules are compiled with the same set of macros on the command
134 // line.
135 // In this case, clang needs to know that some predefined macros exist
136 // over the command line transitively through the PCH and some are passed
137 // directly over the command line. The preprocessor stores
138 // PCHPredefinesFileID so later it is aware of macros defined transitively
139 // through the PCH's compilation.
140 auto MDLoc = MD->getLocation();
141
142 if (SourceMgr.isWrittenInCommandLineFile(MDLoc)) {
143 auto MDFileID = SourceMgr.getFileID(MDLoc);
144 if (PCHPredefinesFileID.isInvalid())
145 PCHPredefinesFileID = MDFileID;
146 else {
147 // The PCH and all the chain of headers it includes must be
148 // compiled with the exact same set of macros defined over the
149 // command line. No different macros should be defined over
150 // different command line invocations. This means that all the macros'
151 // source locations should have the same MDFileID.
152 assert(MDFileID == PCHPredefinesFileID &&
153 "PCHBuiltinFileID must be consistent!");
154 }
155 }
156 }
157}
158
161 ArrayRef<ModuleMacro *> Overrides,
162 bool &New) {
163 llvm::FoldingSetNodeID ID;
164 ModuleMacro::Profile(ID, Mod, II);
165
166 void *InsertPos;
167 if (auto *MM = ModuleMacros.FindNodeOrInsertPos(ID, InsertPos)) {
168 New = false;
169 return MM;
170 }
171
172 auto *MM = ModuleMacro::create(*this, Mod, II, Macro, Overrides);
173 ModuleMacros.InsertNode(MM, InsertPos);
174
175 // Each overridden macro is now overridden by one more macro.
176 bool HidAny = false;
177 for (auto *O : Overrides) {
178 HidAny |= (O->NumOverriddenBy == 0);
179 ++O->NumOverriddenBy;
180 }
181
182 // If we were the first overrider for any macro, it's no longer a leaf.
183 auto &LeafMacros = LeafModuleMacros[II];
184 if (HidAny) {
185 llvm::erase_if(LeafMacros,
186 [](ModuleMacro *MM) { return MM->NumOverriddenBy != 0; });
187 }
188
189 // The new macro is always a leaf macro.
190 LeafMacros.push_back(MM);
191 // The identifier now has defined macros (that may or may not be visible).
192 II->setHasMacroDefinition(true);
193
194 New = true;
195 return MM;
196}
197
199 const IdentifierInfo *II) {
200 llvm::FoldingSetNodeID ID;
201 ModuleMacro::Profile(ID, Mod, II);
202
203 void *InsertPos;
204 return ModuleMacros.FindNodeOrInsertPos(ID, InsertPos);
205}
206
207void Preprocessor::updateModuleMacroInfo(const IdentifierInfo *II,
208 ModuleMacroInfo &Info) {
209 assert(Info.ActiveModuleMacrosGeneration !=
210 CurSubmoduleState->VisibleModules.getGeneration() &&
211 "don't need to update this macro name info");
212 Info.ActiveModuleMacrosGeneration =
213 CurSubmoduleState->VisibleModules.getGeneration();
214
215 auto Leaf = LeafModuleMacros.find(II);
216 if (Leaf == LeafModuleMacros.end()) {
217 // No imported macros at all: nothing to do.
218 return;
219 }
220
221 Info.ActiveModuleMacros.clear();
222
223 // Every macro that's locally overridden is overridden by a visible macro.
224 llvm::DenseMap<ModuleMacro *, int> NumHiddenOverrides;
225 for (auto *O : Info.OverriddenMacros)
226 NumHiddenOverrides[O] = -1;
227
228 // Collect all macros that are not overridden by a visible macro.
230 for (auto *LeafMM : Leaf->second) {
231 assert(LeafMM->getNumOverridingMacros() == 0 && "leaf macro overridden");
232 if (NumHiddenOverrides.lookup(LeafMM) == 0)
233 Worklist.push_back(LeafMM);
234 }
235 while (!Worklist.empty()) {
236 auto *MM = Worklist.pop_back_val();
237 if (CurSubmoduleState->VisibleModules.isVisible(MM->getOwningModule())) {
238 // We only care about collecting definitions; undefinitions only act
239 // to override other definitions.
240 if (MM->getMacroInfo())
241 Info.ActiveModuleMacros.push_back(MM);
242 } else {
243 for (auto *O : MM->overrides())
244 if ((unsigned)++NumHiddenOverrides[O] == O->getNumOverridingMacros())
245 Worklist.push_back(O);
246 }
247 }
248 // Our reverse postorder walk found the macros in reverse order.
249 std::reverse(Info.ActiveModuleMacros.begin(), Info.ActiveModuleMacros.end());
250
251 // Determine whether the macro name is ambiguous.
252 MacroInfo *MI = nullptr;
253 bool IsSystemMacro = true;
254 bool IsAmbiguous = false;
255 if (auto *MD = Info.MD) {
256 while (isa_and_nonnull<VisibilityMacroDirective>(MD))
257 MD = MD->getPrevious();
258 if (auto *DMD = dyn_cast_or_null<DefMacroDirective>(MD)) {
259 MI = DMD->getInfo();
260 IsSystemMacro &= SourceMgr.isInSystemHeader(DMD->getLocation());
261 }
262 }
263 for (auto *Active : Info.ActiveModuleMacros) {
264 auto *NewMI = Active->getMacroInfo();
265
266 // Before marking the macro as ambiguous, check if this is a case where
267 // both macros are in system headers. If so, we trust that the system
268 // did not get it wrong. This also handles cases where Clang's own
269 // headers have a different spelling of certain system macros:
270 // #define LONG_MAX __LONG_MAX__ (clang's limits.h)
271 // #define LONG_MAX 0x7fffffffffffffffL (system's limits.h)
272 //
273 // FIXME: Remove the defined-in-system-headers check. clang's limits.h
274 // overrides the system limits.h's macros, so there's no conflict here.
275 if (MI && NewMI != MI &&
276 !MI->isIdenticalTo(*NewMI, *this, /*Syntactically=*/true))
277 IsAmbiguous = true;
278 IsSystemMacro &= Active->getOwningModule()->IsSystem ||
279 SourceMgr.isInSystemHeader(NewMI->getDefinitionLoc());
280 MI = NewMI;
281 }
282 Info.IsAmbiguous = IsAmbiguous && !IsSystemMacro;
283}
284
287 auto LeafIt = LeafModuleMacros.find(II);
288 if (LeafIt != LeafModuleMacros.end())
289 Leaf = LeafIt->second;
290 const MacroState *State = nullptr;
291 auto Pos = CurSubmoduleState->Macros.find(II);
292 if (Pos != CurSubmoduleState->Macros.end())
293 State = &Pos->second;
294
295 llvm::errs() << "MacroState " << State << " " << II->getNameStart();
296 if (State && State->isAmbiguous(*this, II))
297 llvm::errs() << " ambiguous";
298 if (State && !State->getOverriddenMacros().empty()) {
299 llvm::errs() << " overrides";
300 for (auto *O : State->getOverriddenMacros())
301 llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
302 }
303 llvm::errs() << "\n";
304
305 // Dump local macro directives.
306 for (auto *MD = State ? State->getLatest() : nullptr; MD;
307 MD = MD->getPrevious()) {
308 llvm::errs() << " ";
309 MD->dump();
310 }
311
312 // Dump module macros.
313 llvm::DenseSet<ModuleMacro*> Active;
314 for (auto *MM : State ? State->getActiveModuleMacros(*this, II)
316 Active.insert(MM);
317 llvm::DenseSet<ModuleMacro*> Visited;
319 while (!Worklist.empty()) {
320 auto *MM = Worklist.pop_back_val();
321 llvm::errs() << " ModuleMacro " << MM << " "
322 << MM->getOwningModule()->getFullModuleName();
323 if (!MM->getMacroInfo())
324 llvm::errs() << " undef";
325
326 if (Active.count(MM))
327 llvm::errs() << " active";
328 else if (!CurSubmoduleState->VisibleModules.isVisible(
329 MM->getOwningModule()))
330 llvm::errs() << " hidden";
331 else if (MM->getMacroInfo())
332 llvm::errs() << " overridden";
333
334 if (!MM->overrides().empty()) {
335 llvm::errs() << " overrides";
336 for (auto *O : MM->overrides()) {
337 llvm::errs() << " " << O->getOwningModule()->getFullModuleName();
338 if (Visited.insert(O).second)
339 Worklist.push_back(O);
340 }
341 }
342 llvm::errs() << "\n";
343 if (auto *MI = MM->getMacroInfo()) {
344 llvm::errs() << " ";
345 MI->dump();
346 llvm::errs() << "\n";
347 }
348 }
349}
350
351/// RegisterBuiltinMacros - Register builtin macros, such as __LINE__ with the
352/// identifier table.
353void Preprocessor::RegisterBuiltinMacros() {
354 Ident__LINE__ = RegisterBuiltinMacro("__LINE__");
355 Ident__FILE__ = RegisterBuiltinMacro("__FILE__");
356 Ident__DATE__ = RegisterBuiltinMacro("__DATE__");
357 Ident__TIME__ = RegisterBuiltinMacro("__TIME__");
358 Ident__COUNTER__ = RegisterBuiltinMacro("__COUNTER__");
359 Ident_Pragma = RegisterBuiltinMacro("_Pragma");
360 Ident__FLT_EVAL_METHOD__ = RegisterBuiltinMacro("__FLT_EVAL_METHOD__");
361
362 // C++ Standing Document Extensions.
364 Ident__has_cpp_attribute = RegisterBuiltinMacro("__has_cpp_attribute");
365 else
366 Ident__has_cpp_attribute = nullptr;
367
368 // GCC Extensions.
369 Ident__BASE_FILE__ = RegisterBuiltinMacro("__BASE_FILE__");
370 Ident__INCLUDE_LEVEL__ = RegisterBuiltinMacro("__INCLUDE_LEVEL__");
371 Ident__TIMESTAMP__ = RegisterBuiltinMacro("__TIMESTAMP__");
372
373 // Microsoft Extensions.
374 if (getLangOpts().MicrosoftExt) {
375 Ident__identifier = RegisterBuiltinMacro("__identifier");
376 Ident__pragma = RegisterBuiltinMacro("__pragma");
377 } else {
378 Ident__identifier = nullptr;
379 Ident__pragma = nullptr;
380 }
381
382 // Clang Extensions.
383 Ident__FILE_NAME__ = RegisterBuiltinMacro("__FILE_NAME__");
384 Ident__has_feature = RegisterBuiltinMacro("__has_feature");
385 Ident__has_extension = RegisterBuiltinMacro("__has_extension");
386 Ident__has_builtin = RegisterBuiltinMacro("__has_builtin");
387 Ident__has_constexpr_builtin =
388 RegisterBuiltinMacro("__has_constexpr_builtin");
389 Ident__has_attribute = RegisterBuiltinMacro("__has_attribute");
390 if (!getLangOpts().CPlusPlus)
391 Ident__has_c_attribute = RegisterBuiltinMacro("__has_c_attribute");
392 else
393 Ident__has_c_attribute = nullptr;
394
395 Ident__has_declspec = RegisterBuiltinMacro("__has_declspec_attribute");
396 Ident__has_embed = RegisterBuiltinMacro("__has_embed");
397 Ident__has_include = RegisterBuiltinMacro("__has_include");
398 Ident__has_include_next = RegisterBuiltinMacro("__has_include_next");
399 Ident__has_warning = RegisterBuiltinMacro("__has_warning");
400 Ident__is_identifier = RegisterBuiltinMacro("__is_identifier");
401 Ident__is_target_arch = RegisterBuiltinMacro("__is_target_arch");
402 Ident__is_target_vendor = RegisterBuiltinMacro("__is_target_vendor");
403 Ident__is_target_os = RegisterBuiltinMacro("__is_target_os");
404 Ident__is_target_environment =
405 RegisterBuiltinMacro("__is_target_environment");
406 Ident__is_target_variant_os = RegisterBuiltinMacro("__is_target_variant_os");
407 Ident__is_target_variant_environment =
408 RegisterBuiltinMacro("__is_target_variant_environment");
409
410 // Modules.
411 Ident__building_module = RegisterBuiltinMacro("__building_module");
412 if (!getLangOpts().CurrentModule.empty())
413 Ident__MODULE__ = RegisterBuiltinMacro("__MODULE__");
414 else
415 Ident__MODULE__ = nullptr;
416}
417
418/// isTrivialSingleTokenExpansion - Return true if MI, which has a single token
419/// in its expansion, currently expands to that token literally.
421 const IdentifierInfo *MacroIdent,
422 Preprocessor &PP) {
424
425 // If the token isn't an identifier, it's always literally expanded.
426 if (!II) return true;
427
428 // If the information about this identifier is out of date, update it from
429 // the external source.
430 if (II->isOutOfDate())
432
433 // If the identifier is a macro, and if that macro is enabled, it may be
434 // expanded so it's not a trivial expansion.
435 if (auto *ExpansionMI = PP.getMacroInfo(II))
436 if (ExpansionMI->isEnabled() &&
437 // Fast expanding "#define X X" is ok, because X would be disabled.
438 II != MacroIdent)
439 return false;
440
441 // If this is an object-like macro invocation, it is safe to trivially expand
442 // it.
443 if (MI->isObjectLike()) return true;
444
445 // If this is a function-like macro invocation, it's safe to trivially expand
446 // as long as the identifier is not a macro argument.
447 return !llvm::is_contained(MI->params(), II);
448}
449
450/// HandleMacroExpandedIdentifier - If an identifier token is read that is to be
451/// expanded as a macro, handle it and return the next token as 'Identifier'.
452bool Preprocessor::HandleMacroExpandedIdentifier(Token &Identifier,
453 const MacroDefinition &M) {
454 emitMacroExpansionWarnings(Identifier);
455
456 MacroInfo *MI = M.getMacroInfo();
457
458 // If this is a macro expansion in the "#if !defined(x)" line for the file,
459 // then the macro could expand to different things in other contexts, we need
460 // to disable the optimization in this case.
461 if (CurPPLexer) CurPPLexer->MIOpt.ExpandedMacro();
462
463 // If this is a builtin macro, like __LINE__ or _Pragma, handle it specially.
464 if (MI->isBuiltinMacro()) {
465 if (Callbacks)
466 Callbacks->MacroExpands(Identifier, M, Identifier.getLocation(),
467 /*Args=*/nullptr);
468 ExpandBuiltinMacro(Identifier);
469 return true;
470 }
471
472 /// Args - If this is a function-like macro expansion, this contains,
473 /// for each macro argument, the list of tokens that were provided to the
474 /// invocation.
475 MacroArgs *Args = nullptr;
476
477 // Remember where the end of the expansion occurred. For an object-like
478 // macro, this is the identifier. For a function-like macro, this is the ')'.
479 SourceLocation ExpansionEnd = Identifier.getLocation();
480
481 // If this is a function-like macro, read the arguments.
482 if (MI->isFunctionLike()) {
483 // Remember that we are now parsing the arguments to a macro invocation.
484 // Preprocessor directives used inside macro arguments are not portable, and
485 // this enables the warning.
486 InMacroArgs = true;
487 ArgMacro = &Identifier;
488
489 Args = ReadMacroCallArgumentList(Identifier, MI, ExpansionEnd);
490
491 // Finished parsing args.
492 InMacroArgs = false;
493 ArgMacro = nullptr;
494
495 // If there was an error parsing the arguments, bail out.
496 if (!Args) return true;
497
498 ++NumFnMacroExpanded;
499 } else {
500 ++NumMacroExpanded;
501 }
502
503 // Notice that this macro has been used.
504 markMacroAsUsed(MI);
505
506 // Remember where the token is expanded.
507 SourceLocation ExpandLoc = Identifier.getLocation();
508 SourceRange ExpansionRange(ExpandLoc, ExpansionEnd);
509
510 if (Callbacks) {
511 if (InMacroArgs) {
512 // We can have macro expansion inside a conditional directive while
513 // reading the function macro arguments. To ensure, in that case, that
514 // MacroExpands callbacks still happen in source order, queue this
515 // callback to have it happen after the function macro callback.
516 DelayedMacroExpandsCallbacks.push_back(
517 MacroExpandsInfo(Identifier, M, ExpansionRange));
518 } else {
519 Callbacks->MacroExpands(Identifier, M, ExpansionRange, Args);
520 if (!DelayedMacroExpandsCallbacks.empty()) {
521 for (const MacroExpandsInfo &Info : DelayedMacroExpandsCallbacks) {
522 // FIXME: We lose macro args info with delayed callback.
523 Callbacks->MacroExpands(Info.Tok, Info.MD, Info.Range,
524 /*Args=*/nullptr);
525 }
526 DelayedMacroExpandsCallbacks.clear();
527 }
528 }
529 }
530
531 // If the macro definition is ambiguous, complain.
532 if (M.isAmbiguous()) {
533 Diag(Identifier, diag::warn_pp_ambiguous_macro)
534 << Identifier.getIdentifierInfo();
535 Diag(MI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_chosen)
536 << Identifier.getIdentifierInfo();
537 M.forAllDefinitions([&](const MacroInfo *OtherMI) {
538 if (OtherMI != MI)
539 Diag(OtherMI->getDefinitionLoc(), diag::note_pp_ambiguous_macro_other)
540 << Identifier.getIdentifierInfo();
541 });
542 }
543
544 // If we started lexing a macro, enter the macro expansion body.
545
546 // If this macro expands to no tokens, don't bother to push it onto the
547 // expansion stack, only to take it right back off.
548 if (MI->getNumTokens() == 0) {
549 // No need for arg info.
550 if (Args) Args->destroy(*this);
551
552 // Propagate whitespace info as if we had pushed, then popped,
553 // a macro context.
555 PropagateLineStartLeadingSpaceInfo(Identifier);
556 ++NumFastMacroExpanded;
557 return false;
558 } else if (MI->getNumTokens() == 1 &&
560 *this)) {
561 // Otherwise, if this macro expands into a single trivially-expanded
562 // token: expand it now. This handles common cases like
563 // "#define VAL 42".
564
565 // No need for arg info.
566 if (Args) Args->destroy(*this);
567
568 // Propagate the isAtStartOfLine/hasLeadingSpace markers of the macro
569 // identifier to the expanded token.
570 bool isAtStartOfLine = Identifier.isAtStartOfLine();
571 bool hasLeadingSpace = Identifier.hasLeadingSpace();
572
573 // Replace the result token.
574 Identifier = MI->getReplacementToken(0);
575
576 // Restore the StartOfLine/LeadingSpace markers.
577 Identifier.setFlagValue(Token::StartOfLine , isAtStartOfLine);
578 Identifier.setFlagValue(Token::LeadingSpace, hasLeadingSpace);
579
580 // Update the tokens location to include both its expansion and physical
581 // locations.
582 SourceLocation Loc =
583 SourceMgr.createExpansionLoc(Identifier.getLocation(), ExpandLoc,
584 ExpansionEnd,Identifier.getLength());
585 Identifier.setLocation(Loc);
586
587 // If this is a disabled macro or #define X X, we must mark the result as
588 // unexpandable.
589 if (IdentifierInfo *NewII = Identifier.getIdentifierInfo()) {
590 if (MacroInfo *NewMI = getMacroInfo(NewII))
591 if (!NewMI->isEnabled() || NewMI == MI) {
592 Identifier.setFlag(Token::DisableExpand);
593 // Don't warn for "#define X X" like "#define bool bool" from
594 // stdbool.h.
595 if (NewMI != MI || MI->isFunctionLike())
596 Diag(Identifier, diag::pp_disabled_macro_expansion);
597 }
598 }
599
600 // Since this is not an identifier token, it can't be macro expanded, so
601 // we're done.
602 ++NumFastMacroExpanded;
603 return true;
604 }
605
606 // Start expanding the macro.
607 EnterMacro(Identifier, ExpansionEnd, MI, Args);
608 return false;
609}
610
615
616/// CheckMatchedBrackets - Returns true if the braces and parentheses in the
617/// token vector are properly nested.
620 for (SmallVectorImpl<Token>::const_iterator I = Tokens.begin(),
621 E = Tokens.end();
622 I != E; ++I) {
623 if (I->is(tok::l_paren)) {
624 Brackets.push_back(Paren);
625 } else if (I->is(tok::r_paren)) {
626 if (Brackets.empty() || Brackets.back() == Brace)
627 return false;
628 Brackets.pop_back();
629 } else if (I->is(tok::l_brace)) {
630 Brackets.push_back(Brace);
631 } else if (I->is(tok::r_brace)) {
632 if (Brackets.empty() || Brackets.back() == Paren)
633 return false;
634 Brackets.pop_back();
635 }
636 }
637 return Brackets.empty();
638}
639
640/// GenerateNewArgTokens - Returns true if OldTokens can be converted to a new
641/// vector of tokens in NewTokens. The new number of arguments will be placed
642/// in NumArgs and the ranges which need to surrounded in parentheses will be
643/// in ParenHints.
644/// Returns false if the token stream cannot be changed. If this is because
645/// of an initializer list starting a macro argument, the range of those
646/// initializer lists will be place in InitLists.
648 SmallVectorImpl<Token> &OldTokens,
649 SmallVectorImpl<Token> &NewTokens,
650 unsigned &NumArgs,
652 SmallVectorImpl<SourceRange> &InitLists) {
653 if (!CheckMatchedBrackets(OldTokens))
654 return false;
655
656 // Once it is known that the brackets are matched, only a simple count of the
657 // braces is needed.
658 unsigned Braces = 0;
659
660 // First token of a new macro argument.
661 SmallVectorImpl<Token>::iterator ArgStartIterator = OldTokens.begin();
662
663 // First closing brace in a new macro argument. Used to generate
664 // SourceRanges for InitLists.
665 SmallVectorImpl<Token>::iterator ClosingBrace = OldTokens.end();
666 NumArgs = 0;
667 Token TempToken;
668 // Set to true when a macro separator token is found inside a braced list.
669 // If true, the fixed argument spans multiple old arguments and ParenHints
670 // will be updated.
671 bool FoundSeparatorToken = false;
672 for (SmallVectorImpl<Token>::iterator I = OldTokens.begin(),
673 E = OldTokens.end();
674 I != E; ++I) {
675 if (I->is(tok::l_brace)) {
676 ++Braces;
677 } else if (I->is(tok::r_brace)) {
678 --Braces;
679 if (Braces == 0 && ClosingBrace == E && FoundSeparatorToken)
680 ClosingBrace = I;
681 } else if (I->is(tok::eof)) {
682 // EOF token is used to separate macro arguments
683 if (Braces != 0) {
684 // Assume comma separator is actually braced list separator and change
685 // it back to a comma.
686 FoundSeparatorToken = true;
687 I->setKind(tok::comma);
688 I->setLength(1);
689 } else { // Braces == 0
690 // Separator token still separates arguments.
691 ++NumArgs;
692
693 // If the argument starts with a brace, it can't be fixed with
694 // parentheses. A different diagnostic will be given.
695 if (FoundSeparatorToken && ArgStartIterator->is(tok::l_brace)) {
696 InitLists.push_back(
697 SourceRange(ArgStartIterator->getLocation(),
698 PP.getLocForEndOfToken(ClosingBrace->getLocation())));
699 ClosingBrace = E;
700 }
701
702 // Add left paren
703 if (FoundSeparatorToken) {
704 TempToken.startToken();
705 TempToken.setKind(tok::l_paren);
706 TempToken.setLocation(ArgStartIterator->getLocation());
707 TempToken.setLength(0);
708 NewTokens.push_back(TempToken);
709 }
710
711 // Copy over argument tokens
712 NewTokens.insert(NewTokens.end(), ArgStartIterator, I);
713
714 // Add right paren and store the paren locations in ParenHints
715 if (FoundSeparatorToken) {
716 SourceLocation Loc = PP.getLocForEndOfToken((I - 1)->getLocation());
717 TempToken.startToken();
718 TempToken.setKind(tok::r_paren);
719 TempToken.setLocation(Loc);
720 TempToken.setLength(0);
721 NewTokens.push_back(TempToken);
722 ParenHints.push_back(SourceRange(ArgStartIterator->getLocation(),
723 Loc));
724 }
725
726 // Copy separator token
727 NewTokens.push_back(*I);
728
729 // Reset values
730 ArgStartIterator = I + 1;
731 FoundSeparatorToken = false;
732 }
733 }
734 }
735
736 return !ParenHints.empty() && InitLists.empty();
737}
738
739/// ReadFunctionLikeMacroArgs - After reading "MACRO" and knowing that the next
740/// token is the '(' of the macro, this method is invoked to read all of the
741/// actual arguments specified for the macro invocation. This returns null on
742/// error.
743MacroArgs *Preprocessor::ReadMacroCallArgumentList(Token &MacroName,
744 MacroInfo *MI,
745 SourceLocation &MacroEnd) {
746 // The number of fixed arguments to parse.
747 unsigned NumFixedArgsLeft = MI->getNumParams();
748 bool isVariadic = MI->isVariadic();
749
750 // Outer loop, while there are more arguments, keep reading them.
751 Token Tok;
752
753 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
754 // an argument value in a macro could expand to ',' or '(' or ')'.
756 assert(Tok.is(tok::l_paren) && "Error computing l-paren-ness?");
757
758 // ArgTokens - Build up a list of tokens that make up each argument. Each
759 // argument is separated by an EOF token. Use a SmallVector so we can avoid
760 // heap allocations in the common case.
761 SmallVector<Token, 64> ArgTokens;
762 bool ContainsCodeCompletionTok = false;
763 bool FoundElidedComma = false;
764
765 SourceLocation TooManyArgsLoc;
766
767 unsigned NumActuals = 0;
768 while (Tok.isNot(tok::r_paren)) {
769 if (ContainsCodeCompletionTok && Tok.isOneOf(tok::eof, tok::eod))
770 break;
771
772 assert(Tok.isOneOf(tok::l_paren, tok::comma) &&
773 "only expect argument separators here");
774
775 size_t ArgTokenStart = ArgTokens.size();
776 SourceLocation ArgStartLoc = Tok.getLocation();
777
778 // C99 6.10.3p11: Keep track of the number of l_parens we have seen. Note
779 // that we already consumed the first one.
780 unsigned NumParens = 0;
781
782 while (true) {
783 // Read arguments as unexpanded tokens. This avoids issues, e.g., where
784 // an argument value in a macro could expand to ',' or '(' or ')'.
786
787 if (Tok.isOneOf(tok::eof, tok::eod)) { // "#if f(<eof>" & "#if f(\n"
788 if (!ContainsCodeCompletionTok) {
789 Diag(MacroName, diag::err_unterm_macro_invoc);
790 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
791 << MacroName.getIdentifierInfo();
792 // Do not lose the EOF/EOD. Return it to the client.
793 MacroName = Tok;
794 return nullptr;
795 }
796 // Do not lose the EOF/EOD.
797 auto Toks = std::make_unique<Token[]>(1);
798 Toks[0] = Tok;
799 EnterTokenStream(std::move(Toks), 1, true, /*IsReinject*/ false);
800 break;
801 } else if (Tok.is(tok::r_paren)) {
802 // If we found the ) token, the macro arg list is done.
803 if (NumParens-- == 0) {
804 MacroEnd = Tok.getLocation();
805 if (!ArgTokens.empty() &&
806 ArgTokens.back().commaAfterElided()) {
807 FoundElidedComma = true;
808 }
809 break;
810 }
811 } else if (Tok.is(tok::l_paren)) {
812 ++NumParens;
813 } else if (Tok.is(tok::comma)) {
814 // In Microsoft-compatibility mode, single commas from nested macro
815 // expansions should not be considered as argument separators. We test
816 // for this with the IgnoredComma token flag.
818 // However, in MSVC's preprocessor, subsequent expansions do treat
819 // these commas as argument separators. This leads to a common
820 // workaround used in macros that need to work in both MSVC and
821 // compliant preprocessors. Therefore, the IgnoredComma flag can only
822 // apply once to any given token.
824 } else if (NumParens == 0) {
825 // Comma ends this argument if there are more fixed arguments
826 // expected. However, if this is a variadic macro, and this is part of
827 // the variadic part, then the comma is just an argument token.
828 if (!isVariadic)
829 break;
830 if (NumFixedArgsLeft > 1)
831 break;
832 }
833 } else if (Tok.is(tok::comment) && !KeepMacroComments) {
834 // If this is a comment token in the argument list and we're just in
835 // -C mode (not -CC mode), discard the comment.
836 continue;
837 } else if (!Tok.isAnnotation() && Tok.getIdentifierInfo() != nullptr) {
838 // Reading macro arguments can cause macros that we are currently
839 // expanding from to be popped off the expansion stack. Doing so causes
840 // them to be reenabled for expansion. Here we record whether any
841 // identifiers we lex as macro arguments correspond to disabled macros.
842 // If so, we mark the token as noexpand. This is a subtle aspect of
843 // C99 6.10.3.4p2.
844 if (MacroInfo *MI = getMacroInfo(Tok.getIdentifierInfo()))
845 if (!MI->isEnabled())
847 } else if (Tok.is(tok::code_completion)) {
848 ContainsCodeCompletionTok = true;
849 if (CodeComplete)
850 CodeComplete->CodeCompleteMacroArgument(MacroName.getIdentifierInfo(),
851 MI, NumActuals);
852 // Don't mark that we reached the code-completion point because the
853 // parser is going to handle the token and there will be another
854 // code-completion callback.
855 }
856
857 ArgTokens.push_back(Tok);
858 }
859
860 // If this was an empty argument list foo(), don't add this as an empty
861 // argument.
862 if (ArgTokens.empty() && Tok.getKind() == tok::r_paren)
863 break;
864
865 // If this is not a variadic macro, and too many args were specified, emit
866 // an error.
867 if (!isVariadic && NumFixedArgsLeft == 0 && TooManyArgsLoc.isInvalid()) {
868 if (ArgTokens.size() != ArgTokenStart)
869 TooManyArgsLoc = ArgTokens[ArgTokenStart].getLocation();
870 else
871 TooManyArgsLoc = ArgStartLoc;
872 }
873
874 // Empty arguments are standard in C99 and C++0x, and are supported as an
875 // extension in other modes.
876 if (ArgTokens.size() == ArgTokenStart && !getLangOpts().C99)
878 ? diag::warn_cxx98_compat_empty_fnmacro_arg
879 : diag::ext_empty_fnmacro_arg);
880
881 // Add a marker EOF token to the end of the token list for this argument.
882 Token EOFTok;
883 EOFTok.startToken();
884 EOFTok.setKind(tok::eof);
885 EOFTok.setLocation(Tok.getLocation());
886 EOFTok.setLength(0);
887 ArgTokens.push_back(EOFTok);
888 ++NumActuals;
889 if (!ContainsCodeCompletionTok && NumFixedArgsLeft != 0)
890 --NumFixedArgsLeft;
891 }
892
893 // Okay, we either found the r_paren. Check to see if we parsed too few
894 // arguments.
895 unsigned MinArgsExpected = MI->getNumParams();
896
897 // If this is not a variadic macro, and too many args were specified, emit
898 // an error.
899 if (!isVariadic && NumActuals > MinArgsExpected &&
900 !ContainsCodeCompletionTok) {
901 // Emit the diagnostic at the macro name in case there is a missing ).
902 // Emitting it at the , could be far away from the macro name.
903 Diag(TooManyArgsLoc, diag::err_too_many_args_in_macro_invoc);
904 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
905 << MacroName.getIdentifierInfo();
906
907 // Commas from braced initializer lists will be treated as argument
908 // separators inside macros. Attempt to correct for this with parentheses.
909 // TODO: See if this can be generalized to angle brackets for templates
910 // inside macro arguments.
911
912 SmallVector<Token, 4> FixedArgTokens;
913 unsigned FixedNumArgs = 0;
914 SmallVector<SourceRange, 4> ParenHints, InitLists;
915 if (!GenerateNewArgTokens(*this, ArgTokens, FixedArgTokens, FixedNumArgs,
916 ParenHints, InitLists)) {
917 if (!InitLists.empty()) {
918 DiagnosticBuilder DB =
919 Diag(MacroName,
920 diag::note_init_list_at_beginning_of_macro_argument);
921 for (SourceRange Range : InitLists)
922 DB << Range;
923 }
924 return nullptr;
925 }
926 if (FixedNumArgs != MinArgsExpected)
927 return nullptr;
928
929 DiagnosticBuilder DB = Diag(MacroName, diag::note_suggest_parens_for_macro);
930 for (SourceRange ParenLocation : ParenHints) {
931 DB << FixItHint::CreateInsertion(ParenLocation.getBegin(), "(");
932 DB << FixItHint::CreateInsertion(ParenLocation.getEnd(), ")");
933 }
934 ArgTokens.swap(FixedArgTokens);
935 NumActuals = FixedNumArgs;
936 }
937
938 // See MacroArgs instance var for description of this.
939 bool isVarargsElided = false;
940
941 if (ContainsCodeCompletionTok) {
942 // Recover from not-fully-formed macro invocation during code-completion.
943 Token EOFTok;
944 EOFTok.startToken();
945 EOFTok.setKind(tok::eof);
946 EOFTok.setLocation(Tok.getLocation());
947 EOFTok.setLength(0);
948 for (; NumActuals < MinArgsExpected; ++NumActuals)
949 ArgTokens.push_back(EOFTok);
950 }
951
952 if (NumActuals < MinArgsExpected) {
953 // There are several cases where too few arguments is ok, handle them now.
954 if (NumActuals == 0 && MinArgsExpected == 1) {
955 // #define A(X) or #define A(...) ---> A()
956
957 // If there is exactly one argument, and that argument is missing,
958 // then we have an empty "()" argument empty list. This is fine, even if
959 // the macro expects one argument (the argument is just empty).
960 isVarargsElided = MI->isVariadic();
961 } else if ((FoundElidedComma || MI->isVariadic()) &&
962 (NumActuals+1 == MinArgsExpected || // A(x, ...) -> A(X)
963 (NumActuals == 0 && MinArgsExpected == 2))) {// A(x,...) -> A()
964 // Varargs where the named vararg parameter is missing: OK as extension.
965 // #define A(x, ...)
966 // A("blah")
967 //
968 // If the macro contains the comma pasting extension, the diagnostic
969 // is suppressed; we know we'll get another diagnostic later.
970 if (!MI->hasCommaPasting()) {
971 // C++20 [cpp.replace]p15, C23 6.10.5p12
972 //
973 // C++20 and C23 allow this construct, but standards before that
974 // do not (we allow it as an extension).
975 unsigned ID;
977 ID = diag::warn_cxx17_compat_missing_varargs_arg;
978 else if (getLangOpts().CPlusPlus)
979 ID = diag::ext_cxx_missing_varargs_arg;
980 else if (getLangOpts().C23)
981 ID = diag::warn_c17_compat_missing_varargs_arg;
982 else
983 ID = diag::ext_c_missing_varargs_arg;
984 Diag(Tok, ID);
985 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
986 << MacroName.getIdentifierInfo();
987 }
988
989 // Remember this occurred, allowing us to elide the comma when used for
990 // cases like:
991 // #define A(x, foo...) blah(a, ## foo)
992 // #define B(x, ...) blah(a, ## __VA_ARGS__)
993 // #define C(...) blah(a, ## __VA_ARGS__)
994 // A(x) B(x) C()
995 isVarargsElided = true;
996 } else if (!ContainsCodeCompletionTok) {
997 // Otherwise, emit the error.
998 Diag(Tok, diag::err_too_few_args_in_macro_invoc);
999 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
1000 << MacroName.getIdentifierInfo();
1001 return nullptr;
1002 }
1003
1004 // Add a marker EOF token to the end of the token list for this argument.
1005 SourceLocation EndLoc = Tok.getLocation();
1006 Tok.startToken();
1007 Tok.setKind(tok::eof);
1008 Tok.setLocation(EndLoc);
1009 Tok.setLength(0);
1010 ArgTokens.push_back(Tok);
1011
1012 // If we expect two arguments, add both as empty.
1013 if (NumActuals == 0 && MinArgsExpected == 2)
1014 ArgTokens.push_back(Tok);
1015
1016 } else if (NumActuals > MinArgsExpected && !MI->isVariadic() &&
1017 !ContainsCodeCompletionTok) {
1018 // Emit the diagnostic at the macro name in case there is a missing ).
1019 // Emitting it at the , could be far away from the macro name.
1020 Diag(MacroName, diag::err_too_many_args_in_macro_invoc);
1021 Diag(MI->getDefinitionLoc(), diag::note_macro_here)
1022 << MacroName.getIdentifierInfo();
1023 return nullptr;
1024 }
1025
1026 return MacroArgs::create(MI, ArgTokens, isVarargsElided, *this);
1027}
1028
1029/// Keeps macro expanded tokens for TokenLexers.
1030//
1031/// Works like a stack; a TokenLexer adds the macro expanded tokens that is
1032/// going to lex in the cache and when it finishes the tokens are removed
1033/// from the end of the cache.
1034Token *Preprocessor::cacheMacroExpandedTokens(TokenLexer *tokLexer,
1035 ArrayRef<Token> tokens) {
1036 assert(tokLexer);
1037 if (tokens.empty())
1038 return nullptr;
1039
1040 size_t newIndex = MacroExpandedTokens.size();
1041 bool cacheNeedsToGrow = tokens.size() >
1042 MacroExpandedTokens.capacity()-MacroExpandedTokens.size();
1043 MacroExpandedTokens.append(tokens.begin(), tokens.end());
1044
1045 if (cacheNeedsToGrow) {
1046 // Go through all the TokenLexers whose 'Tokens' pointer points in the
1047 // buffer and update the pointers to the (potential) new buffer array.
1048 for (const auto &Lexer : MacroExpandingLexersStack) {
1049 TokenLexer *prevLexer;
1050 size_t tokIndex;
1051 std::tie(prevLexer, tokIndex) = Lexer;
1052 prevLexer->Tokens = MacroExpandedTokens.data() + tokIndex;
1053 }
1054 }
1055
1056 MacroExpandingLexersStack.push_back(std::make_pair(tokLexer, newIndex));
1057 return MacroExpandedTokens.data() + newIndex;
1058}
1059
1060void Preprocessor::removeCachedMacroExpandedTokensOfLastLexer() {
1061 assert(!MacroExpandingLexersStack.empty());
1062 size_t tokIndex = MacroExpandingLexersStack.back().second;
1063 assert(tokIndex < MacroExpandedTokens.size());
1064 // Pop the cached macro expanded tokens from the end.
1065 MacroExpandedTokens.resize(tokIndex);
1066 MacroExpandingLexersStack.pop_back();
1067}
1068
1069/// ComputeDATE_TIME - Compute the current time, enter it into the specified
1070/// scratch buffer, then return DATELoc/TIMELoc locations with the position of
1071/// the identifier tokens inserted.
1072static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc,
1073 Preprocessor &PP) {
1074 time_t TT;
1075 std::tm *TM;
1078 TM = std::gmtime(&TT);
1079 } else {
1080 TT = std::time(nullptr);
1081 TM = std::localtime(&TT);
1082 }
1083
1084 static const char * const Months[] = {
1085 "Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"
1086 };
1087
1088 {
1089 SmallString<32> TmpBuffer;
1090 llvm::raw_svector_ostream TmpStream(TmpBuffer);
1091 if (TM)
1092 TmpStream << llvm::format("\"%s %2d %4d\"", Months[TM->tm_mon],
1093 TM->tm_mday, TM->tm_year + 1900);
1094 else
1095 TmpStream << "??? ?? ????";
1096 Token TmpTok;
1097 TmpTok.startToken();
1098 PP.CreateString(TmpStream.str(), TmpTok);
1099 DATELoc = TmpTok.getLocation();
1100 }
1101
1102 {
1103 SmallString<32> TmpBuffer;
1104 llvm::raw_svector_ostream TmpStream(TmpBuffer);
1105 if (TM)
1106 TmpStream << llvm::format("\"%02d:%02d:%02d\"", TM->tm_hour, TM->tm_min,
1107 TM->tm_sec);
1108 else
1109 TmpStream << "??:??:??";
1110 Token TmpTok;
1111 TmpTok.startToken();
1112 PP.CreateString(TmpStream.str(), TmpTok);
1113 TIMELoc = TmpTok.getLocation();
1114 }
1115}
1116
1117/// HasFeature - Return true if we recognize and implement the feature
1118/// specified by the identifier as a standard language feature.
1119static bool HasFeature(const Preprocessor &PP, StringRef Feature) {
1120 const LangOptions &LangOpts = PP.getLangOpts();
1121
1122 // Normalize the feature name, __foo__ becomes foo.
1123 if (Feature.starts_with("__") && Feature.ends_with("__") &&
1124 Feature.size() >= 4)
1125 Feature = Feature.substr(2, Feature.size() - 4);
1126
1127#define FEATURE(Name, Predicate) .Case(#Name, Predicate)
1128 return llvm::StringSwitch<bool>(Feature)
1129#include "clang/Basic/Features.def"
1130 .Default(false);
1131#undef FEATURE
1132}
1133
1134/// HasExtension - Return true if we recognize and implement the feature
1135/// specified by the identifier, either as an extension or a standard language
1136/// feature.
1137static bool HasExtension(const Preprocessor &PP, StringRef Extension) {
1138 if (HasFeature(PP, Extension))
1139 return true;
1140
1141 // If the use of an extension results in an error diagnostic, extensions are
1142 // effectively unavailable, so just return false here.
1145 return false;
1146
1147 const LangOptions &LangOpts = PP.getLangOpts();
1148
1149 // Normalize the extension name, __foo__ becomes foo.
1150 if (Extension.starts_with("__") && Extension.ends_with("__") &&
1151 Extension.size() >= 4)
1152 Extension = Extension.substr(2, Extension.size() - 4);
1153
1154 // Because we inherit the feature list from HasFeature, this string switch
1155 // must be less restrictive than HasFeature's.
1156#define EXTENSION(Name, Predicate) .Case(#Name, Predicate)
1157 return llvm::StringSwitch<bool>(Extension)
1158#include "clang/Basic/Features.def"
1159 .Default(false);
1160#undef EXTENSION
1161}
1162
1163/// EvaluateHasIncludeCommon - Process a '__has_include("path")'
1164/// or '__has_include_next("path")' expression.
1165/// Returns true if successful.
1167 Preprocessor &PP,
1168 ConstSearchDirIterator LookupFrom,
1169 const FileEntry *LookupFromFile) {
1170 // Save the location of the current token. If a '(' is later found, use
1171 // that location. If not, use the end of this location instead.
1172 SourceLocation LParenLoc = Tok.getLocation();
1173
1174 // These expressions are only allowed within a preprocessor directive.
1175 if (!PP.isParsingIfOrElifDirective()) {
1176 PP.Diag(LParenLoc, diag::err_pp_directive_required) << II;
1177 // Return a valid identifier token.
1178 assert(Tok.is(tok::identifier));
1179 Tok.setIdentifierInfo(II);
1180 return false;
1181 }
1182
1183 // Get '('. If we don't have a '(', try to form a header-name token.
1184 do {
1185 if (PP.LexHeaderName(Tok))
1186 return false;
1187 } while (Tok.getKind() == tok::comment);
1188
1189 // Ensure we have a '('.
1190 if (Tok.isNot(tok::l_paren)) {
1191 // No '(', use end of last token.
1192 LParenLoc = PP.getLocForEndOfToken(LParenLoc);
1193 PP.Diag(LParenLoc, diag::err_pp_expected_after) << II << tok::l_paren;
1194 // If the next token looks like a filename or the start of one,
1195 // assume it is and process it as such.
1196 if (Tok.isNot(tok::header_name))
1197 return false;
1198 } else {
1199 // Save '(' location for possible missing ')' message.
1200 LParenLoc = Tok.getLocation();
1201 if (PP.LexHeaderName(Tok))
1202 return false;
1203 }
1204
1205 if (Tok.isNot(tok::header_name)) {
1206 PP.Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1207 return false;
1208 }
1209
1210 // Reserve a buffer to get the spelling.
1211 SmallString<128> FilenameBuffer;
1212 bool Invalid = false;
1213 StringRef Filename = PP.getSpelling(Tok, FilenameBuffer, &Invalid);
1214 if (Invalid)
1215 return false;
1216
1217 SourceLocation FilenameLoc = Tok.getLocation();
1218
1219 // Get ')'.
1220 PP.LexNonComment(Tok);
1221
1222 // Ensure we have a trailing ).
1223 if (Tok.isNot(tok::r_paren)) {
1224 PP.Diag(PP.getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
1225 << II << tok::r_paren;
1226 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1227 return false;
1228 }
1229
1230 bool isAngled = PP.GetIncludeFilenameSpelling(Tok.getLocation(), Filename);
1231 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1232 // error.
1233 if (Filename.empty())
1234 return false;
1235
1236 // Passing this to LookupFile forces header search to check whether the found
1237 // file belongs to a module. Skipping that check could incorrectly mark
1238 // modular header as textual, causing issues down the line.
1240
1241 // Search include directories.
1243 PP.LookupFile(FilenameLoc, Filename, isAngled, LookupFrom, LookupFromFile,
1244 nullptr, nullptr, nullptr, &KH, nullptr, nullptr);
1245
1246 if (PPCallbacks *Callbacks = PP.getPPCallbacks()) {
1248 if (File)
1250 Callbacks->HasInclude(FilenameLoc, Filename, isAngled, File, FileType);
1251 }
1252
1253 // Get the result value. A result of true means the file exists.
1254 return File.has_value();
1255}
1256
1257/// EvaluateHasEmbed - Process a '__has_embed("foo" params...)' expression.
1258/// Returns a filled optional with the value if successful; otherwise, empty.
1259EmbedResult Preprocessor::EvaluateHasEmbed(Token &Tok, IdentifierInfo *II) {
1260 // These expressions are only allowed within a preprocessor directive.
1261 if (!this->isParsingIfOrElifDirective()) {
1262 Diag(Tok, diag::err_pp_directive_required) << II;
1263 // Return a valid identifier token.
1264 assert(Tok.is(tok::identifier));
1266 return EmbedResult::Invalid;
1267 }
1268
1269 // Ensure we have a '('.
1271 if (Tok.isNot(tok::l_paren)) {
1272 Diag(Tok, diag::err_pp_expected_after) << II << tok::l_paren;
1273 // If the next token looks like a filename or the start of one,
1274 // assume it is and process it as such.
1275 return EmbedResult::Invalid;
1276 }
1277
1278 // Save '(' location for possible missing ')' message and then lex the header
1279 // name token for the embed resource.
1280 SourceLocation LParenLoc = Tok.getLocation();
1281 if (this->LexHeaderName(Tok))
1282 return EmbedResult::Invalid;
1283
1284 if (Tok.isNot(tok::header_name)) {
1285 Diag(Tok.getLocation(), diag::err_pp_expects_filename);
1286 return EmbedResult::Invalid;
1287 }
1288
1289 SourceLocation FilenameLoc = Tok.getLocation();
1290 Token FilenameTok = Tok;
1291
1292 std::optional<LexEmbedParametersResult> Params =
1293 this->LexEmbedParameters(Tok, /*ForHasEmbed=*/true);
1294
1295 if (!Params)
1296 return EmbedResult::Invalid;
1297
1298 if (Tok.isNot(tok::r_paren)) {
1299 Diag(this->getLocForEndOfToken(FilenameLoc), diag::err_pp_expected_after)
1300 << II << tok::r_paren;
1301 Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1302 if (Tok.isNot(tok::eod))
1304 return EmbedResult::Invalid;
1305 }
1306
1307 if (Params->UnrecognizedParams > 0)
1308 return EmbedResult::NotFound;
1309
1310 SmallString<128> FilenameBuffer;
1311 StringRef Filename = this->getSpelling(FilenameTok, FilenameBuffer);
1312 if (Filename.empty())
1313 return EmbedResult::Empty;
1314
1315 bool isAngled =
1316 this->GetIncludeFilenameSpelling(FilenameTok.getLocation(), Filename);
1317 // If GetIncludeFilenameSpelling set the start ptr to null, there was an
1318 // error.
1319 const FileEntry *LookupFromFile =
1321 : static_cast<FileEntry *>(nullptr);
1322 OptionalFileEntryRef MaybeFileEntry =
1323 this->LookupEmbedFile(Filename, isAngled, false, LookupFromFile);
1324 if (Callbacks) {
1325 Callbacks->HasEmbed(LParenLoc, Filename, isAngled, MaybeFileEntry);
1326 }
1327 if (!MaybeFileEntry)
1328 return EmbedResult::NotFound;
1329
1330 size_t FileSize = MaybeFileEntry->getSize();
1331 // First, "offset" into the file (this reduces the amount of data we can read
1332 // from the file).
1333 if (Params->MaybeOffsetParam) {
1334 if (Params->MaybeOffsetParam->Offset > FileSize)
1335 FileSize = 0;
1336 else
1337 FileSize -= Params->MaybeOffsetParam->Offset;
1338 }
1339
1340 // Second, limit the data from the file (this also reduces the amount of data
1341 // we can read from the file).
1342 if (Params->MaybeLimitParam) {
1343 if (Params->MaybeLimitParam->Limit > FileSize)
1344 FileSize = 0;
1345 else
1346 FileSize = Params->MaybeLimitParam->Limit;
1347 }
1348
1349 // If we have no data left to read, the file is empty, otherwise we have the
1350 // expected resource.
1351 if (FileSize == 0)
1352 return EmbedResult::Empty;
1353 return EmbedResult::Found;
1354}
1355
1356bool Preprocessor::EvaluateHasInclude(Token &Tok, IdentifierInfo *II) {
1357 return EvaluateHasIncludeCommon(Tok, II, *this, nullptr, nullptr);
1358}
1359
1360bool Preprocessor::EvaluateHasIncludeNext(Token &Tok, IdentifierInfo *II) {
1361 ConstSearchDirIterator Lookup = nullptr;
1362 const FileEntry *LookupFromFile;
1363 std::tie(Lookup, LookupFromFile) = getIncludeNextStart(Tok);
1364
1365 return EvaluateHasIncludeCommon(Tok, II, *this, Lookup, LookupFromFile);
1366}
1367
1368/// Process single-argument builtin feature-like macros that return
1369/// integer values.
1370static void EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream& OS,
1371 Token &Tok, IdentifierInfo *II,
1372 Preprocessor &PP, bool ExpandArgs,
1373 llvm::function_ref<
1374 int(Token &Tok,
1375 bool &HasLexedNextTok)> Op) {
1376 // Parse the initial '('.
1378 if (Tok.isNot(tok::l_paren)) {
1379 PP.Diag(Tok.getLocation(), diag::err_pp_expected_after) << II
1380 << tok::l_paren;
1381
1382 // Provide a dummy '0' value on output stream to elide further errors.
1383 if (!Tok.isOneOf(tok::eof, tok::eod)) {
1384 OS << 0;
1385 Tok.setKind(tok::numeric_constant);
1386 }
1387 return;
1388 }
1389
1390 unsigned ParenDepth = 1;
1391 SourceLocation LParenLoc = Tok.getLocation();
1392 std::optional<int> Result;
1393
1394 Token ResultTok;
1395 bool SuppressDiagnostic = false;
1396 while (true) {
1397 // Parse next token.
1398 if (ExpandArgs)
1399 PP.Lex(Tok);
1400 else
1402
1403already_lexed:
1404 switch (Tok.getKind()) {
1405 case tok::eof:
1406 case tok::eod:
1407 // Don't provide even a dummy value if the eod or eof marker is
1408 // reached. Simply provide a diagnostic.
1409 PP.Diag(Tok.getLocation(), diag::err_unterm_macro_invoc);
1410 return;
1411
1412 case tok::comma:
1413 if (!SuppressDiagnostic) {
1414 PP.Diag(Tok.getLocation(), diag::err_too_many_args_in_macro_invoc);
1415 SuppressDiagnostic = true;
1416 }
1417 continue;
1418
1419 case tok::l_paren:
1420 ++ParenDepth;
1421 if (Result)
1422 break;
1423 if (!SuppressDiagnostic) {
1424 PP.Diag(Tok.getLocation(), diag::err_pp_nested_paren) << II;
1425 SuppressDiagnostic = true;
1426 }
1427 continue;
1428
1429 case tok::r_paren:
1430 if (--ParenDepth > 0)
1431 continue;
1432
1433 // The last ')' has been reached; return the value if one found or
1434 // a diagnostic and a dummy value.
1435 if (Result) {
1436 OS << *Result;
1437 // For strict conformance to __has_cpp_attribute rules, use 'L'
1438 // suffix for dated literals.
1439 if (*Result > 1)
1440 OS << 'L';
1441 } else {
1442 OS << 0;
1443 if (!SuppressDiagnostic)
1444 PP.Diag(Tok.getLocation(), diag::err_too_few_args_in_macro_invoc);
1445 }
1446 Tok.setKind(tok::numeric_constant);
1447 return;
1448
1449 default: {
1450 // Parse the macro argument, if one not found so far.
1451 if (Result)
1452 break;
1453
1454 bool HasLexedNextToken = false;
1455 Result = Op(Tok, HasLexedNextToken);
1456 ResultTok = Tok;
1457 if (HasLexedNextToken)
1458 goto already_lexed;
1459 continue;
1460 }
1461 }
1462
1463 // Diagnose missing ')'.
1464 if (!SuppressDiagnostic) {
1465 if (auto Diag = PP.Diag(Tok.getLocation(), diag::err_pp_expected_after)) {
1466 if (IdentifierInfo *LastII = ResultTok.getIdentifierInfo())
1467 Diag << LastII;
1468 else
1469 Diag << ResultTok.getKind();
1470 Diag << tok::r_paren << ResultTok.getLocation();
1471 }
1472 PP.Diag(LParenLoc, diag::note_matching) << tok::l_paren;
1473 SuppressDiagnostic = true;
1474 }
1475 }
1476}
1477
1478/// Helper function to return the IdentifierInfo structure of a Token
1479/// or generate a diagnostic if none available.
1481 Preprocessor &PP,
1482 signed DiagID) {
1483 IdentifierInfo *II;
1484 if (!Tok.isAnnotation() && (II = Tok.getIdentifierInfo()))
1485 return II;
1486
1487 PP.Diag(Tok.getLocation(), DiagID);
1488 return nullptr;
1489}
1490
1491/// Implements the __is_target_arch builtin macro.
1492static bool isTargetArch(const TargetInfo &TI, const IdentifierInfo *II) {
1493 llvm::Triple Arch(II->getName().lower() + "--");
1494 const llvm::Triple &TT = TI.getTriple();
1495 if (TT.isThumb()) {
1496 // arm matches thumb or thumbv7. armv7 matches thumbv7.
1497 if ((Arch.getSubArch() == llvm::Triple::NoSubArch ||
1498 Arch.getSubArch() == TT.getSubArch()) &&
1499 ((TT.getArch() == llvm::Triple::thumb &&
1500 Arch.getArch() == llvm::Triple::arm) ||
1501 (TT.getArch() == llvm::Triple::thumbeb &&
1502 Arch.getArch() == llvm::Triple::armeb)))
1503 return true;
1504 }
1505 // Check the parsed arch when it has no sub arch to allow Clang to
1506 // match thumb to thumbv7 but to prohibit matching thumbv6 to thumbv7.
1507 return (Arch.getSubArch() == llvm::Triple::NoSubArch ||
1508 Arch.getSubArch() == TT.getSubArch()) &&
1509 Arch.getArch() == TT.getArch();
1510}
1511
1512/// Implements the __is_target_vendor builtin macro.
1513static bool isTargetVendor(const TargetInfo &TI, const IdentifierInfo *II) {
1514 StringRef VendorName = TI.getTriple().getVendorName();
1515 if (VendorName.empty())
1516 VendorName = "unknown";
1517 return VendorName.equals_insensitive(II->getName());
1518}
1519
1520/// Implements the __is_target_os builtin macro.
1521static bool isTargetOS(const TargetInfo &TI, const IdentifierInfo *II) {
1522 llvm::Triple OS(llvm::Twine("unknown-unknown-") + II->getName().lower());
1523 if (OS.getOS() == llvm::Triple::Darwin) {
1524 // Darwin matches macos, ios, etc.
1525 return TI.getTriple().isOSDarwin();
1526 }
1527 return TI.getTriple().getOS() == OS.getOS();
1528}
1529
1530/// Implements the __is_target_environment builtin macro.
1531static bool isTargetEnvironment(const TargetInfo &TI,
1532 const IdentifierInfo *II) {
1533 llvm::Triple Env(llvm::Twine("---") + II->getName().lower());
1534 // The unknown environment is matched only if
1535 // '__is_target_environment(unknown)' is used.
1536 if (Env.getEnvironment() == llvm::Triple::UnknownEnvironment &&
1537 Env.getEnvironmentName() != "unknown")
1538 return false;
1539 return TI.getTriple().getEnvironment() == Env.getEnvironment();
1540}
1541
1542/// Implements the __is_target_variant_os builtin macro.
1543static bool isTargetVariantOS(const TargetInfo &TI, const IdentifierInfo *II) {
1544 if (TI.getTriple().isOSDarwin()) {
1545 const llvm::Triple *VariantTriple = TI.getDarwinTargetVariantTriple();
1546 if (!VariantTriple)
1547 return false;
1548
1549 llvm::Triple OS(llvm::Twine("unknown-unknown-") + II->getName().lower());
1550 if (OS.getOS() == llvm::Triple::Darwin) {
1551 // Darwin matches macos, ios, etc.
1552 return VariantTriple->isOSDarwin();
1553 }
1554 return VariantTriple->getOS() == OS.getOS();
1555 }
1556 return false;
1557}
1558
1559/// Implements the __is_target_variant_environment builtin macro.
1561 const IdentifierInfo *II) {
1562 if (TI.getTriple().isOSDarwin()) {
1563 const llvm::Triple *VariantTriple = TI.getDarwinTargetVariantTriple();
1564 if (!VariantTriple)
1565 return false;
1566 llvm::Triple Env(llvm::Twine("---") + II->getName().lower());
1567 return VariantTriple->getEnvironment() == Env.getEnvironment();
1568 }
1569 return false;
1570}
1571
1572#if defined(__sun__) && defined(__svr4__) && defined(__clang__) && \
1573 __clang__ < 20
1574// GCC mangles std::tm as tm for binary compatibility on Solaris (Issue
1575// #33114). We need to match this to allow the std::put_time calls to link
1576// (PR #99075). clang 20 contains a fix, but the workaround is still needed
1577// with older versions.
1578asm("_ZNKSt8time_putIcSt19ostreambuf_iteratorIcSt11char_traitsIcEEE3putES3_"
1579 "RSt8ios_basecPKSt2tmPKcSB_ = "
1580 "_ZNKSt8time_putIcSt19ostreambuf_iteratorIcSt11char_traitsIcEEE3putES3_"
1581 "RSt8ios_basecPK2tmPKcSB_");
1582#endif
1583
1584static bool IsBuiltinTrait(Token &Tok) {
1585
1586#define TYPE_TRAIT_1(Spelling, Name, Key) \
1587 case tok::kw_##Spelling: \
1588 return true;
1589#define TYPE_TRAIT_2(Spelling, Name, Key) \
1590 case tok::kw_##Spelling: \
1591 return true;
1592#define TYPE_TRAIT_N(Spelling, Name, Key) \
1593 case tok::kw_##Spelling: \
1594 return true;
1595#define ARRAY_TYPE_TRAIT(Spelling, Name, Key) \
1596 case tok::kw_##Spelling: \
1597 return true;
1598#define EXPRESSION_TRAIT(Spelling, Name, Key) \
1599 case tok::kw_##Spelling: \
1600 return true;
1601#define TRANSFORM_TYPE_TRAIT_DEF(K, Spelling) \
1602 case tok::kw___##Spelling: \
1603 return true;
1604
1605 switch (Tok.getKind()) {
1606 default:
1607 return false;
1608#include "clang/Basic/TokenKinds.def"
1609 }
1610}
1611
1612/// ExpandBuiltinMacro - If an identifier token is read that is to be expanded
1613/// as a builtin macro, handle it and return the next token as 'Tok'.
1614void Preprocessor::ExpandBuiltinMacro(Token &Tok) {
1615 // Figure out which token this is.
1616 IdentifierInfo *II = Tok.getIdentifierInfo();
1617 assert(II && "Can't be a macro without id info!");
1618
1619 // If this is an _Pragma or Microsoft __pragma directive, expand it,
1620 // invoke the pragma handler, then lex the token after it.
1621 if (II == Ident_Pragma)
1622 return Handle_Pragma(Tok);
1623 else if (II == Ident__pragma) // in non-MS mode this is null
1624 return HandleMicrosoft__pragma(Tok);
1625
1626 ++NumBuiltinMacroExpanded;
1627
1628 SmallString<128> TmpBuffer;
1629 llvm::raw_svector_ostream OS(TmpBuffer);
1630
1631 // Set up the return result.
1632 Tok.setIdentifierInfo(nullptr);
1634 bool IsAtStartOfLine = Tok.isAtStartOfLine();
1635 bool HasLeadingSpace = Tok.hasLeadingSpace();
1636
1637 if (II == Ident__LINE__) {
1638 // C99 6.10.8: "__LINE__: The presumed line number (within the current
1639 // source file) of the current source line (an integer constant)". This can
1640 // be affected by #line.
1641 SourceLocation Loc = Tok.getLocation();
1642
1643 // Advance to the location of the first _, this might not be the first byte
1644 // of the token if it starts with an escaped newline.
1645 Loc = AdvanceToTokenCharacter(Loc, 0);
1646
1647 // One wrinkle here is that GCC expands __LINE__ to location of the *end* of
1648 // a macro expansion. This doesn't matter for object-like macros, but
1649 // can matter for a function-like macro that expands to contain __LINE__.
1650 // Skip down through expansion points until we find a file loc for the
1651 // end of the expansion history.
1652 Loc = SourceMgr.getExpansionRange(Loc).getEnd();
1653 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Loc);
1654
1655 // __LINE__ expands to a simple numeric value.
1656 OS << (PLoc.isValid()? PLoc.getLine() : 1);
1657 Tok.setKind(tok::numeric_constant);
1658 } else if (II == Ident__FILE__ || II == Ident__BASE_FILE__ ||
1659 II == Ident__FILE_NAME__) {
1660 // C99 6.10.8: "__FILE__: The presumed name of the current source file (a
1661 // character string literal)". This can be affected by #line.
1662 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1663
1664 // __BASE_FILE__ is a GNU extension that returns the top of the presumed
1665 // #include stack instead of the current file.
1666 if (II == Ident__BASE_FILE__ && PLoc.isValid()) {
1667 SourceLocation NextLoc = PLoc.getIncludeLoc();
1668 while (NextLoc.isValid()) {
1669 PLoc = SourceMgr.getPresumedLoc(NextLoc);
1670 if (PLoc.isInvalid())
1671 break;
1672
1673 NextLoc = PLoc.getIncludeLoc();
1674 }
1675 }
1676
1677 // Escape this filename. Turn '\' -> '\\' '"' -> '\"'
1678 SmallString<256> FN;
1679 if (PLoc.isValid()) {
1680 // __FILE_NAME__ is a Clang-specific extension that expands to the
1681 // the last part of __FILE__.
1682 if (II == Ident__FILE_NAME__) {
1684 } else {
1685 FN += PLoc.getFilename();
1687 }
1688 Lexer::Stringify(FN);
1689 OS << '"' << FN << '"';
1690 }
1691 Tok.setKind(tok::string_literal);
1692 } else if (II == Ident__DATE__) {
1693 Diag(Tok.getLocation(), diag::warn_pp_date_time);
1694 if (!DATELoc.isValid())
1695 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1696 Tok.setKind(tok::string_literal);
1697 Tok.setLength(strlen("\"Mmm dd yyyy\""));
1698 Tok.setLocation(SourceMgr.createExpansionLoc(DATELoc, Tok.getLocation(),
1699 Tok.getLocation(),
1700 Tok.getLength()));
1701 return;
1702 } else if (II == Ident__TIME__) {
1703 Diag(Tok.getLocation(), diag::warn_pp_date_time);
1704 if (!TIMELoc.isValid())
1705 ComputeDATE_TIME(DATELoc, TIMELoc, *this);
1706 Tok.setKind(tok::string_literal);
1707 Tok.setLength(strlen("\"hh:mm:ss\""));
1708 Tok.setLocation(SourceMgr.createExpansionLoc(TIMELoc, Tok.getLocation(),
1709 Tok.getLocation(),
1710 Tok.getLength()));
1711 return;
1712 } else if (II == Ident__INCLUDE_LEVEL__) {
1713 // Compute the presumed include depth of this token. This can be affected
1714 // by GNU line markers.
1715 unsigned Depth = 0;
1716
1717 PresumedLoc PLoc = SourceMgr.getPresumedLoc(Tok.getLocation());
1718 if (PLoc.isValid()) {
1719 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1720 for (; PLoc.isValid(); ++Depth)
1721 PLoc = SourceMgr.getPresumedLoc(PLoc.getIncludeLoc());
1722 }
1723
1724 // __INCLUDE_LEVEL__ expands to a simple numeric value.
1725 OS << Depth;
1726 Tok.setKind(tok::numeric_constant);
1727 } else if (II == Ident__TIMESTAMP__) {
1728 Diag(Tok.getLocation(), diag::warn_pp_date_time);
1729 // MSVC, ICC, GCC, VisualAge C++ extension. The generated string should be
1730 // of the form "Ddd Mmm dd hh::mm::ss yyyy", which is returned by asctime.
1731 std::string Result;
1732 std::stringstream TmpStream;
1733 TmpStream.imbue(std::locale("C"));
1734 if (getPreprocessorOpts().SourceDateEpoch) {
1735 time_t TT = *getPreprocessorOpts().SourceDateEpoch;
1736 std::tm *TM = std::gmtime(&TT);
1737 TmpStream << std::put_time(TM, "%a %b %e %T %Y");
1738 } else {
1739 // Get the file that we are lexing out of. If we're currently lexing from
1740 // a macro, dig into the include stack.
1741 const FileEntry *CurFile = nullptr;
1742 if (PreprocessorLexer *TheLexer = getCurrentFileLexer())
1743 CurFile = SourceMgr.getFileEntryForID(TheLexer->getFileID());
1744 if (CurFile) {
1745 time_t TT = CurFile->getModificationTime();
1746 struct tm *TM = localtime(&TT);
1747 TmpStream << std::put_time(TM, "%a %b %e %T %Y");
1748 }
1749 }
1750 Result = TmpStream.str();
1751 if (Result.empty())
1752 Result = "??? ??? ?? ??:??:?? ????";
1753 OS << '"' << Result << '"';
1754 Tok.setKind(tok::string_literal);
1755 } else if (II == Ident__FLT_EVAL_METHOD__) {
1756 // __FLT_EVAL_METHOD__ is set to the default value.
1757 OS << getTUFPEvalMethod();
1758 // __FLT_EVAL_METHOD__ expands to a simple numeric value.
1759 Tok.setKind(tok::numeric_constant);
1760 if (getLastFPEvalPragmaLocation().isValid()) {
1761 // The program is ill-formed. The value of __FLT_EVAL_METHOD__ is altered
1762 // by the pragma.
1763 Diag(Tok, diag::err_illegal_use_of_flt_eval_macro);
1764 Diag(getLastFPEvalPragmaLocation(), diag::note_pragma_entered_here);
1765 }
1766 } else if (II == Ident__COUNTER__) {
1768 getLangOpts().C2y ? diag::warn_counter : diag::ext_counter);
1769 // __COUNTER__ expands to a simple numeric value that must be less than
1770 // 2147483647.
1771 constexpr uint32_t MaxPosValue = std::numeric_limits<int32_t>::max();
1772 if (CounterValue > MaxPosValue) {
1773 Diag(Tok.getLocation(), diag::err_counter_overflow);
1774 // Retain the maximal value so we don't issue conversion-related
1775 // diagnostics by overflowing into a long long. While this does produce
1776 // a duplicate value, there's no way to ignore this error so there's no
1777 // translation anyway.
1778 CounterValue = MaxPosValue;
1779 }
1780 OS << CounterValue++;
1781 Tok.setKind(tok::numeric_constant);
1782 } else if (II == Ident__has_feature) {
1783 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
1784 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1785 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1786 diag::err_feature_check_malformed);
1787 return II && HasFeature(*this, II->getName());
1788 });
1789 } else if (II == Ident__has_extension) {
1790 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
1791 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1792 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1793 diag::err_feature_check_malformed);
1794 return II && HasExtension(*this, II->getName());
1795 });
1796 } else if (II == Ident__has_builtin) {
1798 OS, Tok, II, *this, false,
1799 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1800 IdentifierInfo *II = ExpectFeatureIdentifierInfo(
1801 Tok, *this, diag::err_feature_check_malformed);
1802 if (!II)
1803 return false;
1804 unsigned BuiltinID = II->getBuiltinID();
1805 if (BuiltinID != 0) {
1806 switch (II->getBuiltinID()) {
1807 case Builtin::BI__builtin_cpu_is:
1808 return getTargetInfo().supportsCpuIs();
1809 case Builtin::BI__builtin_cpu_init:
1810 return getTargetInfo().supportsCpuInit();
1811 case Builtin::BI__builtin_cpu_supports:
1813 case Builtin::BI__builtin_operator_new:
1814 case Builtin::BI__builtin_operator_delete:
1815 // denotes date of behavior change to support calling arbitrary
1816 // usual allocation and deallocation functions. Required by libc++
1817 return 201802;
1818 default:
1819 // __has_builtin should return false for aux builtins.
1820 if (getBuiltinInfo().isAuxBuiltinID(BuiltinID))
1821 return false;
1823 getBuiltinInfo().getRequiredFeatures(BuiltinID),
1824 getTargetInfo().getTargetOpts().FeatureMap);
1825 }
1826 return true;
1827 } else if (IsBuiltinTrait(Tok)) {
1828 return true;
1829 } else if (II->getTokenID() != tok::identifier &&
1830 II->getName().starts_with("__builtin_")) {
1831 return true;
1832 } else {
1833 return llvm::StringSwitch<bool>(II->getName())
1834 // Report builtin templates as being builtins.
1835#define BuiltinTemplate(BTName) .Case(#BTName, getLangOpts().CPlusPlus)
1836#include "clang/Basic/BuiltinTemplates.inc"
1837 // Likewise for some builtin preprocessor macros.
1838 // FIXME: This is inconsistent; we usually suggest detecting
1839 // builtin macros via #ifdef. Don't add more cases here.
1840 .Case("__is_target_arch", true)
1841 .Case("__is_target_vendor", true)
1842 .Case("__is_target_os", true)
1843 .Case("__is_target_environment", true)
1844 .Case("__is_target_variant_os", true)
1845 .Case("__is_target_variant_environment", true)
1846 .Default(false);
1847 }
1848 });
1849 } else if (II == Ident__has_constexpr_builtin) {
1851 OS, Tok, II, *this, false,
1852 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1853 IdentifierInfo *II = ExpectFeatureIdentifierInfo(
1854 Tok, *this, diag::err_feature_check_malformed);
1855 if (!II)
1856 return false;
1857 unsigned BuiltinOp = II->getBuiltinID();
1858 return BuiltinOp != 0 &&
1859 this->getBuiltinInfo().isConstantEvaluated(BuiltinOp);
1860 });
1861 } else if (II == Ident__is_identifier) {
1862 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
1863 [](Token &Tok, bool &HasLexedNextToken) -> int {
1864 return Tok.is(tok::identifier);
1865 });
1866 } else if (II == Ident__has_attribute) {
1867 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, true,
1868 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1869 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1870 diag::err_feature_check_malformed);
1872 II, getTargetInfo(), getLangOpts())
1873 : 0;
1874 });
1875 } else if (II == Ident__has_declspec) {
1876 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, true,
1877 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1878 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1879 diag::err_feature_check_malformed);
1880 if (II) {
1881 const LangOptions &LangOpts = getLangOpts();
1882 return LangOpts.DeclSpecKeyword &&
1884 II, getTargetInfo(), LangOpts);
1885 }
1886
1887 return false;
1888 });
1889 } else if (II == Ident__has_cpp_attribute ||
1890 II == Ident__has_c_attribute) {
1891 bool IsCXX = II == Ident__has_cpp_attribute;
1892 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, true,
1893 [&](Token &Tok, bool &HasLexedNextToken) -> int {
1894 IdentifierInfo *ScopeII = nullptr;
1895 IdentifierInfo *II = ExpectFeatureIdentifierInfo(
1896 Tok, *this, diag::err_feature_check_malformed);
1897 if (!II)
1898 return false;
1899
1900 // It is possible to receive a scope token. Read the "::", if it is
1901 // available, and the subsequent identifier.
1903 if (Tok.isNot(tok::coloncolon))
1904 HasLexedNextToken = true;
1905 else {
1906 ScopeII = II;
1907 // Lex an expanded token for the attribute name.
1908 Lex(Tok);
1909 II = ExpectFeatureIdentifierInfo(Tok, *this,
1910 diag::err_feature_check_malformed);
1911 }
1912
1916 return II ? hasAttribute(Syntax, ScopeII, II, getTargetInfo(),
1917 getLangOpts())
1918 : 0;
1919 });
1920 } else if (II == Ident__has_include ||
1921 II == Ident__has_include_next) {
1922 // The argument to these two builtins should be a parenthesized
1923 // file name string literal using angle brackets (<>) or
1924 // double-quotes ("").
1925 bool Value;
1926 if (II == Ident__has_include)
1927 Value = EvaluateHasInclude(Tok, II);
1928 else
1929 Value = EvaluateHasIncludeNext(Tok, II);
1930
1931 if (Tok.isNot(tok::r_paren))
1932 return;
1933 OS << (int)Value;
1934 Tok.setKind(tok::numeric_constant);
1935 } else if (II == Ident__has_embed) {
1936 // The argument to these two builtins should be a parenthesized
1937 // file name string literal using angle brackets (<>) or
1938 // double-quotes (""), optionally followed by a series of
1939 // arguments similar to form like attributes.
1940 EmbedResult Value = EvaluateHasEmbed(Tok, II);
1942 return;
1943
1944 Tok.setKind(tok::numeric_constant);
1945 OS << static_cast<int>(Value);
1946 } else if (II == Ident__has_warning) {
1947 // The argument should be a parenthesized string literal.
1948 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
1949 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1950 std::string WarningName;
1951 SourceLocation StrStartLoc = Tok.getLocation();
1952
1953 HasLexedNextToken = Tok.is(tok::string_literal);
1954 if (!FinishLexStringLiteral(Tok, WarningName, "'__has_warning'",
1955 /*AllowMacroExpansion=*/false))
1956 return false;
1957
1958 // FIXME: Should we accept "-R..." flags here, or should that be
1959 // handled by a separate __has_remark?
1960 if (WarningName.size() < 3 || WarningName[0] != '-' ||
1961 WarningName[1] != 'W') {
1962 Diag(StrStartLoc, diag::warn_has_warning_invalid_option);
1963 return false;
1964 }
1965
1966 // Finally, check if the warning flags maps to a diagnostic group.
1967 // We construct a SmallVector here to talk to getDiagnosticIDs().
1968 // Although we don't use the result, this isn't a hot path, and not
1969 // worth special casing.
1970 SmallVector<diag::kind, 10> Diags;
1971 return !getDiagnostics().getDiagnosticIDs()->
1973 WarningName.substr(2), Diags);
1974 });
1975 } else if (II == Ident__building_module) {
1976 // The argument to this builtin should be an identifier. The
1977 // builtin evaluates to 1 when that identifier names the module we are
1978 // currently building.
1979 EvaluateFeatureLikeBuiltinMacro(OS, Tok, II, *this, false,
1980 [this](Token &Tok, bool &HasLexedNextToken) -> int {
1981 IdentifierInfo *II = ExpectFeatureIdentifierInfo(Tok, *this,
1982 diag::err_expected_id_building_module);
1983 return getLangOpts().isCompilingModule() && II &&
1984 (II->getName() == getLangOpts().CurrentModule);
1985 });
1986 } else if (II == Ident__MODULE__) {
1987 // The current module as an identifier.
1989 IdentifierInfo *ModuleII = getIdentifierInfo(getLangOpts().CurrentModule);
1990 Tok.setIdentifierInfo(ModuleII);
1991 Tok.setKind(ModuleII->getTokenID());
1992 } else if (II == Ident__identifier) {
1993 SourceLocation Loc = Tok.getLocation();
1994
1995 // We're expecting '__identifier' '(' identifier ')'. Try to recover
1996 // if the parens are missing.
1998 if (Tok.isNot(tok::l_paren)) {
1999 // No '(', use end of last token.
2000 Diag(getLocForEndOfToken(Loc), diag::err_pp_expected_after)
2001 << II << tok::l_paren;
2002 // If the next token isn't valid as our argument, we can't recover.
2004 Tok.setKind(tok::identifier);
2005 return;
2006 }
2007
2008 SourceLocation LParenLoc = Tok.getLocation();
2010
2012 Tok.setKind(tok::identifier);
2013 else if (Tok.is(tok::string_literal) && !Tok.hasUDSuffix()) {
2014 StringLiteralParser Literal(Tok, *this,
2016 if (Literal.hadError)
2017 return;
2018
2020 Tok.setKind(tok::identifier);
2021 } else {
2022 Diag(Tok.getLocation(), diag::err_pp_identifier_arg_not_identifier)
2023 << Tok.getKind();
2024 // Don't walk past anything that's not a real token.
2025 if (Tok.isOneOf(tok::eof, tok::eod) || Tok.isAnnotation())
2026 return;
2027 }
2028
2029 // Discard the ')', preserving 'Tok' as our result.
2030 Token RParen;
2031 LexNonComment(RParen);
2032 if (RParen.isNot(tok::r_paren)) {
2033 Diag(getLocForEndOfToken(Tok.getLocation()), diag::err_pp_expected_after)
2034 << Tok.getKind() << tok::r_paren;
2035 Diag(LParenLoc, diag::note_matching) << tok::l_paren;
2036 }
2037 return;
2038 } else if (II == Ident__is_target_arch) {
2040 OS, Tok, II, *this, false,
2041 [this](Token &Tok, bool &HasLexedNextToken) -> int {
2042 IdentifierInfo *II = ExpectFeatureIdentifierInfo(
2043 Tok, *this, diag::err_feature_check_malformed);
2044 return II && isTargetArch(getTargetInfo(), II);
2045 });
2046 } else if (II == Ident__is_target_vendor) {
2048 OS, Tok, II, *this, false,
2049 [this](Token &Tok, bool &HasLexedNextToken) -> int {
2050 IdentifierInfo *II = ExpectFeatureIdentifierInfo(
2051 Tok, *this, diag::err_feature_check_malformed);
2052 return II && isTargetVendor(getTargetInfo(), II);
2053 });
2054 } else if (II == Ident__is_target_os) {
2056 OS, Tok, II, *this, false,
2057 [this](Token &Tok, bool &HasLexedNextToken) -> int {
2058 IdentifierInfo *II = ExpectFeatureIdentifierInfo(
2059 Tok, *this, diag::err_feature_check_malformed);
2060 return II && isTargetOS(getTargetInfo(), II);
2061 });
2062 } else if (II == Ident__is_target_environment) {
2064 OS, Tok, II, *this, false,
2065 [this](Token &Tok, bool &HasLexedNextToken) -> int {
2066 IdentifierInfo *II = ExpectFeatureIdentifierInfo(
2067 Tok, *this, diag::err_feature_check_malformed);
2068 return II && isTargetEnvironment(getTargetInfo(), II);
2069 });
2070 } else if (II == Ident__is_target_variant_os) {
2072 OS, Tok, II, *this, false,
2073 [this](Token &Tok, bool &HasLexedNextToken) -> int {
2074 IdentifierInfo *II = ExpectFeatureIdentifierInfo(
2075 Tok, *this, diag::err_feature_check_malformed);
2076 return II && isTargetVariantOS(getTargetInfo(), II);
2077 });
2078 } else if (II == Ident__is_target_variant_environment) {
2080 OS, Tok, II, *this, false,
2081 [this](Token &Tok, bool &HasLexedNextToken) -> int {
2082 IdentifierInfo *II = ExpectFeatureIdentifierInfo(
2083 Tok, *this, diag::err_feature_check_malformed);
2084 return II && isTargetVariantEnvironment(getTargetInfo(), II);
2085 });
2086 } else {
2087 llvm_unreachable("Unknown identifier!");
2088 }
2090 Tok.setFlagValue(Token::StartOfLine, IsAtStartOfLine);
2091 Tok.setFlagValue(Token::LeadingSpace, HasLeadingSpace);
2093}
2094
2096 // If the 'used' status changed, and the macro requires 'unused' warning,
2097 // remove its SourceLocation from the warn-for-unused-macro locations.
2098 if (MI->isWarnIfUnused() && !MI->isUsed())
2099 WarnUnusedMacroLocs.erase(MI->getDefinitionLoc());
2100 MI->setIsUsed(true);
2101}
2102
2104 const LangOptions &LangOpts,
2105 const TargetInfo &TI) {
2106 LangOpts.remapPathPrefix(Path);
2107 if (LangOpts.UseTargetPathSeparator) {
2108 if (TI.getTriple().isOSWindows())
2109 llvm::sys::path::remove_dots(Path, false,
2110 llvm::sys::path::Style::windows_backslash);
2111 else
2112 llvm::sys::path::remove_dots(Path, false, llvm::sys::path::Style::posix);
2113 }
2114}
2115
2117 const PresumedLoc &PLoc,
2118 const LangOptions &LangOpts,
2119 const TargetInfo &TI) {
2120 // Try to get the last path component, failing that return the original
2121 // presumed location.
2122 StringRef PLFileName = llvm::sys::path::filename(PLoc.getFilename());
2123 if (PLFileName.empty())
2124 PLFileName = PLoc.getFilename();
2125 FileName.append(PLFileName.begin(), PLFileName.end());
2126 processPathForFileMacro(FileName, LangOpts, TI);
2127}
Defines enum values for all the target-independent builtin functions.
static bool getDiagnosticsInGroup(diag::Flavor Flavor, const WarningOption *Group, SmallVectorImpl< diag::kind > &Diags, diag::CustomDiagInfo *CustomDiagInfo)
Return true if any diagnostics were found in this group, even if they were filtered out due to having...
Token Tok
The Token.
Defines the clang::IdentifierInfo, clang::IdentifierTable, and clang::Selector interfaces.
Forward-declares and imports various common LLVM datatypes that clang wants to use unqualified.
Defines the clang::LangOptions interface.
static DiagnosticBuilder Diag(DiagnosticsEngine *Diags, const LangOptions &Features, FullSourceLoc TokLoc, const char *TokBegin, const char *TokRangeBegin, const char *TokRangeEnd, unsigned DiagID)
Produce a diagnostic highlighting some portion of a literal.
llvm::MachO::FileType FileType
Definition MachO.h:46
Defines the clang::MacroInfo and clang::MacroDirective classes.
static bool HasExtension(const Preprocessor &PP, StringRef Extension)
HasExtension - Return true if we recognize and implement the feature specified by the identifier,...
static bool CheckMatchedBrackets(const SmallVectorImpl< Token > &Tokens)
CheckMatchedBrackets - Returns true if the braces and parentheses in the token vector are properly ne...
static bool EvaluateHasIncludeCommon(Token &Tok, IdentifierInfo *II, Preprocessor &PP, ConstSearchDirIterator LookupFrom, const FileEntry *LookupFromFile)
EvaluateHasIncludeCommon - Process a '__has_include("path")' or '__has_include_next("path")' expressi...
static bool GenerateNewArgTokens(Preprocessor &PP, SmallVectorImpl< Token > &OldTokens, SmallVectorImpl< Token > &NewTokens, unsigned &NumArgs, SmallVectorImpl< SourceRange > &ParenHints, SmallVectorImpl< SourceRange > &InitLists)
GenerateNewArgTokens - Returns true if OldTokens can be converted to a new vector of tokens in NewTok...
static bool isTargetVariantOS(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_variant_os builtin macro.
static bool isTrivialSingleTokenExpansion(const MacroInfo *MI, const IdentifierInfo *MacroIdent, Preprocessor &PP)
isTrivialSingleTokenExpansion - Return true if MI, which has a single token in its expansion,...
static bool isTargetArch(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_arch builtin macro.
static void ComputeDATE_TIME(SourceLocation &DATELoc, SourceLocation &TIMELoc, Preprocessor &PP)
ComputeDATE_TIME - Compute the current time, enter it into the specified scratch buffer,...
static bool isTargetVariantEnvironment(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_variant_environment builtin macro.
static bool isTargetEnvironment(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_environment builtin macro.
static bool IsBuiltinTrait(Token &Tok)
static bool isTargetOS(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_os builtin macro.
static bool isTargetVendor(const TargetInfo &TI, const IdentifierInfo *II)
Implements the __is_target_vendor builtin macro.
static void EvaluateFeatureLikeBuiltinMacro(llvm::raw_svector_ostream &OS, Token &Tok, IdentifierInfo *II, Preprocessor &PP, bool ExpandArgs, llvm::function_ref< int(Token &Tok, bool &HasLexedNextTok)> Op)
Process single-argument builtin feature-like macros that return integer values.
static bool HasFeature(const Preprocessor &PP, StringRef Feature)
HasFeature - Return true if we recognize and implement the feature specified by the identifier as a s...
static IdentifierInfo * ExpectFeatureIdentifierInfo(Token &Tok, Preprocessor &PP, signed DiagID)
Helper function to return the IdentifierInfo structure of a Token or generate a diagnostic if none av...
Defines the PreprocessorLexer interface.
Defines the clang::Preprocessor interface.
Defines the clang::SourceLocation class and associated facilities.
Syntax
The style used to specify an attribute.
bool isConstantEvaluated(unsigned ID) const
Return true if this function can be constant evaluated by Clang frontend.
Definition Builtins.h:459
diag::Severity getExtensionHandlingBehavior() const
Definition Diagnostic.h:810
const IntrusiveRefCntPtr< DiagnosticIDs > & getDiagnosticIDs() const
Definition Diagnostic.h:592
virtual void updateOutOfDateIdentifier(const IdentifierInfo &II)=0
Update an out-of-date identifier.
off_t getSize() const
Definition FileEntry.h:346
Cached information about one file (either on disk or in the virtual file system).
Definition FileEntry.h:302
time_t getModificationTime() const
Definition FileEntry.h:333
static FixItHint CreateInsertion(SourceLocation InsertionLoc, StringRef Code, bool BeforePreviousInsertions=false)
Create a code modification hint that inserts the given code string at a specific location.
Definition Diagnostic.h:103
SrcMgr::CharacteristicKind getFileDirFlavor(FileEntryRef File)
Return whether the specified file is a normal header, a system header, or a C++ friendly system heade...
One of these records is kept for each identifier that is lexed.
unsigned getBuiltinID() const
Return a value indicating whether this is a builtin function.
tok::TokenKind getTokenID() const
If this is a source-language token (e.g.
bool hadMacroDefinition() const
Returns true if this identifier was #defined to some value at any moment.
bool isFromAST() const
Return true if the identifier in its current state was loaded from an AST file.
const char * getNameStart() const
Return the beginning of the actual null-terminated string for this identifier.
void setHasMacroDefinition(bool Val)
bool isOutOfDate() const
Determine whether the information for this identifier is out of date with respect to the external sou...
void setChangedSinceDeserialization()
Note that this identifier has changed since it was loaded from an AST file.
StringRef getName() const
Return the actual identifier string.
Keeps track of the various options that can be enabled, which controls the dialect of C or C++ that i...
bool isCompilingModule() const
Are we compiling a module?
std::string CurrentModule
The name of the current module, of which the main source file is a part.
static std::string Stringify(StringRef Str, bool Charify=false)
Stringify - Convert the specified string into a C string by i) escaping '\' and " characters and ii) ...
Definition Lexer.cpp:308
MacroArgs - An instance of this class captures information about the formal arguments specified to a ...
Definition MacroArgs.h:30
static MacroArgs * create(const MacroInfo *MI, ArrayRef< Token > UnexpArgTokens, bool VarargsElided, Preprocessor &PP)
MacroArgs ctor function - Create a new MacroArgs object with the specified macro and argument info.
Definition MacroArgs.cpp:23
void destroy(Preprocessor &PP)
destroy - Destroy and deallocate the memory for this object.
Definition MacroArgs.cpp:77
A description of the current definition of a macro.
Definition MacroInfo.h:590
MacroInfo * getMacroInfo() const
Get the MacroInfo that should be used for this definition.
Definition MacroInfo.h:606
bool isAmbiguous() const
true if the definition is ambiguous, false otherwise.
Definition MacroInfo.h:615
void forAllDefinitions(Fn F) const
Definition MacroInfo.h:626
Encapsulates changes to the "macros namespace" (the location where the macro name became active,...
Definition MacroInfo.h:313
const MacroDirective * getPrevious() const
Get previous definition of the macro with the same name.
Definition MacroInfo.h:354
void setPrevious(MacroDirective *Prev)
Set previous definition of the macro with the same name.
Definition MacroInfo.h:351
SourceLocation getLocation() const
Definition MacroInfo.h:348
bool isDefined() const
Definition MacroInfo.h:410
Encapsulates the data about a macro definition (e.g.
Definition MacroInfo.h:39
bool isIdenticalTo(const MacroInfo &Other, Preprocessor &PP, bool Syntactically) const
Return true if the specified macro definition is equal to this macro in spelling, arguments,...
Definition MacroInfo.cpp:89
bool isUsed() const
Return false if this macro is defined in the main file and has not yet been used.
Definition MacroInfo.h:224
bool isFunctionLike() const
Definition MacroInfo.h:201
ArrayRef< const IdentifierInfo * > params() const
Definition MacroInfo.h:185
unsigned getNumTokens() const
Return the number of tokens that this macro expands to.
Definition MacroInfo.h:235
void dump() const
unsigned getNumParams() const
Definition MacroInfo.h:184
const Token & getReplacementToken(unsigned Tok) const
Definition MacroInfo.h:237
bool isBuiltinMacro() const
Return true if this macro requires processing before expansion.
Definition MacroInfo.h:217
SourceLocation getDefinitionLoc() const
Return the location that the macro was defined at.
Definition MacroInfo.h:125
bool isVariadic() const
Definition MacroInfo.h:209
bool hasCommaPasting() const
Definition MacroInfo.h:219
bool isObjectLike() const
Definition MacroInfo.h:202
bool isWarnIfUnused() const
Return true if we should emit a warning if the macro is unused.
Definition MacroInfo.h:232
bool isEnabled() const
Return true if this macro is enabled.
Definition MacroInfo.h:281
void setIsUsed(bool Val)
Set the value of the IsUsed flag.
Definition MacroInfo.h:154
Represents a macro directive exported by a module.
Definition MacroInfo.h:514
static ModuleMacro * create(Preprocessor &PP, Module *OwningModule, const IdentifierInfo *II, MacroInfo *Macro, ArrayRef< ModuleMacro * > Overrides)
void Profile(llvm::FoldingSetNodeID &ID) const
Definition MacroInfo.h:545
A header that is known to reside within a given module, whether it was included or excluded.
Definition ModuleMap.h:158
Describes a module or submodule.
Definition Module.h:144
This interface provides a way to observe the actions of the preprocessor as it does its thing.
Definition PPCallbacks.h:37
OptionalFileEntryRef getFileEntry() const
getFileEntry - Return the FileEntry corresponding to this FileID.
std::optional< uint64_t > SourceDateEpoch
If set, the UNIX timestamp specified by SOURCE_DATE_EPOCH.
Engages in a tight little dance with the lexer to efficiently preprocess tokens.
SourceLocation getLastFPEvalPragmaLocation() const
bool FinishLexStringLiteral(Token &Result, std::string &String, const char *DiagnosticTag, bool AllowMacroExpansion)
Complete the lexing of a string literal where the first token has already been lexed (see LexStringLi...
void dumpMacroInfo(const IdentifierInfo *II)
ModuleMacro * addModuleMacro(Module *Mod, IdentifierInfo *II, MacroInfo *Macro, ArrayRef< ModuleMacro * > Overrides, bool &IsNew)
Register an exported macro for a module and identifier.
void setLoadedMacroDirective(IdentifierInfo *II, MacroDirective *ED, MacroDirective *MD)
Set a MacroDirective that was loaded from a PCH file.
OptionalFileEntryRef LookupEmbedFile(StringRef Filename, bool isAngled, bool OpenFile, const FileEntry *LookupFromFile=nullptr)
Given a "Filename" or <Filename> reference, look up the indicated embed resource.
PPCallbacks * getPPCallbacks() const
const MacroInfo * getMacroInfo(const IdentifierInfo *II) const
void CreateString(StringRef Str, Token &Tok, SourceLocation ExpansionLocStart=SourceLocation(), SourceLocation ExpansionLocEnd=SourceLocation())
Plop the specified string into a scratch buffer and set the specified token's location and length to ...
void markMacroAsUsed(MacroInfo *MI)
A macro is used, update information about macros that need unused warnings.
MacroDirective * getLocalMacroDirectiveHistory(const IdentifierInfo *II) const
Given an identifier, return the latest non-imported macro directive for that identifier.
friend class MacroArgs
void Lex(Token &Result)
Lex the next token for this preprocessor.
bool isParsingIfOrElifDirective() const
True if we are currently preprocessing a if or elif directive.
void LexNonComment(Token &Result)
Lex a token.
SourceRange DiscardUntilEndOfDirective()
Read and discard all tokens remaining on the current line until the tok::eod token is found.
IdentifierInfo * getIdentifierInfo(StringRef Name) const
Return information about the specified preprocessor identifier token.
SourceLocation AdvanceToTokenCharacter(SourceLocation TokStart, unsigned Char) const
Given a location that specifies the start of a token, return a new location that specifies a characte...
static void processPathToFileName(SmallVectorImpl< char > &FileName, const PresumedLoc &PLoc, const LangOptions &LangOpts, const TargetInfo &TI)
const TargetInfo & getTargetInfo() const
bool LexHeaderName(Token &Result, bool AllowMacroExpansion=true)
Lex a token, forming a header-name token if possible.
void LexUnexpandedToken(Token &Result)
Just like Lex, but disables macro expansion of identifier tokens.
ModuleMacro * getModuleMacro(Module *Mod, const IdentifierInfo *II)
StringRef getSpelling(SourceLocation loc, SmallVectorImpl< char > &buffer, bool *invalid=nullptr) const
Return the 'spelling' of the token at the given location; does not go up to the spelling location or ...
bool GetIncludeFilenameSpelling(SourceLocation Loc, StringRef &Buffer)
Turn the specified lexer token into a fully checked and spelled filename, e.g.
PreprocessorLexer * getCurrentFileLexer() const
Return the current file lexer being lexed from.
HeaderSearch & getHeaderSearchInfo() const
void emitMacroExpansionWarnings(const Token &Identifier, bool IsIfnDef=false) const
ExternalPreprocessorSource * getExternalSource() const
OptionalFileEntryRef LookupFile(SourceLocation FilenameLoc, StringRef Filename, bool isAngled, ConstSearchDirIterator FromDir, const FileEntry *FromFile, ConstSearchDirIterator *CurDir, SmallVectorImpl< char > *SearchPath, SmallVectorImpl< char > *RelativePath, ModuleMap::KnownHeader *SuggestedModule, bool *IsMapped, bool *IsFrameworkFound, bool SkipCache=false, bool OpenFile=true, bool CacheFailures=true)
Given a "foo" or <foo> reference, look up the indicated file.
Builtin::Context & getBuiltinInfo()
const PreprocessorOptions & getPreprocessorOpts() const
Retrieve the preprocessor options used to initialize this preprocessor.
LangOptions::FPEvalMethodKind getTUFPEvalMethod() const
const LangOptions & getLangOpts() const
static void processPathForFileMacro(SmallVectorImpl< char > &Path, const LangOptions &LangOpts, const TargetInfo &TI)
DiagnosticsEngine & getDiagnostics() const
SourceLocation getLocForEndOfToken(SourceLocation Loc, unsigned Offset=0)
Computes the source location just past the end of the token at this source location.
std::optional< LexEmbedParametersResult > LexEmbedParameters(Token &Current, bool ForHasEmbed)
Lex the parameters for an embed directive, returns nullopt on error.
void EnterMacro(Token &Tok, SourceLocation ILEnd, MacroInfo *Macro, MacroArgs *Args)
Add a Macro to the top of the include stack and start lexing tokens from it instead of the current bu...
DiagnosticBuilder Diag(SourceLocation Loc, unsigned DiagID) const
Forwarding function for diagnostics.
void appendMacroDirective(IdentifierInfo *II, MacroDirective *MD)
Add a directive to the macro directive history for this identifier.
Represents an unpacked "presumed" location which can be presented to the user.
const char * getFilename() const
Return the presumed filename of this location.
unsigned getLine() const
Return the presumed line number of this location.
bool isInvalid() const
Return true if this object is invalid or uninitialized.
SourceLocation getIncludeLoc() const
Return the presumed include location of this location.
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
A trivial tuple used to represent a source range.
Exposes information about the current target.
Definition TargetInfo.h:226
virtual bool supportsCpuSupports() const
virtual bool supportsCpuInit() const
const llvm::Triple & getTriple() const
Returns the target triple of the primary target.
const llvm::Triple * getDarwinTargetVariantTriple() const
Returns the darwin target variant triple, the variant of the deployment target for which the code is ...
virtual bool supportsCpuIs() const
TokenLexer - This implements a lexer that returns tokens from a macro body or token stream instead of...
Definition TokenLexer.h:30
Token - This structure provides full information about a lexed token.
Definition Token.h:36
IdentifierInfo * getIdentifierInfo() const
Definition Token.h:195
unsigned getFlags() const
Return the internal represtation of the flags.
Definition Token.h:270
void clearFlag(TokenFlags Flag)
Unset the specified flag.
Definition Token.h:262
SourceLocation getLocation() const
Return a source location identifier for the specified offset in the current file.
Definition Token.h:140
unsigned getLength() const
Definition Token.h:143
void setLength(unsigned Len)
Definition Token.h:149
void setKind(tok::TokenKind K)
Definition Token.h:98
bool is(tok::TokenKind K) const
is/isNot - Predicates to check if this token is a specific kind, as in "if (Tok.is(tok::l_brace)) {....
Definition Token.h:102
tok::TokenKind getKind() const
Definition Token.h:97
bool isAtStartOfLine() const
isAtStartOfLine - Return true if this token is at the start of a line.
Definition Token.h:284
bool isOneOf(Ts... Ks) const
Definition Token.h:103
@ DisableExpand
Definition Token.h:79
@ IgnoredComma
Definition Token.h:84
@ LeadingEmptyMacro
Definition Token.h:81
@ LeadingSpace
Definition Token.h:77
@ StartOfLine
Definition Token.h:75
@ NeedsCleaning
Definition Token.h:80
bool hasLeadingSpace() const
Return true if this token has whitespace before it.
Definition Token.h:288
void setLocation(SourceLocation L)
Definition Token.h:148
bool isNot(tok::TokenKind K) const
Definition Token.h:109
bool isAnnotation() const
Return true if this is any of tok::annot_* kind tokens.
Definition Token.h:129
bool hasUDSuffix() const
Return true if this token is a string or character literal which has a ud-suffix.
Definition Token.h:311
void startToken()
Reset all flags to cleared.
Definition Token.h:185
void setIdentifierInfo(IdentifierInfo *II)
Definition Token.h:204
void setFlagValue(TokenFlags Flag, bool Val)
Set a flag to either true or false.
Definition Token.h:275
void setFlag(TokenFlags Flag)
Set the specified flag.
Definition Token.h:252
unsigned getGeneration() const
Get the current visibility generation.
Definition Module.h:887
Defines the clang::TargetInfo interface.
bool evaluateRequiredTargetFeatures(llvm::StringRef RequiredFatures, const llvm::StringMap< bool > &TargetFetureMap)
Returns true if the required target features of a builtin function are enabled.
CharacteristicKind
Indicates whether a file or directory holds normal user code, system code, or system code which is im...
uint32_t Literal
Literals are represented as positive integers.
Definition CNFFormula.h:35
@ WarningOrError
A diagnostic that indicates a problem or potential problem.
@ Error
Present this diagnostic as an error.
@ OS
Indicates that the tracking object is a descendant of a referenced-counted OSObject,...
The JSON file list parser is used to communicate input to InstallAPI.
CustomizableOptional< FileEntryRef > OptionalFileEntryRef
Definition FileEntry.h:208
@ CPlusPlus20
@ CPlusPlus
@ CPlusPlus11
int hasAttribute(AttributeCommonInfo::Syntax Syntax, llvm::StringRef ScopeName, llvm::StringRef AttrName, const TargetInfo &Target, const LangOptions &LangOpts, bool CheckPlugins)
Return the version number associated with the attribute if we recognize and implement the attribute s...
detail::SearchDirIteratorImpl< true > ConstSearchDirIterator
nullptr
This class represents a compute construct, representing a 'Kind' of ‘parallel’, 'serial',...
@ Result
The result type of a method or function.
Definition TypeBase.h:905
@ Braces
New-expression has a C++11 list-initializer.
Definition ExprCXX.h:2248
unsigned int uint32_t