Bug Summary

File:lib/MC/MCParser/AsmParser.cpp
Warning:line 3346, column 7
Value stored to 'FileNumber' is never read

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name AsmParser.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-eagerly-assume -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -mrelocation-model pic -pic-level 2 -mthread-model posix -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-7/lib/clang/7.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/lib/MC/MCParser -I /build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser -I /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/include -I /build/llvm-toolchain-snapshot-7~svn326551/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/x86_64-linux-gnu/c++/7.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/7.3.0/../../../../include/c++/7.3.0/backward -internal-isystem /usr/include/clang/7.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-7/lib/clang/7.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-7~svn326551/build-llvm/lib/MC/MCParser -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-checker optin.performance.Padding -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-03-02-155150-1477-1 -x c++ /build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp
1//===- AsmParser.cpp - Parser for Assembly Files --------------------------===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This class implements the parser for assembly files.
11//
12//===----------------------------------------------------------------------===//
13
14#include "llvm/ADT/APFloat.h"
15#include "llvm/ADT/APInt.h"
16#include "llvm/ADT/ArrayRef.h"
17#include "llvm/ADT/None.h"
18#include "llvm/ADT/STLExtras.h"
19#include "llvm/ADT/SmallString.h"
20#include "llvm/ADT/SmallVector.h"
21#include "llvm/ADT/StringExtras.h"
22#include "llvm/ADT/StringMap.h"
23#include "llvm/ADT/StringRef.h"
24#include "llvm/ADT/Twine.h"
25#include "llvm/BinaryFormat/Dwarf.h"
26#include "llvm/MC/MCAsmInfo.h"
27#include "llvm/MC/MCCodeView.h"
28#include "llvm/MC/MCContext.h"
29#include "llvm/MC/MCDirectives.h"
30#include "llvm/MC/MCDwarf.h"
31#include "llvm/MC/MCExpr.h"
32#include "llvm/MC/MCInstPrinter.h"
33#include "llvm/MC/MCInstrDesc.h"
34#include "llvm/MC/MCInstrInfo.h"
35#include "llvm/MC/MCObjectFileInfo.h"
36#include "llvm/MC/MCParser/AsmCond.h"
37#include "llvm/MC/MCParser/AsmLexer.h"
38#include "llvm/MC/MCParser/MCAsmLexer.h"
39#include "llvm/MC/MCParser/MCAsmParser.h"
40#include "llvm/MC/MCParser/MCAsmParserExtension.h"
41#include "llvm/MC/MCParser/MCAsmParserUtils.h"
42#include "llvm/MC/MCParser/MCParsedAsmOperand.h"
43#include "llvm/MC/MCParser/MCTargetAsmParser.h"
44#include "llvm/MC/MCRegisterInfo.h"
45#include "llvm/MC/MCSection.h"
46#include "llvm/MC/MCStreamer.h"
47#include "llvm/MC/MCSymbol.h"
48#include "llvm/MC/MCTargetOptions.h"
49#include "llvm/MC/MCValue.h"
50#include "llvm/Support/Casting.h"
51#include "llvm/Support/CommandLine.h"
52#include "llvm/Support/ErrorHandling.h"
53#include "llvm/Support/MD5.h"
54#include "llvm/Support/MathExtras.h"
55#include "llvm/Support/MemoryBuffer.h"
56#include "llvm/Support/SMLoc.h"
57#include "llvm/Support/SourceMgr.h"
58#include "llvm/Support/raw_ostream.h"
59#include <algorithm>
60#include <cassert>
61#include <cctype>
62#include <climits>
63#include <cstddef>
64#include <cstdint>
65#include <deque>
66#include <memory>
67#include <sstream>
68#include <string>
69#include <tuple>
70#include <utility>
71#include <vector>
72
73using namespace llvm;
74
75MCAsmParserSemaCallback::~MCAsmParserSemaCallback() = default;
76
77static cl::opt<unsigned> AsmMacroMaxNestingDepth(
78 "asm-macro-max-nesting-depth", cl::init(20), cl::Hidden,
79 cl::desc("The maximum nesting depth allowed for assembly macros."));
80
81namespace {
82
83/// \brief Helper types for tracking macro definitions.
84typedef std::vector<AsmToken> MCAsmMacroArgument;
85typedef std::vector<MCAsmMacroArgument> MCAsmMacroArguments;
86
87/// \brief Helper class for storing information about an active macro
88/// instantiation.
89struct MacroInstantiation {
90 /// The location of the instantiation.
91 SMLoc InstantiationLoc;
92
93 /// The buffer where parsing should resume upon instantiation completion.
94 int ExitBuffer;
95
96 /// The location where parsing should resume upon instantiation completion.
97 SMLoc ExitLoc;
98
99 /// The depth of TheCondStack at the start of the instantiation.
100 size_t CondStackDepth;
101
102public:
103 MacroInstantiation(SMLoc IL, int EB, SMLoc EL, size_t CondStackDepth);
104};
105
106struct ParseStatementInfo {
107 /// \brief The parsed operands from the last parsed statement.
108 SmallVector<std::unique_ptr<MCParsedAsmOperand>, 8> ParsedOperands;
109
110 /// \brief The opcode from the last parsed instruction.
111 unsigned Opcode = ~0U;
112
113 /// \brief Was there an error parsing the inline assembly?
114 bool ParseError = false;
115
116 SmallVectorImpl<AsmRewrite> *AsmRewrites = nullptr;
117
118 ParseStatementInfo() = delete;
119 ParseStatementInfo(SmallVectorImpl<AsmRewrite> *rewrites)
120 : AsmRewrites(rewrites) {}
121};
122
123/// \brief The concrete assembly parser instance.
124class AsmParser : public MCAsmParser {
125private:
126 AsmLexer Lexer;
127 MCContext &Ctx;
128 MCStreamer &Out;
129 const MCAsmInfo &MAI;
130 SourceMgr &SrcMgr;
131 SourceMgr::DiagHandlerTy SavedDiagHandler;
132 void *SavedDiagContext;
133 std::unique_ptr<MCAsmParserExtension> PlatformParser;
134
135 /// This is the current buffer index we're lexing from as managed by the
136 /// SourceMgr object.
137 unsigned CurBuffer;
138
139 AsmCond TheCondState;
140 std::vector<AsmCond> TheCondStack;
141
142 /// \brief maps directive names to handler methods in parser
143 /// extensions. Extensions register themselves in this map by calling
144 /// addDirectiveHandler.
145 StringMap<ExtensionDirectiveHandler> ExtensionDirectiveMap;
146
147 /// \brief Stack of active macro instantiations.
148 std::vector<MacroInstantiation*> ActiveMacros;
149
150 /// \brief List of bodies of anonymous macros.
151 std::deque<MCAsmMacro> MacroLikeBodies;
152
153 /// Boolean tracking whether macro substitution is enabled.
154 unsigned MacrosEnabledFlag : 1;
155
156 /// \brief Keeps track of how many .macro's have been instantiated.
157 unsigned NumOfMacroInstantiations;
158
159 /// The values from the last parsed cpp hash file line comment if any.
160 struct CppHashInfoTy {
161 StringRef Filename;
162 int64_t LineNumber = 0;
163 SMLoc Loc;
164 unsigned Buf = 0;
165 };
166 CppHashInfoTy CppHashInfo;
167
168 /// \brief List of forward directional labels for diagnosis at the end.
169 SmallVector<std::tuple<SMLoc, CppHashInfoTy, MCSymbol *>, 4> DirLabels;
170
171 /// When generating dwarf for assembly source files we need to calculate the
172 /// logical line number based on the last parsed cpp hash file line comment
173 /// and current line. Since this is slow and messes up the SourceMgr's
174 /// cache we save the last info we queried with SrcMgr.FindLineNumber().
175 SMLoc LastQueryIDLoc;
176 unsigned LastQueryBuffer;
177 unsigned LastQueryLine;
178
179 /// AssemblerDialect. ~OU means unset value and use value provided by MAI.
180 unsigned AssemblerDialect = ~0U;
181
182 /// \brief is Darwin compatibility enabled?
183 bool IsDarwin = false;
184
185 /// \brief Are we parsing ms-style inline assembly?
186 bool ParsingInlineAsm = false;
187
188public:
189 AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
190 const MCAsmInfo &MAI, unsigned CB);
191 AsmParser(const AsmParser &) = delete;
192 AsmParser &operator=(const AsmParser &) = delete;
193 ~AsmParser() override;
194
195 bool Run(bool NoInitialTextSection, bool NoFinalize = false) override;
196
197 void addDirectiveHandler(StringRef Directive,
198 ExtensionDirectiveHandler Handler) override {
199 ExtensionDirectiveMap[Directive] = Handler;
200 }
201
202 void addAliasForDirective(StringRef Directive, StringRef Alias) override {
203 DirectiveKindMap[Directive] = DirectiveKindMap[Alias];
204 }
205
206 /// @name MCAsmParser Interface
207 /// {
208
209 SourceMgr &getSourceManager() override { return SrcMgr; }
210 MCAsmLexer &getLexer() override { return Lexer; }
211 MCContext &getContext() override { return Ctx; }
212 MCStreamer &getStreamer() override { return Out; }
213
214 CodeViewContext &getCVContext() { return Ctx.getCVContext(); }
215
216 unsigned getAssemblerDialect() override {
217 if (AssemblerDialect == ~0U)
218 return MAI.getAssemblerDialect();
219 else
220 return AssemblerDialect;
221 }
222 void setAssemblerDialect(unsigned i) override {
223 AssemblerDialect = i;
224 }
225
226 void Note(SMLoc L, const Twine &Msg, SMRange Range = None) override;
227 bool Warning(SMLoc L, const Twine &Msg, SMRange Range = None) override;
228 bool printError(SMLoc L, const Twine &Msg, SMRange Range = None) override;
229
230 const AsmToken &Lex() override;
231
232 void setParsingInlineAsm(bool V) override {
233 ParsingInlineAsm = V;
234 Lexer.setParsingMSInlineAsm(V);
235 }
236 bool isParsingInlineAsm() override { return ParsingInlineAsm; }
237
238 bool parseMSInlineAsm(void *AsmLoc, std::string &AsmString,
239 unsigned &NumOutputs, unsigned &NumInputs,
240 SmallVectorImpl<std::pair<void *,bool>> &OpDecls,
241 SmallVectorImpl<std::string> &Constraints,
242 SmallVectorImpl<std::string> &Clobbers,
243 const MCInstrInfo *MII, const MCInstPrinter *IP,
244 MCAsmParserSemaCallback &SI) override;
245
246 bool parseExpression(const MCExpr *&Res);
247 bool parseExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
248 bool parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) override;
249 bool parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) override;
250 bool parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
251 SMLoc &EndLoc) override;
252 bool parseAbsoluteExpression(int64_t &Res) override;
253
254 /// \brief Parse a floating point expression using the float \p Semantics
255 /// and set \p Res to the value.
256 bool parseRealValue(const fltSemantics &Semantics, APInt &Res);
257
258 /// \brief Parse an identifier or string (as a quoted identifier)
259 /// and set \p Res to the identifier contents.
260 bool parseIdentifier(StringRef &Res) override;
261 void eatToEndOfStatement() override;
262
263 bool checkForValidSection() override;
264
265 /// }
266
267private:
268 bool isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc);
269 void altMacroString(StringRef AltMacroStr, std::string &Res);
270 bool parseStatement(ParseStatementInfo &Info,
271 MCAsmParserSemaCallback *SI);
272 bool parseCurlyBlockScope(SmallVectorImpl<AsmRewrite>& AsmStrRewrites);
273 bool parseCppHashLineFilenameComment(SMLoc L);
274
275 void checkForBadMacro(SMLoc DirectiveLoc, StringRef Name, StringRef Body,
276 ArrayRef<MCAsmMacroParameter> Parameters);
277 bool expandMacro(raw_svector_ostream &OS, StringRef Body,
278 ArrayRef<MCAsmMacroParameter> Parameters,
279 ArrayRef<MCAsmMacroArgument> A, bool EnableAtPseudoVariable,
280 SMLoc L);
281
282 /// \brief Are macros enabled in the parser?
283 bool areMacrosEnabled() {return MacrosEnabledFlag;}
284
285 /// \brief Control a flag in the parser that enables or disables macros.
286 void setMacrosEnabled(bool Flag) {MacrosEnabledFlag = Flag;}
287
288 /// \brief Are we inside a macro instantiation?
289 bool isInsideMacroInstantiation() {return !ActiveMacros.empty();}
290
291 /// \brief Handle entry to macro instantiation.
292 ///
293 /// \param M The macro.
294 /// \param NameLoc Instantiation location.
295 bool handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc);
296
297 /// \brief Handle exit from macro instantiation.
298 void handleMacroExit();
299
300 /// \brief Extract AsmTokens for a macro argument.
301 bool parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg);
302
303 /// \brief Parse all macro arguments for a given macro.
304 bool parseMacroArguments(const MCAsmMacro *M, MCAsmMacroArguments &A);
305
306 void printMacroInstantiations();
307 void printMessage(SMLoc Loc, SourceMgr::DiagKind Kind, const Twine &Msg,
308 SMRange Range = None) const {
309 ArrayRef<SMRange> Ranges(Range);
310 SrcMgr.PrintMessage(Loc, Kind, Msg, Ranges);
311 }
312 static void DiagHandler(const SMDiagnostic &Diag, void *Context);
313
314 /// \brief Enter the specified file. This returns true on failure.
315 bool enterIncludeFile(const std::string &Filename);
316
317 /// \brief Process the specified file for the .incbin directive.
318 /// This returns true on failure.
319 bool processIncbinFile(const std::string &Filename, int64_t Skip = 0,
320 const MCExpr *Count = nullptr, SMLoc Loc = SMLoc());
321
322 /// \brief Reset the current lexer position to that given by \p Loc. The
323 /// current token is not set; clients should ensure Lex() is called
324 /// subsequently.
325 ///
326 /// \param InBuffer If not 0, should be the known buffer id that contains the
327 /// location.
328 void jumpToLoc(SMLoc Loc, unsigned InBuffer = 0);
329
330 /// \brief Parse up to the end of statement and a return the contents from the
331 /// current token until the end of the statement; the current token on exit
332 /// will be either the EndOfStatement or EOF.
333 StringRef parseStringToEndOfStatement() override;
334
335 /// \brief Parse until the end of a statement or a comma is encountered,
336 /// return the contents from the current token up to the end or comma.
337 StringRef parseStringToComma();
338
339 bool parseAssignment(StringRef Name, bool allow_redef,
340 bool NoDeadStrip = false);
341
342 unsigned getBinOpPrecedence(AsmToken::TokenKind K,
343 MCBinaryExpr::Opcode &Kind);
344
345 bool parseBinOpRHS(unsigned Precedence, const MCExpr *&Res, SMLoc &EndLoc);
346 bool parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc);
347 bool parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc);
348
349 bool parseRegisterOrRegisterNumber(int64_t &Register, SMLoc DirectiveLoc);
350
351 bool parseCVFunctionId(int64_t &FunctionId, StringRef DirectiveName);
352 bool parseCVFileId(int64_t &FileId, StringRef DirectiveName);
353
354 // Generic (target and platform independent) directive parsing.
355 enum DirectiveKind {
356 DK_NO_DIRECTIVE, // Placeholder
357 DK_SET,
358 DK_EQU,
359 DK_EQUIV,
360 DK_ASCII,
361 DK_ASCIZ,
362 DK_STRING,
363 DK_BYTE,
364 DK_SHORT,
365 DK_RELOC,
366 DK_VALUE,
367 DK_2BYTE,
368 DK_LONG,
369 DK_INT,
370 DK_4BYTE,
371 DK_QUAD,
372 DK_8BYTE,
373 DK_OCTA,
374 DK_DC,
375 DK_DC_A,
376 DK_DC_B,
377 DK_DC_D,
378 DK_DC_L,
379 DK_DC_S,
380 DK_DC_W,
381 DK_DC_X,
382 DK_DCB,
383 DK_DCB_B,
384 DK_DCB_D,
385 DK_DCB_L,
386 DK_DCB_S,
387 DK_DCB_W,
388 DK_DCB_X,
389 DK_DS,
390 DK_DS_B,
391 DK_DS_D,
392 DK_DS_L,
393 DK_DS_P,
394 DK_DS_S,
395 DK_DS_W,
396 DK_DS_X,
397 DK_SINGLE,
398 DK_FLOAT,
399 DK_DOUBLE,
400 DK_ALIGN,
401 DK_ALIGN32,
402 DK_BALIGN,
403 DK_BALIGNW,
404 DK_BALIGNL,
405 DK_P2ALIGN,
406 DK_P2ALIGNW,
407 DK_P2ALIGNL,
408 DK_ORG,
409 DK_FILL,
410 DK_ENDR,
411 DK_BUNDLE_ALIGN_MODE,
412 DK_BUNDLE_LOCK,
413 DK_BUNDLE_UNLOCK,
414 DK_ZERO,
415 DK_EXTERN,
416 DK_GLOBL,
417 DK_GLOBAL,
418 DK_LAZY_REFERENCE,
419 DK_NO_DEAD_STRIP,
420 DK_SYMBOL_RESOLVER,
421 DK_PRIVATE_EXTERN,
422 DK_REFERENCE,
423 DK_WEAK_DEFINITION,
424 DK_WEAK_REFERENCE,
425 DK_WEAK_DEF_CAN_BE_HIDDEN,
426 DK_COMM,
427 DK_COMMON,
428 DK_LCOMM,
429 DK_ABORT,
430 DK_INCLUDE,
431 DK_INCBIN,
432 DK_CODE16,
433 DK_CODE16GCC,
434 DK_REPT,
435 DK_IRP,
436 DK_IRPC,
437 DK_IF,
438 DK_IFEQ,
439 DK_IFGE,
440 DK_IFGT,
441 DK_IFLE,
442 DK_IFLT,
443 DK_IFNE,
444 DK_IFB,
445 DK_IFNB,
446 DK_IFC,
447 DK_IFEQS,
448 DK_IFNC,
449 DK_IFNES,
450 DK_IFDEF,
451 DK_IFNDEF,
452 DK_IFNOTDEF,
453 DK_ELSEIF,
454 DK_ELSE,
455 DK_ENDIF,
456 DK_SPACE,
457 DK_SKIP,
458 DK_FILE,
459 DK_LINE,
460 DK_LOC,
461 DK_STABS,
462 DK_CV_FILE,
463 DK_CV_FUNC_ID,
464 DK_CV_INLINE_SITE_ID,
465 DK_CV_LOC,
466 DK_CV_LINETABLE,
467 DK_CV_INLINE_LINETABLE,
468 DK_CV_DEF_RANGE,
469 DK_CV_STRINGTABLE,
470 DK_CV_FILECHECKSUMS,
471 DK_CV_FILECHECKSUM_OFFSET,
472 DK_CV_FPO_DATA,
473 DK_CFI_SECTIONS,
474 DK_CFI_STARTPROC,
475 DK_CFI_ENDPROC,
476 DK_CFI_DEF_CFA,
477 DK_CFI_DEF_CFA_OFFSET,
478 DK_CFI_ADJUST_CFA_OFFSET,
479 DK_CFI_DEF_CFA_REGISTER,
480 DK_CFI_OFFSET,
481 DK_CFI_REL_OFFSET,
482 DK_CFI_PERSONALITY,
483 DK_CFI_LSDA,
484 DK_CFI_REMEMBER_STATE,
485 DK_CFI_RESTORE_STATE,
486 DK_CFI_SAME_VALUE,
487 DK_CFI_RESTORE,
488 DK_CFI_ESCAPE,
489 DK_CFI_RETURN_COLUMN,
490 DK_CFI_SIGNAL_FRAME,
491 DK_CFI_UNDEFINED,
492 DK_CFI_REGISTER,
493 DK_CFI_WINDOW_SAVE,
494 DK_MACROS_ON,
495 DK_MACROS_OFF,
496 DK_ALTMACRO,
497 DK_NOALTMACRO,
498 DK_MACRO,
499 DK_EXITM,
500 DK_ENDM,
501 DK_ENDMACRO,
502 DK_PURGEM,
503 DK_SLEB128,
504 DK_ULEB128,
505 DK_ERR,
506 DK_ERROR,
507 DK_WARNING,
508 DK_PRINT,
509 DK_END
510 };
511
512 /// \brief Maps directive name --> DirectiveKind enum, for
513 /// directives parsed by this class.
514 StringMap<DirectiveKind> DirectiveKindMap;
515
516 // ".ascii", ".asciz", ".string"
517 bool parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated);
518 bool parseDirectiveReloc(SMLoc DirectiveLoc); // ".reloc"
519 bool parseDirectiveValue(StringRef IDVal,
520 unsigned Size); // ".byte", ".long", ...
521 bool parseDirectiveOctaValue(StringRef IDVal); // ".octa", ...
522 bool parseDirectiveRealValue(StringRef IDVal,
523 const fltSemantics &); // ".single", ...
524 bool parseDirectiveFill(); // ".fill"
525 bool parseDirectiveZero(); // ".zero"
526 // ".set", ".equ", ".equiv"
527 bool parseDirectiveSet(StringRef IDVal, bool allow_redef);
528 bool parseDirectiveOrg(); // ".org"
529 // ".align{,32}", ".p2align{,w,l}"
530 bool parseDirectiveAlign(bool IsPow2, unsigned ValueSize);
531
532 // ".file", ".line", ".loc", ".stabs"
533 bool parseDirectiveFile(SMLoc DirectiveLoc);
534 bool parseDirectiveLine();
535 bool parseDirectiveLoc();
536 bool parseDirectiveStabs();
537
538 // ".cv_file", ".cv_func_id", ".cv_inline_site_id", ".cv_loc", ".cv_linetable",
539 // ".cv_inline_linetable", ".cv_def_range"
540 bool parseDirectiveCVFile();
541 bool parseDirectiveCVFuncId();
542 bool parseDirectiveCVInlineSiteId();
543 bool parseDirectiveCVLoc();
544 bool parseDirectiveCVLinetable();
545 bool parseDirectiveCVInlineLinetable();
546 bool parseDirectiveCVDefRange();
547 bool parseDirectiveCVStringTable();
548 bool parseDirectiveCVFileChecksums();
549 bool parseDirectiveCVFileChecksumOffset();
550 bool parseDirectiveCVFPOData();
551
552 // .cfi directives
553 bool parseDirectiveCFIRegister(SMLoc DirectiveLoc);
554 bool parseDirectiveCFIWindowSave();
555 bool parseDirectiveCFISections();
556 bool parseDirectiveCFIStartProc();
557 bool parseDirectiveCFIEndProc();
558 bool parseDirectiveCFIDefCfaOffset();
559 bool parseDirectiveCFIDefCfa(SMLoc DirectiveLoc);
560 bool parseDirectiveCFIAdjustCfaOffset();
561 bool parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc);
562 bool parseDirectiveCFIOffset(SMLoc DirectiveLoc);
563 bool parseDirectiveCFIRelOffset(SMLoc DirectiveLoc);
564 bool parseDirectiveCFIPersonalityOrLsda(bool IsPersonality);
565 bool parseDirectiveCFIRememberState();
566 bool parseDirectiveCFIRestoreState();
567 bool parseDirectiveCFISameValue(SMLoc DirectiveLoc);
568 bool parseDirectiveCFIRestore(SMLoc DirectiveLoc);
569 bool parseDirectiveCFIEscape();
570 bool parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc);
571 bool parseDirectiveCFISignalFrame();
572 bool parseDirectiveCFIUndefined(SMLoc DirectiveLoc);
573
574 // macro directives
575 bool parseDirectivePurgeMacro(SMLoc DirectiveLoc);
576 bool parseDirectiveExitMacro(StringRef Directive);
577 bool parseDirectiveEndMacro(StringRef Directive);
578 bool parseDirectiveMacro(SMLoc DirectiveLoc);
579 bool parseDirectiveMacrosOnOff(StringRef Directive);
580 // alternate macro mode directives
581 bool parseDirectiveAltmacro(StringRef Directive);
582 // ".bundle_align_mode"
583 bool parseDirectiveBundleAlignMode();
584 // ".bundle_lock"
585 bool parseDirectiveBundleLock();
586 // ".bundle_unlock"
587 bool parseDirectiveBundleUnlock();
588
589 // ".space", ".skip"
590 bool parseDirectiveSpace(StringRef IDVal);
591
592 // ".dcb"
593 bool parseDirectiveDCB(StringRef IDVal, unsigned Size);
594 bool parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &);
595 // ".ds"
596 bool parseDirectiveDS(StringRef IDVal, unsigned Size);
597
598 // .sleb128 (Signed=true) and .uleb128 (Signed=false)
599 bool parseDirectiveLEB128(bool Signed);
600
601 /// \brief Parse a directive like ".globl" which
602 /// accepts a single symbol (which should be a label or an external).
603 bool parseDirectiveSymbolAttribute(MCSymbolAttr Attr);
604
605 bool parseDirectiveComm(bool IsLocal); // ".comm" and ".lcomm"
606
607 bool parseDirectiveAbort(); // ".abort"
608 bool parseDirectiveInclude(); // ".include"
609 bool parseDirectiveIncbin(); // ".incbin"
610
611 // ".if", ".ifeq", ".ifge", ".ifgt" , ".ifle", ".iflt" or ".ifne"
612 bool parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind);
613 // ".ifb" or ".ifnb", depending on ExpectBlank.
614 bool parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank);
615 // ".ifc" or ".ifnc", depending on ExpectEqual.
616 bool parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual);
617 // ".ifeqs" or ".ifnes", depending on ExpectEqual.
618 bool parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual);
619 // ".ifdef" or ".ifndef", depending on expect_defined
620 bool parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined);
621 bool parseDirectiveElseIf(SMLoc DirectiveLoc); // ".elseif"
622 bool parseDirectiveElse(SMLoc DirectiveLoc); // ".else"
623 bool parseDirectiveEndIf(SMLoc DirectiveLoc); // .endif
624 bool parseEscapedString(std::string &Data) override;
625
626 const MCExpr *applyModifierToExpr(const MCExpr *E,
627 MCSymbolRefExpr::VariantKind Variant);
628
629 // Macro-like directives
630 MCAsmMacro *parseMacroLikeBody(SMLoc DirectiveLoc);
631 void instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
632 raw_svector_ostream &OS);
633 bool parseDirectiveRept(SMLoc DirectiveLoc, StringRef Directive);
634 bool parseDirectiveIrp(SMLoc DirectiveLoc); // ".irp"
635 bool parseDirectiveIrpc(SMLoc DirectiveLoc); // ".irpc"
636 bool parseDirectiveEndr(SMLoc DirectiveLoc); // ".endr"
637
638 // "_emit" or "__emit"
639 bool parseDirectiveMSEmit(SMLoc DirectiveLoc, ParseStatementInfo &Info,
640 size_t Len);
641
642 // "align"
643 bool parseDirectiveMSAlign(SMLoc DirectiveLoc, ParseStatementInfo &Info);
644
645 // "end"
646 bool parseDirectiveEnd(SMLoc DirectiveLoc);
647
648 // ".err" or ".error"
649 bool parseDirectiveError(SMLoc DirectiveLoc, bool WithMessage);
650
651 // ".warning"
652 bool parseDirectiveWarning(SMLoc DirectiveLoc);
653
654 // .print <double-quotes-string>
655 bool parseDirectivePrint(SMLoc DirectiveLoc);
656
657 void initializeDirectiveKindMap();
658};
659
660} // end anonymous namespace
661
662namespace llvm {
663
664extern MCAsmParserExtension *createDarwinAsmParser();
665extern MCAsmParserExtension *createELFAsmParser();
666extern MCAsmParserExtension *createCOFFAsmParser();
667
668} // end namespace llvm
669
670enum { DEFAULT_ADDRSPACE = 0 };
671
672AsmParser::AsmParser(SourceMgr &SM, MCContext &Ctx, MCStreamer &Out,
673 const MCAsmInfo &MAI, unsigned CB = 0)
674 : Lexer(MAI), Ctx(Ctx), Out(Out), MAI(MAI), SrcMgr(SM),
675 CurBuffer(CB ? CB : SM.getMainFileID()), MacrosEnabledFlag(true) {
676 HadError = false;
677 // Save the old handler.
678 SavedDiagHandler = SrcMgr.getDiagHandler();
679 SavedDiagContext = SrcMgr.getDiagContext();
680 // Set our own handler which calls the saved handler.
681 SrcMgr.setDiagHandler(DiagHandler, this);
682 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
683
684 // Initialize the platform / file format parser.
685 switch (Ctx.getObjectFileInfo()->getObjectFileType()) {
686 case MCObjectFileInfo::IsCOFF:
687 PlatformParser.reset(createCOFFAsmParser());
688 break;
689 case MCObjectFileInfo::IsMachO:
690 PlatformParser.reset(createDarwinAsmParser());
691 IsDarwin = true;
692 break;
693 case MCObjectFileInfo::IsELF:
694 PlatformParser.reset(createELFAsmParser());
695 break;
696 case MCObjectFileInfo::IsWasm:
697 llvm_unreachable("Wasm parsing not supported yet")::llvm::llvm_unreachable_internal("Wasm parsing not supported yet"
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 697)
;
698 break;
699 }
700
701 PlatformParser->Initialize(*this);
702 initializeDirectiveKindMap();
703
704 NumOfMacroInstantiations = 0;
705}
706
707AsmParser::~AsmParser() {
708 assert((HadError || ActiveMacros.empty()) &&(static_cast <bool> ((HadError || ActiveMacros.empty())
&& "Unexpected active macro instantiation!") ? void (
0) : __assert_fail ("(HadError || ActiveMacros.empty()) && \"Unexpected active macro instantiation!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 709, __extension__ __PRETTY_FUNCTION__))
709 "Unexpected active macro instantiation!")(static_cast <bool> ((HadError || ActiveMacros.empty())
&& "Unexpected active macro instantiation!") ? void (
0) : __assert_fail ("(HadError || ActiveMacros.empty()) && \"Unexpected active macro instantiation!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 709, __extension__ __PRETTY_FUNCTION__))
;
710
711 // Restore the saved diagnostics handler and context for use during
712 // finalization.
713 SrcMgr.setDiagHandler(SavedDiagHandler, SavedDiagContext);
714}
715
716void AsmParser::printMacroInstantiations() {
717 // Print the active macro instantiation stack.
718 for (std::vector<MacroInstantiation *>::const_reverse_iterator
719 it = ActiveMacros.rbegin(),
720 ie = ActiveMacros.rend();
721 it != ie; ++it)
722 printMessage((*it)->InstantiationLoc, SourceMgr::DK_Note,
723 "while in macro instantiation");
724}
725
726void AsmParser::Note(SMLoc L, const Twine &Msg, SMRange Range) {
727 printPendingErrors();
728 printMessage(L, SourceMgr::DK_Note, Msg, Range);
729 printMacroInstantiations();
730}
731
732bool AsmParser::Warning(SMLoc L, const Twine &Msg, SMRange Range) {
733 if(getTargetParser().getTargetOptions().MCNoWarn)
734 return false;
735 if (getTargetParser().getTargetOptions().MCFatalWarnings)
736 return Error(L, Msg, Range);
737 printMessage(L, SourceMgr::DK_Warning, Msg, Range);
738 printMacroInstantiations();
739 return false;
740}
741
742bool AsmParser::printError(SMLoc L, const Twine &Msg, SMRange Range) {
743 HadError = true;
744 printMessage(L, SourceMgr::DK_Error, Msg, Range);
745 printMacroInstantiations();
746 return true;
747}
748
749bool AsmParser::enterIncludeFile(const std::string &Filename) {
750 std::string IncludedFile;
751 unsigned NewBuf =
752 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
753 if (!NewBuf)
754 return true;
755
756 CurBuffer = NewBuf;
757 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
758 return false;
759}
760
761/// Process the specified .incbin file by searching for it in the include paths
762/// then just emitting the byte contents of the file to the streamer. This
763/// returns true on failure.
764bool AsmParser::processIncbinFile(const std::string &Filename, int64_t Skip,
765 const MCExpr *Count, SMLoc Loc) {
766 std::string IncludedFile;
767 unsigned NewBuf =
768 SrcMgr.AddIncludeFile(Filename, Lexer.getLoc(), IncludedFile);
769 if (!NewBuf)
770 return true;
771
772 // Pick up the bytes from the file and emit them.
773 StringRef Bytes = SrcMgr.getMemoryBuffer(NewBuf)->getBuffer();
774 Bytes = Bytes.drop_front(Skip);
775 if (Count) {
776 int64_t Res;
777 if (!Count->evaluateAsAbsolute(Res))
778 return Error(Loc, "expected absolute expression");
779 if (Res < 0)
780 return Warning(Loc, "negative count has no effect");
781 Bytes = Bytes.take_front(Res);
782 }
783 getStreamer().EmitBytes(Bytes);
784 return false;
785}
786
787void AsmParser::jumpToLoc(SMLoc Loc, unsigned InBuffer) {
788 CurBuffer = InBuffer ? InBuffer : SrcMgr.FindBufferContainingLoc(Loc);
789 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer(),
790 Loc.getPointer());
791}
792
793const AsmToken &AsmParser::Lex() {
794 if (Lexer.getTok().is(AsmToken::Error))
795 Error(Lexer.getErrLoc(), Lexer.getErr());
796
797 // if it's a end of statement with a comment in it
798 if (getTok().is(AsmToken::EndOfStatement)) {
799 // if this is a line comment output it.
800 if (!getTok().getString().empty() && getTok().getString().front() != '\n' &&
801 getTok().getString().front() != '\r' && MAI.preserveAsmComments())
802 Out.addExplicitComment(Twine(getTok().getString()));
803 }
804
805 const AsmToken *tok = &Lexer.Lex();
806
807 // Parse comments here to be deferred until end of next statement.
808 while (tok->is(AsmToken::Comment)) {
809 if (MAI.preserveAsmComments())
810 Out.addExplicitComment(Twine(tok->getString()));
811 tok = &Lexer.Lex();
812 }
813
814 if (tok->is(AsmToken::Eof)) {
815 // If this is the end of an included file, pop the parent file off the
816 // include stack.
817 SMLoc ParentIncludeLoc = SrcMgr.getParentIncludeLoc(CurBuffer);
818 if (ParentIncludeLoc != SMLoc()) {
819 jumpToLoc(ParentIncludeLoc);
820 return Lex();
821 }
822 }
823
824 return *tok;
825}
826
827bool AsmParser::Run(bool NoInitialTextSection, bool NoFinalize) {
828 // Create the initial section, if requested.
829 if (!NoInitialTextSection)
830 Out.InitSections(false);
831
832 // Prime the lexer.
833 Lex();
834
835 HadError = false;
836 AsmCond StartingCondState = TheCondState;
837 SmallVector<AsmRewrite, 4> AsmStrRewrites;
838
839 // If we are generating dwarf for assembly source files save the initial text
840 // section and generate a .file directive.
841 if (getContext().getGenDwarfForAssembly()) {
842 MCSection *Sec = getStreamer().getCurrentSectionOnly();
843 if (!Sec->getBeginSymbol()) {
844 MCSymbol *SectionStartSym = getContext().createTempSymbol();
845 getStreamer().EmitLabel(SectionStartSym);
846 Sec->setBeginSymbol(SectionStartSym);
847 }
848 bool InsertResult = getContext().addGenDwarfSection(Sec);
849 assert(InsertResult && ".text section should not have debug info yet")(static_cast <bool> (InsertResult && ".text section should not have debug info yet"
) ? void (0) : __assert_fail ("InsertResult && \".text section should not have debug info yet\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 849, __extension__ __PRETTY_FUNCTION__))
;
850 (void)InsertResult;
851 getContext().setGenDwarfFileNumber(getStreamer().EmitDwarfFileDirective(
852 0, StringRef(), getContext().getMainFileName()));
853 }
854
855 // While we have input, parse each statement.
856 while (Lexer.isNot(AsmToken::Eof)) {
857 ParseStatementInfo Info(&AsmStrRewrites);
858 if (!parseStatement(Info, nullptr))
859 continue;
860
861 // If we have a Lexer Error we are on an Error Token. Load in Lexer Error
862 // for printing ErrMsg via Lex() only if no (presumably better) parser error
863 // exists.
864 if (!hasPendingError() && Lexer.getTok().is(AsmToken::Error)) {
865 Lex();
866 }
867
868 // parseStatement returned true so may need to emit an error.
869 printPendingErrors();
870
871 // Skipping to the next line if needed.
872 if (!getLexer().isAtStartOfStatement())
873 eatToEndOfStatement();
874 }
875
876 // All errors should have been emitted.
877 assert(!hasPendingError() && "unexpected error from parseStatement")(static_cast <bool> (!hasPendingError() && "unexpected error from parseStatement"
) ? void (0) : __assert_fail ("!hasPendingError() && \"unexpected error from parseStatement\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 877, __extension__ __PRETTY_FUNCTION__))
;
878
879 getTargetParser().flushPendingInstructions(getStreamer());
880
881 if (TheCondState.TheCond != StartingCondState.TheCond ||
882 TheCondState.Ignore != StartingCondState.Ignore)
883 printError(getTok().getLoc(), "unmatched .ifs or .elses");
884 // Check to see there are no empty DwarfFile slots.
885 const auto &LineTables = getContext().getMCDwarfLineTables();
886 if (!LineTables.empty()) {
887 unsigned Index = 0;
888 for (const auto &File : LineTables.begin()->second.getMCDwarfFiles()) {
889 if (File.Name.empty() && Index != 0)
890 printError(getTok().getLoc(), "unassigned file number: " +
891 Twine(Index) +
892 " for .file directives");
893 ++Index;
894 }
895 }
896
897 // Check to see that all assembler local symbols were actually defined.
898 // Targets that don't do subsections via symbols may not want this, though,
899 // so conservatively exclude them. Only do this if we're finalizing, though,
900 // as otherwise we won't necessarilly have seen everything yet.
901 if (!NoFinalize) {
902 if (MAI.hasSubsectionsViaSymbols()) {
903 for (const auto &TableEntry : getContext().getSymbols()) {
904 MCSymbol *Sym = TableEntry.getValue();
905 // Variable symbols may not be marked as defined, so check those
906 // explicitly. If we know it's a variable, we have a definition for
907 // the purposes of this check.
908 if (Sym->isTemporary() && !Sym->isVariable() && !Sym->isDefined())
909 // FIXME: We would really like to refer back to where the symbol was
910 // first referenced for a source location. We need to add something
911 // to track that. Currently, we just point to the end of the file.
912 printError(getTok().getLoc(), "assembler local symbol '" +
913 Sym->getName() + "' not defined");
914 }
915 }
916
917 // Temporary symbols like the ones for directional jumps don't go in the
918 // symbol table. They also need to be diagnosed in all (final) cases.
919 for (std::tuple<SMLoc, CppHashInfoTy, MCSymbol *> &LocSym : DirLabels) {
920 if (std::get<2>(LocSym)->isUndefined()) {
921 // Reset the state of any "# line file" directives we've seen to the
922 // context as it was at the diagnostic site.
923 CppHashInfo = std::get<1>(LocSym);
924 printError(std::get<0>(LocSym), "directional label undefined");
925 }
926 }
927 }
928
929 // Finalize the output stream if there are no errors and if the client wants
930 // us to.
931 if (!HadError && !NoFinalize)
932 Out.Finish();
933
934 return HadError || getContext().hadError();
935}
936
937bool AsmParser::checkForValidSection() {
938 if (!ParsingInlineAsm && !getStreamer().getCurrentSectionOnly()) {
939 Out.InitSections(false);
940 return Error(getTok().getLoc(),
941 "expected section directive before assembly directive");
942 }
943 return false;
944}
945
946/// \brief Throw away the rest of the line for testing purposes.
947void AsmParser::eatToEndOfStatement() {
948 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
949 Lexer.Lex();
950
951 // Eat EOL.
952 if (Lexer.is(AsmToken::EndOfStatement))
953 Lexer.Lex();
954}
955
956StringRef AsmParser::parseStringToEndOfStatement() {
957 const char *Start = getTok().getLoc().getPointer();
958
959 while (Lexer.isNot(AsmToken::EndOfStatement) && Lexer.isNot(AsmToken::Eof))
960 Lexer.Lex();
961
962 const char *End = getTok().getLoc().getPointer();
963 return StringRef(Start, End - Start);
964}
965
966StringRef AsmParser::parseStringToComma() {
967 const char *Start = getTok().getLoc().getPointer();
968
969 while (Lexer.isNot(AsmToken::EndOfStatement) &&
970 Lexer.isNot(AsmToken::Comma) && Lexer.isNot(AsmToken::Eof))
971 Lexer.Lex();
972
973 const char *End = getTok().getLoc().getPointer();
974 return StringRef(Start, End - Start);
975}
976
977/// \brief Parse a paren expression and return it.
978/// NOTE: This assumes the leading '(' has already been consumed.
979///
980/// parenexpr ::= expr)
981///
982bool AsmParser::parseParenExpr(const MCExpr *&Res, SMLoc &EndLoc) {
983 if (parseExpression(Res))
984 return true;
985 if (Lexer.isNot(AsmToken::RParen))
986 return TokError("expected ')' in parentheses expression");
987 EndLoc = Lexer.getTok().getEndLoc();
988 Lex();
989 return false;
990}
991
992/// \brief Parse a bracket expression and return it.
993/// NOTE: This assumes the leading '[' has already been consumed.
994///
995/// bracketexpr ::= expr]
996///
997bool AsmParser::parseBracketExpr(const MCExpr *&Res, SMLoc &EndLoc) {
998 if (parseExpression(Res))
999 return true;
1000 EndLoc = getTok().getEndLoc();
1001 if (parseToken(AsmToken::RBrac, "expected ']' in brackets expression"))
1002 return true;
1003 return false;
1004}
1005
1006/// \brief Parse a primary expression and return it.
1007/// primaryexpr ::= (parenexpr
1008/// primaryexpr ::= symbol
1009/// primaryexpr ::= number
1010/// primaryexpr ::= '.'
1011/// primaryexpr ::= ~,+,- primaryexpr
1012bool AsmParser::parsePrimaryExpr(const MCExpr *&Res, SMLoc &EndLoc) {
1013 SMLoc FirstTokenLoc = getLexer().getLoc();
1014 AsmToken::TokenKind FirstTokenKind = Lexer.getKind();
1015 switch (FirstTokenKind) {
1016 default:
1017 return TokError("unknown token in expression");
1018 // If we have an error assume that we've already handled it.
1019 case AsmToken::Error:
1020 return true;
1021 case AsmToken::Exclaim:
1022 Lex(); // Eat the operator.
1023 if (parsePrimaryExpr(Res, EndLoc))
1024 return true;
1025 Res = MCUnaryExpr::createLNot(Res, getContext(), FirstTokenLoc);
1026 return false;
1027 case AsmToken::Dollar:
1028 case AsmToken::At:
1029 case AsmToken::String:
1030 case AsmToken::Identifier: {
1031 StringRef Identifier;
1032 if (parseIdentifier(Identifier)) {
1033 // We may have failed but $ may be a valid token.
1034 if (getTok().is(AsmToken::Dollar)) {
1035 if (Lexer.getMAI().getDollarIsPC()) {
1036 Lex();
1037 // This is a '$' reference, which references the current PC. Emit a
1038 // temporary label to the streamer and refer to it.
1039 MCSymbol *Sym = Ctx.createTempSymbol();
1040 Out.EmitLabel(Sym);
1041 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None,
1042 getContext());
1043 EndLoc = FirstTokenLoc;
1044 return false;
1045 }
1046 return Error(FirstTokenLoc, "invalid token in expression");
1047 }
1048 }
1049 // Parse symbol variant
1050 std::pair<StringRef, StringRef> Split;
1051 if (!MAI.useParensForSymbolVariant()) {
1052 if (FirstTokenKind == AsmToken::String) {
1053 if (Lexer.is(AsmToken::At)) {
1054 Lex(); // eat @
1055 SMLoc AtLoc = getLexer().getLoc();
1056 StringRef VName;
1057 if (parseIdentifier(VName))
1058 return Error(AtLoc, "expected symbol variant after '@'");
1059
1060 Split = std::make_pair(Identifier, VName);
1061 }
1062 } else {
1063 Split = Identifier.split('@');
1064 }
1065 } else if (Lexer.is(AsmToken::LParen)) {
1066 Lex(); // eat '('.
1067 StringRef VName;
1068 parseIdentifier(VName);
1069 // eat ')'.
1070 if (parseToken(AsmToken::RParen,
1071 "unexpected token in variant, expected ')'"))
1072 return true;
1073 Split = std::make_pair(Identifier, VName);
1074 }
1075
1076 EndLoc = SMLoc::getFromPointer(Identifier.end());
1077
1078 // This is a symbol reference.
1079 StringRef SymbolName = Identifier;
1080 if (SymbolName.empty())
1081 return true;
1082
1083 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1084
1085 // Lookup the symbol variant if used.
1086 if (!Split.second.empty()) {
1087 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
1088 if (Variant != MCSymbolRefExpr::VK_Invalid) {
1089 SymbolName = Split.first;
1090 } else if (MAI.doesAllowAtInName() && !MAI.useParensForSymbolVariant()) {
1091 Variant = MCSymbolRefExpr::VK_None;
1092 } else {
1093 return Error(SMLoc::getFromPointer(Split.second.begin()),
1094 "invalid variant '" + Split.second + "'");
1095 }
1096 }
1097
1098 MCSymbol *Sym = getContext().getOrCreateSymbol(SymbolName);
1099
1100 // If this is an absolute variable reference, substitute it now to preserve
1101 // semantics in the face of reassignment.
1102 if (Sym->isVariable() &&
1103 isa<MCConstantExpr>(Sym->getVariableValue(/*SetUsed*/ false))) {
1104 if (Variant)
1105 return Error(EndLoc, "unexpected modifier on variable reference");
1106
1107 Res = Sym->getVariableValue(/*SetUsed*/ false);
1108 return false;
1109 }
1110
1111 // Otherwise create a symbol ref.
1112 Res = MCSymbolRefExpr::create(Sym, Variant, getContext(), FirstTokenLoc);
1113 return false;
1114 }
1115 case AsmToken::BigNum:
1116 return TokError("literal value out of range for directive");
1117 case AsmToken::Integer: {
1118 SMLoc Loc = getTok().getLoc();
1119 int64_t IntVal = getTok().getIntVal();
1120 Res = MCConstantExpr::create(IntVal, getContext());
1121 EndLoc = Lexer.getTok().getEndLoc();
1122 Lex(); // Eat token.
1123 // Look for 'b' or 'f' following an Integer as a directional label
1124 if (Lexer.getKind() == AsmToken::Identifier) {
1125 StringRef IDVal = getTok().getString();
1126 // Lookup the symbol variant if used.
1127 std::pair<StringRef, StringRef> Split = IDVal.split('@');
1128 MCSymbolRefExpr::VariantKind Variant = MCSymbolRefExpr::VK_None;
1129 if (Split.first.size() != IDVal.size()) {
1130 Variant = MCSymbolRefExpr::getVariantKindForName(Split.second);
1131 if (Variant == MCSymbolRefExpr::VK_Invalid)
1132 return TokError("invalid variant '" + Split.second + "'");
1133 IDVal = Split.first;
1134 }
1135 if (IDVal == "f" || IDVal == "b") {
1136 MCSymbol *Sym =
1137 Ctx.getDirectionalLocalSymbol(IntVal, IDVal == "b");
1138 Res = MCSymbolRefExpr::create(Sym, Variant, getContext());
1139 if (IDVal == "b" && Sym->isUndefined())
1140 return Error(Loc, "directional label undefined");
1141 DirLabels.push_back(std::make_tuple(Loc, CppHashInfo, Sym));
1142 EndLoc = Lexer.getTok().getEndLoc();
1143 Lex(); // Eat identifier.
1144 }
1145 }
1146 return false;
1147 }
1148 case AsmToken::Real: {
1149 APFloat RealVal(APFloat::IEEEdouble(), getTok().getString());
1150 uint64_t IntVal = RealVal.bitcastToAPInt().getZExtValue();
1151 Res = MCConstantExpr::create(IntVal, getContext());
1152 EndLoc = Lexer.getTok().getEndLoc();
1153 Lex(); // Eat token.
1154 return false;
1155 }
1156 case AsmToken::Dot: {
1157 // This is a '.' reference, which references the current PC. Emit a
1158 // temporary label to the streamer and refer to it.
1159 MCSymbol *Sym = Ctx.createTempSymbol();
1160 Out.EmitLabel(Sym);
1161 Res = MCSymbolRefExpr::create(Sym, MCSymbolRefExpr::VK_None, getContext());
1162 EndLoc = Lexer.getTok().getEndLoc();
1163 Lex(); // Eat identifier.
1164 return false;
1165 }
1166 case AsmToken::LParen:
1167 Lex(); // Eat the '('.
1168 return parseParenExpr(Res, EndLoc);
1169 case AsmToken::LBrac:
1170 if (!PlatformParser->HasBracketExpressions())
1171 return TokError("brackets expression not supported on this target");
1172 Lex(); // Eat the '['.
1173 return parseBracketExpr(Res, EndLoc);
1174 case AsmToken::Minus:
1175 Lex(); // Eat the operator.
1176 if (parsePrimaryExpr(Res, EndLoc))
1177 return true;
1178 Res = MCUnaryExpr::createMinus(Res, getContext(), FirstTokenLoc);
1179 return false;
1180 case AsmToken::Plus:
1181 Lex(); // Eat the operator.
1182 if (parsePrimaryExpr(Res, EndLoc))
1183 return true;
1184 Res = MCUnaryExpr::createPlus(Res, getContext(), FirstTokenLoc);
1185 return false;
1186 case AsmToken::Tilde:
1187 Lex(); // Eat the operator.
1188 if (parsePrimaryExpr(Res, EndLoc))
1189 return true;
1190 Res = MCUnaryExpr::createNot(Res, getContext(), FirstTokenLoc);
1191 return false;
1192 // MIPS unary expression operators. The lexer won't generate these tokens if
1193 // MCAsmInfo::HasMipsExpressions is false for the target.
1194 case AsmToken::PercentCall16:
1195 case AsmToken::PercentCall_Hi:
1196 case AsmToken::PercentCall_Lo:
1197 case AsmToken::PercentDtprel_Hi:
1198 case AsmToken::PercentDtprel_Lo:
1199 case AsmToken::PercentGot:
1200 case AsmToken::PercentGot_Disp:
1201 case AsmToken::PercentGot_Hi:
1202 case AsmToken::PercentGot_Lo:
1203 case AsmToken::PercentGot_Ofst:
1204 case AsmToken::PercentGot_Page:
1205 case AsmToken::PercentGottprel:
1206 case AsmToken::PercentGp_Rel:
1207 case AsmToken::PercentHi:
1208 case AsmToken::PercentHigher:
1209 case AsmToken::PercentHighest:
1210 case AsmToken::PercentLo:
1211 case AsmToken::PercentNeg:
1212 case AsmToken::PercentPcrel_Hi:
1213 case AsmToken::PercentPcrel_Lo:
1214 case AsmToken::PercentTlsgd:
1215 case AsmToken::PercentTlsldm:
1216 case AsmToken::PercentTprel_Hi:
1217 case AsmToken::PercentTprel_Lo:
1218 Lex(); // Eat the operator.
1219 if (Lexer.isNot(AsmToken::LParen))
1220 return TokError("expected '(' after operator");
1221 Lex(); // Eat the operator.
1222 if (parseExpression(Res, EndLoc))
1223 return true;
1224 if (Lexer.isNot(AsmToken::RParen))
1225 return TokError("expected ')'");
1226 Lex(); // Eat the operator.
1227 Res = getTargetParser().createTargetUnaryExpr(Res, FirstTokenKind, Ctx);
1228 return !Res;
1229 }
1230}
1231
1232bool AsmParser::parseExpression(const MCExpr *&Res) {
1233 SMLoc EndLoc;
1234 return parseExpression(Res, EndLoc);
1235}
1236
1237const MCExpr *
1238AsmParser::applyModifierToExpr(const MCExpr *E,
1239 MCSymbolRefExpr::VariantKind Variant) {
1240 // Ask the target implementation about this expression first.
1241 const MCExpr *NewE = getTargetParser().applyModifierToExpr(E, Variant, Ctx);
1242 if (NewE)
1243 return NewE;
1244 // Recurse over the given expression, rebuilding it to apply the given variant
1245 // if there is exactly one symbol.
1246 switch (E->getKind()) {
1247 case MCExpr::Target:
1248 case MCExpr::Constant:
1249 return nullptr;
1250
1251 case MCExpr::SymbolRef: {
1252 const MCSymbolRefExpr *SRE = cast<MCSymbolRefExpr>(E);
1253
1254 if (SRE->getKind() != MCSymbolRefExpr::VK_None) {
1255 TokError("invalid variant on expression '" + getTok().getIdentifier() +
1256 "' (already modified)");
1257 return E;
1258 }
1259
1260 return MCSymbolRefExpr::create(&SRE->getSymbol(), Variant, getContext());
1261 }
1262
1263 case MCExpr::Unary: {
1264 const MCUnaryExpr *UE = cast<MCUnaryExpr>(E);
1265 const MCExpr *Sub = applyModifierToExpr(UE->getSubExpr(), Variant);
1266 if (!Sub)
1267 return nullptr;
1268 return MCUnaryExpr::create(UE->getOpcode(), Sub, getContext());
1269 }
1270
1271 case MCExpr::Binary: {
1272 const MCBinaryExpr *BE = cast<MCBinaryExpr>(E);
1273 const MCExpr *LHS = applyModifierToExpr(BE->getLHS(), Variant);
1274 const MCExpr *RHS = applyModifierToExpr(BE->getRHS(), Variant);
1275
1276 if (!LHS && !RHS)
1277 return nullptr;
1278
1279 if (!LHS)
1280 LHS = BE->getLHS();
1281 if (!RHS)
1282 RHS = BE->getRHS();
1283
1284 return MCBinaryExpr::create(BE->getOpcode(), LHS, RHS, getContext());
1285 }
1286 }
1287
1288 llvm_unreachable("Invalid expression kind!")::llvm::llvm_unreachable_internal("Invalid expression kind!",
"/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 1288)
;
1289}
1290
1291/// This function checks if the next token is <string> type or arithmetic.
1292/// string that begin with character '<' must end with character '>'.
1293/// otherwise it is arithmetics.
1294/// If the function returns a 'true' value,
1295/// the End argument will be filled with the last location pointed to the '>'
1296/// character.
1297
1298/// There is a gap between the AltMacro's documentation and the single quote implementation.
1299/// GCC does not fully support this feature and so we will not support it.
1300/// TODO: Adding single quote as a string.
1301bool AsmParser::isAltmacroString(SMLoc &StrLoc, SMLoc &EndLoc) {
1302 assert((StrLoc.getPointer() != NULL) &&(static_cast <bool> ((StrLoc.getPointer() != __null) &&
"Argument to the function cannot be a NULL value") ? void (0
) : __assert_fail ("(StrLoc.getPointer() != NULL) && \"Argument to the function cannot be a NULL value\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 1303, __extension__ __PRETTY_FUNCTION__))
1303 "Argument to the function cannot be a NULL value")(static_cast <bool> ((StrLoc.getPointer() != __null) &&
"Argument to the function cannot be a NULL value") ? void (0
) : __assert_fail ("(StrLoc.getPointer() != NULL) && \"Argument to the function cannot be a NULL value\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 1303, __extension__ __PRETTY_FUNCTION__))
;
1304 const char *CharPtr = StrLoc.getPointer();
1305 while ((*CharPtr != '>') && (*CharPtr != '\n') && (*CharPtr != '\r') &&
1306 (*CharPtr != '\0')) {
1307 if (*CharPtr == '!')
1308 CharPtr++;
1309 CharPtr++;
1310 }
1311 if (*CharPtr == '>') {
1312 EndLoc = StrLoc.getFromPointer(CharPtr + 1);
1313 return true;
1314 }
1315 return false;
1316}
1317
1318/// \brief creating a string without the escape characters '!'.
1319void AsmParser::altMacroString(StringRef AltMacroStr,std::string &Res) {
1320 for (size_t Pos = 0; Pos < AltMacroStr.size(); Pos++) {
1321 if (AltMacroStr[Pos] == '!')
1322 Pos++;
1323 Res += AltMacroStr[Pos];
1324 }
1325}
1326
1327/// \brief Parse an expression and return it.
1328///
1329/// expr ::= expr &&,|| expr -> lowest.
1330/// expr ::= expr |,^,&,! expr
1331/// expr ::= expr ==,!=,<>,<,<=,>,>= expr
1332/// expr ::= expr <<,>> expr
1333/// expr ::= expr +,- expr
1334/// expr ::= expr *,/,% expr -> highest.
1335/// expr ::= primaryexpr
1336///
1337bool AsmParser::parseExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1338 // Parse the expression.
1339 Res = nullptr;
1340 if (parsePrimaryExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc))
1341 return true;
1342
1343 // As a special case, we support 'a op b @ modifier' by rewriting the
1344 // expression to include the modifier. This is inefficient, but in general we
1345 // expect users to use 'a@modifier op b'.
1346 if (Lexer.getKind() == AsmToken::At) {
1347 Lex();
1348
1349 if (Lexer.isNot(AsmToken::Identifier))
1350 return TokError("unexpected symbol modifier following '@'");
1351
1352 MCSymbolRefExpr::VariantKind Variant =
1353 MCSymbolRefExpr::getVariantKindForName(getTok().getIdentifier());
1354 if (Variant == MCSymbolRefExpr::VK_Invalid)
1355 return TokError("invalid variant '" + getTok().getIdentifier() + "'");
1356
1357 const MCExpr *ModifiedRes = applyModifierToExpr(Res, Variant);
1358 if (!ModifiedRes) {
1359 return TokError("invalid modifier '" + getTok().getIdentifier() +
1360 "' (no symbols present)");
1361 }
1362
1363 Res = ModifiedRes;
1364 Lex();
1365 }
1366
1367 // Try to constant fold it up front, if possible.
1368 int64_t Value;
1369 if (Res->evaluateAsAbsolute(Value))
1370 Res = MCConstantExpr::create(Value, getContext());
1371
1372 return false;
1373}
1374
1375bool AsmParser::parseParenExpression(const MCExpr *&Res, SMLoc &EndLoc) {
1376 Res = nullptr;
1377 return parseParenExpr(Res, EndLoc) || parseBinOpRHS(1, Res, EndLoc);
1378}
1379
1380bool AsmParser::parseParenExprOfDepth(unsigned ParenDepth, const MCExpr *&Res,
1381 SMLoc &EndLoc) {
1382 if (parseParenExpr(Res, EndLoc))
1383 return true;
1384
1385 for (; ParenDepth > 0; --ParenDepth) {
1386 if (parseBinOpRHS(1, Res, EndLoc))
1387 return true;
1388
1389 // We don't Lex() the last RParen.
1390 // This is the same behavior as parseParenExpression().
1391 if (ParenDepth - 1 > 0) {
1392 EndLoc = getTok().getEndLoc();
1393 if (parseToken(AsmToken::RParen,
1394 "expected ')' in parentheses expression"))
1395 return true;
1396 }
1397 }
1398 return false;
1399}
1400
1401bool AsmParser::parseAbsoluteExpression(int64_t &Res) {
1402 const MCExpr *Expr;
1403
1404 SMLoc StartLoc = Lexer.getLoc();
1405 if (parseExpression(Expr))
1406 return true;
1407
1408 if (!Expr->evaluateAsAbsolute(Res))
1409 return Error(StartLoc, "expected absolute expression");
1410
1411 return false;
1412}
1413
1414static unsigned getDarwinBinOpPrecedence(AsmToken::TokenKind K,
1415 MCBinaryExpr::Opcode &Kind,
1416 bool ShouldUseLogicalShr) {
1417 switch (K) {
1418 default:
1419 return 0; // not a binop.
1420
1421 // Lowest Precedence: &&, ||
1422 case AsmToken::AmpAmp:
1423 Kind = MCBinaryExpr::LAnd;
1424 return 1;
1425 case AsmToken::PipePipe:
1426 Kind = MCBinaryExpr::LOr;
1427 return 1;
1428
1429 // Low Precedence: |, &, ^
1430 //
1431 // FIXME: gas seems to support '!' as an infix operator?
1432 case AsmToken::Pipe:
1433 Kind = MCBinaryExpr::Or;
1434 return 2;
1435 case AsmToken::Caret:
1436 Kind = MCBinaryExpr::Xor;
1437 return 2;
1438 case AsmToken::Amp:
1439 Kind = MCBinaryExpr::And;
1440 return 2;
1441
1442 // Low Intermediate Precedence: ==, !=, <>, <, <=, >, >=
1443 case AsmToken::EqualEqual:
1444 Kind = MCBinaryExpr::EQ;
1445 return 3;
1446 case AsmToken::ExclaimEqual:
1447 case AsmToken::LessGreater:
1448 Kind = MCBinaryExpr::NE;
1449 return 3;
1450 case AsmToken::Less:
1451 Kind = MCBinaryExpr::LT;
1452 return 3;
1453 case AsmToken::LessEqual:
1454 Kind = MCBinaryExpr::LTE;
1455 return 3;
1456 case AsmToken::Greater:
1457 Kind = MCBinaryExpr::GT;
1458 return 3;
1459 case AsmToken::GreaterEqual:
1460 Kind = MCBinaryExpr::GTE;
1461 return 3;
1462
1463 // Intermediate Precedence: <<, >>
1464 case AsmToken::LessLess:
1465 Kind = MCBinaryExpr::Shl;
1466 return 4;
1467 case AsmToken::GreaterGreater:
1468 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1469 return 4;
1470
1471 // High Intermediate Precedence: +, -
1472 case AsmToken::Plus:
1473 Kind = MCBinaryExpr::Add;
1474 return 5;
1475 case AsmToken::Minus:
1476 Kind = MCBinaryExpr::Sub;
1477 return 5;
1478
1479 // Highest Precedence: *, /, %
1480 case AsmToken::Star:
1481 Kind = MCBinaryExpr::Mul;
1482 return 6;
1483 case AsmToken::Slash:
1484 Kind = MCBinaryExpr::Div;
1485 return 6;
1486 case AsmToken::Percent:
1487 Kind = MCBinaryExpr::Mod;
1488 return 6;
1489 }
1490}
1491
1492static unsigned getGNUBinOpPrecedence(AsmToken::TokenKind K,
1493 MCBinaryExpr::Opcode &Kind,
1494 bool ShouldUseLogicalShr) {
1495 switch (K) {
1496 default:
1497 return 0; // not a binop.
1498
1499 // Lowest Precedence: &&, ||
1500 case AsmToken::AmpAmp:
1501 Kind = MCBinaryExpr::LAnd;
1502 return 2;
1503 case AsmToken::PipePipe:
1504 Kind = MCBinaryExpr::LOr;
1505 return 1;
1506
1507 // Low Precedence: ==, !=, <>, <, <=, >, >=
1508 case AsmToken::EqualEqual:
1509 Kind = MCBinaryExpr::EQ;
1510 return 3;
1511 case AsmToken::ExclaimEqual:
1512 case AsmToken::LessGreater:
1513 Kind = MCBinaryExpr::NE;
1514 return 3;
1515 case AsmToken::Less:
1516 Kind = MCBinaryExpr::LT;
1517 return 3;
1518 case AsmToken::LessEqual:
1519 Kind = MCBinaryExpr::LTE;
1520 return 3;
1521 case AsmToken::Greater:
1522 Kind = MCBinaryExpr::GT;
1523 return 3;
1524 case AsmToken::GreaterEqual:
1525 Kind = MCBinaryExpr::GTE;
1526 return 3;
1527
1528 // Low Intermediate Precedence: +, -
1529 case AsmToken::Plus:
1530 Kind = MCBinaryExpr::Add;
1531 return 4;
1532 case AsmToken::Minus:
1533 Kind = MCBinaryExpr::Sub;
1534 return 4;
1535
1536 // High Intermediate Precedence: |, &, ^
1537 //
1538 // FIXME: gas seems to support '!' as an infix operator?
1539 case AsmToken::Pipe:
1540 Kind = MCBinaryExpr::Or;
1541 return 5;
1542 case AsmToken::Caret:
1543 Kind = MCBinaryExpr::Xor;
1544 return 5;
1545 case AsmToken::Amp:
1546 Kind = MCBinaryExpr::And;
1547 return 5;
1548
1549 // Highest Precedence: *, /, %, <<, >>
1550 case AsmToken::Star:
1551 Kind = MCBinaryExpr::Mul;
1552 return 6;
1553 case AsmToken::Slash:
1554 Kind = MCBinaryExpr::Div;
1555 return 6;
1556 case AsmToken::Percent:
1557 Kind = MCBinaryExpr::Mod;
1558 return 6;
1559 case AsmToken::LessLess:
1560 Kind = MCBinaryExpr::Shl;
1561 return 6;
1562 case AsmToken::GreaterGreater:
1563 Kind = ShouldUseLogicalShr ? MCBinaryExpr::LShr : MCBinaryExpr::AShr;
1564 return 6;
1565 }
1566}
1567
1568unsigned AsmParser::getBinOpPrecedence(AsmToken::TokenKind K,
1569 MCBinaryExpr::Opcode &Kind) {
1570 bool ShouldUseLogicalShr = MAI.shouldUseLogicalShr();
1571 return IsDarwin ? getDarwinBinOpPrecedence(K, Kind, ShouldUseLogicalShr)
1572 : getGNUBinOpPrecedence(K, Kind, ShouldUseLogicalShr);
1573}
1574
1575/// \brief Parse all binary operators with precedence >= 'Precedence'.
1576/// Res contains the LHS of the expression on input.
1577bool AsmParser::parseBinOpRHS(unsigned Precedence, const MCExpr *&Res,
1578 SMLoc &EndLoc) {
1579 SMLoc StartLoc = Lexer.getLoc();
1580 while (true) {
1581 MCBinaryExpr::Opcode Kind = MCBinaryExpr::Add;
1582 unsigned TokPrec = getBinOpPrecedence(Lexer.getKind(), Kind);
1583
1584 // If the next token is lower precedence than we are allowed to eat, return
1585 // successfully with what we ate already.
1586 if (TokPrec < Precedence)
1587 return false;
1588
1589 Lex();
1590
1591 // Eat the next primary expression.
1592 const MCExpr *RHS;
1593 if (parsePrimaryExpr(RHS, EndLoc))
1594 return true;
1595
1596 // If BinOp binds less tightly with RHS than the operator after RHS, let
1597 // the pending operator take RHS as its LHS.
1598 MCBinaryExpr::Opcode Dummy;
1599 unsigned NextTokPrec = getBinOpPrecedence(Lexer.getKind(), Dummy);
1600 if (TokPrec < NextTokPrec && parseBinOpRHS(TokPrec + 1, RHS, EndLoc))
1601 return true;
1602
1603 // Merge LHS and RHS according to operator.
1604 Res = MCBinaryExpr::create(Kind, Res, RHS, getContext(), StartLoc);
1605 }
1606}
1607
1608/// ParseStatement:
1609/// ::= EndOfStatement
1610/// ::= Label* Directive ...Operands... EndOfStatement
1611/// ::= Label* Identifier OperandList* EndOfStatement
1612bool AsmParser::parseStatement(ParseStatementInfo &Info,
1613 MCAsmParserSemaCallback *SI) {
1614 assert(!hasPendingError() && "parseStatement started with pending error")(static_cast <bool> (!hasPendingError() && "parseStatement started with pending error"
) ? void (0) : __assert_fail ("!hasPendingError() && \"parseStatement started with pending error\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 1614, __extension__ __PRETTY_FUNCTION__))
;
1615 // Eat initial spaces and comments
1616 while (Lexer.is(AsmToken::Space))
1617 Lex();
1618 if (Lexer.is(AsmToken::EndOfStatement)) {
1619 // if this is a line comment we can drop it safely
1620 if (getTok().getString().empty() || getTok().getString().front() == '\r' ||
1621 getTok().getString().front() == '\n')
1622 Out.AddBlankLine();
1623 Lex();
1624 return false;
1625 }
1626 // Statements always start with an identifier.
1627 AsmToken ID = getTok();
1628 SMLoc IDLoc = ID.getLoc();
1629 StringRef IDVal;
1630 int64_t LocalLabelVal = -1;
1631 if (Lexer.is(AsmToken::HashDirective))
1632 return parseCppHashLineFilenameComment(IDLoc);
1633 // Allow an integer followed by a ':' as a directional local label.
1634 if (Lexer.is(AsmToken::Integer)) {
1635 LocalLabelVal = getTok().getIntVal();
1636 if (LocalLabelVal < 0) {
1637 if (!TheCondState.Ignore) {
1638 Lex(); // always eat a token
1639 return Error(IDLoc, "unexpected token at start of statement");
1640 }
1641 IDVal = "";
1642 } else {
1643 IDVal = getTok().getString();
1644 Lex(); // Consume the integer token to be used as an identifier token.
1645 if (Lexer.getKind() != AsmToken::Colon) {
1646 if (!TheCondState.Ignore) {
1647 Lex(); // always eat a token
1648 return Error(IDLoc, "unexpected token at start of statement");
1649 }
1650 }
1651 }
1652 } else if (Lexer.is(AsmToken::Dot)) {
1653 // Treat '.' as a valid identifier in this context.
1654 Lex();
1655 IDVal = ".";
1656 } else if (Lexer.is(AsmToken::LCurly)) {
1657 // Treat '{' as a valid identifier in this context.
1658 Lex();
1659 IDVal = "{";
1660
1661 } else if (Lexer.is(AsmToken::RCurly)) {
1662 // Treat '}' as a valid identifier in this context.
1663 Lex();
1664 IDVal = "}";
1665 } else if (Lexer.is(AsmToken::Star) &&
1666 getTargetParser().starIsStartOfStatement()) {
1667 // Accept '*' as a valid start of statement.
1668 Lex();
1669 IDVal = "*";
1670 } else if (parseIdentifier(IDVal)) {
1671 if (!TheCondState.Ignore) {
1672 Lex(); // always eat a token
1673 return Error(IDLoc, "unexpected token at start of statement");
1674 }
1675 IDVal = "";
1676 }
1677
1678 // Handle conditional assembly here before checking for skipping. We
1679 // have to do this so that .endif isn't skipped in a ".if 0" block for
1680 // example.
1681 StringMap<DirectiveKind>::const_iterator DirKindIt =
1682 DirectiveKindMap.find(IDVal);
1683 DirectiveKind DirKind = (DirKindIt == DirectiveKindMap.end())
1684 ? DK_NO_DIRECTIVE
1685 : DirKindIt->getValue();
1686 switch (DirKind) {
1687 default:
1688 break;
1689 case DK_IF:
1690 case DK_IFEQ:
1691 case DK_IFGE:
1692 case DK_IFGT:
1693 case DK_IFLE:
1694 case DK_IFLT:
1695 case DK_IFNE:
1696 return parseDirectiveIf(IDLoc, DirKind);
1697 case DK_IFB:
1698 return parseDirectiveIfb(IDLoc, true);
1699 case DK_IFNB:
1700 return parseDirectiveIfb(IDLoc, false);
1701 case DK_IFC:
1702 return parseDirectiveIfc(IDLoc, true);
1703 case DK_IFEQS:
1704 return parseDirectiveIfeqs(IDLoc, true);
1705 case DK_IFNC:
1706 return parseDirectiveIfc(IDLoc, false);
1707 case DK_IFNES:
1708 return parseDirectiveIfeqs(IDLoc, false);
1709 case DK_IFDEF:
1710 return parseDirectiveIfdef(IDLoc, true);
1711 case DK_IFNDEF:
1712 case DK_IFNOTDEF:
1713 return parseDirectiveIfdef(IDLoc, false);
1714 case DK_ELSEIF:
1715 return parseDirectiveElseIf(IDLoc);
1716 case DK_ELSE:
1717 return parseDirectiveElse(IDLoc);
1718 case DK_ENDIF:
1719 return parseDirectiveEndIf(IDLoc);
1720 }
1721
1722 // Ignore the statement if in the middle of inactive conditional
1723 // (e.g. ".if 0").
1724 if (TheCondState.Ignore) {
1725 eatToEndOfStatement();
1726 return false;
1727 }
1728
1729 // FIXME: Recurse on local labels?
1730
1731 // See what kind of statement we have.
1732 switch (Lexer.getKind()) {
1733 case AsmToken::Colon: {
1734 if (!getTargetParser().isLabel(ID))
1735 break;
1736 if (checkForValidSection())
1737 return true;
1738
1739 // identifier ':' -> Label.
1740 Lex();
1741
1742 // Diagnose attempt to use '.' as a label.
1743 if (IDVal == ".")
1744 return Error(IDLoc, "invalid use of pseudo-symbol '.' as a label");
1745
1746 // Diagnose attempt to use a variable as a label.
1747 //
1748 // FIXME: Diagnostics. Note the location of the definition as a label.
1749 // FIXME: This doesn't diagnose assignment to a symbol which has been
1750 // implicitly marked as external.
1751 MCSymbol *Sym;
1752 if (LocalLabelVal == -1) {
1753 if (ParsingInlineAsm && SI) {
1754 StringRef RewrittenLabel =
1755 SI->LookupInlineAsmLabel(IDVal, getSourceManager(), IDLoc, true);
1756 assert(!RewrittenLabel.empty() &&(static_cast <bool> (!RewrittenLabel.empty() &&
"We should have an internal name here.") ? void (0) : __assert_fail
("!RewrittenLabel.empty() && \"We should have an internal name here.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 1757, __extension__ __PRETTY_FUNCTION__))
1757 "We should have an internal name here.")(static_cast <bool> (!RewrittenLabel.empty() &&
"We should have an internal name here.") ? void (0) : __assert_fail
("!RewrittenLabel.empty() && \"We should have an internal name here.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 1757, __extension__ __PRETTY_FUNCTION__))
;
1758 Info.AsmRewrites->emplace_back(AOK_Label, IDLoc, IDVal.size(),
1759 RewrittenLabel);
1760 IDVal = RewrittenLabel;
1761 }
1762 Sym = getContext().getOrCreateSymbol(IDVal);
1763 } else
1764 Sym = Ctx.createDirectionalLocalSymbol(LocalLabelVal);
1765 // End of Labels should be treated as end of line for lexing
1766 // purposes but that information is not available to the Lexer who
1767 // does not understand Labels. This may cause us to see a Hash
1768 // here instead of a preprocessor line comment.
1769 if (getTok().is(AsmToken::Hash)) {
1770 StringRef CommentStr = parseStringToEndOfStatement();
1771 Lexer.Lex();
1772 Lexer.UnLex(AsmToken(AsmToken::EndOfStatement, CommentStr));
1773 }
1774
1775 // Consume any end of statement token, if present, to avoid spurious
1776 // AddBlankLine calls().
1777 if (getTok().is(AsmToken::EndOfStatement)) {
1778 Lex();
1779 }
1780
1781 // Emit the label.
1782 if (!getTargetParser().isParsingInlineAsm())
1783 Out.EmitLabel(Sym, IDLoc);
1784
1785 // If we are generating dwarf for assembly source files then gather the
1786 // info to make a dwarf label entry for this label if needed.
1787 if (getContext().getGenDwarfForAssembly())
1788 MCGenDwarfLabelEntry::Make(Sym, &getStreamer(), getSourceManager(),
1789 IDLoc);
1790
1791 getTargetParser().onLabelParsed(Sym);
1792
1793 return false;
1794 }
1795
1796 case AsmToken::Equal:
1797 if (!getTargetParser().equalIsAsmAssignment())
1798 break;
1799 // identifier '=' ... -> assignment statement
1800 Lex();
1801
1802 return parseAssignment(IDVal, true);
1803
1804 default: // Normal instruction or directive.
1805 break;
1806 }
1807
1808 // If macros are enabled, check to see if this is a macro instantiation.
1809 if (areMacrosEnabled())
1810 if (const MCAsmMacro *M = getContext().lookupMacro(IDVal)) {
1811 return handleMacroEntry(M, IDLoc);
1812 }
1813
1814 // Otherwise, we have a normal instruction or directive.
1815
1816 // Directives start with "."
1817 if (IDVal[0] == '.' && IDVal != ".") {
1818 // There are several entities interested in parsing directives:
1819 //
1820 // 1. The target-specific assembly parser. Some directives are target
1821 // specific or may potentially behave differently on certain targets.
1822 // 2. Asm parser extensions. For example, platform-specific parsers
1823 // (like the ELF parser) register themselves as extensions.
1824 // 3. The generic directive parser implemented by this class. These are
1825 // all the directives that behave in a target and platform independent
1826 // manner, or at least have a default behavior that's shared between
1827 // all targets and platforms.
1828
1829 getTargetParser().flushPendingInstructions(getStreamer());
1830
1831 SMLoc StartTokLoc = getTok().getLoc();
1832 bool TPDirectiveReturn = getTargetParser().ParseDirective(ID);
1833
1834 if (hasPendingError())
1835 return true;
1836 // Currently the return value should be true if we are
1837 // uninterested but as this is at odds with the standard parsing
1838 // convention (return true = error) we have instances of a parsed
1839 // directive that fails returning true as an error. Catch these
1840 // cases as best as possible errors here.
1841 if (TPDirectiveReturn && StartTokLoc != getTok().getLoc())
1842 return true;
1843 // Return if we did some parsing or believe we succeeded.
1844 if (!TPDirectiveReturn || StartTokLoc != getTok().getLoc())
1845 return false;
1846
1847 // Next, check the extension directive map to see if any extension has
1848 // registered itself to parse this directive.
1849 std::pair<MCAsmParserExtension *, DirectiveHandler> Handler =
1850 ExtensionDirectiveMap.lookup(IDVal);
1851 if (Handler.first)
1852 return (*Handler.second)(Handler.first, IDVal, IDLoc);
1853
1854 // Finally, if no one else is interested in this directive, it must be
1855 // generic and familiar to this class.
1856 switch (DirKind) {
1857 default:
1858 break;
1859 case DK_SET:
1860 case DK_EQU:
1861 return parseDirectiveSet(IDVal, true);
1862 case DK_EQUIV:
1863 return parseDirectiveSet(IDVal, false);
1864 case DK_ASCII:
1865 return parseDirectiveAscii(IDVal, false);
1866 case DK_ASCIZ:
1867 case DK_STRING:
1868 return parseDirectiveAscii(IDVal, true);
1869 case DK_BYTE:
1870 case DK_DC_B:
1871 return parseDirectiveValue(IDVal, 1);
1872 case DK_DC:
1873 case DK_DC_W:
1874 case DK_SHORT:
1875 case DK_VALUE:
1876 case DK_2BYTE:
1877 return parseDirectiveValue(IDVal, 2);
1878 case DK_LONG:
1879 case DK_INT:
1880 case DK_4BYTE:
1881 case DK_DC_L:
1882 return parseDirectiveValue(IDVal, 4);
1883 case DK_QUAD:
1884 case DK_8BYTE:
1885 return parseDirectiveValue(IDVal, 8);
1886 case DK_DC_A:
1887 return parseDirectiveValue(
1888 IDVal, getContext().getAsmInfo()->getCodePointerSize());
1889 case DK_OCTA:
1890 return parseDirectiveOctaValue(IDVal);
1891 case DK_SINGLE:
1892 case DK_FLOAT:
1893 case DK_DC_S:
1894 return parseDirectiveRealValue(IDVal, APFloat::IEEEsingle());
1895 case DK_DOUBLE:
1896 case DK_DC_D:
1897 return parseDirectiveRealValue(IDVal, APFloat::IEEEdouble());
1898 case DK_ALIGN: {
1899 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1900 return parseDirectiveAlign(IsPow2, /*ExprSize=*/1);
1901 }
1902 case DK_ALIGN32: {
1903 bool IsPow2 = !getContext().getAsmInfo()->getAlignmentIsInBytes();
1904 return parseDirectiveAlign(IsPow2, /*ExprSize=*/4);
1905 }
1906 case DK_BALIGN:
1907 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/1);
1908 case DK_BALIGNW:
1909 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/2);
1910 case DK_BALIGNL:
1911 return parseDirectiveAlign(/*IsPow2=*/false, /*ExprSize=*/4);
1912 case DK_P2ALIGN:
1913 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/1);
1914 case DK_P2ALIGNW:
1915 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/2);
1916 case DK_P2ALIGNL:
1917 return parseDirectiveAlign(/*IsPow2=*/true, /*ExprSize=*/4);
1918 case DK_ORG:
1919 return parseDirectiveOrg();
1920 case DK_FILL:
1921 return parseDirectiveFill();
1922 case DK_ZERO:
1923 return parseDirectiveZero();
1924 case DK_EXTERN:
1925 eatToEndOfStatement(); // .extern is the default, ignore it.
1926 return false;
1927 case DK_GLOBL:
1928 case DK_GLOBAL:
1929 return parseDirectiveSymbolAttribute(MCSA_Global);
1930 case DK_LAZY_REFERENCE:
1931 return parseDirectiveSymbolAttribute(MCSA_LazyReference);
1932 case DK_NO_DEAD_STRIP:
1933 return parseDirectiveSymbolAttribute(MCSA_NoDeadStrip);
1934 case DK_SYMBOL_RESOLVER:
1935 return parseDirectiveSymbolAttribute(MCSA_SymbolResolver);
1936 case DK_PRIVATE_EXTERN:
1937 return parseDirectiveSymbolAttribute(MCSA_PrivateExtern);
1938 case DK_REFERENCE:
1939 return parseDirectiveSymbolAttribute(MCSA_Reference);
1940 case DK_WEAK_DEFINITION:
1941 return parseDirectiveSymbolAttribute(MCSA_WeakDefinition);
1942 case DK_WEAK_REFERENCE:
1943 return parseDirectiveSymbolAttribute(MCSA_WeakReference);
1944 case DK_WEAK_DEF_CAN_BE_HIDDEN:
1945 return parseDirectiveSymbolAttribute(MCSA_WeakDefAutoPrivate);
1946 case DK_COMM:
1947 case DK_COMMON:
1948 return parseDirectiveComm(/*IsLocal=*/false);
1949 case DK_LCOMM:
1950 return parseDirectiveComm(/*IsLocal=*/true);
1951 case DK_ABORT:
1952 return parseDirectiveAbort();
1953 case DK_INCLUDE:
1954 return parseDirectiveInclude();
1955 case DK_INCBIN:
1956 return parseDirectiveIncbin();
1957 case DK_CODE16:
1958 case DK_CODE16GCC:
1959 return TokError(Twine(IDVal) +
1960 " not currently supported for this target");
1961 case DK_REPT:
1962 return parseDirectiveRept(IDLoc, IDVal);
1963 case DK_IRP:
1964 return parseDirectiveIrp(IDLoc);
1965 case DK_IRPC:
1966 return parseDirectiveIrpc(IDLoc);
1967 case DK_ENDR:
1968 return parseDirectiveEndr(IDLoc);
1969 case DK_BUNDLE_ALIGN_MODE:
1970 return parseDirectiveBundleAlignMode();
1971 case DK_BUNDLE_LOCK:
1972 return parseDirectiveBundleLock();
1973 case DK_BUNDLE_UNLOCK:
1974 return parseDirectiveBundleUnlock();
1975 case DK_SLEB128:
1976 return parseDirectiveLEB128(true);
1977 case DK_ULEB128:
1978 return parseDirectiveLEB128(false);
1979 case DK_SPACE:
1980 case DK_SKIP:
1981 return parseDirectiveSpace(IDVal);
1982 case DK_FILE:
1983 return parseDirectiveFile(IDLoc);
1984 case DK_LINE:
1985 return parseDirectiveLine();
1986 case DK_LOC:
1987 return parseDirectiveLoc();
1988 case DK_STABS:
1989 return parseDirectiveStabs();
1990 case DK_CV_FILE:
1991 return parseDirectiveCVFile();
1992 case DK_CV_FUNC_ID:
1993 return parseDirectiveCVFuncId();
1994 case DK_CV_INLINE_SITE_ID:
1995 return parseDirectiveCVInlineSiteId();
1996 case DK_CV_LOC:
1997 return parseDirectiveCVLoc();
1998 case DK_CV_LINETABLE:
1999 return parseDirectiveCVLinetable();
2000 case DK_CV_INLINE_LINETABLE:
2001 return parseDirectiveCVInlineLinetable();
2002 case DK_CV_DEF_RANGE:
2003 return parseDirectiveCVDefRange();
2004 case DK_CV_STRINGTABLE:
2005 return parseDirectiveCVStringTable();
2006 case DK_CV_FILECHECKSUMS:
2007 return parseDirectiveCVFileChecksums();
2008 case DK_CV_FILECHECKSUM_OFFSET:
2009 return parseDirectiveCVFileChecksumOffset();
2010 case DK_CV_FPO_DATA:
2011 return parseDirectiveCVFPOData();
2012 case DK_CFI_SECTIONS:
2013 return parseDirectiveCFISections();
2014 case DK_CFI_STARTPROC:
2015 return parseDirectiveCFIStartProc();
2016 case DK_CFI_ENDPROC:
2017 return parseDirectiveCFIEndProc();
2018 case DK_CFI_DEF_CFA:
2019 return parseDirectiveCFIDefCfa(IDLoc);
2020 case DK_CFI_DEF_CFA_OFFSET:
2021 return parseDirectiveCFIDefCfaOffset();
2022 case DK_CFI_ADJUST_CFA_OFFSET:
2023 return parseDirectiveCFIAdjustCfaOffset();
2024 case DK_CFI_DEF_CFA_REGISTER:
2025 return parseDirectiveCFIDefCfaRegister(IDLoc);
2026 case DK_CFI_OFFSET:
2027 return parseDirectiveCFIOffset(IDLoc);
2028 case DK_CFI_REL_OFFSET:
2029 return parseDirectiveCFIRelOffset(IDLoc);
2030 case DK_CFI_PERSONALITY:
2031 return parseDirectiveCFIPersonalityOrLsda(true);
2032 case DK_CFI_LSDA:
2033 return parseDirectiveCFIPersonalityOrLsda(false);
2034 case DK_CFI_REMEMBER_STATE:
2035 return parseDirectiveCFIRememberState();
2036 case DK_CFI_RESTORE_STATE:
2037 return parseDirectiveCFIRestoreState();
2038 case DK_CFI_SAME_VALUE:
2039 return parseDirectiveCFISameValue(IDLoc);
2040 case DK_CFI_RESTORE:
2041 return parseDirectiveCFIRestore(IDLoc);
2042 case DK_CFI_ESCAPE:
2043 return parseDirectiveCFIEscape();
2044 case DK_CFI_RETURN_COLUMN:
2045 return parseDirectiveCFIReturnColumn(IDLoc);
2046 case DK_CFI_SIGNAL_FRAME:
2047 return parseDirectiveCFISignalFrame();
2048 case DK_CFI_UNDEFINED:
2049 return parseDirectiveCFIUndefined(IDLoc);
2050 case DK_CFI_REGISTER:
2051 return parseDirectiveCFIRegister(IDLoc);
2052 case DK_CFI_WINDOW_SAVE:
2053 return parseDirectiveCFIWindowSave();
2054 case DK_MACROS_ON:
2055 case DK_MACROS_OFF:
2056 return parseDirectiveMacrosOnOff(IDVal);
2057 case DK_MACRO:
2058 return parseDirectiveMacro(IDLoc);
2059 case DK_ALTMACRO:
2060 case DK_NOALTMACRO:
2061 return parseDirectiveAltmacro(IDVal);
2062 case DK_EXITM:
2063 return parseDirectiveExitMacro(IDVal);
2064 case DK_ENDM:
2065 case DK_ENDMACRO:
2066 return parseDirectiveEndMacro(IDVal);
2067 case DK_PURGEM:
2068 return parseDirectivePurgeMacro(IDLoc);
2069 case DK_END:
2070 return parseDirectiveEnd(IDLoc);
2071 case DK_ERR:
2072 return parseDirectiveError(IDLoc, false);
2073 case DK_ERROR:
2074 return parseDirectiveError(IDLoc, true);
2075 case DK_WARNING:
2076 return parseDirectiveWarning(IDLoc);
2077 case DK_RELOC:
2078 return parseDirectiveReloc(IDLoc);
2079 case DK_DCB:
2080 case DK_DCB_W:
2081 return parseDirectiveDCB(IDVal, 2);
2082 case DK_DCB_B:
2083 return parseDirectiveDCB(IDVal, 1);
2084 case DK_DCB_D:
2085 return parseDirectiveRealDCB(IDVal, APFloat::IEEEdouble());
2086 case DK_DCB_L:
2087 return parseDirectiveDCB(IDVal, 4);
2088 case DK_DCB_S:
2089 return parseDirectiveRealDCB(IDVal, APFloat::IEEEsingle());
2090 case DK_DC_X:
2091 case DK_DCB_X:
2092 return TokError(Twine(IDVal) +
2093 " not currently supported for this target");
2094 case DK_DS:
2095 case DK_DS_W:
2096 return parseDirectiveDS(IDVal, 2);
2097 case DK_DS_B:
2098 return parseDirectiveDS(IDVal, 1);
2099 case DK_DS_D:
2100 return parseDirectiveDS(IDVal, 8);
2101 case DK_DS_L:
2102 case DK_DS_S:
2103 return parseDirectiveDS(IDVal, 4);
2104 case DK_DS_P:
2105 case DK_DS_X:
2106 return parseDirectiveDS(IDVal, 12);
2107 case DK_PRINT:
2108 return parseDirectivePrint(IDLoc);
2109 }
2110
2111 return Error(IDLoc, "unknown directive");
2112 }
2113
2114 // __asm _emit or __asm __emit
2115 if (ParsingInlineAsm && (IDVal == "_emit" || IDVal == "__emit" ||
2116 IDVal == "_EMIT" || IDVal == "__EMIT"))
2117 return parseDirectiveMSEmit(IDLoc, Info, IDVal.size());
2118
2119 // __asm align
2120 if (ParsingInlineAsm && (IDVal == "align" || IDVal == "ALIGN"))
2121 return parseDirectiveMSAlign(IDLoc, Info);
2122
2123 if (ParsingInlineAsm && (IDVal == "even" || IDVal == "EVEN"))
2124 Info.AsmRewrites->emplace_back(AOK_EVEN, IDLoc, 4);
2125 if (checkForValidSection())
2126 return true;
2127
2128 // Canonicalize the opcode to lower case.
2129 std::string OpcodeStr = IDVal.lower();
2130 ParseInstructionInfo IInfo(Info.AsmRewrites);
2131 bool ParseHadError = getTargetParser().ParseInstruction(IInfo, OpcodeStr, ID,
2132 Info.ParsedOperands);
2133 Info.ParseError = ParseHadError;
2134
2135 // Dump the parsed representation, if requested.
2136 if (getShowParsedOperands()) {
2137 SmallString<256> Str;
2138 raw_svector_ostream OS(Str);
2139 OS << "parsed instruction: [";
2140 for (unsigned i = 0; i != Info.ParsedOperands.size(); ++i) {
2141 if (i != 0)
2142 OS << ", ";
2143 Info.ParsedOperands[i]->print(OS);
2144 }
2145 OS << "]";
2146
2147 printMessage(IDLoc, SourceMgr::DK_Note, OS.str());
2148 }
2149
2150 // Fail even if ParseInstruction erroneously returns false.
2151 if (hasPendingError() || ParseHadError)
2152 return true;
2153
2154 // If we are generating dwarf for the current section then generate a .loc
2155 // directive for the instruction.
2156 if (!ParseHadError && getContext().getGenDwarfForAssembly() &&
2157 getContext().getGenDwarfSectionSyms().count(
2158 getStreamer().getCurrentSectionOnly())) {
2159 unsigned Line;
2160 if (ActiveMacros.empty())
2161 Line = SrcMgr.FindLineNumber(IDLoc, CurBuffer);
2162 else
2163 Line = SrcMgr.FindLineNumber(ActiveMacros.front()->InstantiationLoc,
2164 ActiveMacros.front()->ExitBuffer);
2165
2166 // If we previously parsed a cpp hash file line comment then make sure the
2167 // current Dwarf File is for the CppHashFilename if not then emit the
2168 // Dwarf File table for it and adjust the line number for the .loc.
2169 if (!CppHashInfo.Filename.empty()) {
2170 unsigned FileNumber = getStreamer().EmitDwarfFileDirective(
2171 0, StringRef(), CppHashInfo.Filename);
2172 getContext().setGenDwarfFileNumber(FileNumber);
2173
2174 // Since SrcMgr.FindLineNumber() is slow and messes up the SourceMgr's
2175 // cache with the different Loc from the call above we save the last
2176 // info we queried here with SrcMgr.FindLineNumber().
2177 unsigned CppHashLocLineNo;
2178 if (LastQueryIDLoc == CppHashInfo.Loc &&
2179 LastQueryBuffer == CppHashInfo.Buf)
2180 CppHashLocLineNo = LastQueryLine;
2181 else {
2182 CppHashLocLineNo =
2183 SrcMgr.FindLineNumber(CppHashInfo.Loc, CppHashInfo.Buf);
2184 LastQueryLine = CppHashLocLineNo;
2185 LastQueryIDLoc = CppHashInfo.Loc;
2186 LastQueryBuffer = CppHashInfo.Buf;
2187 }
2188 Line = CppHashInfo.LineNumber - 1 + (Line - CppHashLocLineNo);
2189 }
2190
2191 getStreamer().EmitDwarfLocDirective(
2192 getContext().getGenDwarfFileNumber(), Line, 0,
2193 DWARF2_LINE_DEFAULT_IS_STMT1 ? DWARF2_FLAG_IS_STMT(1 << 0) : 0, 0, 0,
2194 StringRef());
2195 }
2196
2197 // If parsing succeeded, match the instruction.
2198 if (!ParseHadError) {
2199 uint64_t ErrorInfo;
2200 if (getTargetParser().MatchAndEmitInstruction(
2201 IDLoc, Info.Opcode, Info.ParsedOperands, Out, ErrorInfo,
2202 getTargetParser().isParsingInlineAsm()))
2203 return true;
2204 }
2205 return false;
2206}
2207
2208// Parse and erase curly braces marking block start/end
2209bool
2210AsmParser::parseCurlyBlockScope(SmallVectorImpl<AsmRewrite> &AsmStrRewrites) {
2211 // Identify curly brace marking block start/end
2212 if (Lexer.isNot(AsmToken::LCurly) && Lexer.isNot(AsmToken::RCurly))
2213 return false;
2214
2215 SMLoc StartLoc = Lexer.getLoc();
2216 Lex(); // Eat the brace
2217 if (Lexer.is(AsmToken::EndOfStatement))
2218 Lex(); // Eat EndOfStatement following the brace
2219
2220 // Erase the block start/end brace from the output asm string
2221 AsmStrRewrites.emplace_back(AOK_Skip, StartLoc, Lexer.getLoc().getPointer() -
2222 StartLoc.getPointer());
2223 return true;
2224}
2225
2226/// parseCppHashLineFilenameComment as this:
2227/// ::= # number "filename"
2228bool AsmParser::parseCppHashLineFilenameComment(SMLoc L) {
2229 Lex(); // Eat the hash token.
2230 // Lexer only ever emits HashDirective if it fully formed if it's
2231 // done the checking already so this is an internal error.
2232 assert(getTok().is(AsmToken::Integer) &&(static_cast <bool> (getTok().is(AsmToken::Integer) &&
"Lexing Cpp line comment: Expected Integer") ? void (0) : __assert_fail
("getTok().is(AsmToken::Integer) && \"Lexing Cpp line comment: Expected Integer\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 2233, __extension__ __PRETTY_FUNCTION__))
2233 "Lexing Cpp line comment: Expected Integer")(static_cast <bool> (getTok().is(AsmToken::Integer) &&
"Lexing Cpp line comment: Expected Integer") ? void (0) : __assert_fail
("getTok().is(AsmToken::Integer) && \"Lexing Cpp line comment: Expected Integer\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 2233, __extension__ __PRETTY_FUNCTION__))
;
2234 int64_t LineNumber = getTok().getIntVal();
2235 Lex();
2236 assert(getTok().is(AsmToken::String) &&(static_cast <bool> (getTok().is(AsmToken::String) &&
"Lexing Cpp line comment: Expected String") ? void (0) : __assert_fail
("getTok().is(AsmToken::String) && \"Lexing Cpp line comment: Expected String\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 2237, __extension__ __PRETTY_FUNCTION__))
2237 "Lexing Cpp line comment: Expected String")(static_cast <bool> (getTok().is(AsmToken::String) &&
"Lexing Cpp line comment: Expected String") ? void (0) : __assert_fail
("getTok().is(AsmToken::String) && \"Lexing Cpp line comment: Expected String\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 2237, __extension__ __PRETTY_FUNCTION__))
;
2238 StringRef Filename = getTok().getString();
2239 Lex();
2240
2241 // Get rid of the enclosing quotes.
2242 Filename = Filename.substr(1, Filename.size() - 2);
2243
2244 // Save the SMLoc, Filename and LineNumber for later use by diagnostics.
2245 CppHashInfo.Loc = L;
2246 CppHashInfo.Filename = Filename;
2247 CppHashInfo.LineNumber = LineNumber;
2248 CppHashInfo.Buf = CurBuffer;
2249 return false;
2250}
2251
2252/// \brief will use the last parsed cpp hash line filename comment
2253/// for the Filename and LineNo if any in the diagnostic.
2254void AsmParser::DiagHandler(const SMDiagnostic &Diag, void *Context) {
2255 const AsmParser *Parser = static_cast<const AsmParser *>(Context);
2256 raw_ostream &OS = errs();
2257
2258 const SourceMgr &DiagSrcMgr = *Diag.getSourceMgr();
2259 SMLoc DiagLoc = Diag.getLoc();
2260 unsigned DiagBuf = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2261 unsigned CppHashBuf =
2262 Parser->SrcMgr.FindBufferContainingLoc(Parser->CppHashInfo.Loc);
2263
2264 // Like SourceMgr::printMessage() we need to print the include stack if any
2265 // before printing the message.
2266 unsigned DiagCurBuffer = DiagSrcMgr.FindBufferContainingLoc(DiagLoc);
2267 if (!Parser->SavedDiagHandler && DiagCurBuffer &&
2268 DiagCurBuffer != DiagSrcMgr.getMainFileID()) {
2269 SMLoc ParentIncludeLoc = DiagSrcMgr.getParentIncludeLoc(DiagCurBuffer);
2270 DiagSrcMgr.PrintIncludeStack(ParentIncludeLoc, OS);
2271 }
2272
2273 // If we have not parsed a cpp hash line filename comment or the source
2274 // manager changed or buffer changed (like in a nested include) then just
2275 // print the normal diagnostic using its Filename and LineNo.
2276 if (!Parser->CppHashInfo.LineNumber || &DiagSrcMgr != &Parser->SrcMgr ||
2277 DiagBuf != CppHashBuf) {
2278 if (Parser->SavedDiagHandler)
2279 Parser->SavedDiagHandler(Diag, Parser->SavedDiagContext);
2280 else
2281 Diag.print(nullptr, OS);
2282 return;
2283 }
2284
2285 // Use the CppHashFilename and calculate a line number based on the
2286 // CppHashInfo.Loc and CppHashInfo.LineNumber relative to this Diag's SMLoc
2287 // for the diagnostic.
2288 const std::string &Filename = Parser->CppHashInfo.Filename;
2289
2290 int DiagLocLineNo = DiagSrcMgr.FindLineNumber(DiagLoc, DiagBuf);
2291 int CppHashLocLineNo =
2292 Parser->SrcMgr.FindLineNumber(Parser->CppHashInfo.Loc, CppHashBuf);
2293 int LineNo =
2294 Parser->CppHashInfo.LineNumber - 1 + (DiagLocLineNo - CppHashLocLineNo);
2295
2296 SMDiagnostic NewDiag(*Diag.getSourceMgr(), Diag.getLoc(), Filename, LineNo,
2297 Diag.getColumnNo(), Diag.getKind(), Diag.getMessage(),
2298 Diag.getLineContents(), Diag.getRanges());
2299
2300 if (Parser->SavedDiagHandler)
2301 Parser->SavedDiagHandler(NewDiag, Parser->SavedDiagContext);
2302 else
2303 NewDiag.print(nullptr, OS);
2304}
2305
2306// FIXME: This is mostly duplicated from the function in AsmLexer.cpp. The
2307// difference being that that function accepts '@' as part of identifiers and
2308// we can't do that. AsmLexer.cpp should probably be changed to handle
2309// '@' as a special case when needed.
2310static bool isIdentifierChar(char c) {
2311 return isalnum(static_cast<unsigned char>(c)) || c == '_' || c == '$' ||
2312 c == '.';
2313}
2314
2315bool AsmParser::expandMacro(raw_svector_ostream &OS, StringRef Body,
2316 ArrayRef<MCAsmMacroParameter> Parameters,
2317 ArrayRef<MCAsmMacroArgument> A,
2318 bool EnableAtPseudoVariable, SMLoc L) {
2319 unsigned NParameters = Parameters.size();
2320 bool HasVararg = NParameters ? Parameters.back().Vararg : false;
2321 if ((!IsDarwin || NParameters != 0) && NParameters != A.size())
2322 return Error(L, "Wrong number of arguments");
2323
2324 // A macro without parameters is handled differently on Darwin:
2325 // gas accepts no arguments and does no substitutions
2326 while (!Body.empty()) {
2327 // Scan for the next substitution.
2328 std::size_t End = Body.size(), Pos = 0;
2329 for (; Pos != End; ++Pos) {
2330 // Check for a substitution or escape.
2331 if (IsDarwin && !NParameters) {
2332 // This macro has no parameters, look for $0, $1, etc.
2333 if (Body[Pos] != '$' || Pos + 1 == End)
2334 continue;
2335
2336 char Next = Body[Pos + 1];
2337 if (Next == '$' || Next == 'n' ||
2338 isdigit(static_cast<unsigned char>(Next)))
2339 break;
2340 } else {
2341 // This macro has parameters, look for \foo, \bar, etc.
2342 if (Body[Pos] == '\\' && Pos + 1 != End)
2343 break;
2344 }
2345 }
2346
2347 // Add the prefix.
2348 OS << Body.slice(0, Pos);
2349
2350 // Check if we reached the end.
2351 if (Pos == End)
2352 break;
2353
2354 if (IsDarwin && !NParameters) {
2355 switch (Body[Pos + 1]) {
2356 // $$ => $
2357 case '$':
2358 OS << '$';
2359 break;
2360
2361 // $n => number of arguments
2362 case 'n':
2363 OS << A.size();
2364 break;
2365
2366 // $[0-9] => argument
2367 default: {
2368 // Missing arguments are ignored.
2369 unsigned Index = Body[Pos + 1] - '0';
2370 if (Index >= A.size())
2371 break;
2372
2373 // Otherwise substitute with the token values, with spaces eliminated.
2374 for (const AsmToken &Token : A[Index])
2375 OS << Token.getString();
2376 break;
2377 }
2378 }
2379 Pos += 2;
2380 } else {
2381 unsigned I = Pos + 1;
2382
2383 // Check for the \@ pseudo-variable.
2384 if (EnableAtPseudoVariable && Body[I] == '@' && I + 1 != End)
2385 ++I;
2386 else
2387 while (isIdentifierChar(Body[I]) && I + 1 != End)
2388 ++I;
2389
2390 const char *Begin = Body.data() + Pos + 1;
2391 StringRef Argument(Begin, I - (Pos + 1));
2392 unsigned Index = 0;
2393
2394 if (Argument == "@") {
2395 OS << NumOfMacroInstantiations;
2396 Pos += 2;
2397 } else {
2398 for (; Index < NParameters; ++Index)
2399 if (Parameters[Index].Name == Argument)
2400 break;
2401
2402 if (Index == NParameters) {
2403 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
2404 Pos += 3;
2405 else {
2406 OS << '\\' << Argument;
2407 Pos = I;
2408 }
2409 } else {
2410 bool VarargParameter = HasVararg && Index == (NParameters - 1);
2411 for (const AsmToken &Token : A[Index])
2412 // For altmacro mode, you can write '%expr'.
2413 // The prefix '%' evaluates the expression 'expr'
2414 // and uses the result as a string (e.g. replace %(1+2) with the string "3").
2415 // Here, we identify the integer token which is the result of the
2416 // absolute expression evaluation and replace it with its string representation.
2417 if ((Lexer.IsaAltMacroMode()) &&
2418 (*(Token.getString().begin()) == '%') && Token.is(AsmToken::Integer))
2419 // Emit an integer value to the buffer.
2420 OS << Token.getIntVal();
2421 // Only Token that was validated as a string and begins with '<'
2422 // is considered altMacroString!!!
2423 else if ((Lexer.IsaAltMacroMode()) &&
2424 (*(Token.getString().begin()) == '<') &&
2425 Token.is(AsmToken::String)) {
2426 std::string Res;
2427 altMacroString(Token.getStringContents(), Res);
2428 OS << Res;
2429 }
2430 // We expect no quotes around the string's contents when
2431 // parsing for varargs.
2432 else if (Token.isNot(AsmToken::String) || VarargParameter)
2433 OS << Token.getString();
2434 else
2435 OS << Token.getStringContents();
2436
2437 Pos += 1 + Argument.size();
2438 }
2439 }
2440 }
2441 // Update the scan point.
2442 Body = Body.substr(Pos);
2443 }
2444
2445 return false;
2446}
2447
2448MacroInstantiation::MacroInstantiation(SMLoc IL, int EB, SMLoc EL,
2449 size_t CondStackDepth)
2450 : InstantiationLoc(IL), ExitBuffer(EB), ExitLoc(EL),
2451 CondStackDepth(CondStackDepth) {}
2452
2453static bool isOperator(AsmToken::TokenKind kind) {
2454 switch (kind) {
2455 default:
2456 return false;
2457 case AsmToken::Plus:
2458 case AsmToken::Minus:
2459 case AsmToken::Tilde:
2460 case AsmToken::Slash:
2461 case AsmToken::Star:
2462 case AsmToken::Dot:
2463 case AsmToken::Equal:
2464 case AsmToken::EqualEqual:
2465 case AsmToken::Pipe:
2466 case AsmToken::PipePipe:
2467 case AsmToken::Caret:
2468 case AsmToken::Amp:
2469 case AsmToken::AmpAmp:
2470 case AsmToken::Exclaim:
2471 case AsmToken::ExclaimEqual:
2472 case AsmToken::Less:
2473 case AsmToken::LessEqual:
2474 case AsmToken::LessLess:
2475 case AsmToken::LessGreater:
2476 case AsmToken::Greater:
2477 case AsmToken::GreaterEqual:
2478 case AsmToken::GreaterGreater:
2479 return true;
2480 }
2481}
2482
2483namespace {
2484
2485class AsmLexerSkipSpaceRAII {
2486public:
2487 AsmLexerSkipSpaceRAII(AsmLexer &Lexer, bool SkipSpace) : Lexer(Lexer) {
2488 Lexer.setSkipSpace(SkipSpace);
2489 }
2490
2491 ~AsmLexerSkipSpaceRAII() {
2492 Lexer.setSkipSpace(true);
2493 }
2494
2495private:
2496 AsmLexer &Lexer;
2497};
2498
2499} // end anonymous namespace
2500
2501bool AsmParser::parseMacroArgument(MCAsmMacroArgument &MA, bool Vararg) {
2502
2503 if (Vararg) {
2504 if (Lexer.isNot(AsmToken::EndOfStatement)) {
2505 StringRef Str = parseStringToEndOfStatement();
2506 MA.emplace_back(AsmToken::String, Str);
2507 }
2508 return false;
2509 }
2510
2511 unsigned ParenLevel = 0;
2512
2513 // Darwin doesn't use spaces to delmit arguments.
2514 AsmLexerSkipSpaceRAII ScopedSkipSpace(Lexer, IsDarwin);
2515
2516 bool SpaceEaten;
2517
2518 while (true) {
2519 SpaceEaten = false;
2520 if (Lexer.is(AsmToken::Eof) || Lexer.is(AsmToken::Equal))
2521 return TokError("unexpected token in macro instantiation");
2522
2523 if (ParenLevel == 0) {
2524
2525 if (Lexer.is(AsmToken::Comma))
2526 break;
2527
2528 if (Lexer.is(AsmToken::Space)) {
2529 SpaceEaten = true;
2530 Lexer.Lex(); // Eat spaces
2531 }
2532
2533 // Spaces can delimit parameters, but could also be part an expression.
2534 // If the token after a space is an operator, add the token and the next
2535 // one into this argument
2536 if (!IsDarwin) {
2537 if (isOperator(Lexer.getKind())) {
2538 MA.push_back(getTok());
2539 Lexer.Lex();
2540
2541 // Whitespace after an operator can be ignored.
2542 if (Lexer.is(AsmToken::Space))
2543 Lexer.Lex();
2544
2545 continue;
2546 }
2547 }
2548 if (SpaceEaten)
2549 break;
2550 }
2551
2552 // handleMacroEntry relies on not advancing the lexer here
2553 // to be able to fill in the remaining default parameter values
2554 if (Lexer.is(AsmToken::EndOfStatement))
2555 break;
2556
2557 // Adjust the current parentheses level.
2558 if (Lexer.is(AsmToken::LParen))
2559 ++ParenLevel;
2560 else if (Lexer.is(AsmToken::RParen) && ParenLevel)
2561 --ParenLevel;
2562
2563 // Append the token to the current argument list.
2564 MA.push_back(getTok());
2565 Lexer.Lex();
2566 }
2567
2568 if (ParenLevel != 0)
2569 return TokError("unbalanced parentheses in macro argument");
2570 return false;
2571}
2572
2573// Parse the macro instantiation arguments.
2574bool AsmParser::parseMacroArguments(const MCAsmMacro *M,
2575 MCAsmMacroArguments &A) {
2576 const unsigned NParameters = M ? M->Parameters.size() : 0;
2577 bool NamedParametersFound = false;
2578 SmallVector<SMLoc, 4> FALocs;
2579
2580 A.resize(NParameters);
2581 FALocs.resize(NParameters);
2582
2583 // Parse two kinds of macro invocations:
2584 // - macros defined without any parameters accept an arbitrary number of them
2585 // - macros defined with parameters accept at most that many of them
2586 bool HasVararg = NParameters ? M->Parameters.back().Vararg : false;
2587 for (unsigned Parameter = 0; !NParameters || Parameter < NParameters;
2588 ++Parameter) {
2589 SMLoc IDLoc = Lexer.getLoc();
2590 MCAsmMacroParameter FA;
2591
2592 if (Lexer.is(AsmToken::Identifier) && Lexer.peekTok().is(AsmToken::Equal)) {
2593 if (parseIdentifier(FA.Name))
2594 return Error(IDLoc, "invalid argument identifier for formal argument");
2595
2596 if (Lexer.isNot(AsmToken::Equal))
2597 return TokError("expected '=' after formal parameter identifier");
2598
2599 Lex();
2600
2601 NamedParametersFound = true;
2602 }
2603 bool Vararg = HasVararg && Parameter == (NParameters - 1);
2604
2605 if (NamedParametersFound && FA.Name.empty())
2606 return Error(IDLoc, "cannot mix positional and keyword arguments");
2607
2608 SMLoc StrLoc = Lexer.getLoc();
2609 SMLoc EndLoc;
2610 if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Percent)) {
2611 const MCExpr *AbsoluteExp;
2612 int64_t Value;
2613 /// Eat '%'
2614 Lex();
2615 if (parseExpression(AbsoluteExp, EndLoc))
2616 return false;
2617 if (!AbsoluteExp->evaluateAsAbsolute(Value))
2618 return Error(StrLoc, "expected absolute expression");
2619 const char *StrChar = StrLoc.getPointer();
2620 const char *EndChar = EndLoc.getPointer();
2621 AsmToken newToken(AsmToken::Integer, StringRef(StrChar , EndChar - StrChar), Value);
2622 FA.Value.push_back(newToken);
2623 } else if (Lexer.IsaAltMacroMode() && Lexer.is(AsmToken::Less) &&
2624 isAltmacroString(StrLoc, EndLoc)) {
2625 const char *StrChar = StrLoc.getPointer();
2626 const char *EndChar = EndLoc.getPointer();
2627 jumpToLoc(EndLoc, CurBuffer);
2628 /// Eat from '<' to '>'
2629 Lex();
2630 AsmToken newToken(AsmToken::String, StringRef(StrChar, EndChar - StrChar));
2631 FA.Value.push_back(newToken);
2632 } else if(parseMacroArgument(FA.Value, Vararg))
2633 return true;
2634
2635 unsigned PI = Parameter;
2636 if (!FA.Name.empty()) {
2637 unsigned FAI = 0;
2638 for (FAI = 0; FAI < NParameters; ++FAI)
2639 if (M->Parameters[FAI].Name == FA.Name)
2640 break;
2641
2642 if (FAI >= NParameters) {
2643 assert(M && "expected macro to be defined")(static_cast <bool> (M && "expected macro to be defined"
) ? void (0) : __assert_fail ("M && \"expected macro to be defined\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 2643, __extension__ __PRETTY_FUNCTION__))
;
2644 return Error(IDLoc, "parameter named '" + FA.Name +
2645 "' does not exist for macro '" + M->Name + "'");
2646 }
2647 PI = FAI;
2648 }
2649
2650 if (!FA.Value.empty()) {
2651 if (A.size() <= PI)
2652 A.resize(PI + 1);
2653 A[PI] = FA.Value;
2654
2655 if (FALocs.size() <= PI)
2656 FALocs.resize(PI + 1);
2657
2658 FALocs[PI] = Lexer.getLoc();
2659 }
2660
2661 // At the end of the statement, fill in remaining arguments that have
2662 // default values. If there aren't any, then the next argument is
2663 // required but missing
2664 if (Lexer.is(AsmToken::EndOfStatement)) {
2665 bool Failure = false;
2666 for (unsigned FAI = 0; FAI < NParameters; ++FAI) {
2667 if (A[FAI].empty()) {
2668 if (M->Parameters[FAI].Required) {
2669 Error(FALocs[FAI].isValid() ? FALocs[FAI] : Lexer.getLoc(),
2670 "missing value for required parameter "
2671 "'" + M->Parameters[FAI].Name + "' in macro '" + M->Name + "'");
2672 Failure = true;
2673 }
2674
2675 if (!M->Parameters[FAI].Value.empty())
2676 A[FAI] = M->Parameters[FAI].Value;
2677 }
2678 }
2679 return Failure;
2680 }
2681
2682 if (Lexer.is(AsmToken::Comma))
2683 Lex();
2684 }
2685
2686 return TokError("too many positional arguments");
2687}
2688
2689bool AsmParser::handleMacroEntry(const MCAsmMacro *M, SMLoc NameLoc) {
2690 // Arbitrarily limit macro nesting depth (default matches 'as'). We can
2691 // eliminate this, although we should protect against infinite loops.
2692 unsigned MaxNestingDepth = AsmMacroMaxNestingDepth;
2693 if (ActiveMacros.size() == MaxNestingDepth) {
2694 std::ostringstream MaxNestingDepthError;
2695 MaxNestingDepthError << "macros cannot be nested more than "
2696 << MaxNestingDepth << " levels deep."
2697 << " Use -asm-macro-max-nesting-depth to increase "
2698 "this limit.";
2699 return TokError(MaxNestingDepthError.str());
2700 }
2701
2702 MCAsmMacroArguments A;
2703 if (parseMacroArguments(M, A))
2704 return true;
2705
2706 // Macro instantiation is lexical, unfortunately. We construct a new buffer
2707 // to hold the macro body with substitutions.
2708 SmallString<256> Buf;
2709 StringRef Body = M->Body;
2710 raw_svector_ostream OS(Buf);
2711
2712 if (expandMacro(OS, Body, M->Parameters, A, true, getTok().getLoc()))
2713 return true;
2714
2715 // We include the .endmacro in the buffer as our cue to exit the macro
2716 // instantiation.
2717 OS << ".endmacro\n";
2718
2719 std::unique_ptr<MemoryBuffer> Instantiation =
2720 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
2721
2722 // Create the macro instantiation object and add to the current macro
2723 // instantiation stack.
2724 MacroInstantiation *MI = new MacroInstantiation(
2725 NameLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
2726 ActiveMacros.push_back(MI);
2727
2728 ++NumOfMacroInstantiations;
2729
2730 // Jump to the macro instantiation and prime the lexer.
2731 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
2732 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
2733 Lex();
2734
2735 return false;
2736}
2737
2738void AsmParser::handleMacroExit() {
2739 // Jump to the EndOfStatement we should return to, and consume it.
2740 jumpToLoc(ActiveMacros.back()->ExitLoc, ActiveMacros.back()->ExitBuffer);
2741 Lex();
2742
2743 // Pop the instantiation entry.
2744 delete ActiveMacros.back();
2745 ActiveMacros.pop_back();
2746}
2747
2748bool AsmParser::parseAssignment(StringRef Name, bool allow_redef,
2749 bool NoDeadStrip) {
2750 MCSymbol *Sym;
2751 const MCExpr *Value;
2752 if (MCParserUtils::parseAssignmentExpression(Name, allow_redef, *this, Sym,
2753 Value))
2754 return true;
2755
2756 if (!Sym) {
2757 // In the case where we parse an expression starting with a '.', we will
2758 // not generate an error, nor will we create a symbol. In this case we
2759 // should just return out.
2760 return false;
2761 }
2762
2763 // Do the assignment.
2764 Out.EmitAssignment(Sym, Value);
2765 if (NoDeadStrip)
2766 Out.EmitSymbolAttribute(Sym, MCSA_NoDeadStrip);
2767
2768 return false;
2769}
2770
2771/// parseIdentifier:
2772/// ::= identifier
2773/// ::= string
2774bool AsmParser::parseIdentifier(StringRef &Res) {
2775 // The assembler has relaxed rules for accepting identifiers, in particular we
2776 // allow things like '.globl $foo' and '.def @feat.00', which would normally be
2777 // separate tokens. At this level, we have already lexed so we cannot (currently)
2778 // handle this as a context dependent token, instead we detect adjacent tokens
2779 // and return the combined identifier.
2780 if (Lexer.is(AsmToken::Dollar) || Lexer.is(AsmToken::At)) {
2781 SMLoc PrefixLoc = getLexer().getLoc();
2782
2783 // Consume the prefix character, and check for a following identifier.
2784
2785 AsmToken Buf[1];
2786 Lexer.peekTokens(Buf, false);
2787
2788 if (Buf[0].isNot(AsmToken::Identifier))
2789 return true;
2790
2791 // We have a '$' or '@' followed by an identifier, make sure they are adjacent.
2792 if (PrefixLoc.getPointer() + 1 != Buf[0].getLoc().getPointer())
2793 return true;
2794
2795 // eat $ or @
2796 Lexer.Lex(); // Lexer's Lex guarantees consecutive token.
2797 // Construct the joined identifier and consume the token.
2798 Res =
2799 StringRef(PrefixLoc.getPointer(), getTok().getIdentifier().size() + 1);
2800 Lex(); // Parser Lex to maintain invariants.
2801 return false;
2802 }
2803
2804 if (Lexer.isNot(AsmToken::Identifier) && Lexer.isNot(AsmToken::String))
2805 return true;
2806
2807 Res = getTok().getIdentifier();
2808
2809 Lex(); // Consume the identifier token.
2810
2811 return false;
2812}
2813
2814/// parseDirectiveSet:
2815/// ::= .equ identifier ',' expression
2816/// ::= .equiv identifier ',' expression
2817/// ::= .set identifier ',' expression
2818bool AsmParser::parseDirectiveSet(StringRef IDVal, bool allow_redef) {
2819 StringRef Name;
2820 if (check(parseIdentifier(Name), "expected identifier") ||
2821 parseToken(AsmToken::Comma) || parseAssignment(Name, allow_redef, true))
2822 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2823 return false;
2824}
2825
2826bool AsmParser::parseEscapedString(std::string &Data) {
2827 if (check(getTok().isNot(AsmToken::String), "expected string"))
2828 return true;
2829
2830 Data = "";
2831 StringRef Str = getTok().getStringContents();
2832 for (unsigned i = 0, e = Str.size(); i != e; ++i) {
2833 if (Str[i] != '\\') {
2834 Data += Str[i];
2835 continue;
2836 }
2837
2838 // Recognize escaped characters. Note that this escape semantics currently
2839 // loosely follows Darwin 'as'. Notably, it doesn't support hex escapes.
2840 ++i;
2841 if (i == e)
2842 return TokError("unexpected backslash at end of string");
2843
2844 // Recognize octal sequences.
2845 if ((unsigned)(Str[i] - '0') <= 7) {
2846 // Consume up to three octal characters.
2847 unsigned Value = Str[i] - '0';
2848
2849 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2850 ++i;
2851 Value = Value * 8 + (Str[i] - '0');
2852
2853 if (i + 1 != e && ((unsigned)(Str[i + 1] - '0')) <= 7) {
2854 ++i;
2855 Value = Value * 8 + (Str[i] - '0');
2856 }
2857 }
2858
2859 if (Value > 255)
2860 return TokError("invalid octal escape sequence (out of range)");
2861
2862 Data += (unsigned char)Value;
2863 continue;
2864 }
2865
2866 // Otherwise recognize individual escapes.
2867 switch (Str[i]) {
2868 default:
2869 // Just reject invalid escape sequences for now.
2870 return TokError("invalid escape sequence (unrecognized character)");
2871
2872 case 'b': Data += '\b'; break;
2873 case 'f': Data += '\f'; break;
2874 case 'n': Data += '\n'; break;
2875 case 'r': Data += '\r'; break;
2876 case 't': Data += '\t'; break;
2877 case '"': Data += '"'; break;
2878 case '\\': Data += '\\'; break;
2879 }
2880 }
2881
2882 Lex();
2883 return false;
2884}
2885
2886/// parseDirectiveAscii:
2887/// ::= ( .ascii | .asciz | .string ) [ "string" ( , "string" )* ]
2888bool AsmParser::parseDirectiveAscii(StringRef IDVal, bool ZeroTerminated) {
2889 auto parseOp = [&]() -> bool {
2890 std::string Data;
2891 if (checkForValidSection() || parseEscapedString(Data))
2892 return true;
2893 getStreamer().EmitBytes(Data);
2894 if (ZeroTerminated)
2895 getStreamer().EmitBytes(StringRef("\0", 1));
2896 return false;
2897 };
2898
2899 if (parseMany(parseOp))
2900 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2901 return false;
2902}
2903
2904/// parseDirectiveReloc
2905/// ::= .reloc expression , identifier [ , expression ]
2906bool AsmParser::parseDirectiveReloc(SMLoc DirectiveLoc) {
2907 const MCExpr *Offset;
2908 const MCExpr *Expr = nullptr;
2909
2910 SMLoc OffsetLoc = Lexer.getTok().getLoc();
2911 int64_t OffsetValue;
2912 // We can only deal with constant expressions at the moment.
2913
2914 if (parseExpression(Offset))
2915 return true;
2916
2917 if (check(!Offset->evaluateAsAbsolute(OffsetValue), OffsetLoc,
2918 "expression is not a constant value") ||
2919 check(OffsetValue < 0, OffsetLoc, "expression is negative") ||
2920 parseToken(AsmToken::Comma, "expected comma") ||
2921 check(getTok().isNot(AsmToken::Identifier), "expected relocation name"))
2922 return true;
2923
2924 SMLoc NameLoc = Lexer.getTok().getLoc();
2925 StringRef Name = Lexer.getTok().getIdentifier();
2926 Lex();
2927
2928 if (Lexer.is(AsmToken::Comma)) {
2929 Lex();
2930 SMLoc ExprLoc = Lexer.getLoc();
2931 if (parseExpression(Expr))
2932 return true;
2933
2934 MCValue Value;
2935 if (!Expr->evaluateAsRelocatable(Value, nullptr, nullptr))
2936 return Error(ExprLoc, "expression must be relocatable");
2937 }
2938
2939 if (parseToken(AsmToken::EndOfStatement,
2940 "unexpected token in .reloc directive"))
2941 return true;
2942
2943 if (getStreamer().EmitRelocDirective(*Offset, Name, Expr, DirectiveLoc))
2944 return Error(NameLoc, "unknown relocation name");
2945
2946 return false;
2947}
2948
2949/// parseDirectiveValue
2950/// ::= (.byte | .short | ... ) [ expression (, expression)* ]
2951bool AsmParser::parseDirectiveValue(StringRef IDVal, unsigned Size) {
2952 auto parseOp = [&]() -> bool {
2953 const MCExpr *Value;
2954 SMLoc ExprLoc = getLexer().getLoc();
2955 if (checkForValidSection() || parseExpression(Value))
2956 return true;
2957 // Special case constant expressions to match code generator.
2958 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
2959 assert(Size <= 8 && "Invalid size")(static_cast <bool> (Size <= 8 && "Invalid size"
) ? void (0) : __assert_fail ("Size <= 8 && \"Invalid size\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 2959, __extension__ __PRETTY_FUNCTION__))
;
2960 uint64_t IntValue = MCE->getValue();
2961 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
2962 return Error(ExprLoc, "out of range literal value");
2963 getStreamer().EmitIntValue(IntValue, Size);
2964 } else
2965 getStreamer().EmitValue(Value, Size, ExprLoc);
2966 return false;
2967 };
2968
2969 if (parseMany(parseOp))
2970 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
2971 return false;
2972}
2973
2974/// ParseDirectiveOctaValue
2975/// ::= .octa [ hexconstant (, hexconstant)* ]
2976
2977bool AsmParser::parseDirectiveOctaValue(StringRef IDVal) {
2978 auto parseOp = [&]() -> bool {
2979 if (checkForValidSection())
2980 return true;
2981 if (getTok().isNot(AsmToken::Integer) && getTok().isNot(AsmToken::BigNum))
2982 return TokError("unknown token in expression");
2983 SMLoc ExprLoc = getTok().getLoc();
2984 APInt IntValue = getTok().getAPIntVal();
2985 uint64_t hi, lo;
2986 Lex();
2987 if (!IntValue.isIntN(128))
2988 return Error(ExprLoc, "out of range literal value");
2989 if (!IntValue.isIntN(64)) {
2990 hi = IntValue.getHiBits(IntValue.getBitWidth() - 64).getZExtValue();
2991 lo = IntValue.getLoBits(64).getZExtValue();
2992 } else {
2993 hi = 0;
2994 lo = IntValue.getZExtValue();
2995 }
2996 if (MAI.isLittleEndian()) {
2997 getStreamer().EmitIntValue(lo, 8);
2998 getStreamer().EmitIntValue(hi, 8);
2999 } else {
3000 getStreamer().EmitIntValue(hi, 8);
3001 getStreamer().EmitIntValue(lo, 8);
3002 }
3003 return false;
3004 };
3005
3006 if (parseMany(parseOp))
3007 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
3008 return false;
3009}
3010
3011bool AsmParser::parseRealValue(const fltSemantics &Semantics, APInt &Res) {
3012 // We don't truly support arithmetic on floating point expressions, so we
3013 // have to manually parse unary prefixes.
3014 bool IsNeg = false;
3015 if (getLexer().is(AsmToken::Minus)) {
3016 Lexer.Lex();
3017 IsNeg = true;
3018 } else if (getLexer().is(AsmToken::Plus))
3019 Lexer.Lex();
3020
3021 if (Lexer.is(AsmToken::Error))
3022 return TokError(Lexer.getErr());
3023 if (Lexer.isNot(AsmToken::Integer) && Lexer.isNot(AsmToken::Real) &&
3024 Lexer.isNot(AsmToken::Identifier))
3025 return TokError("unexpected token in directive");
3026
3027 // Convert to an APFloat.
3028 APFloat Value(Semantics);
3029 StringRef IDVal = getTok().getString();
3030 if (getLexer().is(AsmToken::Identifier)) {
3031 if (!IDVal.compare_lower("infinity") || !IDVal.compare_lower("inf"))
3032 Value = APFloat::getInf(Semantics);
3033 else if (!IDVal.compare_lower("nan"))
3034 Value = APFloat::getNaN(Semantics, false, ~0);
3035 else
3036 return TokError("invalid floating point literal");
3037 } else if (Value.convertFromString(IDVal, APFloat::rmNearestTiesToEven) ==
3038 APFloat::opInvalidOp)
3039 return TokError("invalid floating point literal");
3040 if (IsNeg)
3041 Value.changeSign();
3042
3043 // Consume the numeric token.
3044 Lex();
3045
3046 Res = Value.bitcastToAPInt();
3047
3048 return false;
3049}
3050
3051/// parseDirectiveRealValue
3052/// ::= (.single | .double) [ expression (, expression)* ]
3053bool AsmParser::parseDirectiveRealValue(StringRef IDVal,
3054 const fltSemantics &Semantics) {
3055 auto parseOp = [&]() -> bool {
3056 APInt AsInt;
3057 if (checkForValidSection() || parseRealValue(Semantics, AsInt))
3058 return true;
3059 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
3060 AsInt.getBitWidth() / 8);
3061 return false;
3062 };
3063
3064 if (parseMany(parseOp))
3065 return addErrorSuffix(" in '" + Twine(IDVal) + "' directive");
3066 return false;
3067}
3068
3069/// parseDirectiveZero
3070/// ::= .zero expression
3071bool AsmParser::parseDirectiveZero() {
3072 SMLoc NumBytesLoc = Lexer.getLoc();
3073 const MCExpr *NumBytes;
3074 if (checkForValidSection() || parseExpression(NumBytes))
3075 return true;
3076
3077 int64_t Val = 0;
3078 if (getLexer().is(AsmToken::Comma)) {
3079 Lex();
3080 if (parseAbsoluteExpression(Val))
3081 return true;
3082 }
3083
3084 if (parseToken(AsmToken::EndOfStatement,
3085 "unexpected token in '.zero' directive"))
3086 return true;
3087 getStreamer().emitFill(*NumBytes, Val, NumBytesLoc);
3088
3089 return false;
3090}
3091
3092/// parseDirectiveFill
3093/// ::= .fill expression [ , expression [ , expression ] ]
3094bool AsmParser::parseDirectiveFill() {
3095 SMLoc NumValuesLoc = Lexer.getLoc();
3096 const MCExpr *NumValues;
3097 if (checkForValidSection() || parseExpression(NumValues))
3098 return true;
3099
3100 int64_t FillSize = 1;
3101 int64_t FillExpr = 0;
3102
3103 SMLoc SizeLoc, ExprLoc;
3104
3105 if (parseOptionalToken(AsmToken::Comma)) {
3106 SizeLoc = getTok().getLoc();
3107 if (parseAbsoluteExpression(FillSize))
3108 return true;
3109 if (parseOptionalToken(AsmToken::Comma)) {
3110 ExprLoc = getTok().getLoc();
3111 if (parseAbsoluteExpression(FillExpr))
3112 return true;
3113 }
3114 }
3115 if (parseToken(AsmToken::EndOfStatement,
3116 "unexpected token in '.fill' directive"))
3117 return true;
3118
3119 if (FillSize < 0) {
3120 Warning(SizeLoc, "'.fill' directive with negative size has no effect");
3121 return false;
3122 }
3123 if (FillSize > 8) {
3124 Warning(SizeLoc, "'.fill' directive with size greater than 8 has been truncated to 8");
3125 FillSize = 8;
3126 }
3127
3128 if (!isUInt<32>(FillExpr) && FillSize > 4)
3129 Warning(ExprLoc, "'.fill' directive pattern has been truncated to 32-bits");
3130
3131 getStreamer().emitFill(*NumValues, FillSize, FillExpr, NumValuesLoc);
3132
3133 return false;
3134}
3135
3136/// parseDirectiveOrg
3137/// ::= .org expression [ , expression ]
3138bool AsmParser::parseDirectiveOrg() {
3139 const MCExpr *Offset;
3140 SMLoc OffsetLoc = Lexer.getLoc();
3141 if (checkForValidSection() || parseExpression(Offset))
3142 return true;
3143
3144 // Parse optional fill expression.
3145 int64_t FillExpr = 0;
3146 if (parseOptionalToken(AsmToken::Comma))
3147 if (parseAbsoluteExpression(FillExpr))
3148 return addErrorSuffix(" in '.org' directive");
3149 if (parseToken(AsmToken::EndOfStatement))
3150 return addErrorSuffix(" in '.org' directive");
3151
3152 getStreamer().emitValueToOffset(Offset, FillExpr, OffsetLoc);
3153 return false;
3154}
3155
3156/// parseDirectiveAlign
3157/// ::= {.align, ...} expression [ , expression [ , expression ]]
3158bool AsmParser::parseDirectiveAlign(bool IsPow2, unsigned ValueSize) {
3159 SMLoc AlignmentLoc = getLexer().getLoc();
3160 int64_t Alignment;
3161 SMLoc MaxBytesLoc;
3162 bool HasFillExpr = false;
3163 int64_t FillExpr = 0;
3164 int64_t MaxBytesToFill = 0;
3165
3166 auto parseAlign = [&]() -> bool {
3167 if (parseAbsoluteExpression(Alignment))
3168 return true;
3169 if (parseOptionalToken(AsmToken::Comma)) {
3170 // The fill expression can be omitted while specifying a maximum number of
3171 // alignment bytes, e.g:
3172 // .align 3,,4
3173 if (getTok().isNot(AsmToken::Comma)) {
3174 HasFillExpr = true;
3175 if (parseAbsoluteExpression(FillExpr))
3176 return true;
3177 }
3178 if (parseOptionalToken(AsmToken::Comma))
3179 if (parseTokenLoc(MaxBytesLoc) ||
3180 parseAbsoluteExpression(MaxBytesToFill))
3181 return true;
3182 }
3183 return parseToken(AsmToken::EndOfStatement);
3184 };
3185
3186 if (checkForValidSection())
3187 return addErrorSuffix(" in directive");
3188 // Ignore empty '.p2align' directives for GNU-as compatibility
3189 if (IsPow2 && (ValueSize == 1) && getTok().is(AsmToken::EndOfStatement)) {
3190 Warning(AlignmentLoc, "p2align directive with no operand(s) is ignored");
3191 return parseToken(AsmToken::EndOfStatement);
3192 }
3193 if (parseAlign())
3194 return addErrorSuffix(" in directive");
3195
3196 // Always emit an alignment here even if we thrown an error.
3197 bool ReturnVal = false;
3198
3199 // Compute alignment in bytes.
3200 if (IsPow2) {
3201 // FIXME: Diagnose overflow.
3202 if (Alignment >= 32) {
3203 ReturnVal |= Error(AlignmentLoc, "invalid alignment value");
3204 Alignment = 31;
3205 }
3206
3207 Alignment = 1ULL << Alignment;
3208 } else {
3209 // Reject alignments that aren't either a power of two or zero,
3210 // for gas compatibility. Alignment of zero is silently rounded
3211 // up to one.
3212 if (Alignment == 0)
3213 Alignment = 1;
3214 if (!isPowerOf2_64(Alignment))
3215 ReturnVal |= Error(AlignmentLoc, "alignment must be a power of 2");
3216 }
3217
3218 // Diagnose non-sensical max bytes to align.
3219 if (MaxBytesLoc.isValid()) {
3220 if (MaxBytesToFill < 1) {
3221 ReturnVal |= Error(MaxBytesLoc,
3222 "alignment directive can never be satisfied in this "
3223 "many bytes, ignoring maximum bytes expression");
3224 MaxBytesToFill = 0;
3225 }
3226
3227 if (MaxBytesToFill >= Alignment) {
3228 Warning(MaxBytesLoc, "maximum bytes expression exceeds alignment and "
3229 "has no effect");
3230 MaxBytesToFill = 0;
3231 }
3232 }
3233
3234 // Check whether we should use optimal code alignment for this .align
3235 // directive.
3236 const MCSection *Section = getStreamer().getCurrentSectionOnly();
3237 assert(Section && "must have section to emit alignment")(static_cast <bool> (Section && "must have section to emit alignment"
) ? void (0) : __assert_fail ("Section && \"must have section to emit alignment\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 3237, __extension__ __PRETTY_FUNCTION__))
;
3238 bool UseCodeAlign = Section->UseCodeAlign();
3239 if ((!HasFillExpr || Lexer.getMAI().getTextAlignFillValue() == FillExpr) &&
3240 ValueSize == 1 && UseCodeAlign) {
3241 getStreamer().EmitCodeAlignment(Alignment, MaxBytesToFill);
3242 } else {
3243 // FIXME: Target specific behavior about how the "extra" bytes are filled.
3244 getStreamer().EmitValueToAlignment(Alignment, FillExpr, ValueSize,
3245 MaxBytesToFill);
3246 }
3247
3248 return ReturnVal;
3249}
3250
3251/// parseDirectiveFile
3252/// ::= .file filename
3253/// ::= .file number [directory] filename [md5 checksum] [source source-text]
3254bool AsmParser::parseDirectiveFile(SMLoc DirectiveLoc) {
3255 // FIXME: I'm not sure what this is.
3256 int64_t FileNumber = -1;
3257 if (getLexer().is(AsmToken::Integer)) {
3258 FileNumber = getTok().getIntVal();
3259 Lex();
3260
3261 if (FileNumber < 1)
3262 return TokError("file number less than one");
3263 }
3264
3265 std::string Path = getTok().getString();
3266
3267 // Usually the directory and filename together, otherwise just the directory.
3268 // Allow the strings to have escaped octal character sequence.
3269 if (check(getTok().isNot(AsmToken::String),
3270 "unexpected token in '.file' directive") ||
3271 parseEscapedString(Path))
3272 return true;
3273
3274 StringRef Directory;
3275 StringRef Filename;
3276 std::string FilenameData;
3277 if (getLexer().is(AsmToken::String)) {
3278 if (check(FileNumber == -1,
3279 "explicit path specified, but no file number") ||
3280 parseEscapedString(FilenameData))
3281 return true;
3282 Filename = FilenameData;
3283 Directory = Path;
3284 } else {
3285 Filename = Path;
3286 }
3287
3288 std::string Checksum;
3289
3290 Optional<StringRef> Source;
3291 bool HasSource = false;
3292 std::string SourceString;
3293
3294 while (!parseOptionalToken(AsmToken::EndOfStatement)) {
3295 StringRef Keyword;
3296 if (check(getTok().isNot(AsmToken::Identifier),
3297 "unexpected token in '.file' directive") ||
3298 parseIdentifier(Keyword))
3299 return true;
3300 if (Keyword == "md5") {
3301 if (check(FileNumber == -1,
3302 "MD5 checksum specified, but no file number") ||
3303 check(getTok().isNot(AsmToken::String),
3304 "unexpected token in '.file' directive") ||
3305 parseEscapedString(Checksum) ||
3306 check(Checksum.size() != 32, "invalid MD5 checksum specified"))
3307 return true;
3308 } else if (Keyword == "source") {
3309 HasSource = true;
3310 if (check(FileNumber == -1,
3311 "source specified, but no file number") ||
3312 check(getTok().isNot(AsmToken::String),
3313 "unexpected token in '.file' directive") ||
3314 parseEscapedString(SourceString))
3315 return true;
3316 } else {
3317 return TokError("unexpected token in '.file' directive");
3318 }
3319 }
3320
3321 if (FileNumber == -1)
3322 getStreamer().EmitFileDirective(Filename);
3323 else {
3324 MD5::MD5Result *CKMem = nullptr;
3325 if (!Checksum.empty()) {
3326 Checksum = fromHex(Checksum);
3327 if (check(Checksum.size() != 16, "invalid MD5 checksum specified"))
3328 return true;
3329 CKMem = (MD5::MD5Result *)Ctx.allocate(sizeof(MD5::MD5Result), 1);
3330 memcpy(&CKMem->Bytes, Checksum.data(), 16);
3331 }
3332 if (HasSource) {
3333 char *SourceBuf = static_cast<char *>(Ctx.allocate(SourceString.size()));
3334 memcpy(SourceBuf, SourceString.data(), SourceString.size());
3335 Source = StringRef(SourceBuf, SourceString.size());
3336 }
3337 // If there is -g option as well as debug info from directive file,
3338 // we turn off -g option, directly use the existing debug info instead.
3339 if (getContext().getGenDwarfForAssembly())
3340 getContext().setGenDwarfForAssembly(false);
3341 else {
3342 Expected<unsigned> FileNumOrErr = getStreamer().tryEmitDwarfFileDirective(
3343 FileNumber, Directory, Filename, CKMem, Source);
3344 if (!FileNumOrErr)
3345 return Error(DirectiveLoc, toString(FileNumOrErr.takeError()));
3346 FileNumber = FileNumOrErr.get();
Value stored to 'FileNumber' is never read
3347 }
3348 }
3349
3350 return false;
3351}
3352
3353/// parseDirectiveLine
3354/// ::= .line [number]
3355bool AsmParser::parseDirectiveLine() {
3356 int64_t LineNumber;
3357 if (getLexer().is(AsmToken::Integer)) {
3358 if (parseIntToken(LineNumber, "unexpected token in '.line' directive"))
3359 return true;
3360 (void)LineNumber;
3361 // FIXME: Do something with the .line.
3362 }
3363 if (parseToken(AsmToken::EndOfStatement,
3364 "unexpected token in '.line' directive"))
3365 return true;
3366
3367 return false;
3368}
3369
3370/// parseDirectiveLoc
3371/// ::= .loc FileNumber [LineNumber] [ColumnPos] [basic_block] [prologue_end]
3372/// [epilogue_begin] [is_stmt VALUE] [isa VALUE]
3373/// The first number is a file number, must have been previously assigned with
3374/// a .file directive, the second number is the line number and optionally the
3375/// third number is a column position (zero if not specified). The remaining
3376/// optional items are .loc sub-directives.
3377bool AsmParser::parseDirectiveLoc() {
3378 int64_t FileNumber = 0, LineNumber = 0;
3379 SMLoc Loc = getTok().getLoc();
3380 if (parseIntToken(FileNumber, "unexpected token in '.loc' directive") ||
3381 check(FileNumber < 1, Loc,
3382 "file number less than one in '.loc' directive") ||
3383 check(!getContext().isValidDwarfFileNumber(FileNumber), Loc,
3384 "unassigned file number in '.loc' directive"))
3385 return true;
3386
3387 // optional
3388 if (getLexer().is(AsmToken::Integer)) {
3389 LineNumber = getTok().getIntVal();
3390 if (LineNumber < 0)
3391 return TokError("line number less than zero in '.loc' directive");
3392 Lex();
3393 }
3394
3395 int64_t ColumnPos = 0;
3396 if (getLexer().is(AsmToken::Integer)) {
3397 ColumnPos = getTok().getIntVal();
3398 if (ColumnPos < 0)
3399 return TokError("column position less than zero in '.loc' directive");
3400 Lex();
3401 }
3402
3403 unsigned Flags = DWARF2_LINE_DEFAULT_IS_STMT1 ? DWARF2_FLAG_IS_STMT(1 << 0) : 0;
3404 unsigned Isa = 0;
3405 int64_t Discriminator = 0;
3406
3407 auto parseLocOp = [&]() -> bool {
3408 StringRef Name;
3409 SMLoc Loc = getTok().getLoc();
3410 if (parseIdentifier(Name))
3411 return TokError("unexpected token in '.loc' directive");
3412
3413 if (Name == "basic_block")
3414 Flags |= DWARF2_FLAG_BASIC_BLOCK(1 << 1);
3415 else if (Name == "prologue_end")
3416 Flags |= DWARF2_FLAG_PROLOGUE_END(1 << 2);
3417 else if (Name == "epilogue_begin")
3418 Flags |= DWARF2_FLAG_EPILOGUE_BEGIN(1 << 3);
3419 else if (Name == "is_stmt") {
3420 Loc = getTok().getLoc();
3421 const MCExpr *Value;
3422 if (parseExpression(Value))
3423 return true;
3424 // The expression must be the constant 0 or 1.
3425 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3426 int Value = MCE->getValue();
3427 if (Value == 0)
3428 Flags &= ~DWARF2_FLAG_IS_STMT(1 << 0);
3429 else if (Value == 1)
3430 Flags |= DWARF2_FLAG_IS_STMT(1 << 0);
3431 else
3432 return Error(Loc, "is_stmt value not 0 or 1");
3433 } else {
3434 return Error(Loc, "is_stmt value not the constant value of 0 or 1");
3435 }
3436 } else if (Name == "isa") {
3437 Loc = getTok().getLoc();
3438 const MCExpr *Value;
3439 if (parseExpression(Value))
3440 return true;
3441 // The expression must be a constant greater or equal to 0.
3442 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
3443 int Value = MCE->getValue();
3444 if (Value < 0)
3445 return Error(Loc, "isa number less than zero");
3446 Isa = Value;
3447 } else {
3448 return Error(Loc, "isa number not a constant value");
3449 }
3450 } else if (Name == "discriminator") {
3451 if (parseAbsoluteExpression(Discriminator))
3452 return true;
3453 } else {
3454 return Error(Loc, "unknown sub-directive in '.loc' directive");
3455 }
3456 return false;
3457 };
3458
3459 if (parseMany(parseLocOp, false /*hasComma*/))
3460 return true;
3461
3462 getStreamer().EmitDwarfLocDirective(FileNumber, LineNumber, ColumnPos, Flags,
3463 Isa, Discriminator, StringRef());
3464
3465 return false;
3466}
3467
3468/// parseDirectiveStabs
3469/// ::= .stabs string, number, number, number
3470bool AsmParser::parseDirectiveStabs() {
3471 return TokError("unsupported directive '.stabs'");
3472}
3473
3474/// parseDirectiveCVFile
3475/// ::= .cv_file number filename [checksum] [checksumkind]
3476bool AsmParser::parseDirectiveCVFile() {
3477 SMLoc FileNumberLoc = getTok().getLoc();
3478 int64_t FileNumber;
3479 std::string Filename;
3480 std::string Checksum;
3481 int64_t ChecksumKind = 0;
3482
3483 if (parseIntToken(FileNumber,
3484 "expected file number in '.cv_file' directive") ||
3485 check(FileNumber < 1, FileNumberLoc, "file number less than one") ||
3486 check(getTok().isNot(AsmToken::String),
3487 "unexpected token in '.cv_file' directive") ||
3488 parseEscapedString(Filename))
3489 return true;
3490 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3491 if (check(getTok().isNot(AsmToken::String),
3492 "unexpected token in '.cv_file' directive") ||
3493 parseEscapedString(Checksum) ||
3494 parseIntToken(ChecksumKind,
3495 "expected checksum kind in '.cv_file' directive") ||
3496 parseToken(AsmToken::EndOfStatement,
3497 "unexpected token in '.cv_file' directive"))
3498 return true;
3499 }
3500
3501 Checksum = fromHex(Checksum);
3502 void *CKMem = Ctx.allocate(Checksum.size(), 1);
3503 memcpy(CKMem, Checksum.data(), Checksum.size());
3504 ArrayRef<uint8_t> ChecksumAsBytes(reinterpret_cast<const uint8_t *>(CKMem),
3505 Checksum.size());
3506
3507 if (!getStreamer().EmitCVFileDirective(FileNumber, Filename, ChecksumAsBytes,
3508 static_cast<uint8_t>(ChecksumKind)))
3509 return Error(FileNumberLoc, "file number already allocated");
3510
3511 return false;
3512}
3513
3514bool AsmParser::parseCVFunctionId(int64_t &FunctionId,
3515 StringRef DirectiveName) {
3516 SMLoc Loc;
3517 return parseTokenLoc(Loc) ||
3518 parseIntToken(FunctionId, "expected function id in '" + DirectiveName +
3519 "' directive") ||
3520 check(FunctionId < 0 || FunctionId >= UINT_MAX(2147483647 *2U +1U), Loc,
3521 "expected function id within range [0, UINT_MAX)");
3522}
3523
3524bool AsmParser::parseCVFileId(int64_t &FileNumber, StringRef DirectiveName) {
3525 SMLoc Loc;
3526 return parseTokenLoc(Loc) ||
3527 parseIntToken(FileNumber, "expected integer in '" + DirectiveName +
3528 "' directive") ||
3529 check(FileNumber < 1, Loc, "file number less than one in '" +
3530 DirectiveName + "' directive") ||
3531 check(!getCVContext().isValidFileNumber(FileNumber), Loc,
3532 "unassigned file number in '" + DirectiveName + "' directive");
3533}
3534
3535/// parseDirectiveCVFuncId
3536/// ::= .cv_func_id FunctionId
3537///
3538/// Introduces a function ID that can be used with .cv_loc.
3539bool AsmParser::parseDirectiveCVFuncId() {
3540 SMLoc FunctionIdLoc = getTok().getLoc();
3541 int64_t FunctionId;
3542
3543 if (parseCVFunctionId(FunctionId, ".cv_func_id") ||
3544 parseToken(AsmToken::EndOfStatement,
3545 "unexpected token in '.cv_func_id' directive"))
3546 return true;
3547
3548 if (!getStreamer().EmitCVFuncIdDirective(FunctionId))
3549 return Error(FunctionIdLoc, "function id already allocated");
3550
3551 return false;
3552}
3553
3554/// parseDirectiveCVInlineSiteId
3555/// ::= .cv_inline_site_id FunctionId
3556/// "within" IAFunc
3557/// "inlined_at" IAFile IALine [IACol]
3558///
3559/// Introduces a function ID that can be used with .cv_loc. Includes "inlined
3560/// at" source location information for use in the line table of the caller,
3561/// whether the caller is a real function or another inlined call site.
3562bool AsmParser::parseDirectiveCVInlineSiteId() {
3563 SMLoc FunctionIdLoc = getTok().getLoc();
3564 int64_t FunctionId;
3565 int64_t IAFunc;
3566 int64_t IAFile;
3567 int64_t IALine;
3568 int64_t IACol = 0;
3569
3570 // FunctionId
3571 if (parseCVFunctionId(FunctionId, ".cv_inline_site_id"))
3572 return true;
3573
3574 // "within"
3575 if (check((getLexer().isNot(AsmToken::Identifier) ||
3576 getTok().getIdentifier() != "within"),
3577 "expected 'within' identifier in '.cv_inline_site_id' directive"))
3578 return true;
3579 Lex();
3580
3581 // IAFunc
3582 if (parseCVFunctionId(IAFunc, ".cv_inline_site_id"))
3583 return true;
3584
3585 // "inlined_at"
3586 if (check((getLexer().isNot(AsmToken::Identifier) ||
3587 getTok().getIdentifier() != "inlined_at"),
3588 "expected 'inlined_at' identifier in '.cv_inline_site_id' "
3589 "directive") )
3590 return true;
3591 Lex();
3592
3593 // IAFile IALine
3594 if (parseCVFileId(IAFile, ".cv_inline_site_id") ||
3595 parseIntToken(IALine, "expected line number after 'inlined_at'"))
3596 return true;
3597
3598 // [IACol]
3599 if (getLexer().is(AsmToken::Integer)) {
3600 IACol = getTok().getIntVal();
3601 Lex();
3602 }
3603
3604 if (parseToken(AsmToken::EndOfStatement,
3605 "unexpected token in '.cv_inline_site_id' directive"))
3606 return true;
3607
3608 if (!getStreamer().EmitCVInlineSiteIdDirective(FunctionId, IAFunc, IAFile,
3609 IALine, IACol, FunctionIdLoc))
3610 return Error(FunctionIdLoc, "function id already allocated");
3611
3612 return false;
3613}
3614
3615/// parseDirectiveCVLoc
3616/// ::= .cv_loc FunctionId FileNumber [LineNumber] [ColumnPos] [prologue_end]
3617/// [is_stmt VALUE]
3618/// The first number is a file number, must have been previously assigned with
3619/// a .file directive, the second number is the line number and optionally the
3620/// third number is a column position (zero if not specified). The remaining
3621/// optional items are .loc sub-directives.
3622bool AsmParser::parseDirectiveCVLoc() {
3623 SMLoc DirectiveLoc = getTok().getLoc();
3624 int64_t FunctionId, FileNumber;
3625 if (parseCVFunctionId(FunctionId, ".cv_loc") ||
3626 parseCVFileId(FileNumber, ".cv_loc"))
3627 return true;
3628
3629 int64_t LineNumber = 0;
3630 if (getLexer().is(AsmToken::Integer)) {
3631 LineNumber = getTok().getIntVal();
3632 if (LineNumber < 0)
3633 return TokError("line number less than zero in '.cv_loc' directive");
3634 Lex();
3635 }
3636
3637 int64_t ColumnPos = 0;
3638 if (getLexer().is(AsmToken::Integer)) {
3639 ColumnPos = getTok().getIntVal();
3640 if (ColumnPos < 0)
3641 return TokError("column position less than zero in '.cv_loc' directive");
3642 Lex();
3643 }
3644
3645 bool PrologueEnd = false;
3646 uint64_t IsStmt = 0;
3647
3648 auto parseOp = [&]() -> bool {
3649 StringRef Name;
3650 SMLoc Loc = getTok().getLoc();
3651 if (parseIdentifier(Name))
3652 return TokError("unexpected token in '.cv_loc' directive");
3653 if (Name == "prologue_end")
3654 PrologueEnd = true;
3655 else if (Name == "is_stmt") {
3656 Loc = getTok().getLoc();
3657 const MCExpr *Value;
3658 if (parseExpression(Value))
3659 return true;
3660 // The expression must be the constant 0 or 1.
3661 IsStmt = ~0ULL;
3662 if (const auto *MCE = dyn_cast<MCConstantExpr>(Value))
3663 IsStmt = MCE->getValue();
3664
3665 if (IsStmt > 1)
3666 return Error(Loc, "is_stmt value not 0 or 1");
3667 } else {
3668 return Error(Loc, "unknown sub-directive in '.cv_loc' directive");
3669 }
3670 return false;
3671 };
3672
3673 if (parseMany(parseOp, false /*hasComma*/))
3674 return true;
3675
3676 getStreamer().EmitCVLocDirective(FunctionId, FileNumber, LineNumber,
3677 ColumnPos, PrologueEnd, IsStmt, StringRef(),
3678 DirectiveLoc);
3679 return false;
3680}
3681
3682/// parseDirectiveCVLinetable
3683/// ::= .cv_linetable FunctionId, FnStart, FnEnd
3684bool AsmParser::parseDirectiveCVLinetable() {
3685 int64_t FunctionId;
3686 StringRef FnStartName, FnEndName;
3687 SMLoc Loc = getTok().getLoc();
3688 if (parseCVFunctionId(FunctionId, ".cv_linetable") ||
3689 parseToken(AsmToken::Comma,
3690 "unexpected token in '.cv_linetable' directive") ||
3691 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3692 "expected identifier in directive") ||
3693 parseToken(AsmToken::Comma,
3694 "unexpected token in '.cv_linetable' directive") ||
3695 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3696 "expected identifier in directive"))
3697 return true;
3698
3699 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3700 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3701
3702 getStreamer().EmitCVLinetableDirective(FunctionId, FnStartSym, FnEndSym);
3703 return false;
3704}
3705
3706/// parseDirectiveCVInlineLinetable
3707/// ::= .cv_inline_linetable PrimaryFunctionId FileId LineNum FnStart FnEnd
3708bool AsmParser::parseDirectiveCVInlineLinetable() {
3709 int64_t PrimaryFunctionId, SourceFileId, SourceLineNum;
3710 StringRef FnStartName, FnEndName;
3711 SMLoc Loc = getTok().getLoc();
3712 if (parseCVFunctionId(PrimaryFunctionId, ".cv_inline_linetable") ||
3713 parseTokenLoc(Loc) ||
3714 parseIntToken(
3715 SourceFileId,
3716 "expected SourceField in '.cv_inline_linetable' directive") ||
3717 check(SourceFileId <= 0, Loc,
3718 "File id less than zero in '.cv_inline_linetable' directive") ||
3719 parseTokenLoc(Loc) ||
3720 parseIntToken(
3721 SourceLineNum,
3722 "expected SourceLineNum in '.cv_inline_linetable' directive") ||
3723 check(SourceLineNum < 0, Loc,
3724 "Line number less than zero in '.cv_inline_linetable' directive") ||
3725 parseTokenLoc(Loc) || check(parseIdentifier(FnStartName), Loc,
3726 "expected identifier in directive") ||
3727 parseTokenLoc(Loc) || check(parseIdentifier(FnEndName), Loc,
3728 "expected identifier in directive"))
3729 return true;
3730
3731 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3732 return true;
3733
3734 MCSymbol *FnStartSym = getContext().getOrCreateSymbol(FnStartName);
3735 MCSymbol *FnEndSym = getContext().getOrCreateSymbol(FnEndName);
3736 getStreamer().EmitCVInlineLinetableDirective(PrimaryFunctionId, SourceFileId,
3737 SourceLineNum, FnStartSym,
3738 FnEndSym);
3739 return false;
3740}
3741
3742/// parseDirectiveCVDefRange
3743/// ::= .cv_def_range RangeStart RangeEnd (GapStart GapEnd)*, bytes*
3744bool AsmParser::parseDirectiveCVDefRange() {
3745 SMLoc Loc;
3746 std::vector<std::pair<const MCSymbol *, const MCSymbol *>> Ranges;
3747 while (getLexer().is(AsmToken::Identifier)) {
3748 Loc = getLexer().getLoc();
3749 StringRef GapStartName;
3750 if (parseIdentifier(GapStartName))
3751 return Error(Loc, "expected identifier in directive");
3752 MCSymbol *GapStartSym = getContext().getOrCreateSymbol(GapStartName);
3753
3754 Loc = getLexer().getLoc();
3755 StringRef GapEndName;
3756 if (parseIdentifier(GapEndName))
3757 return Error(Loc, "expected identifier in directive");
3758 MCSymbol *GapEndSym = getContext().getOrCreateSymbol(GapEndName);
3759
3760 Ranges.push_back({GapStartSym, GapEndSym});
3761 }
3762
3763 std::string FixedSizePortion;
3764 if (parseToken(AsmToken::Comma, "unexpected token in directive") ||
3765 parseEscapedString(FixedSizePortion))
3766 return true;
3767
3768 getStreamer().EmitCVDefRangeDirective(Ranges, FixedSizePortion);
3769 return false;
3770}
3771
3772/// parseDirectiveCVStringTable
3773/// ::= .cv_stringtable
3774bool AsmParser::parseDirectiveCVStringTable() {
3775 getStreamer().EmitCVStringTableDirective();
3776 return false;
3777}
3778
3779/// parseDirectiveCVFileChecksums
3780/// ::= .cv_filechecksums
3781bool AsmParser::parseDirectiveCVFileChecksums() {
3782 getStreamer().EmitCVFileChecksumsDirective();
3783 return false;
3784}
3785
3786/// parseDirectiveCVFileChecksumOffset
3787/// ::= .cv_filechecksumoffset fileno
3788bool AsmParser::parseDirectiveCVFileChecksumOffset() {
3789 int64_t FileNo;
3790 if (parseIntToken(FileNo, "expected identifier in directive"))
3791 return true;
3792 if (parseToken(AsmToken::EndOfStatement, "Expected End of Statement"))
3793 return true;
3794 getStreamer().EmitCVFileChecksumOffsetDirective(FileNo);
3795 return false;
3796}
3797
3798/// parseDirectiveCVFPOData
3799/// ::= .cv_fpo_data procsym
3800bool AsmParser::parseDirectiveCVFPOData() {
3801 SMLoc DirLoc = getLexer().getLoc();
3802 StringRef ProcName;
3803 if (parseIdentifier(ProcName))
3804 return TokError("expected symbol name");
3805 if (parseEOL("unexpected tokens"))
3806 return addErrorSuffix(" in '.cv_fpo_data' directive");
3807 MCSymbol *ProcSym = getContext().getOrCreateSymbol(ProcName);
3808 getStreamer().EmitCVFPOData(ProcSym, DirLoc);
3809 return false;
3810}
3811
3812/// parseDirectiveCFISections
3813/// ::= .cfi_sections section [, section]
3814bool AsmParser::parseDirectiveCFISections() {
3815 StringRef Name;
3816 bool EH = false;
3817 bool Debug = false;
3818
3819 if (parseIdentifier(Name))
3820 return TokError("Expected an identifier");
3821
3822 if (Name == ".eh_frame")
3823 EH = true;
3824 else if (Name == ".debug_frame")
3825 Debug = true;
3826
3827 if (getLexer().is(AsmToken::Comma)) {
3828 Lex();
3829
3830 if (parseIdentifier(Name))
3831 return TokError("Expected an identifier");
3832
3833 if (Name == ".eh_frame")
3834 EH = true;
3835 else if (Name == ".debug_frame")
3836 Debug = true;
3837 }
3838
3839 getStreamer().EmitCFISections(EH, Debug);
3840 return false;
3841}
3842
3843/// parseDirectiveCFIStartProc
3844/// ::= .cfi_startproc [simple]
3845bool AsmParser::parseDirectiveCFIStartProc() {
3846 StringRef Simple;
3847 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
3848 if (check(parseIdentifier(Simple) || Simple != "simple",
3849 "unexpected token") ||
3850 parseToken(AsmToken::EndOfStatement))
3851 return addErrorSuffix(" in '.cfi_startproc' directive");
3852 }
3853
3854 getStreamer().EmitCFIStartProc(!Simple.empty());
3855 return false;
3856}
3857
3858/// parseDirectiveCFIEndProc
3859/// ::= .cfi_endproc
3860bool AsmParser::parseDirectiveCFIEndProc() {
3861 getStreamer().EmitCFIEndProc();
3862 return false;
3863}
3864
3865/// \brief parse register name or number.
3866bool AsmParser::parseRegisterOrRegisterNumber(int64_t &Register,
3867 SMLoc DirectiveLoc) {
3868 unsigned RegNo;
3869
3870 if (getLexer().isNot(AsmToken::Integer)) {
3871 if (getTargetParser().ParseRegister(RegNo, DirectiveLoc, DirectiveLoc))
3872 return true;
3873 Register = getContext().getRegisterInfo()->getDwarfRegNum(RegNo, true);
3874 } else
3875 return parseAbsoluteExpression(Register);
3876
3877 return false;
3878}
3879
3880/// parseDirectiveCFIDefCfa
3881/// ::= .cfi_def_cfa register, offset
3882bool AsmParser::parseDirectiveCFIDefCfa(SMLoc DirectiveLoc) {
3883 int64_t Register = 0, Offset = 0;
3884 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3885 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3886 parseAbsoluteExpression(Offset))
3887 return true;
3888
3889 getStreamer().EmitCFIDefCfa(Register, Offset);
3890 return false;
3891}
3892
3893/// parseDirectiveCFIDefCfaOffset
3894/// ::= .cfi_def_cfa_offset offset
3895bool AsmParser::parseDirectiveCFIDefCfaOffset() {
3896 int64_t Offset = 0;
3897 if (parseAbsoluteExpression(Offset))
3898 return true;
3899
3900 getStreamer().EmitCFIDefCfaOffset(Offset);
3901 return false;
3902}
3903
3904/// parseDirectiveCFIRegister
3905/// ::= .cfi_register register, register
3906bool AsmParser::parseDirectiveCFIRegister(SMLoc DirectiveLoc) {
3907 int64_t Register1 = 0, Register2 = 0;
3908 if (parseRegisterOrRegisterNumber(Register1, DirectiveLoc) ||
3909 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3910 parseRegisterOrRegisterNumber(Register2, DirectiveLoc))
3911 return true;
3912
3913 getStreamer().EmitCFIRegister(Register1, Register2);
3914 return false;
3915}
3916
3917/// parseDirectiveCFIWindowSave
3918/// ::= .cfi_window_save
3919bool AsmParser::parseDirectiveCFIWindowSave() {
3920 getStreamer().EmitCFIWindowSave();
3921 return false;
3922}
3923
3924/// parseDirectiveCFIAdjustCfaOffset
3925/// ::= .cfi_adjust_cfa_offset adjustment
3926bool AsmParser::parseDirectiveCFIAdjustCfaOffset() {
3927 int64_t Adjustment = 0;
3928 if (parseAbsoluteExpression(Adjustment))
3929 return true;
3930
3931 getStreamer().EmitCFIAdjustCfaOffset(Adjustment);
3932 return false;
3933}
3934
3935/// parseDirectiveCFIDefCfaRegister
3936/// ::= .cfi_def_cfa_register register
3937bool AsmParser::parseDirectiveCFIDefCfaRegister(SMLoc DirectiveLoc) {
3938 int64_t Register = 0;
3939 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
3940 return true;
3941
3942 getStreamer().EmitCFIDefCfaRegister(Register);
3943 return false;
3944}
3945
3946/// parseDirectiveCFIOffset
3947/// ::= .cfi_offset register, offset
3948bool AsmParser::parseDirectiveCFIOffset(SMLoc DirectiveLoc) {
3949 int64_t Register = 0;
3950 int64_t Offset = 0;
3951
3952 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3953 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3954 parseAbsoluteExpression(Offset))
3955 return true;
3956
3957 getStreamer().EmitCFIOffset(Register, Offset);
3958 return false;
3959}
3960
3961/// parseDirectiveCFIRelOffset
3962/// ::= .cfi_rel_offset register, offset
3963bool AsmParser::parseDirectiveCFIRelOffset(SMLoc DirectiveLoc) {
3964 int64_t Register = 0, Offset = 0;
3965
3966 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc) ||
3967 parseToken(AsmToken::Comma, "unexpected token in directive") ||
3968 parseAbsoluteExpression(Offset))
3969 return true;
3970
3971 getStreamer().EmitCFIRelOffset(Register, Offset);
3972 return false;
3973}
3974
3975static bool isValidEncoding(int64_t Encoding) {
3976 if (Encoding & ~0xff)
3977 return false;
3978
3979 if (Encoding == dwarf::DW_EH_PE_omit)
3980 return true;
3981
3982 const unsigned Format = Encoding & 0xf;
3983 if (Format != dwarf::DW_EH_PE_absptr && Format != dwarf::DW_EH_PE_udata2 &&
3984 Format != dwarf::DW_EH_PE_udata4 && Format != dwarf::DW_EH_PE_udata8 &&
3985 Format != dwarf::DW_EH_PE_sdata2 && Format != dwarf::DW_EH_PE_sdata4 &&
3986 Format != dwarf::DW_EH_PE_sdata8 && Format != dwarf::DW_EH_PE_signed)
3987 return false;
3988
3989 const unsigned Application = Encoding & 0x70;
3990 if (Application != dwarf::DW_EH_PE_absptr &&
3991 Application != dwarf::DW_EH_PE_pcrel)
3992 return false;
3993
3994 return true;
3995}
3996
3997/// parseDirectiveCFIPersonalityOrLsda
3998/// IsPersonality true for cfi_personality, false for cfi_lsda
3999/// ::= .cfi_personality encoding, [symbol_name]
4000/// ::= .cfi_lsda encoding, [symbol_name]
4001bool AsmParser::parseDirectiveCFIPersonalityOrLsda(bool IsPersonality) {
4002 int64_t Encoding = 0;
4003 if (parseAbsoluteExpression(Encoding))
4004 return true;
4005 if (Encoding == dwarf::DW_EH_PE_omit)
4006 return false;
4007
4008 StringRef Name;
4009 if (check(!isValidEncoding(Encoding), "unsupported encoding.") ||
4010 parseToken(AsmToken::Comma, "unexpected token in directive") ||
4011 check(parseIdentifier(Name), "expected identifier in directive"))
4012 return true;
4013
4014 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4015
4016 if (IsPersonality)
4017 getStreamer().EmitCFIPersonality(Sym, Encoding);
4018 else
4019 getStreamer().EmitCFILsda(Sym, Encoding);
4020 return false;
4021}
4022
4023/// parseDirectiveCFIRememberState
4024/// ::= .cfi_remember_state
4025bool AsmParser::parseDirectiveCFIRememberState() {
4026 getStreamer().EmitCFIRememberState();
4027 return false;
4028}
4029
4030/// parseDirectiveCFIRestoreState
4031/// ::= .cfi_remember_state
4032bool AsmParser::parseDirectiveCFIRestoreState() {
4033 getStreamer().EmitCFIRestoreState();
4034 return false;
4035}
4036
4037/// parseDirectiveCFISameValue
4038/// ::= .cfi_same_value register
4039bool AsmParser::parseDirectiveCFISameValue(SMLoc DirectiveLoc) {
4040 int64_t Register = 0;
4041
4042 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4043 return true;
4044
4045 getStreamer().EmitCFISameValue(Register);
4046 return false;
4047}
4048
4049/// parseDirectiveCFIRestore
4050/// ::= .cfi_restore register
4051bool AsmParser::parseDirectiveCFIRestore(SMLoc DirectiveLoc) {
4052 int64_t Register = 0;
4053 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4054 return true;
4055
4056 getStreamer().EmitCFIRestore(Register);
4057 return false;
4058}
4059
4060/// parseDirectiveCFIEscape
4061/// ::= .cfi_escape expression[,...]
4062bool AsmParser::parseDirectiveCFIEscape() {
4063 std::string Values;
4064 int64_t CurrValue;
4065 if (parseAbsoluteExpression(CurrValue))
4066 return true;
4067
4068 Values.push_back((uint8_t)CurrValue);
4069
4070 while (getLexer().is(AsmToken::Comma)) {
4071 Lex();
4072
4073 if (parseAbsoluteExpression(CurrValue))
4074 return true;
4075
4076 Values.push_back((uint8_t)CurrValue);
4077 }
4078
4079 getStreamer().EmitCFIEscape(Values);
4080 return false;
4081}
4082
4083/// parseDirectiveCFIReturnColumn
4084/// ::= .cfi_return_column register
4085bool AsmParser::parseDirectiveCFIReturnColumn(SMLoc DirectiveLoc) {
4086 int64_t Register = 0;
4087 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4088 return true;
4089 getStreamer().EmitCFIReturnColumn(Register);
4090 return false;
4091}
4092
4093/// parseDirectiveCFISignalFrame
4094/// ::= .cfi_signal_frame
4095bool AsmParser::parseDirectiveCFISignalFrame() {
4096 if (parseToken(AsmToken::EndOfStatement,
4097 "unexpected token in '.cfi_signal_frame'"))
4098 return true;
4099
4100 getStreamer().EmitCFISignalFrame();
4101 return false;
4102}
4103
4104/// parseDirectiveCFIUndefined
4105/// ::= .cfi_undefined register
4106bool AsmParser::parseDirectiveCFIUndefined(SMLoc DirectiveLoc) {
4107 int64_t Register = 0;
4108
4109 if (parseRegisterOrRegisterNumber(Register, DirectiveLoc))
4110 return true;
4111
4112 getStreamer().EmitCFIUndefined(Register);
4113 return false;
4114}
4115
4116/// parseDirectiveAltmacro
4117/// ::= .altmacro
4118/// ::= .noaltmacro
4119bool AsmParser::parseDirectiveAltmacro(StringRef Directive) {
4120 if (getLexer().isNot(AsmToken::EndOfStatement))
4121 return TokError("unexpected token in '" + Directive + "' directive");
4122 if (Directive == ".altmacro")
4123 getLexer().SetAltMacroMode(true);
4124 else
4125 getLexer().SetAltMacroMode(false);
4126 return false;
4127}
4128
4129/// parseDirectiveMacrosOnOff
4130/// ::= .macros_on
4131/// ::= .macros_off
4132bool AsmParser::parseDirectiveMacrosOnOff(StringRef Directive) {
4133 if (parseToken(AsmToken::EndOfStatement,
4134 "unexpected token in '" + Directive + "' directive"))
4135 return true;
4136
4137 setMacrosEnabled(Directive == ".macros_on");
4138 return false;
4139}
4140
4141/// parseDirectiveMacro
4142/// ::= .macro name[,] [parameters]
4143bool AsmParser::parseDirectiveMacro(SMLoc DirectiveLoc) {
4144 StringRef Name;
4145 if (parseIdentifier(Name))
4146 return TokError("expected identifier in '.macro' directive");
4147
4148 if (getLexer().is(AsmToken::Comma))
4149 Lex();
4150
4151 MCAsmMacroParameters Parameters;
4152 while (getLexer().isNot(AsmToken::EndOfStatement)) {
4153
4154 if (!Parameters.empty() && Parameters.back().Vararg)
4155 return Error(Lexer.getLoc(),
4156 "Vararg parameter '" + Parameters.back().Name +
4157 "' should be last one in the list of parameters.");
4158
4159 MCAsmMacroParameter Parameter;
4160 if (parseIdentifier(Parameter.Name))
4161 return TokError("expected identifier in '.macro' directive");
4162
4163 // Emit an error if two (or more) named parameters share the same name
4164 for (const MCAsmMacroParameter& CurrParam : Parameters)
4165 if (CurrParam.Name.equals(Parameter.Name))
4166 return TokError("macro '" + Name + "' has multiple parameters"
4167 " named '" + Parameter.Name + "'");
4168
4169 if (Lexer.is(AsmToken::Colon)) {
4170 Lex(); // consume ':'
4171
4172 SMLoc QualLoc;
4173 StringRef Qualifier;
4174
4175 QualLoc = Lexer.getLoc();
4176 if (parseIdentifier(Qualifier))
4177 return Error(QualLoc, "missing parameter qualifier for "
4178 "'" + Parameter.Name + "' in macro '" + Name + "'");
4179
4180 if (Qualifier == "req")
4181 Parameter.Required = true;
4182 else if (Qualifier == "vararg")
4183 Parameter.Vararg = true;
4184 else
4185 return Error(QualLoc, Qualifier + " is not a valid parameter qualifier "
4186 "for '" + Parameter.Name + "' in macro '" + Name + "'");
4187 }
4188
4189 if (getLexer().is(AsmToken::Equal)) {
4190 Lex();
4191
4192 SMLoc ParamLoc;
4193
4194 ParamLoc = Lexer.getLoc();
4195 if (parseMacroArgument(Parameter.Value, /*Vararg=*/false ))
4196 return true;
4197
4198 if (Parameter.Required)
4199 Warning(ParamLoc, "pointless default value for required parameter "
4200 "'" + Parameter.Name + "' in macro '" + Name + "'");
4201 }
4202
4203 Parameters.push_back(std::move(Parameter));
4204
4205 if (getLexer().is(AsmToken::Comma))
4206 Lex();
4207 }
4208
4209 // Eat just the end of statement.
4210 Lexer.Lex();
4211
4212 // Consuming deferred text, so use Lexer.Lex to ignore Lexing Errors
4213 AsmToken EndToken, StartToken = getTok();
4214 unsigned MacroDepth = 0;
4215 // Lex the macro definition.
4216 while (true) {
4217 // Ignore Lexing errors in macros.
4218 while (Lexer.is(AsmToken::Error)) {
4219 Lexer.Lex();
4220 }
4221
4222 // Check whether we have reached the end of the file.
4223 if (getLexer().is(AsmToken::Eof))
4224 return Error(DirectiveLoc, "no matching '.endmacro' in definition");
4225
4226 // Otherwise, check whether we have reach the .endmacro.
4227 if (getLexer().is(AsmToken::Identifier)) {
4228 if (getTok().getIdentifier() == ".endm" ||
4229 getTok().getIdentifier() == ".endmacro") {
4230 if (MacroDepth == 0) { // Outermost macro.
4231 EndToken = getTok();
4232 Lexer.Lex();
4233 if (getLexer().isNot(AsmToken::EndOfStatement))
4234 return TokError("unexpected token in '" + EndToken.getIdentifier() +
4235 "' directive");
4236 break;
4237 } else {
4238 // Otherwise we just found the end of an inner macro.
4239 --MacroDepth;
4240 }
4241 } else if (getTok().getIdentifier() == ".macro") {
4242 // We allow nested macros. Those aren't instantiated until the outermost
4243 // macro is expanded so just ignore them for now.
4244 ++MacroDepth;
4245 }
4246 }
4247
4248 // Otherwise, scan til the end of the statement.
4249 eatToEndOfStatement();
4250 }
4251
4252 if (getContext().lookupMacro(Name)) {
4253 return Error(DirectiveLoc, "macro '" + Name + "' is already defined");
4254 }
4255
4256 const char *BodyStart = StartToken.getLoc().getPointer();
4257 const char *BodyEnd = EndToken.getLoc().getPointer();
4258 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
4259 checkForBadMacro(DirectiveLoc, Name, Body, Parameters);
4260 getContext().defineMacro(Name, MCAsmMacro(Name, Body, std::move(Parameters)));
4261 return false;
4262}
4263
4264/// checkForBadMacro
4265///
4266/// With the support added for named parameters there may be code out there that
4267/// is transitioning from positional parameters. In versions of gas that did
4268/// not support named parameters they would be ignored on the macro definition.
4269/// But to support both styles of parameters this is not possible so if a macro
4270/// definition has named parameters but does not use them and has what appears
4271/// to be positional parameters, strings like $1, $2, ... and $n, then issue a
4272/// warning that the positional parameter found in body which have no effect.
4273/// Hoping the developer will either remove the named parameters from the macro
4274/// definition so the positional parameters get used if that was what was
4275/// intended or change the macro to use the named parameters. It is possible
4276/// this warning will trigger when the none of the named parameters are used
4277/// and the strings like $1 are infact to simply to be passed trough unchanged.
4278void AsmParser::checkForBadMacro(SMLoc DirectiveLoc, StringRef Name,
4279 StringRef Body,
4280 ArrayRef<MCAsmMacroParameter> Parameters) {
4281 // If this macro is not defined with named parameters the warning we are
4282 // checking for here doesn't apply.
4283 unsigned NParameters = Parameters.size();
4284 if (NParameters == 0)
4285 return;
4286
4287 bool NamedParametersFound = false;
4288 bool PositionalParametersFound = false;
4289
4290 // Look at the body of the macro for use of both the named parameters and what
4291 // are likely to be positional parameters. This is what expandMacro() is
4292 // doing when it finds the parameters in the body.
4293 while (!Body.empty()) {
4294 // Scan for the next possible parameter.
4295 std::size_t End = Body.size(), Pos = 0;
4296 for (; Pos != End; ++Pos) {
4297 // Check for a substitution or escape.
4298 // This macro is defined with parameters, look for \foo, \bar, etc.
4299 if (Body[Pos] == '\\' && Pos + 1 != End)
4300 break;
4301
4302 // This macro should have parameters, but look for $0, $1, ..., $n too.
4303 if (Body[Pos] != '$' || Pos + 1 == End)
4304 continue;
4305 char Next = Body[Pos + 1];
4306 if (Next == '$' || Next == 'n' ||
4307 isdigit(static_cast<unsigned char>(Next)))
4308 break;
4309 }
4310
4311 // Check if we reached the end.
4312 if (Pos == End)
4313 break;
4314
4315 if (Body[Pos] == '$') {
4316 switch (Body[Pos + 1]) {
4317 // $$ => $
4318 case '$':
4319 break;
4320
4321 // $n => number of arguments
4322 case 'n':
4323 PositionalParametersFound = true;
4324 break;
4325
4326 // $[0-9] => argument
4327 default: {
4328 PositionalParametersFound = true;
4329 break;
4330 }
4331 }
4332 Pos += 2;
4333 } else {
4334 unsigned I = Pos + 1;
4335 while (isIdentifierChar(Body[I]) && I + 1 != End)
4336 ++I;
4337
4338 const char *Begin = Body.data() + Pos + 1;
4339 StringRef Argument(Begin, I - (Pos + 1));
4340 unsigned Index = 0;
4341 for (; Index < NParameters; ++Index)
4342 if (Parameters[Index].Name == Argument)
4343 break;
4344
4345 if (Index == NParameters) {
4346 if (Body[Pos + 1] == '(' && Body[Pos + 2] == ')')
4347 Pos += 3;
4348 else {
4349 Pos = I;
4350 }
4351 } else {
4352 NamedParametersFound = true;
4353 Pos += 1 + Argument.size();
4354 }
4355 }
4356 // Update the scan point.
4357 Body = Body.substr(Pos);
4358 }
4359
4360 if (!NamedParametersFound && PositionalParametersFound)
4361 Warning(DirectiveLoc, "macro defined with named parameters which are not "
4362 "used in macro body, possible positional parameter "
4363 "found in body which will have no effect");
4364}
4365
4366/// parseDirectiveExitMacro
4367/// ::= .exitm
4368bool AsmParser::parseDirectiveExitMacro(StringRef Directive) {
4369 if (parseToken(AsmToken::EndOfStatement,
4370 "unexpected token in '" + Directive + "' directive"))
4371 return true;
4372
4373 if (!isInsideMacroInstantiation())
4374 return TokError("unexpected '" + Directive + "' in file, "
4375 "no current macro definition");
4376
4377 // Exit all conditionals that are active in the current macro.
4378 while (TheCondStack.size() != ActiveMacros.back()->CondStackDepth) {
4379 TheCondState = TheCondStack.back();
4380 TheCondStack.pop_back();
4381 }
4382
4383 handleMacroExit();
4384 return false;
4385}
4386
4387/// parseDirectiveEndMacro
4388/// ::= .endm
4389/// ::= .endmacro
4390bool AsmParser::parseDirectiveEndMacro(StringRef Directive) {
4391 if (getLexer().isNot(AsmToken::EndOfStatement))
4392 return TokError("unexpected token in '" + Directive + "' directive");
4393
4394 // If we are inside a macro instantiation, terminate the current
4395 // instantiation.
4396 if (isInsideMacroInstantiation()) {
4397 handleMacroExit();
4398 return false;
4399 }
4400
4401 // Otherwise, this .endmacro is a stray entry in the file; well formed
4402 // .endmacro directives are handled during the macro definition parsing.
4403 return TokError("unexpected '" + Directive + "' in file, "
4404 "no current macro definition");
4405}
4406
4407/// parseDirectivePurgeMacro
4408/// ::= .purgem
4409bool AsmParser::parseDirectivePurgeMacro(SMLoc DirectiveLoc) {
4410 StringRef Name;
4411 SMLoc Loc;
4412 if (parseTokenLoc(Loc) ||
4413 check(parseIdentifier(Name), Loc,
4414 "expected identifier in '.purgem' directive") ||
4415 parseToken(AsmToken::EndOfStatement,
4416 "unexpected token in '.purgem' directive"))
4417 return true;
4418
4419 if (!getContext().lookupMacro(Name))
4420 return Error(DirectiveLoc, "macro '" + Name + "' is not defined");
4421
4422 getContext().undefineMacro(Name);
4423 return false;
4424}
4425
4426/// parseDirectiveBundleAlignMode
4427/// ::= {.bundle_align_mode} expression
4428bool AsmParser::parseDirectiveBundleAlignMode() {
4429 // Expect a single argument: an expression that evaluates to a constant
4430 // in the inclusive range 0-30.
4431 SMLoc ExprLoc = getLexer().getLoc();
4432 int64_t AlignSizePow2;
4433 if (checkForValidSection() || parseAbsoluteExpression(AlignSizePow2) ||
4434 parseToken(AsmToken::EndOfStatement, "unexpected token after expression "
4435 "in '.bundle_align_mode' "
4436 "directive") ||
4437 check(AlignSizePow2 < 0 || AlignSizePow2 > 30, ExprLoc,
4438 "invalid bundle alignment size (expected between 0 and 30)"))
4439 return true;
4440
4441 // Because of AlignSizePow2's verified range we can safely truncate it to
4442 // unsigned.
4443 getStreamer().EmitBundleAlignMode(static_cast<unsigned>(AlignSizePow2));
4444 return false;
4445}
4446
4447/// parseDirectiveBundleLock
4448/// ::= {.bundle_lock} [align_to_end]
4449bool AsmParser::parseDirectiveBundleLock() {
4450 if (checkForValidSection())
4451 return true;
4452 bool AlignToEnd = false;
4453
4454 StringRef Option;
4455 SMLoc Loc = getTok().getLoc();
4456 const char *kInvalidOptionError =
4457 "invalid option for '.bundle_lock' directive";
4458
4459 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
4460 if (check(parseIdentifier(Option), Loc, kInvalidOptionError) ||
4461 check(Option != "align_to_end", Loc, kInvalidOptionError) ||
4462 parseToken(AsmToken::EndOfStatement,
4463 "unexpected token after '.bundle_lock' directive option"))
4464 return true;
4465 AlignToEnd = true;
4466 }
4467
4468 getStreamer().EmitBundleLock(AlignToEnd);
4469 return false;
4470}
4471
4472/// parseDirectiveBundleLock
4473/// ::= {.bundle_lock}
4474bool AsmParser::parseDirectiveBundleUnlock() {
4475 if (checkForValidSection() ||
4476 parseToken(AsmToken::EndOfStatement,
4477 "unexpected token in '.bundle_unlock' directive"))
4478 return true;
4479
4480 getStreamer().EmitBundleUnlock();
4481 return false;
4482}
4483
4484/// parseDirectiveSpace
4485/// ::= (.skip | .space) expression [ , expression ]
4486bool AsmParser::parseDirectiveSpace(StringRef IDVal) {
4487 SMLoc NumBytesLoc = Lexer.getLoc();
4488 const MCExpr *NumBytes;
4489 if (checkForValidSection() || parseExpression(NumBytes))
4490 return true;
4491
4492 int64_t FillExpr = 0;
4493 if (parseOptionalToken(AsmToken::Comma))
4494 if (parseAbsoluteExpression(FillExpr))
4495 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4496 if (parseToken(AsmToken::EndOfStatement))
4497 return addErrorSuffix("in '" + Twine(IDVal) + "' directive");
4498
4499 // FIXME: Sometimes the fill expr is 'nop' if it isn't supplied, instead of 0.
4500 getStreamer().emitFill(*NumBytes, FillExpr, NumBytesLoc);
4501
4502 return false;
4503}
4504
4505/// parseDirectiveDCB
4506/// ::= .dcb.{b, l, w} expression, expression
4507bool AsmParser::parseDirectiveDCB(StringRef IDVal, unsigned Size) {
4508 SMLoc NumValuesLoc = Lexer.getLoc();
4509 int64_t NumValues;
4510 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4511 return true;
4512
4513 if (NumValues < 0) {
4514 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4515 return false;
4516 }
4517
4518 if (parseToken(AsmToken::Comma,
4519 "unexpected token in '" + Twine(IDVal) + "' directive"))
4520 return true;
4521
4522 const MCExpr *Value;
4523 SMLoc ExprLoc = getLexer().getLoc();
4524 if (parseExpression(Value))
4525 return true;
4526
4527 // Special case constant expressions to match code generator.
4528 if (const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value)) {
4529 assert(Size <= 8 && "Invalid size")(static_cast <bool> (Size <= 8 && "Invalid size"
) ? void (0) : __assert_fail ("Size <= 8 && \"Invalid size\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 4529, __extension__ __PRETTY_FUNCTION__))
;
4530 uint64_t IntValue = MCE->getValue();
4531 if (!isUIntN(8 * Size, IntValue) && !isIntN(8 * Size, IntValue))
4532 return Error(ExprLoc, "literal value out of range for directive");
4533 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4534 getStreamer().EmitIntValue(IntValue, Size);
4535 } else {
4536 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4537 getStreamer().EmitValue(Value, Size, ExprLoc);
4538 }
4539
4540 if (parseToken(AsmToken::EndOfStatement,
4541 "unexpected token in '" + Twine(IDVal) + "' directive"))
4542 return true;
4543
4544 return false;
4545}
4546
4547/// parseDirectiveRealDCB
4548/// ::= .dcb.{d, s} expression, expression
4549bool AsmParser::parseDirectiveRealDCB(StringRef IDVal, const fltSemantics &Semantics) {
4550 SMLoc NumValuesLoc = Lexer.getLoc();
4551 int64_t NumValues;
4552 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4553 return true;
4554
4555 if (NumValues < 0) {
4556 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4557 return false;
4558 }
4559
4560 if (parseToken(AsmToken::Comma,
4561 "unexpected token in '" + Twine(IDVal) + "' directive"))
4562 return true;
4563
4564 APInt AsInt;
4565 if (parseRealValue(Semantics, AsInt))
4566 return true;
4567
4568 if (parseToken(AsmToken::EndOfStatement,
4569 "unexpected token in '" + Twine(IDVal) + "' directive"))
4570 return true;
4571
4572 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4573 getStreamer().EmitIntValue(AsInt.getLimitedValue(),
4574 AsInt.getBitWidth() / 8);
4575
4576 return false;
4577}
4578
4579/// parseDirectiveDS
4580/// ::= .ds.{b, d, l, p, s, w, x} expression
4581bool AsmParser::parseDirectiveDS(StringRef IDVal, unsigned Size) {
4582 SMLoc NumValuesLoc = Lexer.getLoc();
4583 int64_t NumValues;
4584 if (checkForValidSection() || parseAbsoluteExpression(NumValues))
4585 return true;
4586
4587 if (NumValues < 0) {
4588 Warning(NumValuesLoc, "'" + Twine(IDVal) + "' directive with negative repeat count has no effect");
4589 return false;
4590 }
4591
4592 if (parseToken(AsmToken::EndOfStatement,
4593 "unexpected token in '" + Twine(IDVal) + "' directive"))
4594 return true;
4595
4596 for (uint64_t i = 0, e = NumValues; i != e; ++i)
4597 getStreamer().emitFill(Size, 0);
4598
4599 return false;
4600}
4601
4602/// parseDirectiveLEB128
4603/// ::= (.sleb128 | .uleb128) [ expression (, expression)* ]
4604bool AsmParser::parseDirectiveLEB128(bool Signed) {
4605 if (checkForValidSection())
4606 return true;
4607
4608 auto parseOp = [&]() -> bool {
4609 const MCExpr *Value;
4610 if (parseExpression(Value))
4611 return true;
4612 if (Signed)
4613 getStreamer().EmitSLEB128Value(Value);
4614 else
4615 getStreamer().EmitULEB128Value(Value);
4616 return false;
4617 };
4618
4619 if (parseMany(parseOp))
4620 return addErrorSuffix(" in directive");
4621
4622 return false;
4623}
4624
4625/// parseDirectiveSymbolAttribute
4626/// ::= { ".globl", ".weak", ... } [ identifier ( , identifier )* ]
4627bool AsmParser::parseDirectiveSymbolAttribute(MCSymbolAttr Attr) {
4628 auto parseOp = [&]() -> bool {
4629 StringRef Name;
4630 SMLoc Loc = getTok().getLoc();
4631 if (parseIdentifier(Name))
4632 return Error(Loc, "expected identifier");
4633 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4634
4635 // Assembler local symbols don't make any sense here. Complain loudly.
4636 if (Sym->isTemporary())
4637 return Error(Loc, "non-local symbol required");
4638
4639 if (!getStreamer().EmitSymbolAttribute(Sym, Attr))
4640 return Error(Loc, "unable to emit symbol attribute");
4641 return false;
4642 };
4643
4644 if (parseMany(parseOp))
4645 return addErrorSuffix(" in directive");
4646 return false;
4647}
4648
4649/// parseDirectiveComm
4650/// ::= ( .comm | .lcomm ) identifier , size_expression [ , align_expression ]
4651bool AsmParser::parseDirectiveComm(bool IsLocal) {
4652 if (checkForValidSection())
4653 return true;
4654
4655 SMLoc IDLoc = getLexer().getLoc();
4656 StringRef Name;
4657 if (parseIdentifier(Name))
4658 return TokError("expected identifier in directive");
4659
4660 // Handle the identifier as the key symbol.
4661 MCSymbol *Sym = getContext().getOrCreateSymbol(Name);
4662
4663 if (getLexer().isNot(AsmToken::Comma))
4664 return TokError("unexpected token in directive");
4665 Lex();
4666
4667 int64_t Size;
4668 SMLoc SizeLoc = getLexer().getLoc();
4669 if (parseAbsoluteExpression(Size))
4670 return true;
4671
4672 int64_t Pow2Alignment = 0;
4673 SMLoc Pow2AlignmentLoc;
4674 if (getLexer().is(AsmToken::Comma)) {
4675 Lex();
4676 Pow2AlignmentLoc = getLexer().getLoc();
4677 if (parseAbsoluteExpression(Pow2Alignment))
4678 return true;
4679
4680 LCOMM::LCOMMType LCOMM = Lexer.getMAI().getLCOMMDirectiveAlignmentType();
4681 if (IsLocal && LCOMM == LCOMM::NoAlignment)
4682 return Error(Pow2AlignmentLoc, "alignment not supported on this target");
4683
4684 // If this target takes alignments in bytes (not log) validate and convert.
4685 if ((!IsLocal && Lexer.getMAI().getCOMMDirectiveAlignmentIsInBytes()) ||
4686 (IsLocal && LCOMM == LCOMM::ByteAlignment)) {
4687 if (!isPowerOf2_64(Pow2Alignment))
4688 return Error(Pow2AlignmentLoc, "alignment must be a power of 2");
4689 Pow2Alignment = Log2_64(Pow2Alignment);
4690 }
4691 }
4692
4693 if (parseToken(AsmToken::EndOfStatement,
4694 "unexpected token in '.comm' or '.lcomm' directive"))
4695 return true;
4696
4697 // NOTE: a size of zero for a .comm should create a undefined symbol
4698 // but a size of .lcomm creates a bss symbol of size zero.
4699 if (Size < 0)
4700 return Error(SizeLoc, "invalid '.comm' or '.lcomm' directive size, can't "
4701 "be less than zero");
4702
4703 // NOTE: The alignment in the directive is a power of 2 value, the assembler
4704 // may internally end up wanting an alignment in bytes.
4705 // FIXME: Diagnose overflow.
4706 if (Pow2Alignment < 0)
4707 return Error(Pow2AlignmentLoc, "invalid '.comm' or '.lcomm' directive "
4708 "alignment, can't be less than zero");
4709
4710 Sym->redefineIfPossible();
4711 if (!Sym->isUndefined())
4712 return Error(IDLoc, "invalid symbol redefinition");
4713
4714 // Create the Symbol as a common or local common with Size and Pow2Alignment
4715 if (IsLocal) {
4716 getStreamer().EmitLocalCommonSymbol(Sym, Size, 1 << Pow2Alignment);
4717 return false;
4718 }
4719
4720 getStreamer().EmitCommonSymbol(Sym, Size, 1 << Pow2Alignment);
4721 return false;
4722}
4723
4724/// parseDirectiveAbort
4725/// ::= .abort [... message ...]
4726bool AsmParser::parseDirectiveAbort() {
4727 // FIXME: Use loc from directive.
4728 SMLoc Loc = getLexer().getLoc();
4729
4730 StringRef Str = parseStringToEndOfStatement();
4731 if (parseToken(AsmToken::EndOfStatement,
4732 "unexpected token in '.abort' directive"))
4733 return true;
4734
4735 if (Str.empty())
4736 return Error(Loc, ".abort detected. Assembly stopping.");
4737 else
4738 return Error(Loc, ".abort '" + Str + "' detected. Assembly stopping.");
4739 // FIXME: Actually abort assembly here.
4740
4741 return false;
4742}
4743
4744/// parseDirectiveInclude
4745/// ::= .include "filename"
4746bool AsmParser::parseDirectiveInclude() {
4747 // Allow the strings to have escaped octal character sequence.
4748 std::string Filename;
4749 SMLoc IncludeLoc = getTok().getLoc();
4750
4751 if (check(getTok().isNot(AsmToken::String),
4752 "expected string in '.include' directive") ||
4753 parseEscapedString(Filename) ||
4754 check(getTok().isNot(AsmToken::EndOfStatement),
4755 "unexpected token in '.include' directive") ||
4756 // Attempt to switch the lexer to the included file before consuming the
4757 // end of statement to avoid losing it when we switch.
4758 check(enterIncludeFile(Filename), IncludeLoc,
4759 "Could not find include file '" + Filename + "'"))
4760 return true;
4761
4762 return false;
4763}
4764
4765/// parseDirectiveIncbin
4766/// ::= .incbin "filename" [ , skip [ , count ] ]
4767bool AsmParser::parseDirectiveIncbin() {
4768 // Allow the strings to have escaped octal character sequence.
4769 std::string Filename;
4770 SMLoc IncbinLoc = getTok().getLoc();
4771 if (check(getTok().isNot(AsmToken::String),
4772 "expected string in '.incbin' directive") ||
4773 parseEscapedString(Filename))
4774 return true;
4775
4776 int64_t Skip = 0;
4777 const MCExpr *Count = nullptr;
4778 SMLoc SkipLoc, CountLoc;
4779 if (parseOptionalToken(AsmToken::Comma)) {
4780 // The skip expression can be omitted while specifying the count, e.g:
4781 // .incbin "filename",,4
4782 if (getTok().isNot(AsmToken::Comma)) {
4783 if (parseTokenLoc(SkipLoc) || parseAbsoluteExpression(Skip))
4784 return true;
4785 }
4786 if (parseOptionalToken(AsmToken::Comma)) {
4787 CountLoc = getTok().getLoc();
4788 if (parseExpression(Count))
4789 return true;
4790 }
4791 }
4792
4793 if (parseToken(AsmToken::EndOfStatement,
4794 "unexpected token in '.incbin' directive"))
4795 return true;
4796
4797 if (check(Skip < 0, SkipLoc, "skip is negative"))
4798 return true;
4799
4800 // Attempt to process the included file.
4801 if (processIncbinFile(Filename, Skip, Count, CountLoc))
4802 return Error(IncbinLoc, "Could not find incbin file '" + Filename + "'");
4803 return false;
4804}
4805
4806/// parseDirectiveIf
4807/// ::= .if{,eq,ge,gt,le,lt,ne} expression
4808bool AsmParser::parseDirectiveIf(SMLoc DirectiveLoc, DirectiveKind DirKind) {
4809 TheCondStack.push_back(TheCondState);
4810 TheCondState.TheCond = AsmCond::IfCond;
4811 if (TheCondState.Ignore) {
4812 eatToEndOfStatement();
4813 } else {
4814 int64_t ExprValue;
4815 if (parseAbsoluteExpression(ExprValue) ||
4816 parseToken(AsmToken::EndOfStatement,
4817 "unexpected token in '.if' directive"))
4818 return true;
4819
4820 switch (DirKind) {
4821 default:
4822 llvm_unreachable("unsupported directive")::llvm::llvm_unreachable_internal("unsupported directive", "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 4822)
;
4823 case DK_IF:
4824 case DK_IFNE:
4825 break;
4826 case DK_IFEQ:
4827 ExprValue = ExprValue == 0;
4828 break;
4829 case DK_IFGE:
4830 ExprValue = ExprValue >= 0;
4831 break;
4832 case DK_IFGT:
4833 ExprValue = ExprValue > 0;
4834 break;
4835 case DK_IFLE:
4836 ExprValue = ExprValue <= 0;
4837 break;
4838 case DK_IFLT:
4839 ExprValue = ExprValue < 0;
4840 break;
4841 }
4842
4843 TheCondState.CondMet = ExprValue;
4844 TheCondState.Ignore = !TheCondState.CondMet;
4845 }
4846
4847 return false;
4848}
4849
4850/// parseDirectiveIfb
4851/// ::= .ifb string
4852bool AsmParser::parseDirectiveIfb(SMLoc DirectiveLoc, bool ExpectBlank) {
4853 TheCondStack.push_back(TheCondState);
4854 TheCondState.TheCond = AsmCond::IfCond;
4855
4856 if (TheCondState.Ignore) {
4857 eatToEndOfStatement();
4858 } else {
4859 StringRef Str = parseStringToEndOfStatement();
4860
4861 if (parseToken(AsmToken::EndOfStatement,
4862 "unexpected token in '.ifb' directive"))
4863 return true;
4864
4865 TheCondState.CondMet = ExpectBlank == Str.empty();
4866 TheCondState.Ignore = !TheCondState.CondMet;
4867 }
4868
4869 return false;
4870}
4871
4872/// parseDirectiveIfc
4873/// ::= .ifc string1, string2
4874/// ::= .ifnc string1, string2
4875bool AsmParser::parseDirectiveIfc(SMLoc DirectiveLoc, bool ExpectEqual) {
4876 TheCondStack.push_back(TheCondState);
4877 TheCondState.TheCond = AsmCond::IfCond;
4878
4879 if (TheCondState.Ignore) {
4880 eatToEndOfStatement();
4881 } else {
4882 StringRef Str1 = parseStringToComma();
4883
4884 if (parseToken(AsmToken::Comma, "unexpected token in '.ifc' directive"))
4885 return true;
4886
4887 StringRef Str2 = parseStringToEndOfStatement();
4888
4889 if (parseToken(AsmToken::EndOfStatement,
4890 "unexpected token in '.ifc' directive"))
4891 return true;
4892
4893 TheCondState.CondMet = ExpectEqual == (Str1.trim() == Str2.trim());
4894 TheCondState.Ignore = !TheCondState.CondMet;
4895 }
4896
4897 return false;
4898}
4899
4900/// parseDirectiveIfeqs
4901/// ::= .ifeqs string1, string2
4902bool AsmParser::parseDirectiveIfeqs(SMLoc DirectiveLoc, bool ExpectEqual) {
4903 if (Lexer.isNot(AsmToken::String)) {
4904 if (ExpectEqual)
4905 return TokError("expected string parameter for '.ifeqs' directive");
4906 return TokError("expected string parameter for '.ifnes' directive");
4907 }
4908
4909 StringRef String1 = getTok().getStringContents();
4910 Lex();
4911
4912 if (Lexer.isNot(AsmToken::Comma)) {
4913 if (ExpectEqual)
4914 return TokError(
4915 "expected comma after first string for '.ifeqs' directive");
4916 return TokError("expected comma after first string for '.ifnes' directive");
4917 }
4918
4919 Lex();
4920
4921 if (Lexer.isNot(AsmToken::String)) {
4922 if (ExpectEqual)
4923 return TokError("expected string parameter for '.ifeqs' directive");
4924 return TokError("expected string parameter for '.ifnes' directive");
4925 }
4926
4927 StringRef String2 = getTok().getStringContents();
4928 Lex();
4929
4930 TheCondStack.push_back(TheCondState);
4931 TheCondState.TheCond = AsmCond::IfCond;
4932 TheCondState.CondMet = ExpectEqual == (String1 == String2);
4933 TheCondState.Ignore = !TheCondState.CondMet;
4934
4935 return false;
4936}
4937
4938/// parseDirectiveIfdef
4939/// ::= .ifdef symbol
4940bool AsmParser::parseDirectiveIfdef(SMLoc DirectiveLoc, bool expect_defined) {
4941 StringRef Name;
4942 TheCondStack.push_back(TheCondState);
4943 TheCondState.TheCond = AsmCond::IfCond;
4944
4945 if (TheCondState.Ignore) {
4946 eatToEndOfStatement();
4947 } else {
4948 if (check(parseIdentifier(Name), "expected identifier after '.ifdef'") ||
4949 parseToken(AsmToken::EndOfStatement, "unexpected token in '.ifdef'"))
4950 return true;
4951
4952 MCSymbol *Sym = getContext().lookupSymbol(Name);
4953
4954 if (expect_defined)
4955 TheCondState.CondMet = (Sym && !Sym->isUndefined());
4956 else
4957 TheCondState.CondMet = (!Sym || Sym->isUndefined());
4958 TheCondState.Ignore = !TheCondState.CondMet;
4959 }
4960
4961 return false;
4962}
4963
4964/// parseDirectiveElseIf
4965/// ::= .elseif expression
4966bool AsmParser::parseDirectiveElseIf(SMLoc DirectiveLoc) {
4967 if (TheCondState.TheCond != AsmCond::IfCond &&
4968 TheCondState.TheCond != AsmCond::ElseIfCond)
4969 return Error(DirectiveLoc, "Encountered a .elseif that doesn't follow an"
4970 " .if or an .elseif");
4971 TheCondState.TheCond = AsmCond::ElseIfCond;
4972
4973 bool LastIgnoreState = false;
4974 if (!TheCondStack.empty())
4975 LastIgnoreState = TheCondStack.back().Ignore;
4976 if (LastIgnoreState || TheCondState.CondMet) {
4977 TheCondState.Ignore = true;
4978 eatToEndOfStatement();
4979 } else {
4980 int64_t ExprValue;
4981 if (parseAbsoluteExpression(ExprValue))
4982 return true;
4983
4984 if (parseToken(AsmToken::EndOfStatement,
4985 "unexpected token in '.elseif' directive"))
4986 return true;
4987
4988 TheCondState.CondMet = ExprValue;
4989 TheCondState.Ignore = !TheCondState.CondMet;
4990 }
4991
4992 return false;
4993}
4994
4995/// parseDirectiveElse
4996/// ::= .else
4997bool AsmParser::parseDirectiveElse(SMLoc DirectiveLoc) {
4998 if (parseToken(AsmToken::EndOfStatement,
4999 "unexpected token in '.else' directive"))
5000 return true;
5001
5002 if (TheCondState.TheCond != AsmCond::IfCond &&
5003 TheCondState.TheCond != AsmCond::ElseIfCond)
5004 return Error(DirectiveLoc, "Encountered a .else that doesn't follow "
5005 " an .if or an .elseif");
5006 TheCondState.TheCond = AsmCond::ElseCond;
5007 bool LastIgnoreState = false;
5008 if (!TheCondStack.empty())
5009 LastIgnoreState = TheCondStack.back().Ignore;
5010 if (LastIgnoreState || TheCondState.CondMet)
5011 TheCondState.Ignore = true;
5012 else
5013 TheCondState.Ignore = false;
5014
5015 return false;
5016}
5017
5018/// parseDirectiveEnd
5019/// ::= .end
5020bool AsmParser::parseDirectiveEnd(SMLoc DirectiveLoc) {
5021 if (parseToken(AsmToken::EndOfStatement,
5022 "unexpected token in '.end' directive"))
5023 return true;
5024
5025 while (Lexer.isNot(AsmToken::Eof))
5026 Lexer.Lex();
5027
5028 return false;
5029}
5030
5031/// parseDirectiveError
5032/// ::= .err
5033/// ::= .error [string]
5034bool AsmParser::parseDirectiveError(SMLoc L, bool WithMessage) {
5035 if (!TheCondStack.empty()) {
5036 if (TheCondStack.back().Ignore) {
5037 eatToEndOfStatement();
5038 return false;
5039 }
5040 }
5041
5042 if (!WithMessage)
5043 return Error(L, ".err encountered");
5044
5045 StringRef Message = ".error directive invoked in source file";
5046 if (Lexer.isNot(AsmToken::EndOfStatement)) {
5047 if (Lexer.isNot(AsmToken::String))
5048 return TokError(".error argument must be a string");
5049
5050 Message = getTok().getStringContents();
5051 Lex();
5052 }
5053
5054 return Error(L, Message);
5055}
5056
5057/// parseDirectiveWarning
5058/// ::= .warning [string]
5059bool AsmParser::parseDirectiveWarning(SMLoc L) {
5060 if (!TheCondStack.empty()) {
5061 if (TheCondStack.back().Ignore) {
5062 eatToEndOfStatement();
5063 return false;
5064 }
5065 }
5066
5067 StringRef Message = ".warning directive invoked in source file";
5068
5069 if (!parseOptionalToken(AsmToken::EndOfStatement)) {
5070 if (Lexer.isNot(AsmToken::String))
5071 return TokError(".warning argument must be a string");
5072
5073 Message = getTok().getStringContents();
5074 Lex();
5075 if (parseToken(AsmToken::EndOfStatement,
5076 "expected end of statement in '.warning' directive"))
5077 return true;
5078 }
5079
5080 return Warning(L, Message);
5081}
5082
5083/// parseDirectiveEndIf
5084/// ::= .endif
5085bool AsmParser::parseDirectiveEndIf(SMLoc DirectiveLoc) {
5086 if (parseToken(AsmToken::EndOfStatement,
5087 "unexpected token in '.endif' directive"))
5088 return true;
5089
5090 if ((TheCondState.TheCond == AsmCond::NoCond) || TheCondStack.empty())
5091 return Error(DirectiveLoc, "Encountered a .endif that doesn't follow "
5092 "an .if or .else");
5093 if (!TheCondStack.empty()) {
5094 TheCondState = TheCondStack.back();
5095 TheCondStack.pop_back();
5096 }
5097
5098 return false;
5099}
5100
5101void AsmParser::initializeDirectiveKindMap() {
5102 DirectiveKindMap[".set"] = DK_SET;
5103 DirectiveKindMap[".equ"] = DK_EQU;
5104 DirectiveKindMap[".equiv"] = DK_EQUIV;
5105 DirectiveKindMap[".ascii"] = DK_ASCII;
5106 DirectiveKindMap[".asciz"] = DK_ASCIZ;
5107 DirectiveKindMap[".string"] = DK_STRING;
5108 DirectiveKindMap[".byte"] = DK_BYTE;
5109 DirectiveKindMap[".short"] = DK_SHORT;
5110 DirectiveKindMap[".value"] = DK_VALUE;
5111 DirectiveKindMap[".2byte"] = DK_2BYTE;
5112 DirectiveKindMap[".long"] = DK_LONG;
5113 DirectiveKindMap[".int"] = DK_INT;
5114 DirectiveKindMap[".4byte"] = DK_4BYTE;
5115 DirectiveKindMap[".quad"] = DK_QUAD;
5116 DirectiveKindMap[".8byte"] = DK_8BYTE;
5117 DirectiveKindMap[".octa"] = DK_OCTA;
5118 DirectiveKindMap[".single"] = DK_SINGLE;
5119 DirectiveKindMap[".float"] = DK_FLOAT;
5120 DirectiveKindMap[".double"] = DK_DOUBLE;
5121 DirectiveKindMap[".align"] = DK_ALIGN;
5122 DirectiveKindMap[".align32"] = DK_ALIGN32;
5123 DirectiveKindMap[".balign"] = DK_BALIGN;
5124 DirectiveKindMap[".balignw"] = DK_BALIGNW;
5125 DirectiveKindMap[".balignl"] = DK_BALIGNL;
5126 DirectiveKindMap[".p2align"] = DK_P2ALIGN;
5127 DirectiveKindMap[".p2alignw"] = DK_P2ALIGNW;
5128 DirectiveKindMap[".p2alignl"] = DK_P2ALIGNL;
5129 DirectiveKindMap[".org"] = DK_ORG;
5130 DirectiveKindMap[".fill"] = DK_FILL;
5131 DirectiveKindMap[".zero"] = DK_ZERO;
5132 DirectiveKindMap[".extern"] = DK_EXTERN;
5133 DirectiveKindMap[".globl"] = DK_GLOBL;
5134 DirectiveKindMap[".global"] = DK_GLOBAL;
5135 DirectiveKindMap[".lazy_reference"] = DK_LAZY_REFERENCE;
5136 DirectiveKindMap[".no_dead_strip"] = DK_NO_DEAD_STRIP;
5137 DirectiveKindMap[".symbol_resolver"] = DK_SYMBOL_RESOLVER;
5138 DirectiveKindMap[".private_extern"] = DK_PRIVATE_EXTERN;
5139 DirectiveKindMap[".reference"] = DK_REFERENCE;
5140 DirectiveKindMap[".weak_definition"] = DK_WEAK_DEFINITION;
5141 DirectiveKindMap[".weak_reference"] = DK_WEAK_REFERENCE;
5142 DirectiveKindMap[".weak_def_can_be_hidden"] = DK_WEAK_DEF_CAN_BE_HIDDEN;
5143 DirectiveKindMap[".comm"] = DK_COMM;
5144 DirectiveKindMap[".common"] = DK_COMMON;
5145 DirectiveKindMap[".lcomm"] = DK_LCOMM;
5146 DirectiveKindMap[".abort"] = DK_ABORT;
5147 DirectiveKindMap[".include"] = DK_INCLUDE;
5148 DirectiveKindMap[".incbin"] = DK_INCBIN;
5149 DirectiveKindMap[".code16"] = DK_CODE16;
5150 DirectiveKindMap[".code16gcc"] = DK_CODE16GCC;
5151 DirectiveKindMap[".rept"] = DK_REPT;
5152 DirectiveKindMap[".rep"] = DK_REPT;
5153 DirectiveKindMap[".irp"] = DK_IRP;
5154 DirectiveKindMap[".irpc"] = DK_IRPC;
5155 DirectiveKindMap[".endr"] = DK_ENDR;
5156 DirectiveKindMap[".bundle_align_mode"] = DK_BUNDLE_ALIGN_MODE;
5157 DirectiveKindMap[".bundle_lock"] = DK_BUNDLE_LOCK;
5158 DirectiveKindMap[".bundle_unlock"] = DK_BUNDLE_UNLOCK;
5159 DirectiveKindMap[".if"] = DK_IF;
5160 DirectiveKindMap[".ifeq"] = DK_IFEQ;
5161 DirectiveKindMap[".ifge"] = DK_IFGE;
5162 DirectiveKindMap[".ifgt"] = DK_IFGT;
5163 DirectiveKindMap[".ifle"] = DK_IFLE;
5164 DirectiveKindMap[".iflt"] = DK_IFLT;
5165 DirectiveKindMap[".ifne"] = DK_IFNE;
5166 DirectiveKindMap[".ifb"] = DK_IFB;
5167 DirectiveKindMap[".ifnb"] = DK_IFNB;
5168 DirectiveKindMap[".ifc"] = DK_IFC;
5169 DirectiveKindMap[".ifeqs"] = DK_IFEQS;
5170 DirectiveKindMap[".ifnc"] = DK_IFNC;
5171 DirectiveKindMap[".ifnes"] = DK_IFNES;
5172 DirectiveKindMap[".ifdef"] = DK_IFDEF;
5173 DirectiveKindMap[".ifndef"] = DK_IFNDEF;
5174 DirectiveKindMap[".ifnotdef"] = DK_IFNOTDEF;
5175 DirectiveKindMap[".elseif"] = DK_ELSEIF;
5176 DirectiveKindMap[".else"] = DK_ELSE;
5177 DirectiveKindMap[".end"] = DK_END;
5178 DirectiveKindMap[".endif"] = DK_ENDIF;
5179 DirectiveKindMap[".skip"] = DK_SKIP;
5180 DirectiveKindMap[".space"] = DK_SPACE;
5181 DirectiveKindMap[".file"] = DK_FILE;
5182 DirectiveKindMap[".line"] = DK_LINE;
5183 DirectiveKindMap[".loc"] = DK_LOC;
5184 DirectiveKindMap[".stabs"] = DK_STABS;
5185 DirectiveKindMap[".cv_file"] = DK_CV_FILE;
5186 DirectiveKindMap[".cv_func_id"] = DK_CV_FUNC_ID;
5187 DirectiveKindMap[".cv_loc"] = DK_CV_LOC;
5188 DirectiveKindMap[".cv_linetable"] = DK_CV_LINETABLE;
5189 DirectiveKindMap[".cv_inline_linetable"] = DK_CV_INLINE_LINETABLE;
5190 DirectiveKindMap[".cv_inline_site_id"] = DK_CV_INLINE_SITE_ID;
5191 DirectiveKindMap[".cv_def_range"] = DK_CV_DEF_RANGE;
5192 DirectiveKindMap[".cv_stringtable"] = DK_CV_STRINGTABLE;
5193 DirectiveKindMap[".cv_filechecksums"] = DK_CV_FILECHECKSUMS;
5194 DirectiveKindMap[".cv_filechecksumoffset"] = DK_CV_FILECHECKSUM_OFFSET;
5195 DirectiveKindMap[".cv_fpo_data"] = DK_CV_FPO_DATA;
5196 DirectiveKindMap[".sleb128"] = DK_SLEB128;
5197 DirectiveKindMap[".uleb128"] = DK_ULEB128;
5198 DirectiveKindMap[".cfi_sections"] = DK_CFI_SECTIONS;
5199 DirectiveKindMap[".cfi_startproc"] = DK_CFI_STARTPROC;
5200 DirectiveKindMap[".cfi_endproc"] = DK_CFI_ENDPROC;
5201 DirectiveKindMap[".cfi_def_cfa"] = DK_CFI_DEF_CFA;
5202 DirectiveKindMap[".cfi_def_cfa_offset"] = DK_CFI_DEF_CFA_OFFSET;
5203 DirectiveKindMap[".cfi_adjust_cfa_offset"] = DK_CFI_ADJUST_CFA_OFFSET;
5204 DirectiveKindMap[".cfi_def_cfa_register"] = DK_CFI_DEF_CFA_REGISTER;
5205 DirectiveKindMap[".cfi_offset"] = DK_CFI_OFFSET;
5206 DirectiveKindMap[".cfi_rel_offset"] = DK_CFI_REL_OFFSET;
5207 DirectiveKindMap[".cfi_personality"] = DK_CFI_PERSONALITY;
5208 DirectiveKindMap[".cfi_lsda"] = DK_CFI_LSDA;
5209 DirectiveKindMap[".cfi_remember_state"] = DK_CFI_REMEMBER_STATE;
5210 DirectiveKindMap[".cfi_restore_state"] = DK_CFI_RESTORE_STATE;
5211 DirectiveKindMap[".cfi_same_value"] = DK_CFI_SAME_VALUE;
5212 DirectiveKindMap[".cfi_restore"] = DK_CFI_RESTORE;
5213 DirectiveKindMap[".cfi_escape"] = DK_CFI_ESCAPE;
5214 DirectiveKindMap[".cfi_return_column"] = DK_CFI_RETURN_COLUMN;
5215 DirectiveKindMap[".cfi_signal_frame"] = DK_CFI_SIGNAL_FRAME;
5216 DirectiveKindMap[".cfi_undefined"] = DK_CFI_UNDEFINED;
5217 DirectiveKindMap[".cfi_register"] = DK_CFI_REGISTER;
5218 DirectiveKindMap[".cfi_window_save"] = DK_CFI_WINDOW_SAVE;
5219 DirectiveKindMap[".macros_on"] = DK_MACROS_ON;
5220 DirectiveKindMap[".macros_off"] = DK_MACROS_OFF;
5221 DirectiveKindMap[".macro"] = DK_MACRO;
5222 DirectiveKindMap[".exitm"] = DK_EXITM;
5223 DirectiveKindMap[".endm"] = DK_ENDM;
5224 DirectiveKindMap[".endmacro"] = DK_ENDMACRO;
5225 DirectiveKindMap[".purgem"] = DK_PURGEM;
5226 DirectiveKindMap[".err"] = DK_ERR;
5227 DirectiveKindMap[".error"] = DK_ERROR;
5228 DirectiveKindMap[".warning"] = DK_WARNING;
5229 DirectiveKindMap[".altmacro"] = DK_ALTMACRO;
5230 DirectiveKindMap[".noaltmacro"] = DK_NOALTMACRO;
5231 DirectiveKindMap[".reloc"] = DK_RELOC;
5232 DirectiveKindMap[".dc"] = DK_DC;
5233 DirectiveKindMap[".dc.a"] = DK_DC_A;
5234 DirectiveKindMap[".dc.b"] = DK_DC_B;
5235 DirectiveKindMap[".dc.d"] = DK_DC_D;
5236 DirectiveKindMap[".dc.l"] = DK_DC_L;
5237 DirectiveKindMap[".dc.s"] = DK_DC_S;
5238 DirectiveKindMap[".dc.w"] = DK_DC_W;
5239 DirectiveKindMap[".dc.x"] = DK_DC_X;
5240 DirectiveKindMap[".dcb"] = DK_DCB;
5241 DirectiveKindMap[".dcb.b"] = DK_DCB_B;
5242 DirectiveKindMap[".dcb.d"] = DK_DCB_D;
5243 DirectiveKindMap[".dcb.l"] = DK_DCB_L;
5244 DirectiveKindMap[".dcb.s"] = DK_DCB_S;
5245 DirectiveKindMap[".dcb.w"] = DK_DCB_W;
5246 DirectiveKindMap[".dcb.x"] = DK_DCB_X;
5247 DirectiveKindMap[".ds"] = DK_DS;
5248 DirectiveKindMap[".ds.b"] = DK_DS_B;
5249 DirectiveKindMap[".ds.d"] = DK_DS_D;
5250 DirectiveKindMap[".ds.l"] = DK_DS_L;
5251 DirectiveKindMap[".ds.p"] = DK_DS_P;
5252 DirectiveKindMap[".ds.s"] = DK_DS_S;
5253 DirectiveKindMap[".ds.w"] = DK_DS_W;
5254 DirectiveKindMap[".ds.x"] = DK_DS_X;
5255 DirectiveKindMap[".print"] = DK_PRINT;
5256}
5257
5258MCAsmMacro *AsmParser::parseMacroLikeBody(SMLoc DirectiveLoc) {
5259 AsmToken EndToken, StartToken = getTok();
5260
5261 unsigned NestLevel = 0;
5262 while (true) {
5263 // Check whether we have reached the end of the file.
5264 if (getLexer().is(AsmToken::Eof)) {
5265 printError(DirectiveLoc, "no matching '.endr' in definition");
5266 return nullptr;
5267 }
5268
5269 if (Lexer.is(AsmToken::Identifier) &&
5270 (getTok().getIdentifier() == ".rept" ||
5271 getTok().getIdentifier() == ".irp" ||
5272 getTok().getIdentifier() == ".irpc")) {
5273 ++NestLevel;
5274 }
5275
5276 // Otherwise, check whether we have reached the .endr.
5277 if (Lexer.is(AsmToken::Identifier) && getTok().getIdentifier() == ".endr") {
5278 if (NestLevel == 0) {
5279 EndToken = getTok();
5280 Lex();
5281 if (Lexer.isNot(AsmToken::EndOfStatement)) {
5282 printError(getTok().getLoc(),
5283 "unexpected token in '.endr' directive");
5284 return nullptr;
5285 }
5286 break;
5287 }
5288 --NestLevel;
5289 }
5290
5291 // Otherwise, scan till the end of the statement.
5292 eatToEndOfStatement();
5293 }
5294
5295 const char *BodyStart = StartToken.getLoc().getPointer();
5296 const char *BodyEnd = EndToken.getLoc().getPointer();
5297 StringRef Body = StringRef(BodyStart, BodyEnd - BodyStart);
5298
5299 // We Are Anonymous.
5300 MacroLikeBodies.emplace_back(StringRef(), Body, MCAsmMacroParameters());
5301 return &MacroLikeBodies.back();
5302}
5303
5304void AsmParser::instantiateMacroLikeBody(MCAsmMacro *M, SMLoc DirectiveLoc,
5305 raw_svector_ostream &OS) {
5306 OS << ".endr\n";
5307
5308 std::unique_ptr<MemoryBuffer> Instantiation =
5309 MemoryBuffer::getMemBufferCopy(OS.str(), "<instantiation>");
5310
5311 // Create the macro instantiation object and add to the current macro
5312 // instantiation stack.
5313 MacroInstantiation *MI = new MacroInstantiation(
5314 DirectiveLoc, CurBuffer, getTok().getLoc(), TheCondStack.size());
5315 ActiveMacros.push_back(MI);
5316
5317 // Jump to the macro instantiation and prime the lexer.
5318 CurBuffer = SrcMgr.AddNewSourceBuffer(std::move(Instantiation), SMLoc());
5319 Lexer.setBuffer(SrcMgr.getMemoryBuffer(CurBuffer)->getBuffer());
5320 Lex();
5321}
5322
5323/// parseDirectiveRept
5324/// ::= .rep | .rept count
5325bool AsmParser::parseDirectiveRept(SMLoc DirectiveLoc, StringRef Dir) {
5326 const MCExpr *CountExpr;
5327 SMLoc CountLoc = getTok().getLoc();
5328 if (parseExpression(CountExpr))
5329 return true;
5330
5331 int64_t Count;
5332 if (!CountExpr->evaluateAsAbsolute(Count)) {
5333 return Error(CountLoc, "unexpected token in '" + Dir + "' directive");
5334 }
5335
5336 if (check(Count < 0, CountLoc, "Count is negative") ||
5337 parseToken(AsmToken::EndOfStatement,
5338 "unexpected token in '" + Dir + "' directive"))
5339 return true;
5340
5341 // Lex the rept definition.
5342 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5343 if (!M)
5344 return true;
5345
5346 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5347 // to hold the macro body with substitutions.
5348 SmallString<256> Buf;
5349 raw_svector_ostream OS(Buf);
5350 while (Count--) {
5351 // Note that the AtPseudoVariable is disabled for instantiations of .rep(t).
5352 if (expandMacro(OS, M->Body, None, None, false, getTok().getLoc()))
5353 return true;
5354 }
5355 instantiateMacroLikeBody(M, DirectiveLoc, OS);
5356
5357 return false;
5358}
5359
5360/// parseDirectiveIrp
5361/// ::= .irp symbol,values
5362bool AsmParser::parseDirectiveIrp(SMLoc DirectiveLoc) {
5363 MCAsmMacroParameter Parameter;
5364 MCAsmMacroArguments A;
5365 if (check(parseIdentifier(Parameter.Name),
5366 "expected identifier in '.irp' directive") ||
5367 parseToken(AsmToken::Comma, "expected comma in '.irp' directive") ||
5368 parseMacroArguments(nullptr, A) ||
5369 parseToken(AsmToken::EndOfStatement, "expected End of Statement"))
5370 return true;
5371
5372 // Lex the irp definition.
5373 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5374 if (!M)
5375 return true;
5376
5377 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5378 // to hold the macro body with substitutions.
5379 SmallString<256> Buf;
5380 raw_svector_ostream OS(Buf);
5381
5382 for (const MCAsmMacroArgument &Arg : A) {
5383 // Note that the AtPseudoVariable is enabled for instantiations of .irp.
5384 // This is undocumented, but GAS seems to support it.
5385 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
5386 return true;
5387 }
5388
5389 instantiateMacroLikeBody(M, DirectiveLoc, OS);
5390
5391 return false;
5392}
5393
5394/// parseDirectiveIrpc
5395/// ::= .irpc symbol,values
5396bool AsmParser::parseDirectiveIrpc(SMLoc DirectiveLoc) {
5397 MCAsmMacroParameter Parameter;
5398 MCAsmMacroArguments A;
5399
5400 if (check(parseIdentifier(Parameter.Name),
5401 "expected identifier in '.irpc' directive") ||
5402 parseToken(AsmToken::Comma, "expected comma in '.irpc' directive") ||
5403 parseMacroArguments(nullptr, A))
5404 return true;
5405
5406 if (A.size() != 1 || A.front().size() != 1)
5407 return TokError("unexpected token in '.irpc' directive");
5408
5409 // Eat the end of statement.
5410 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5411 return true;
5412
5413 // Lex the irpc definition.
5414 MCAsmMacro *M = parseMacroLikeBody(DirectiveLoc);
5415 if (!M)
5416 return true;
5417
5418 // Macro instantiation is lexical, unfortunately. We construct a new buffer
5419 // to hold the macro body with substitutions.
5420 SmallString<256> Buf;
5421 raw_svector_ostream OS(Buf);
5422
5423 StringRef Values = A.front().front().getString();
5424 for (std::size_t I = 0, End = Values.size(); I != End; ++I) {
5425 MCAsmMacroArgument Arg;
5426 Arg.emplace_back(AsmToken::Identifier, Values.slice(I, I + 1));
5427
5428 // Note that the AtPseudoVariable is enabled for instantiations of .irpc.
5429 // This is undocumented, but GAS seems to support it.
5430 if (expandMacro(OS, M->Body, Parameter, Arg, true, getTok().getLoc()))
5431 return true;
5432 }
5433
5434 instantiateMacroLikeBody(M, DirectiveLoc, OS);
5435
5436 return false;
5437}
5438
5439bool AsmParser::parseDirectiveEndr(SMLoc DirectiveLoc) {
5440 if (ActiveMacros.empty())
5441 return TokError("unmatched '.endr' directive");
5442
5443 // The only .repl that should get here are the ones created by
5444 // instantiateMacroLikeBody.
5445 assert(getLexer().is(AsmToken::EndOfStatement))(static_cast <bool> (getLexer().is(AsmToken::EndOfStatement
)) ? void (0) : __assert_fail ("getLexer().is(AsmToken::EndOfStatement)"
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 5445, __extension__ __PRETTY_FUNCTION__))
;
5446
5447 handleMacroExit();
5448 return false;
5449}
5450
5451bool AsmParser::parseDirectiveMSEmit(SMLoc IDLoc, ParseStatementInfo &Info,
5452 size_t Len) {
5453 const MCExpr *Value;
5454 SMLoc ExprLoc = getLexer().getLoc();
5455 if (parseExpression(Value))
5456 return true;
5457 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5458 if (!MCE)
5459 return Error(ExprLoc, "unexpected expression in _emit");
5460 uint64_t IntValue = MCE->getValue();
5461 if (!isUInt<8>(IntValue) && !isInt<8>(IntValue))
5462 return Error(ExprLoc, "literal value out of range for directive");
5463
5464 Info.AsmRewrites->emplace_back(AOK_Emit, IDLoc, Len);
5465 return false;
5466}
5467
5468bool AsmParser::parseDirectiveMSAlign(SMLoc IDLoc, ParseStatementInfo &Info) {
5469 const MCExpr *Value;
5470 SMLoc ExprLoc = getLexer().getLoc();
5471 if (parseExpression(Value))
5472 return true;
5473 const MCConstantExpr *MCE = dyn_cast<MCConstantExpr>(Value);
5474 if (!MCE)
5475 return Error(ExprLoc, "unexpected expression in align");
5476 uint64_t IntValue = MCE->getValue();
5477 if (!isPowerOf2_64(IntValue))
5478 return Error(ExprLoc, "literal value not a power of two greater then zero");
5479
5480 Info.AsmRewrites->emplace_back(AOK_Align, IDLoc, 5, Log2_64(IntValue));
5481 return false;
5482}
5483
5484bool AsmParser::parseDirectivePrint(SMLoc DirectiveLoc) {
5485 const AsmToken StrTok = getTok();
5486 Lex();
5487 if (StrTok.isNot(AsmToken::String) || StrTok.getString().front() != '"')
5488 return Error(DirectiveLoc, "expected double quoted string after .print");
5489 if (parseToken(AsmToken::EndOfStatement, "expected end of statement"))
5490 return true;
5491 llvm::outs() << StrTok.getStringContents() << '\n';
5492 return false;
5493}
5494
5495// We are comparing pointers, but the pointers are relative to a single string.
5496// Thus, this should always be deterministic.
5497static int rewritesSort(const AsmRewrite *AsmRewriteA,
5498 const AsmRewrite *AsmRewriteB) {
5499 if (AsmRewriteA->Loc.getPointer() < AsmRewriteB->Loc.getPointer())
5500 return -1;
5501 if (AsmRewriteB->Loc.getPointer() < AsmRewriteA->Loc.getPointer())
5502 return 1;
5503
5504 // It's possible to have a SizeDirective, Imm/ImmPrefix and an Input/Output
5505 // rewrite to the same location. Make sure the SizeDirective rewrite is
5506 // performed first, then the Imm/ImmPrefix and finally the Input/Output. This
5507 // ensures the sort algorithm is stable.
5508 if (AsmRewritePrecedence[AsmRewriteA->Kind] >
5509 AsmRewritePrecedence[AsmRewriteB->Kind])
5510 return -1;
5511
5512 if (AsmRewritePrecedence[AsmRewriteA->Kind] <
5513 AsmRewritePrecedence[AsmRewriteB->Kind])
5514 return 1;
5515 llvm_unreachable("Unstable rewrite sort.")::llvm::llvm_unreachable_internal("Unstable rewrite sort.", "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 5515)
;
5516}
5517
5518bool AsmParser::parseMSInlineAsm(
5519 void *AsmLoc, std::string &AsmString, unsigned &NumOutputs,
5520 unsigned &NumInputs, SmallVectorImpl<std::pair<void *, bool>> &OpDecls,
5521 SmallVectorImpl<std::string> &Constraints,
5522 SmallVectorImpl<std::string> &Clobbers, const MCInstrInfo *MII,
5523 const MCInstPrinter *IP, MCAsmParserSemaCallback &SI) {
5524 SmallVector<void *, 4> InputDecls;
5525 SmallVector<void *, 4> OutputDecls;
5526 SmallVector<bool, 4> InputDeclsAddressOf;
5527 SmallVector<bool, 4> OutputDeclsAddressOf;
5528 SmallVector<std::string, 4> InputConstraints;
5529 SmallVector<std::string, 4> OutputConstraints;
5530 SmallVector<unsigned, 4> ClobberRegs;
5531
5532 SmallVector<AsmRewrite, 4> AsmStrRewrites;
5533
5534 // Prime the lexer.
5535 Lex();
5536
5537 // While we have input, parse each statement.
5538 unsigned InputIdx = 0;
5539 unsigned OutputIdx = 0;
5540 while (getLexer().isNot(AsmToken::Eof)) {
5541 // Parse curly braces marking block start/end
5542 if (parseCurlyBlockScope(AsmStrRewrites))
5543 continue;
5544
5545 ParseStatementInfo Info(&AsmStrRewrites);
5546 bool StatementErr = parseStatement(Info, &SI);
5547
5548 if (StatementErr || Info.ParseError) {
5549 // Emit pending errors if any exist.
5550 printPendingErrors();
5551 return true;
5552 }
5553
5554 // No pending error should exist here.
5555 assert(!hasPendingError() && "unexpected error from parseStatement")(static_cast <bool> (!hasPendingError() && "unexpected error from parseStatement"
) ? void (0) : __assert_fail ("!hasPendingError() && \"unexpected error from parseStatement\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 5555, __extension__ __PRETTY_FUNCTION__))
;
5556
5557 if (Info.Opcode == ~0U)
5558 continue;
5559
5560 const MCInstrDesc &Desc = MII->get(Info.Opcode);
5561
5562 // Build the list of clobbers, outputs and inputs.
5563 for (unsigned i = 1, e = Info.ParsedOperands.size(); i != e; ++i) {
5564 MCParsedAsmOperand &Operand = *Info.ParsedOperands[i];
5565
5566 // Immediate.
5567 if (Operand.isImm())
5568 continue;
5569
5570 // Register operand.
5571 if (Operand.isReg() && !Operand.needAddressOf() &&
5572 !getTargetParser().OmitRegisterFromClobberLists(Operand.getReg())) {
5573 unsigned NumDefs = Desc.getNumDefs();
5574 // Clobber.
5575 if (NumDefs && Operand.getMCOperandNum() < NumDefs)
5576 ClobberRegs.push_back(Operand.getReg());
5577 continue;
5578 }
5579
5580 // Expr/Input or Output.
5581 StringRef SymName = Operand.getSymName();
5582 if (SymName.empty())
5583 continue;
5584
5585 void *OpDecl = Operand.getOpDecl();
5586 if (!OpDecl)
5587 continue;
5588
5589 bool isOutput = (i == 1) && Desc.mayStore();
5590 SMLoc Start = SMLoc::getFromPointer(SymName.data());
5591 if (isOutput) {
5592 ++InputIdx;
5593 OutputDecls.push_back(OpDecl);
5594 OutputDeclsAddressOf.push_back(Operand.needAddressOf());
5595 OutputConstraints.push_back(("=" + Operand.getConstraint()).str());
5596 AsmStrRewrites.emplace_back(AOK_Output, Start, SymName.size());
5597 } else {
5598 InputDecls.push_back(OpDecl);
5599 InputDeclsAddressOf.push_back(Operand.needAddressOf());
5600 InputConstraints.push_back(Operand.getConstraint().str());
5601 AsmStrRewrites.emplace_back(AOK_Input, Start, SymName.size());
5602 }
5603 }
5604
5605 // Consider implicit defs to be clobbers. Think of cpuid and push.
5606 ArrayRef<MCPhysReg> ImpDefs(Desc.getImplicitDefs(),
5607 Desc.getNumImplicitDefs());
5608 ClobberRegs.insert(ClobberRegs.end(), ImpDefs.begin(), ImpDefs.end());
5609 }
5610
5611 // Set the number of Outputs and Inputs.
5612 NumOutputs = OutputDecls.size();
5613 NumInputs = InputDecls.size();
5614
5615 // Set the unique clobbers.
5616 array_pod_sort(ClobberRegs.begin(), ClobberRegs.end());
5617 ClobberRegs.erase(std::unique(ClobberRegs.begin(), ClobberRegs.end()),
5618 ClobberRegs.end());
5619 Clobbers.assign(ClobberRegs.size(), std::string());
5620 for (unsigned I = 0, E = ClobberRegs.size(); I != E; ++I) {
5621 raw_string_ostream OS(Clobbers[I]);
5622 IP->printRegName(OS, ClobberRegs[I]);
5623 }
5624
5625 // Merge the various outputs and inputs. Output are expected first.
5626 if (NumOutputs || NumInputs) {
5627 unsigned NumExprs = NumOutputs + NumInputs;
5628 OpDecls.resize(NumExprs);
5629 Constraints.resize(NumExprs);
5630 for (unsigned i = 0; i < NumOutputs; ++i) {
5631 OpDecls[i] = std::make_pair(OutputDecls[i], OutputDeclsAddressOf[i]);
5632 Constraints[i] = OutputConstraints[i];
5633 }
5634 for (unsigned i = 0, j = NumOutputs; i < NumInputs; ++i, ++j) {
5635 OpDecls[j] = std::make_pair(InputDecls[i], InputDeclsAddressOf[i]);
5636 Constraints[j] = InputConstraints[i];
5637 }
5638 }
5639
5640 // Build the IR assembly string.
5641 std::string AsmStringIR;
5642 raw_string_ostream OS(AsmStringIR);
5643 StringRef ASMString =
5644 SrcMgr.getMemoryBuffer(SrcMgr.getMainFileID())->getBuffer();
5645 const char *AsmStart = ASMString.begin();
5646 const char *AsmEnd = ASMString.end();
5647 array_pod_sort(AsmStrRewrites.begin(), AsmStrRewrites.end(), rewritesSort);
5648 for (const AsmRewrite &AR : AsmStrRewrites) {
5649 AsmRewriteKind Kind = AR.Kind;
5650
5651 const char *Loc = AR.Loc.getPointer();
5652 assert(Loc >= AsmStart && "Expected Loc to be at or after Start!")(static_cast <bool> (Loc >= AsmStart && "Expected Loc to be at or after Start!"
) ? void (0) : __assert_fail ("Loc >= AsmStart && \"Expected Loc to be at or after Start!\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 5652, __extension__ __PRETTY_FUNCTION__))
;
5653
5654 // Emit everything up to the immediate/expression.
5655 if (unsigned Len = Loc - AsmStart)
5656 OS << StringRef(AsmStart, Len);
5657
5658 // Skip the original expression.
5659 if (Kind == AOK_Skip) {
5660 AsmStart = Loc + AR.Len;
5661 continue;
5662 }
5663
5664 unsigned AdditionalSkip = 0;
5665 // Rewrite expressions in $N notation.
5666 switch (Kind) {
5667 default:
5668 break;
5669 case AOK_IntelExpr:
5670 assert(AR.IntelExp.isValid() && "cannot write invalid intel expression")(static_cast <bool> (AR.IntelExp.isValid() && "cannot write invalid intel expression"
) ? void (0) : __assert_fail ("AR.IntelExp.isValid() && \"cannot write invalid intel expression\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 5670, __extension__ __PRETTY_FUNCTION__))
;
5671 if (AR.IntelExp.NeedBracs)
5672 OS << "[";
5673 if (AR.IntelExp.hasBaseReg())
5674 OS << AR.IntelExp.BaseReg;
5675 if (AR.IntelExp.hasIndexReg())
5676 OS << (AR.IntelExp.hasBaseReg() ? " + " : "")
5677 << AR.IntelExp.IndexReg;
5678 if (AR.IntelExp.Scale > 1)
5679 OS << " * $$" << AR.IntelExp.Scale;
5680 if (AR.IntelExp.Imm || !AR.IntelExp.hasRegs())
5681 OS << (AR.IntelExp.hasRegs() ? " + $$" : "$$") << AR.IntelExp.Imm;
5682 if (AR.IntelExp.NeedBracs)
5683 OS << "]";
5684 break;
5685 case AOK_Label:
5686 OS << Ctx.getAsmInfo()->getPrivateLabelPrefix() << AR.Label;
5687 break;
5688 case AOK_Input:
5689 OS << '$' << InputIdx++;
5690 break;
5691 case AOK_Output:
5692 OS << '$' << OutputIdx++;
5693 break;
5694 case AOK_SizeDirective:
5695 switch (AR.Val) {
5696 default: break;
5697 case 8: OS << "byte ptr "; break;
5698 case 16: OS << "word ptr "; break;
5699 case 32: OS << "dword ptr "; break;
5700 case 64: OS << "qword ptr "; break;
5701 case 80: OS << "xword ptr "; break;
5702 case 128: OS << "xmmword ptr "; break;
5703 case 256: OS << "ymmword ptr "; break;
5704 }
5705 break;
5706 case AOK_Emit:
5707 OS << ".byte";
5708 break;
5709 case AOK_Align: {
5710 // MS alignment directives are measured in bytes. If the native assembler
5711 // measures alignment in bytes, we can pass it straight through.
5712 OS << ".align";
5713 if (getContext().getAsmInfo()->getAlignmentIsInBytes())
5714 break;
5715
5716 // Alignment is in log2 form, so print that instead and skip the original
5717 // immediate.
5718 unsigned Val = AR.Val;
5719 OS << ' ' << Val;
5720 assert(Val < 10 && "Expected alignment less then 2^10.")(static_cast <bool> (Val < 10 && "Expected alignment less then 2^10."
) ? void (0) : __assert_fail ("Val < 10 && \"Expected alignment less then 2^10.\""
, "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 5720, __extension__ __PRETTY_FUNCTION__))
;
5721 AdditionalSkip = (Val < 4) ? 2 : Val < 7 ? 3 : 4;
5722 break;
5723 }
5724 case AOK_EVEN:
5725 OS << ".even";
5726 break;
5727 case AOK_EndOfStatement:
5728 OS << "\n\t";
5729 break;
5730 }
5731
5732 // Skip the original expression.
5733 AsmStart = Loc + AR.Len + AdditionalSkip;
5734 }
5735
5736 // Emit the remainder of the asm string.
5737 if (AsmStart != AsmEnd)
5738 OS << StringRef(AsmStart, AsmEnd - AsmStart);
5739
5740 AsmString = OS.str();
5741 return false;
5742}
5743
5744namespace llvm {
5745namespace MCParserUtils {
5746
5747/// Returns whether the given symbol is used anywhere in the given expression,
5748/// or subexpressions.
5749static bool isSymbolUsedInExpression(const MCSymbol *Sym, const MCExpr *Value) {
5750 switch (Value->getKind()) {
5751 case MCExpr::Binary: {
5752 const MCBinaryExpr *BE = static_cast<const MCBinaryExpr *>(Value);
5753 return isSymbolUsedInExpression(Sym, BE->getLHS()) ||
5754 isSymbolUsedInExpression(Sym, BE->getRHS());
5755 }
5756 case MCExpr::Target:
5757 case MCExpr::Constant:
5758 return false;
5759 case MCExpr::SymbolRef: {
5760 const MCSymbol &S =
5761 static_cast<const MCSymbolRefExpr *>(Value)->getSymbol();
5762 if (S.isVariable())
5763 return isSymbolUsedInExpression(Sym, S.getVariableValue());
5764 return &S == Sym;
5765 }
5766 case MCExpr::Unary:
5767 return isSymbolUsedInExpression(
5768 Sym, static_cast<const MCUnaryExpr *>(Value)->getSubExpr());
5769 }
5770
5771 llvm_unreachable("Unknown expr kind!")::llvm::llvm_unreachable_internal("Unknown expr kind!", "/build/llvm-toolchain-snapshot-7~svn326551/lib/MC/MCParser/AsmParser.cpp"
, 5771)
;
5772}
5773
5774bool parseAssignmentExpression(StringRef Name, bool allow_redef,
5775 MCAsmParser &Parser, MCSymbol *&Sym,
5776 const MCExpr *&Value) {
5777
5778 // FIXME: Use better location, we should use proper tokens.
5779 SMLoc EqualLoc = Parser.getTok().getLoc();
5780
5781 if (Parser.parseExpression(Value)) {
5782 return Parser.TokError("missing expression");
5783 }
5784
5785 // Note: we don't count b as used in "a = b". This is to allow
5786 // a = b
5787 // b = c
5788
5789 if (Parser.parseToken(AsmToken::EndOfStatement))
5790 return true;
5791
5792 // Validate that the LHS is allowed to be a variable (either it has not been
5793 // used as a symbol, or it is an absolute symbol).
5794 Sym = Parser.getContext().lookupSymbol(Name);
5795 if (Sym) {
5796 // Diagnose assignment to a label.
5797 //
5798 // FIXME: Diagnostics. Note the location of the definition as a label.
5799 // FIXME: Diagnose assignment to protected identifier (e.g., register name).
5800 if (isSymbolUsedInExpression(Sym, Value))
5801 return Parser.Error(EqualLoc, "Recursive use of '" + Name + "'");
5802 else if (Sym->isUndefined(/*SetUsed*/ false) && !Sym->isUsed() &&
5803 !Sym->isVariable())
5804 ; // Allow redefinitions of undefined symbols only used in directives.
5805 else if (Sym->isVariable() && !Sym->isUsed() && allow_redef)
5806 ; // Allow redefinitions of variables that haven't yet been used.
5807 else if (!Sym->isUndefined() && (!Sym->isVariable() || !allow_redef))
5808 return Parser.Error(EqualLoc, "redefinition of '" + Name + "'");
5809 else if (!Sym->isVariable())
5810 return Parser.Error(EqualLoc, "invalid assignment to '" + Name + "'");
5811 else if (!isa<MCConstantExpr>(Sym->getVariableValue()))
5812 return Parser.Error(EqualLoc,
5813 "invalid reassignment of non-absolute variable '" +
5814 Name + "'");
5815 } else if (Name == ".") {
5816 Parser.getStreamer().emitValueToOffset(Value, 0, EqualLoc);
5817 return false;
5818 } else
5819 Sym = Parser.getContext().getOrCreateSymbol(Name);
5820
5821 Sym->setRedefinable(allow_redef);
5822
5823 return false;
5824}
5825
5826} // end namespace MCParserUtils
5827} // end namespace llvm
5828
5829/// \brief Create an MCAsmParser instance.
5830MCAsmParser *llvm::createMCAsmParser(SourceMgr &SM, MCContext &C,
5831 MCStreamer &Out, const MCAsmInfo &MAI,
5832 unsigned CB) {
5833 return new AsmParser(SM, C, Out, MAI, CB);
5834}