ParseStmtAsm.cpp 29 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808
  1. //===---- ParseStmtAsm.cpp - Assembly Statement Parser --------------------===//
  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 file implements parsing for GCC and Microsoft inline assembly.
  11. //
  12. //===----------------------------------------------------------------------===//
  13. #include "clang/Parse/Parser.h"
  14. #include "RAIIObjectsForParser.h"
  15. #include "clang/AST/ASTContext.h"
  16. #include "clang/Basic/Diagnostic.h"
  17. #include "clang/Basic/TargetInfo.h"
  18. #include "llvm/ADT/SmallString.h"
  19. #include "llvm/MC/MCAsmInfo.h"
  20. #include "llvm/MC/MCContext.h"
  21. #include "llvm/MC/MCInstPrinter.h"
  22. #include "llvm/MC/MCInstrInfo.h"
  23. #include "llvm/MC/MCObjectFileInfo.h"
  24. #include "llvm/MC/MCParser/MCAsmParser.h"
  25. #include "llvm/MC/MCRegisterInfo.h"
  26. #include "llvm/MC/MCStreamer.h"
  27. #include "llvm/MC/MCSubtargetInfo.h"
  28. #include "llvm/MC/MCTargetAsmParser.h"
  29. #include "llvm/MC/MCTargetOptions.h"
  30. #include "llvm/Support/SourceMgr.h"
  31. #include "llvm/Support/TargetRegistry.h"
  32. #include "llvm/Support/TargetSelect.h"
  33. using namespace clang;
  34. #if 0 // HLSL Change - disable this block to avoid having to build/link llvmMC
  35. namespace {
  36. class ClangAsmParserCallback : public llvm::MCAsmParserSemaCallback {
  37. Parser &TheParser;
  38. SourceLocation AsmLoc;
  39. StringRef AsmString;
  40. /// The tokens we streamed into AsmString and handed off to MC.
  41. ArrayRef<Token> AsmToks;
  42. /// The offset of each token in AsmToks within AsmString.
  43. ArrayRef<unsigned> AsmTokOffsets;
  44. public:
  45. ClangAsmParserCallback(Parser &P, SourceLocation Loc, StringRef AsmString,
  46. ArrayRef<Token> Toks, ArrayRef<unsigned> Offsets)
  47. : TheParser(P), AsmLoc(Loc), AsmString(AsmString), AsmToks(Toks),
  48. AsmTokOffsets(Offsets) {
  49. assert(AsmToks.size() == AsmTokOffsets.size());
  50. }
  51. void *LookupInlineAsmIdentifier(StringRef &LineBuf,
  52. llvm::InlineAsmIdentifierInfo &Info,
  53. bool IsUnevaluatedContext) override {
  54. // Collect the desired tokens.
  55. SmallVector<Token, 16> LineToks;
  56. const Token *FirstOrigToken = nullptr;
  57. findTokensForString(LineBuf, LineToks, FirstOrigToken);
  58. unsigned NumConsumedToks;
  59. ExprResult Result = TheParser.ParseMSAsmIdentifier(
  60. LineToks, NumConsumedToks, &Info, IsUnevaluatedContext);
  61. // If we consumed the entire line, tell MC that.
  62. // Also do this if we consumed nothing as a way of reporting failure.
  63. if (NumConsumedToks == 0 || NumConsumedToks == LineToks.size()) {
  64. // By not modifying LineBuf, we're implicitly consuming it all.
  65. // Otherwise, consume up to the original tokens.
  66. } else {
  67. assert(FirstOrigToken && "not using original tokens?");
  68. // Since we're using original tokens, apply that offset.
  69. assert(FirstOrigToken[NumConsumedToks].getLocation() ==
  70. LineToks[NumConsumedToks].getLocation());
  71. unsigned FirstIndex = FirstOrigToken - AsmToks.begin();
  72. unsigned LastIndex = FirstIndex + NumConsumedToks - 1;
  73. // The total length we've consumed is the relative offset
  74. // of the last token we consumed plus its length.
  75. unsigned TotalOffset =
  76. (AsmTokOffsets[LastIndex] + AsmToks[LastIndex].getLength() -
  77. AsmTokOffsets[FirstIndex]);
  78. LineBuf = LineBuf.substr(0, TotalOffset);
  79. }
  80. // Initialize the "decl" with the lookup result.
  81. Info.OpDecl = static_cast<void *>(Result.get());
  82. return Info.OpDecl;
  83. }
  84. StringRef LookupInlineAsmLabel(StringRef Identifier, llvm::SourceMgr &LSM,
  85. llvm::SMLoc Location,
  86. bool Create) override {
  87. SourceLocation Loc = translateLocation(LSM, Location);
  88. LabelDecl *Label =
  89. TheParser.getActions().GetOrCreateMSAsmLabel(Identifier, Loc, Create);
  90. return Label->getMSAsmLabel();
  91. }
  92. bool LookupInlineAsmField(StringRef Base, StringRef Member,
  93. unsigned &Offset) override {
  94. return TheParser.getActions().LookupInlineAsmField(Base, Member, Offset,
  95. AsmLoc);
  96. }
  97. static void DiagHandlerCallback(const llvm::SMDiagnostic &D, void *Context) {
  98. ((ClangAsmParserCallback *)Context)->handleDiagnostic(D);
  99. }
  100. private:
  101. /// Collect the appropriate tokens for the given string.
  102. void findTokensForString(StringRef Str, SmallVectorImpl<Token> &TempToks,
  103. const Token *&FirstOrigToken) const {
  104. // For now, assert that the string we're working with is a substring
  105. // of what we gave to MC. This lets us use the original tokens.
  106. assert(!std::less<const char *>()(Str.begin(), AsmString.begin()) &&
  107. !std::less<const char *>()(AsmString.end(), Str.end()));
  108. // Try to find a token whose offset matches the first token.
  109. unsigned FirstCharOffset = Str.begin() - AsmString.begin();
  110. const unsigned *FirstTokOffset = std::lower_bound(
  111. AsmTokOffsets.begin(), AsmTokOffsets.end(), FirstCharOffset);
  112. // For now, assert that the start of the string exactly
  113. // corresponds to the start of a token.
  114. assert(*FirstTokOffset == FirstCharOffset);
  115. // Use all the original tokens for this line. (We assume the
  116. // end of the line corresponds cleanly to a token break.)
  117. unsigned FirstTokIndex = FirstTokOffset - AsmTokOffsets.begin();
  118. FirstOrigToken = &AsmToks[FirstTokIndex];
  119. unsigned LastCharOffset = Str.end() - AsmString.begin();
  120. for (unsigned i = FirstTokIndex, e = AsmTokOffsets.size(); i != e; ++i) {
  121. if (AsmTokOffsets[i] >= LastCharOffset)
  122. break;
  123. TempToks.push_back(AsmToks[i]);
  124. }
  125. }
  126. SourceLocation translateLocation(const llvm::SourceMgr &LSM, llvm::SMLoc SMLoc) {
  127. // Compute an offset into the inline asm buffer.
  128. // FIXME: This isn't right if .macro is involved (but hopefully, no
  129. // real-world code does that).
  130. const llvm::MemoryBuffer *LBuf =
  131. LSM.getMemoryBuffer(LSM.FindBufferContainingLoc(SMLoc));
  132. unsigned Offset = SMLoc.getPointer() - LBuf->getBufferStart();
  133. // Figure out which token that offset points into.
  134. const unsigned *TokOffsetPtr =
  135. std::lower_bound(AsmTokOffsets.begin(), AsmTokOffsets.end(), Offset);
  136. unsigned TokIndex = TokOffsetPtr - AsmTokOffsets.begin();
  137. unsigned TokOffset = *TokOffsetPtr;
  138. // If we come up with an answer which seems sane, use it; otherwise,
  139. // just point at the __asm keyword.
  140. // FIXME: Assert the answer is sane once we handle .macro correctly.
  141. SourceLocation Loc = AsmLoc;
  142. if (TokIndex < AsmToks.size()) {
  143. const Token &Tok = AsmToks[TokIndex];
  144. Loc = Tok.getLocation();
  145. Loc = Loc.getLocWithOffset(Offset - TokOffset);
  146. }
  147. return Loc;
  148. }
  149. void handleDiagnostic(const llvm::SMDiagnostic &D) {
  150. const llvm::SourceMgr &LSM = *D.getSourceMgr();
  151. SourceLocation Loc = translateLocation(LSM, D.getLoc());
  152. TheParser.Diag(Loc, diag::err_inline_ms_asm_parsing) << D.getMessage();
  153. }
  154. };
  155. }
  156. #endif // HLSL Change - disable this block to avoid having to build/link llvmMC
  157. /// Parse an identifier in an MS-style inline assembly block.
  158. ///
  159. /// \param CastInfo - a void* so that we don't have to teach Parser.h
  160. /// about the actual type.
  161. ExprResult Parser::ParseMSAsmIdentifier(llvm::SmallVectorImpl<Token> &LineToks,
  162. unsigned &NumLineToksConsumed,
  163. void *CastInfo,
  164. bool IsUnevaluatedContext) {
  165. assert(!getLangOpts().HLSL && "no MS assembly support in HLSL"); // HLSL Change
  166. llvm::InlineAsmIdentifierInfo &Info =
  167. *(llvm::InlineAsmIdentifierInfo *)CastInfo;
  168. // Push a fake token on the end so that we don't overrun the token
  169. // stream. We use ';' because it expression-parsing should never
  170. // overrun it.
  171. const tok::TokenKind EndOfStream = tok::semi;
  172. Token EndOfStreamTok;
  173. EndOfStreamTok.startToken();
  174. EndOfStreamTok.setKind(EndOfStream);
  175. LineToks.push_back(EndOfStreamTok);
  176. // Also copy the current token over.
  177. LineToks.push_back(Tok);
  178. PP.EnterTokenStream(LineToks.begin(), LineToks.size(),
  179. /*disable macros*/ true,
  180. /*owns tokens*/ false);
  181. // Clear the current token and advance to the first token in LineToks.
  182. ConsumeAnyToken();
  183. // Parse an optional scope-specifier if we're in C++.
  184. CXXScopeSpec SS;
  185. if (getLangOpts().CPlusPlus) {
  186. ParseOptionalCXXScopeSpecifier(SS, ParsedType(), /*EnteringContext=*/false);
  187. }
  188. // Require an identifier here.
  189. SourceLocation TemplateKWLoc;
  190. UnqualifiedId Id;
  191. bool Invalid =
  192. ParseUnqualifiedId(SS,
  193. /*EnteringContext=*/false,
  194. /*AllowDestructorName=*/false,
  195. /*AllowConstructorName=*/false,
  196. /*ObjectType=*/ParsedType(), TemplateKWLoc, Id);
  197. // Figure out how many tokens we are into LineToks.
  198. unsigned LineIndex = 0;
  199. if (Tok.is(EndOfStream)) {
  200. LineIndex = LineToks.size() - 2;
  201. } else {
  202. while (LineToks[LineIndex].getLocation() != Tok.getLocation()) {
  203. LineIndex++;
  204. assert(LineIndex < LineToks.size() - 2); // we added two extra tokens
  205. }
  206. }
  207. // If we've run into the poison token we inserted before, or there
  208. // was a parsing error, then claim the entire line.
  209. if (Invalid || Tok.is(EndOfStream)) {
  210. NumLineToksConsumed = LineToks.size() - 2;
  211. } else {
  212. // Otherwise, claim up to the start of the next token.
  213. NumLineToksConsumed = LineIndex;
  214. }
  215. // Finally, restore the old parsing state by consuming all the tokens we
  216. // staged before, implicitly killing off the token-lexer we pushed.
  217. for (unsigned i = 0, e = LineToks.size() - LineIndex - 2; i != e; ++i) {
  218. ConsumeAnyToken();
  219. }
  220. assert(Tok.is(EndOfStream));
  221. ConsumeToken();
  222. // Leave LineToks in its original state.
  223. LineToks.pop_back();
  224. LineToks.pop_back();
  225. // Perform the lookup.
  226. return Actions.LookupInlineAsmIdentifier(SS, TemplateKWLoc, Id, Info,
  227. IsUnevaluatedContext);
  228. }
  229. /// Turn a sequence of our tokens back into a string that we can hand
  230. /// to the MC asm parser.
  231. static bool buildMSAsmString(Preprocessor &PP, SourceLocation AsmLoc,
  232. ArrayRef<Token> AsmToks,
  233. SmallVectorImpl<unsigned> &TokOffsets,
  234. SmallString<512> &Asm) {
  235. assert(!AsmToks.empty() && "Didn't expect an empty AsmToks!");
  236. // Is this the start of a new assembly statement?
  237. bool isNewStatement = true;
  238. for (unsigned i = 0, e = AsmToks.size(); i < e; ++i) {
  239. const Token &Tok = AsmToks[i];
  240. // Start each new statement with a newline and a tab.
  241. if (!isNewStatement && (Tok.is(tok::kw_asm) || Tok.isAtStartOfLine())) {
  242. Asm += "\n\t";
  243. isNewStatement = true;
  244. }
  245. // Preserve the existence of leading whitespace except at the
  246. // start of a statement.
  247. if (!isNewStatement && Tok.hasLeadingSpace())
  248. Asm += ' ';
  249. // Remember the offset of this token.
  250. TokOffsets.push_back(Asm.size());
  251. // Don't actually write '__asm' into the assembly stream.
  252. if (Tok.is(tok::kw_asm)) {
  253. // Complain about __asm at the end of the stream.
  254. if (i + 1 == e) {
  255. PP.Diag(AsmLoc, diag::err_asm_empty);
  256. return true;
  257. }
  258. continue;
  259. }
  260. // Append the spelling of the token.
  261. SmallString<32> SpellingBuffer;
  262. bool SpellingInvalid = false;
  263. Asm += PP.getSpelling(Tok, SpellingBuffer, &SpellingInvalid);
  264. assert(!SpellingInvalid && "spelling was invalid after correct parse?");
  265. // We are no longer at the start of a statement.
  266. isNewStatement = false;
  267. }
  268. // Ensure that the buffer is null-terminated.
  269. Asm.push_back('\0');
  270. Asm.pop_back();
  271. assert(TokOffsets.size() == AsmToks.size());
  272. return false;
  273. }
  274. /// ParseMicrosoftAsmStatement. When -fms-extensions/-fasm-blocks is enabled,
  275. /// this routine is called to collect the tokens for an MS asm statement.
  276. ///
  277. /// [MS] ms-asm-statement:
  278. /// ms-asm-block
  279. /// ms-asm-block ms-asm-statement
  280. ///
  281. /// [MS] ms-asm-block:
  282. /// '__asm' ms-asm-line '\n'
  283. /// '__asm' '{' ms-asm-instruction-block[opt] '}' ';'[opt]
  284. ///
  285. /// [MS] ms-asm-instruction-block
  286. /// ms-asm-line
  287. /// ms-asm-line '\n' ms-asm-instruction-block
  288. ///
  289. StmtResult Parser::ParseMicrosoftAsmStatement(SourceLocation AsmLoc) {
  290. assert(!getLangOpts().HLSL && "no MS assembly support in HLSL"); // HLSL Change
  291. #if 1 // HLSL Change - disable this block to avoid having to build/link llvmMC
  292. return StmtResult();
  293. #else
  294. SourceManager &SrcMgr = PP.getSourceManager();
  295. SourceLocation EndLoc = AsmLoc;
  296. SmallVector<Token, 4> AsmToks;
  297. bool SingleLineMode = true;
  298. unsigned BraceNesting = 0;
  299. unsigned short savedBraceCount = BraceCount;
  300. bool InAsmComment = false;
  301. FileID FID;
  302. unsigned LineNo = 0;
  303. unsigned NumTokensRead = 0;
  304. SmallVector<SourceLocation, 4> LBraceLocs;
  305. bool SkippedStartOfLine = false;
  306. if (Tok.is(tok::l_brace)) {
  307. // Braced inline asm: consume the opening brace.
  308. SingleLineMode = false;
  309. BraceNesting = 1;
  310. EndLoc = ConsumeBrace();
  311. LBraceLocs.push_back(EndLoc);
  312. ++NumTokensRead;
  313. } else {
  314. // Single-line inline asm; compute which line it is on.
  315. std::pair<FileID, unsigned> ExpAsmLoc =
  316. SrcMgr.getDecomposedExpansionLoc(EndLoc);
  317. FID = ExpAsmLoc.first;
  318. LineNo = SrcMgr.getLineNumber(FID, ExpAsmLoc.second);
  319. LBraceLocs.push_back(SourceLocation());
  320. }
  321. SourceLocation TokLoc = Tok.getLocation();
  322. do {
  323. // If we hit EOF, we're done, period.
  324. if (isEofOrEom())
  325. break;
  326. if (!InAsmComment && Tok.is(tok::l_brace)) {
  327. // Consume the opening brace.
  328. SkippedStartOfLine = Tok.isAtStartOfLine();
  329. EndLoc = ConsumeBrace();
  330. BraceNesting++;
  331. LBraceLocs.push_back(EndLoc);
  332. TokLoc = Tok.getLocation();
  333. ++NumTokensRead;
  334. continue;
  335. } else if (!InAsmComment && Tok.is(tok::semi)) {
  336. // A semicolon in an asm is the start of a comment.
  337. InAsmComment = true;
  338. if (!SingleLineMode) {
  339. // Compute which line the comment is on.
  340. std::pair<FileID, unsigned> ExpSemiLoc =
  341. SrcMgr.getDecomposedExpansionLoc(TokLoc);
  342. FID = ExpSemiLoc.first;
  343. LineNo = SrcMgr.getLineNumber(FID, ExpSemiLoc.second);
  344. }
  345. } else if (SingleLineMode || InAsmComment) {
  346. // If end-of-line is significant, check whether this token is on a
  347. // new line.
  348. std::pair<FileID, unsigned> ExpLoc =
  349. SrcMgr.getDecomposedExpansionLoc(TokLoc);
  350. if (ExpLoc.first != FID ||
  351. SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second) != LineNo) {
  352. // If this is a single-line __asm, we're done, except if the next
  353. // line begins with an __asm too, in which case we finish a comment
  354. // if needed and then keep processing the next line as a single
  355. // line __asm.
  356. bool isAsm = Tok.is(tok::kw_asm);
  357. if (SingleLineMode && !isAsm)
  358. break;
  359. // We're no longer in a comment.
  360. InAsmComment = false;
  361. if (isAsm) {
  362. LineNo = SrcMgr.getLineNumber(ExpLoc.first, ExpLoc.second);
  363. SkippedStartOfLine = Tok.isAtStartOfLine();
  364. }
  365. } else if (!InAsmComment && Tok.is(tok::r_brace)) {
  366. // In MSVC mode, braces only participate in brace matching and
  367. // separating the asm statements. This is an intentional
  368. // departure from the Apple gcc behavior.
  369. if (!BraceNesting)
  370. break;
  371. }
  372. }
  373. if (!InAsmComment && BraceNesting && Tok.is(tok::r_brace) &&
  374. BraceCount == (savedBraceCount + BraceNesting)) {
  375. // Consume the closing brace.
  376. SkippedStartOfLine = Tok.isAtStartOfLine();
  377. EndLoc = ConsumeBrace();
  378. BraceNesting--;
  379. // Finish if all of the opened braces in the inline asm section were
  380. // consumed.
  381. if (BraceNesting == 0 && !SingleLineMode)
  382. break;
  383. else {
  384. LBraceLocs.pop_back();
  385. TokLoc = Tok.getLocation();
  386. ++NumTokensRead;
  387. continue;
  388. }
  389. }
  390. // Consume the next token; make sure we don't modify the brace count etc.
  391. // if we are in a comment.
  392. EndLoc = TokLoc;
  393. if (InAsmComment)
  394. PP.Lex(Tok);
  395. else {
  396. // Set the token as the start of line if we skipped the original start
  397. // of line token in case it was a nested brace.
  398. if (SkippedStartOfLine)
  399. Tok.setFlag(Token::StartOfLine);
  400. AsmToks.push_back(Tok);
  401. ConsumeAnyToken();
  402. }
  403. TokLoc = Tok.getLocation();
  404. ++NumTokensRead;
  405. SkippedStartOfLine = false;
  406. } while (1);
  407. if (BraceNesting && BraceCount != savedBraceCount) {
  408. // __asm without closing brace (this can happen at EOF).
  409. for (unsigned i = 0; i < BraceNesting; ++i) {
  410. Diag(Tok, diag::err_expected) << tok::r_brace;
  411. Diag(LBraceLocs.back(), diag::note_matching) << tok::l_brace;
  412. LBraceLocs.pop_back();
  413. }
  414. return StmtError();
  415. } else if (NumTokensRead == 0) {
  416. // Empty __asm.
  417. Diag(Tok, diag::err_expected) << tok::l_brace;
  418. return StmtError();
  419. }
  420. // Okay, prepare to use MC to parse the assembly.
  421. SmallVector<StringRef, 4> ConstraintRefs;
  422. SmallVector<Expr *, 4> Exprs;
  423. SmallVector<StringRef, 4> ClobberRefs;
  424. // We need an actual supported target.
  425. const llvm::Triple &TheTriple = Actions.Context.getTargetInfo().getTriple();
  426. llvm::Triple::ArchType ArchTy = TheTriple.getArch();
  427. const std::string &TT = TheTriple.getTriple();
  428. const llvm::Target *TheTarget = nullptr;
  429. bool UnsupportedArch =
  430. (ArchTy != llvm::Triple::x86 && ArchTy != llvm::Triple::x86_64);
  431. if (UnsupportedArch) {
  432. Diag(AsmLoc, diag::err_msasm_unsupported_arch) << TheTriple.getArchName();
  433. } else {
  434. std::string Error;
  435. TheTarget = llvm::TargetRegistry::lookupTarget(TT, Error);
  436. if (!TheTarget)
  437. Diag(AsmLoc, diag::err_msasm_unable_to_create_target) << Error;
  438. }
  439. assert(!LBraceLocs.empty() && "Should have at least one location here");
  440. // If we don't support assembly, or the assembly is empty, we don't
  441. // need to instantiate the AsmParser, etc.
  442. if (!TheTarget || AsmToks.empty()) {
  443. return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, StringRef(),
  444. /*NumOutputs*/ 0, /*NumInputs*/ 0,
  445. ConstraintRefs, ClobberRefs, Exprs, EndLoc);
  446. }
  447. // Expand the tokens into a string buffer.
  448. SmallString<512> AsmString;
  449. SmallVector<unsigned, 8> TokOffsets;
  450. if (buildMSAsmString(PP, AsmLoc, AsmToks, TokOffsets, AsmString))
  451. return StmtError();
  452. std::unique_ptr<llvm::MCRegisterInfo> MRI(TheTarget->createMCRegInfo(TT));
  453. std::unique_ptr<llvm::MCAsmInfo> MAI(TheTarget->createMCAsmInfo(*MRI, TT));
  454. // Get the instruction descriptor.
  455. std::unique_ptr<llvm::MCInstrInfo> MII(TheTarget->createMCInstrInfo());
  456. std::unique_ptr<llvm::MCObjectFileInfo> MOFI(new llvm::MCObjectFileInfo());
  457. std::unique_ptr<llvm::MCSubtargetInfo> STI(
  458. TheTarget->createMCSubtargetInfo(TT, "", ""));
  459. llvm::SourceMgr TempSrcMgr;
  460. llvm::MCContext Ctx(MAI.get(), MRI.get(), MOFI.get(), &TempSrcMgr);
  461. MOFI->InitMCObjectFileInfo(TheTriple, llvm::Reloc::Default,
  462. llvm::CodeModel::Default, Ctx);
  463. std::unique_ptr<llvm::MemoryBuffer> Buffer =
  464. llvm::MemoryBuffer::getMemBuffer(AsmString, "<MS inline asm>");
  465. // Tell SrcMgr about this buffer, which is what the parser will pick up.
  466. TempSrcMgr.AddNewSourceBuffer(std::move(Buffer), llvm::SMLoc());
  467. std::unique_ptr<llvm::MCStreamer> Str(createNullStreamer(Ctx));
  468. std::unique_ptr<llvm::MCAsmParser> Parser(
  469. createMCAsmParser(TempSrcMgr, Ctx, *Str.get(), *MAI));
  470. // FIXME: init MCOptions from sanitizer flags here.
  471. llvm::MCTargetOptions MCOptions;
  472. std::unique_ptr<llvm::MCTargetAsmParser> TargetParser(
  473. TheTarget->createMCAsmParser(*STI, *Parser, *MII, MCOptions));
  474. std::unique_ptr<llvm::MCInstPrinter> IP(
  475. TheTarget->createMCInstPrinter(llvm::Triple(TT), 1, *MAI, *MII, *MRI));
  476. // Change to the Intel dialect.
  477. Parser->setAssemblerDialect(1);
  478. Parser->setTargetParser(*TargetParser.get());
  479. Parser->setParsingInlineAsm(true);
  480. TargetParser->setParsingInlineAsm(true);
  481. ClangAsmParserCallback Callback(*this, AsmLoc, AsmString, AsmToks,
  482. TokOffsets);
  483. TargetParser->setSemaCallback(&Callback);
  484. TempSrcMgr.setDiagHandler(ClangAsmParserCallback::DiagHandlerCallback,
  485. &Callback);
  486. unsigned NumOutputs;
  487. unsigned NumInputs;
  488. std::string AsmStringIR;
  489. SmallVector<std::pair<void *, bool>, 4> OpExprs;
  490. SmallVector<std::string, 4> Constraints;
  491. SmallVector<std::string, 4> Clobbers;
  492. if (Parser->parseMSInlineAsm(AsmLoc.getPtrEncoding(), AsmStringIR, NumOutputs,
  493. NumInputs, OpExprs, Constraints, Clobbers,
  494. MII.get(), IP.get(), Callback))
  495. return StmtError();
  496. // Filter out "fpsw". Clang doesn't accept it, and it always lists flags and
  497. // fpsr as clobbers.
  498. auto End = std::remove(Clobbers.begin(), Clobbers.end(), "fpsw");
  499. Clobbers.erase(End, Clobbers.end());
  500. // Build the vector of clobber StringRefs.
  501. ClobberRefs.insert(ClobberRefs.end(), Clobbers.begin(), Clobbers.end());
  502. // Recast the void pointers and build the vector of constraint StringRefs.
  503. unsigned NumExprs = NumOutputs + NumInputs;
  504. ConstraintRefs.resize(NumExprs);
  505. Exprs.resize(NumExprs);
  506. for (unsigned i = 0, e = NumExprs; i != e; ++i) {
  507. Expr *OpExpr = static_cast<Expr *>(OpExprs[i].first);
  508. if (!OpExpr)
  509. return StmtError();
  510. // Need address of variable.
  511. if (OpExprs[i].second)
  512. OpExpr =
  513. Actions.BuildUnaryOp(getCurScope(), AsmLoc, UO_AddrOf, OpExpr).get();
  514. ConstraintRefs[i] = StringRef(Constraints[i]);
  515. Exprs[i] = OpExpr;
  516. }
  517. // FIXME: We should be passing source locations for better diagnostics.
  518. return Actions.ActOnMSAsmStmt(AsmLoc, LBraceLocs[0], AsmToks, AsmStringIR,
  519. NumOutputs, NumInputs, ConstraintRefs,
  520. ClobberRefs, Exprs, EndLoc);
  521. #endif // HLSL Change
  522. }
  523. /// ParseAsmStatement - Parse a GNU extended asm statement.
  524. /// asm-statement:
  525. /// gnu-asm-statement
  526. /// ms-asm-statement
  527. ///
  528. /// [GNU] gnu-asm-statement:
  529. /// 'asm' type-qualifier[opt] '(' asm-argument ')' ';'
  530. ///
  531. /// [GNU] asm-argument:
  532. /// asm-string-literal
  533. /// asm-string-literal ':' asm-operands[opt]
  534. /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
  535. /// asm-string-literal ':' asm-operands[opt] ':' asm-operands[opt]
  536. /// ':' asm-clobbers
  537. ///
  538. /// [GNU] asm-clobbers:
  539. /// asm-string-literal
  540. /// asm-clobbers ',' asm-string-literal
  541. ///
  542. StmtResult Parser::ParseAsmStatement(bool &msAsm) {
  543. assert(!getLangOpts().HLSL && "no GNU assembly support in HLSL"); // HLSL Change
  544. assert(Tok.is(tok::kw_asm) && "Not an asm stmt");
  545. SourceLocation AsmLoc = ConsumeToken();
  546. if (getLangOpts().AsmBlocks && Tok.isNot(tok::l_paren) &&
  547. !isTypeQualifier()) {
  548. msAsm = true;
  549. return ParseMicrosoftAsmStatement(AsmLoc);
  550. }
  551. DeclSpec DS(AttrFactory);
  552. SourceLocation Loc = Tok.getLocation();
  553. ParseTypeQualifierListOpt(DS, AR_VendorAttributesParsed);
  554. // GNU asms accept, but warn, about type-qualifiers other than volatile.
  555. if (DS.getTypeQualifiers() & DeclSpec::TQ_const)
  556. Diag(Loc, diag::w_asm_qualifier_ignored) << "const";
  557. if (DS.getTypeQualifiers() & DeclSpec::TQ_restrict)
  558. Diag(Loc, diag::w_asm_qualifier_ignored) << "restrict";
  559. // FIXME: Once GCC supports _Atomic, check whether it permits it here.
  560. if (DS.getTypeQualifiers() & DeclSpec::TQ_atomic)
  561. Diag(Loc, diag::w_asm_qualifier_ignored) << "_Atomic";
  562. // Remember if this was a volatile asm.
  563. bool isVolatile = DS.getTypeQualifiers() & DeclSpec::TQ_volatile;
  564. if (Tok.isNot(tok::l_paren)) {
  565. Diag(Tok, diag::err_expected_lparen_after) << "asm";
  566. SkipUntil(tok::r_paren, StopAtSemi);
  567. return StmtError();
  568. }
  569. BalancedDelimiterTracker T(*this, tok::l_paren);
  570. T.consumeOpen();
  571. ExprResult AsmString(ParseAsmStringLiteral());
  572. // Check if GNU-style InlineAsm is disabled.
  573. // Error on anything other than empty string.
  574. if (!(getLangOpts().GNUAsm || AsmString.isInvalid())) {
  575. const auto *SL = cast<StringLiteral>(AsmString.get());
  576. if (!SL->getString().trim().empty())
  577. Diag(Loc, diag::err_gnu_inline_asm_disabled);
  578. }
  579. if (AsmString.isInvalid()) {
  580. // Consume up to and including the closing paren.
  581. T.skipToEnd();
  582. return StmtError();
  583. }
  584. SmallVector<IdentifierInfo *, 4> Names;
  585. ExprVector Constraints;
  586. ExprVector Exprs;
  587. ExprVector Clobbers;
  588. if (Tok.is(tok::r_paren)) {
  589. // We have a simple asm expression like 'asm("foo")'.
  590. T.consumeClose();
  591. return Actions.ActOnGCCAsmStmt(AsmLoc, /*isSimple*/ true, isVolatile,
  592. /*NumOutputs*/ 0, /*NumInputs*/ 0, nullptr,
  593. Constraints, Exprs, AsmString.get(),
  594. Clobbers, T.getCloseLocation());
  595. }
  596. // Parse Outputs, if present.
  597. bool AteExtraColon = false;
  598. if (Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
  599. // In C++ mode, parse "::" like ": :".
  600. AteExtraColon = Tok.is(tok::coloncolon);
  601. ConsumeToken();
  602. if (!AteExtraColon && ParseAsmOperandsOpt(Names, Constraints, Exprs))
  603. return StmtError();
  604. }
  605. unsigned NumOutputs = Names.size();
  606. // Parse Inputs, if present.
  607. if (AteExtraColon || Tok.is(tok::colon) || Tok.is(tok::coloncolon)) {
  608. // In C++ mode, parse "::" like ": :".
  609. if (AteExtraColon)
  610. AteExtraColon = false;
  611. else {
  612. AteExtraColon = Tok.is(tok::coloncolon);
  613. ConsumeToken();
  614. }
  615. if (!AteExtraColon && ParseAsmOperandsOpt(Names, Constraints, Exprs))
  616. return StmtError();
  617. }
  618. assert(Names.size() == Constraints.size() &&
  619. Constraints.size() == Exprs.size() && "Input operand size mismatch!");
  620. unsigned NumInputs = Names.size() - NumOutputs;
  621. // Parse the clobbers, if present.
  622. if (AteExtraColon || Tok.is(tok::colon)) {
  623. if (!AteExtraColon)
  624. ConsumeToken();
  625. // Parse the asm-string list for clobbers if present.
  626. if (Tok.isNot(tok::r_paren)) {
  627. while (1) {
  628. ExprResult Clobber(ParseAsmStringLiteral());
  629. if (Clobber.isInvalid())
  630. break;
  631. Clobbers.push_back(Clobber.get());
  632. if (!TryConsumeToken(tok::comma))
  633. break;
  634. }
  635. }
  636. }
  637. T.consumeClose();
  638. return Actions.ActOnGCCAsmStmt(
  639. AsmLoc, false, isVolatile, NumOutputs, NumInputs, Names.data(),
  640. Constraints, Exprs, AsmString.get(), Clobbers, T.getCloseLocation());
  641. }
  642. /// ParseAsmOperands - Parse the asm-operands production as used by
  643. /// asm-statement, assuming the leading ':' token was eaten.
  644. ///
  645. /// [GNU] asm-operands:
  646. /// asm-operand
  647. /// asm-operands ',' asm-operand
  648. ///
  649. /// [GNU] asm-operand:
  650. /// asm-string-literal '(' expression ')'
  651. /// '[' identifier ']' asm-string-literal '(' expression ')'
  652. ///
  653. //
  654. // FIXME: Avoid unnecessary std::string trashing.
  655. bool Parser::ParseAsmOperandsOpt(SmallVectorImpl<IdentifierInfo *> &Names,
  656. SmallVectorImpl<Expr *> &Constraints,
  657. SmallVectorImpl<Expr *> &Exprs) {
  658. assert(!getLangOpts().HLSL && "no assembly support in HLSL"); // HLSL Change
  659. // 'asm-operands' isn't present?
  660. if (!isTokenStringLiteral() && Tok.isNot(tok::l_square))
  661. return false;
  662. while (1) {
  663. // Read the [id] if present.
  664. if (Tok.is(tok::l_square)) {
  665. BalancedDelimiterTracker T(*this, tok::l_square);
  666. T.consumeOpen();
  667. if (Tok.isNot(tok::identifier)) {
  668. Diag(Tok, diag::err_expected) << tok::identifier;
  669. SkipUntil(tok::r_paren, StopAtSemi);
  670. return true;
  671. }
  672. IdentifierInfo *II = Tok.getIdentifierInfo();
  673. ConsumeToken();
  674. Names.push_back(II);
  675. T.consumeClose();
  676. } else
  677. Names.push_back(nullptr);
  678. ExprResult Constraint(ParseAsmStringLiteral());
  679. if (Constraint.isInvalid()) {
  680. SkipUntil(tok::r_paren, StopAtSemi);
  681. return true;
  682. }
  683. Constraints.push_back(Constraint.get());
  684. if (Tok.isNot(tok::l_paren)) {
  685. Diag(Tok, diag::err_expected_lparen_after) << "asm operand";
  686. SkipUntil(tok::r_paren, StopAtSemi);
  687. return true;
  688. }
  689. // Read the parenthesized expression.
  690. BalancedDelimiterTracker T(*this, tok::l_paren);
  691. T.consumeOpen();
  692. ExprResult Res = Actions.CorrectDelayedTyposInExpr(ParseExpression());
  693. T.consumeClose();
  694. if (Res.isInvalid()) {
  695. SkipUntil(tok::r_paren, StopAtSemi);
  696. return true;
  697. }
  698. Exprs.push_back(Res.get());
  699. // Eat the comma and continue parsing if it exists.
  700. if (!TryConsumeToken(tok::comma))
  701. return false;
  702. }
  703. }