Bug Summary

File:lib/MC/MCParser/AsmParser.cpp
Warning:line 3043, column 7
1st function call argument is an uninitialized value

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