SemaStmtAsm.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930
  1. //===--- SemaStmtAsm.cpp - Semantic Analysis for Asm Statements -----------===//
  2. //
  3. // Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
  4. // See https://llvm.org/LICENSE.txt for license information.
  5. // SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
  6. //
  7. //===----------------------------------------------------------------------===//
  8. //
  9. // This file implements semantic analysis for inline asm statements.
  10. //
  11. //===----------------------------------------------------------------------===//
  12. #include "clang/AST/ExprCXX.h"
  13. #include "clang/AST/RecordLayout.h"
  14. #include "clang/AST/TypeLoc.h"
  15. #include "clang/Basic/TargetInfo.h"
  16. #include "clang/Lex/Preprocessor.h"
  17. #include "clang/Sema/Initialization.h"
  18. #include "clang/Sema/Lookup.h"
  19. #include "clang/Sema/Scope.h"
  20. #include "clang/Sema/ScopeInfo.h"
  21. #include "clang/Sema/SemaInternal.h"
  22. #include "llvm/ADT/ArrayRef.h"
  23. #include "llvm/ADT/StringSet.h"
  24. #include "llvm/MC/MCParser/MCAsmParser.h"
  25. using namespace clang;
  26. using namespace sema;
  27. /// Remove the upper-level LValueToRValue cast from an expression.
  28. static void removeLValueToRValueCast(Expr *E) {
  29. Expr *Parent = E;
  30. Expr *ExprUnderCast = nullptr;
  31. SmallVector<Expr *, 8> ParentsToUpdate;
  32. while (true) {
  33. ParentsToUpdate.push_back(Parent);
  34. if (auto *ParenE = dyn_cast<ParenExpr>(Parent)) {
  35. Parent = ParenE->getSubExpr();
  36. continue;
  37. }
  38. Expr *Child = nullptr;
  39. CastExpr *ParentCast = dyn_cast<CastExpr>(Parent);
  40. if (ParentCast)
  41. Child = ParentCast->getSubExpr();
  42. else
  43. return;
  44. if (auto *CastE = dyn_cast<CastExpr>(Child))
  45. if (CastE->getCastKind() == CK_LValueToRValue) {
  46. ExprUnderCast = CastE->getSubExpr();
  47. // LValueToRValue cast inside GCCAsmStmt requires an explicit cast.
  48. ParentCast->setSubExpr(ExprUnderCast);
  49. break;
  50. }
  51. Parent = Child;
  52. }
  53. // Update parent expressions to have same ValueType as the underlying.
  54. assert(ExprUnderCast &&
  55. "Should be reachable only if LValueToRValue cast was found!");
  56. auto ValueKind = ExprUnderCast->getValueKind();
  57. for (Expr *E : ParentsToUpdate)
  58. E->setValueKind(ValueKind);
  59. }
  60. /// Emit a warning about usage of "noop"-like casts for lvalues (GNU extension)
  61. /// and fix the argument with removing LValueToRValue cast from the expression.
  62. static void emitAndFixInvalidAsmCastLValue(const Expr *LVal, Expr *BadArgument,
  63. Sema &S) {
  64. if (!S.getLangOpts().HeinousExtensions) {
  65. S.Diag(LVal->getBeginLoc(), diag::err_invalid_asm_cast_lvalue)
  66. << BadArgument->getSourceRange();
  67. } else {
  68. S.Diag(LVal->getBeginLoc(), diag::warn_invalid_asm_cast_lvalue)
  69. << BadArgument->getSourceRange();
  70. }
  71. removeLValueToRValueCast(BadArgument);
  72. }
  73. /// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
  74. /// ignore "noop" casts in places where an lvalue is required by an inline asm.
  75. /// We emulate this behavior when -fheinous-gnu-extensions is specified, but
  76. /// provide a strong guidance to not use it.
  77. ///
  78. /// This method checks to see if the argument is an acceptable l-value and
  79. /// returns false if it is a case we can handle.
  80. static bool CheckAsmLValue(Expr *E, Sema &S) {
  81. // Type dependent expressions will be checked during instantiation.
  82. if (E->isTypeDependent())
  83. return false;
  84. if (E->isLValue())
  85. return false; // Cool, this is an lvalue.
  86. // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
  87. // are supposed to allow.
  88. const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
  89. if (E != E2 && E2->isLValue()) {
  90. emitAndFixInvalidAsmCastLValue(E2, E, S);
  91. // Accept, even if we emitted an error diagnostic.
  92. return false;
  93. }
  94. // None of the above, just randomly invalid non-lvalue.
  95. return true;
  96. }
  97. /// isOperandMentioned - Return true if the specified operand # is mentioned
  98. /// anywhere in the decomposed asm string.
  99. static bool
  100. isOperandMentioned(unsigned OpNo,
  101. ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
  102. for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
  103. const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
  104. if (!Piece.isOperand())
  105. continue;
  106. // If this is a reference to the input and if the input was the smaller
  107. // one, then we have to reject this asm.
  108. if (Piece.getOperandNo() == OpNo)
  109. return true;
  110. }
  111. return false;
  112. }
  113. static bool CheckNakedParmReference(Expr *E, Sema &S) {
  114. FunctionDecl *Func = dyn_cast<FunctionDecl>(S.CurContext);
  115. if (!Func)
  116. return false;
  117. if (!Func->hasAttr<NakedAttr>())
  118. return false;
  119. SmallVector<Expr*, 4> WorkList;
  120. WorkList.push_back(E);
  121. while (WorkList.size()) {
  122. Expr *E = WorkList.pop_back_val();
  123. if (isa<CXXThisExpr>(E)) {
  124. S.Diag(E->getBeginLoc(), diag::err_asm_naked_this_ref);
  125. S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
  126. return true;
  127. }
  128. if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
  129. if (isa<ParmVarDecl>(DRE->getDecl())) {
  130. S.Diag(DRE->getBeginLoc(), diag::err_asm_naked_parm_ref);
  131. S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
  132. return true;
  133. }
  134. }
  135. for (Stmt *Child : E->children()) {
  136. if (Expr *E = dyn_cast_or_null<Expr>(Child))
  137. WorkList.push_back(E);
  138. }
  139. }
  140. return false;
  141. }
  142. /// Returns true if given expression is not compatible with inline
  143. /// assembly's memory constraint; false otherwise.
  144. static bool checkExprMemoryConstraintCompat(Sema &S, Expr *E,
  145. TargetInfo::ConstraintInfo &Info,
  146. bool is_input_expr) {
  147. enum {
  148. ExprBitfield = 0,
  149. ExprVectorElt,
  150. ExprGlobalRegVar,
  151. ExprSafeType
  152. } EType = ExprSafeType;
  153. // Bitfields, vector elements and global register variables are not
  154. // compatible.
  155. if (E->refersToBitField())
  156. EType = ExprBitfield;
  157. else if (E->refersToVectorElement())
  158. EType = ExprVectorElt;
  159. else if (E->refersToGlobalRegisterVar())
  160. EType = ExprGlobalRegVar;
  161. if (EType != ExprSafeType) {
  162. S.Diag(E->getBeginLoc(), diag::err_asm_non_addr_value_in_memory_constraint)
  163. << EType << is_input_expr << Info.getConstraintStr()
  164. << E->getSourceRange();
  165. return true;
  166. }
  167. return false;
  168. }
  169. // Extracting the register name from the Expression value,
  170. // if there is no register name to extract, returns ""
  171. static StringRef extractRegisterName(const Expr *Expression,
  172. const TargetInfo &Target) {
  173. Expression = Expression->IgnoreImpCasts();
  174. if (const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(Expression)) {
  175. // Handle cases where the expression is a variable
  176. const VarDecl *Variable = dyn_cast<VarDecl>(AsmDeclRef->getDecl());
  177. if (Variable && Variable->getStorageClass() == SC_Register) {
  178. if (AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>())
  179. if (Target.isValidGCCRegisterName(Attr->getLabel()))
  180. return Target.getNormalizedGCCRegisterName(Attr->getLabel(), true);
  181. }
  182. }
  183. return "";
  184. }
  185. // Checks if there is a conflict between the input and output lists with the
  186. // clobbers list. If there's a conflict, returns the location of the
  187. // conflicted clobber, else returns nullptr
  188. static SourceLocation
  189. getClobberConflictLocation(MultiExprArg Exprs, StringLiteral **Constraints,
  190. StringLiteral **Clobbers, int NumClobbers,
  191. unsigned NumLabels,
  192. const TargetInfo &Target, ASTContext &Cont) {
  193. llvm::StringSet<> InOutVars;
  194. // Collect all the input and output registers from the extended asm
  195. // statement in order to check for conflicts with the clobber list
  196. for (unsigned int i = 0; i < Exprs.size() - NumLabels; ++i) {
  197. StringRef Constraint = Constraints[i]->getString();
  198. StringRef InOutReg = Target.getConstraintRegister(
  199. Constraint, extractRegisterName(Exprs[i], Target));
  200. if (InOutReg != "")
  201. InOutVars.insert(InOutReg);
  202. }
  203. // Check for each item in the clobber list if it conflicts with the input
  204. // or output
  205. for (int i = 0; i < NumClobbers; ++i) {
  206. StringRef Clobber = Clobbers[i]->getString();
  207. // We only check registers, therefore we don't check cc and memory
  208. // clobbers
  209. if (Clobber == "cc" || Clobber == "memory")
  210. continue;
  211. Clobber = Target.getNormalizedGCCRegisterName(Clobber, true);
  212. // Go over the output's registers we collected
  213. if (InOutVars.count(Clobber))
  214. return Clobbers[i]->getBeginLoc();
  215. }
  216. return SourceLocation();
  217. }
  218. StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
  219. bool IsVolatile, unsigned NumOutputs,
  220. unsigned NumInputs, IdentifierInfo **Names,
  221. MultiExprArg constraints, MultiExprArg Exprs,
  222. Expr *asmString, MultiExprArg clobbers,
  223. unsigned NumLabels,
  224. SourceLocation RParenLoc) {
  225. unsigned NumClobbers = clobbers.size();
  226. StringLiteral **Constraints =
  227. reinterpret_cast<StringLiteral**>(constraints.data());
  228. StringLiteral *AsmString = cast<StringLiteral>(asmString);
  229. StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data());
  230. SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
  231. // The parser verifies that there is a string literal here.
  232. assert(AsmString->isAscii());
  233. for (unsigned i = 0; i != NumOutputs; i++) {
  234. StringLiteral *Literal = Constraints[i];
  235. assert(Literal->isAscii());
  236. StringRef OutputName;
  237. if (Names[i])
  238. OutputName = Names[i]->getName();
  239. TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
  240. if (!Context.getTargetInfo().validateOutputConstraint(Info)) {
  241. targetDiag(Literal->getBeginLoc(),
  242. diag::err_asm_invalid_output_constraint)
  243. << Info.getConstraintStr();
  244. return new (Context)
  245. GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
  246. NumInputs, Names, Constraints, Exprs.data(), AsmString,
  247. NumClobbers, Clobbers, NumLabels, RParenLoc);
  248. }
  249. ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
  250. if (ER.isInvalid())
  251. return StmtError();
  252. Exprs[i] = ER.get();
  253. // Check that the output exprs are valid lvalues.
  254. Expr *OutputExpr = Exprs[i];
  255. // Referring to parameters is not allowed in naked functions.
  256. if (CheckNakedParmReference(OutputExpr, *this))
  257. return StmtError();
  258. // Check that the output expression is compatible with memory constraint.
  259. if (Info.allowsMemory() &&
  260. checkExprMemoryConstraintCompat(*this, OutputExpr, Info, false))
  261. return StmtError();
  262. OutputConstraintInfos.push_back(Info);
  263. // If this is dependent, just continue.
  264. if (OutputExpr->isTypeDependent())
  265. continue;
  266. Expr::isModifiableLvalueResult IsLV =
  267. OutputExpr->isModifiableLvalue(Context, /*Loc=*/nullptr);
  268. switch (IsLV) {
  269. case Expr::MLV_Valid:
  270. // Cool, this is an lvalue.
  271. break;
  272. case Expr::MLV_ArrayType:
  273. // This is OK too.
  274. break;
  275. case Expr::MLV_LValueCast: {
  276. const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Context);
  277. emitAndFixInvalidAsmCastLValue(LVal, OutputExpr, *this);
  278. // Accept, even if we emitted an error diagnostic.
  279. break;
  280. }
  281. case Expr::MLV_IncompleteType:
  282. case Expr::MLV_IncompleteVoidType:
  283. if (RequireCompleteType(OutputExpr->getBeginLoc(), Exprs[i]->getType(),
  284. diag::err_dereference_incomplete_type))
  285. return StmtError();
  286. LLVM_FALLTHROUGH;
  287. default:
  288. return StmtError(Diag(OutputExpr->getBeginLoc(),
  289. diag::err_asm_invalid_lvalue_in_output)
  290. << OutputExpr->getSourceRange());
  291. }
  292. unsigned Size = Context.getTypeSize(OutputExpr->getType());
  293. if (!Context.getTargetInfo().validateOutputSize(Literal->getString(),
  294. Size)) {
  295. targetDiag(OutputExpr->getBeginLoc(), diag::err_asm_invalid_output_size)
  296. << Info.getConstraintStr();
  297. return new (Context)
  298. GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
  299. NumInputs, Names, Constraints, Exprs.data(), AsmString,
  300. NumClobbers, Clobbers, NumLabels, RParenLoc);
  301. }
  302. }
  303. SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
  304. for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
  305. StringLiteral *Literal = Constraints[i];
  306. assert(Literal->isAscii());
  307. StringRef InputName;
  308. if (Names[i])
  309. InputName = Names[i]->getName();
  310. TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
  311. if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos,
  312. Info)) {
  313. targetDiag(Literal->getBeginLoc(), diag::err_asm_invalid_input_constraint)
  314. << Info.getConstraintStr();
  315. return new (Context)
  316. GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
  317. NumInputs, Names, Constraints, Exprs.data(), AsmString,
  318. NumClobbers, Clobbers, NumLabels, RParenLoc);
  319. }
  320. ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
  321. if (ER.isInvalid())
  322. return StmtError();
  323. Exprs[i] = ER.get();
  324. Expr *InputExpr = Exprs[i];
  325. // Referring to parameters is not allowed in naked functions.
  326. if (CheckNakedParmReference(InputExpr, *this))
  327. return StmtError();
  328. // Check that the input expression is compatible with memory constraint.
  329. if (Info.allowsMemory() &&
  330. checkExprMemoryConstraintCompat(*this, InputExpr, Info, true))
  331. return StmtError();
  332. // Only allow void types for memory constraints.
  333. if (Info.allowsMemory() && !Info.allowsRegister()) {
  334. if (CheckAsmLValue(InputExpr, *this))
  335. return StmtError(Diag(InputExpr->getBeginLoc(),
  336. diag::err_asm_invalid_lvalue_in_input)
  337. << Info.getConstraintStr()
  338. << InputExpr->getSourceRange());
  339. } else if (Info.requiresImmediateConstant() && !Info.allowsRegister()) {
  340. if (!InputExpr->isValueDependent()) {
  341. Expr::EvalResult EVResult;
  342. if (InputExpr->EvaluateAsRValue(EVResult, Context, true)) {
  343. // For compatibility with GCC, we also allow pointers that would be
  344. // integral constant expressions if they were cast to int.
  345. llvm::APSInt IntResult;
  346. if (EVResult.Val.toIntegralConstant(IntResult, InputExpr->getType(),
  347. Context))
  348. if (!Info.isValidAsmImmediate(IntResult))
  349. return StmtError(Diag(InputExpr->getBeginLoc(),
  350. diag::err_invalid_asm_value_for_constraint)
  351. << IntResult.toString(10)
  352. << Info.getConstraintStr()
  353. << InputExpr->getSourceRange());
  354. }
  355. }
  356. } else {
  357. ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
  358. if (Result.isInvalid())
  359. return StmtError();
  360. Exprs[i] = Result.get();
  361. }
  362. if (Info.allowsRegister()) {
  363. if (InputExpr->getType()->isVoidType()) {
  364. return StmtError(
  365. Diag(InputExpr->getBeginLoc(), diag::err_asm_invalid_type_in_input)
  366. << InputExpr->getType() << Info.getConstraintStr()
  367. << InputExpr->getSourceRange());
  368. }
  369. }
  370. InputConstraintInfos.push_back(Info);
  371. const Type *Ty = Exprs[i]->getType().getTypePtr();
  372. if (Ty->isDependentType())
  373. continue;
  374. if (!Ty->isVoidType() || !Info.allowsMemory())
  375. if (RequireCompleteType(InputExpr->getBeginLoc(), Exprs[i]->getType(),
  376. diag::err_dereference_incomplete_type))
  377. return StmtError();
  378. unsigned Size = Context.getTypeSize(Ty);
  379. if (!Context.getTargetInfo().validateInputSize(Literal->getString(),
  380. Size))
  381. return StmtResult(
  382. targetDiag(InputExpr->getBeginLoc(), diag::err_asm_invalid_input_size)
  383. << Info.getConstraintStr());
  384. }
  385. // Check that the clobbers are valid.
  386. for (unsigned i = 0; i != NumClobbers; i++) {
  387. StringLiteral *Literal = Clobbers[i];
  388. assert(Literal->isAscii());
  389. StringRef Clobber = Literal->getString();
  390. if (!Context.getTargetInfo().isValidClobber(Clobber)) {
  391. targetDiag(Literal->getBeginLoc(), diag::err_asm_unknown_register_name)
  392. << Clobber;
  393. return new (Context)
  394. GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
  395. NumInputs, Names, Constraints, Exprs.data(), AsmString,
  396. NumClobbers, Clobbers, NumLabels, RParenLoc);
  397. }
  398. }
  399. GCCAsmStmt *NS =
  400. new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
  401. NumInputs, Names, Constraints, Exprs.data(),
  402. AsmString, NumClobbers, Clobbers, NumLabels,
  403. RParenLoc);
  404. // Validate the asm string, ensuring it makes sense given the operands we
  405. // have.
  406. SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
  407. unsigned DiagOffs;
  408. if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
  409. targetDiag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
  410. << AsmString->getSourceRange();
  411. return NS;
  412. }
  413. // Validate constraints and modifiers.
  414. for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
  415. GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
  416. if (!Piece.isOperand()) continue;
  417. // Look for the correct constraint index.
  418. unsigned ConstraintIdx = Piece.getOperandNo();
  419. // Labels are the last in the Exprs list.
  420. if (NS->isAsmGoto() && ConstraintIdx >= NS->getNumInputs())
  421. continue;
  422. unsigned NumOperands = NS->getNumOutputs() + NS->getNumInputs();
  423. // Look for the (ConstraintIdx - NumOperands + 1)th constraint with
  424. // modifier '+'.
  425. if (ConstraintIdx >= NumOperands) {
  426. unsigned I = 0, E = NS->getNumOutputs();
  427. for (unsigned Cnt = ConstraintIdx - NumOperands; I != E; ++I)
  428. if (OutputConstraintInfos[I].isReadWrite() && Cnt-- == 0) {
  429. ConstraintIdx = I;
  430. break;
  431. }
  432. assert(I != E && "Invalid operand number should have been caught in "
  433. " AnalyzeAsmString");
  434. }
  435. // Now that we have the right indexes go ahead and check.
  436. StringLiteral *Literal = Constraints[ConstraintIdx];
  437. const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
  438. if (Ty->isDependentType() || Ty->isIncompleteType())
  439. continue;
  440. unsigned Size = Context.getTypeSize(Ty);
  441. std::string SuggestedModifier;
  442. if (!Context.getTargetInfo().validateConstraintModifier(
  443. Literal->getString(), Piece.getModifier(), Size,
  444. SuggestedModifier)) {
  445. targetDiag(Exprs[ConstraintIdx]->getBeginLoc(),
  446. diag::warn_asm_mismatched_size_modifier);
  447. if (!SuggestedModifier.empty()) {
  448. auto B = targetDiag(Piece.getRange().getBegin(),
  449. diag::note_asm_missing_constraint_modifier)
  450. << SuggestedModifier;
  451. SuggestedModifier = "%" + SuggestedModifier + Piece.getString();
  452. B << FixItHint::CreateReplacement(Piece.getRange(), SuggestedModifier);
  453. }
  454. }
  455. }
  456. // Validate tied input operands for type mismatches.
  457. unsigned NumAlternatives = ~0U;
  458. for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) {
  459. TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
  460. StringRef ConstraintStr = Info.getConstraintStr();
  461. unsigned AltCount = ConstraintStr.count(',') + 1;
  462. if (NumAlternatives == ~0U) {
  463. NumAlternatives = AltCount;
  464. } else if (NumAlternatives != AltCount) {
  465. targetDiag(NS->getOutputExpr(i)->getBeginLoc(),
  466. diag::err_asm_unexpected_constraint_alternatives)
  467. << NumAlternatives << AltCount;
  468. return NS;
  469. }
  470. }
  471. SmallVector<size_t, 4> InputMatchedToOutput(OutputConstraintInfos.size(),
  472. ~0U);
  473. for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
  474. TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
  475. StringRef ConstraintStr = Info.getConstraintStr();
  476. unsigned AltCount = ConstraintStr.count(',') + 1;
  477. if (NumAlternatives == ~0U) {
  478. NumAlternatives = AltCount;
  479. } else if (NumAlternatives != AltCount) {
  480. targetDiag(NS->getInputExpr(i)->getBeginLoc(),
  481. diag::err_asm_unexpected_constraint_alternatives)
  482. << NumAlternatives << AltCount;
  483. return NS;
  484. }
  485. // If this is a tied constraint, verify that the output and input have
  486. // either exactly the same type, or that they are int/ptr operands with the
  487. // same size (int/long, int*/long, are ok etc).
  488. if (!Info.hasTiedOperand()) continue;
  489. unsigned TiedTo = Info.getTiedOperand();
  490. unsigned InputOpNo = i+NumOutputs;
  491. Expr *OutputExpr = Exprs[TiedTo];
  492. Expr *InputExpr = Exprs[InputOpNo];
  493. // Make sure no more than one input constraint matches each output.
  494. assert(TiedTo < InputMatchedToOutput.size() && "TiedTo value out of range");
  495. if (InputMatchedToOutput[TiedTo] != ~0U) {
  496. targetDiag(NS->getInputExpr(i)->getBeginLoc(),
  497. diag::err_asm_input_duplicate_match)
  498. << TiedTo;
  499. targetDiag(NS->getInputExpr(InputMatchedToOutput[TiedTo])->getBeginLoc(),
  500. diag::note_asm_input_duplicate_first)
  501. << TiedTo;
  502. return NS;
  503. }
  504. InputMatchedToOutput[TiedTo] = i;
  505. if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
  506. continue;
  507. QualType InTy = InputExpr->getType();
  508. QualType OutTy = OutputExpr->getType();
  509. if (Context.hasSameType(InTy, OutTy))
  510. continue; // All types can be tied to themselves.
  511. // Decide if the input and output are in the same domain (integer/ptr or
  512. // floating point.
  513. enum AsmDomain {
  514. AD_Int, AD_FP, AD_Other
  515. } InputDomain, OutputDomain;
  516. if (InTy->isIntegerType() || InTy->isPointerType())
  517. InputDomain = AD_Int;
  518. else if (InTy->isRealFloatingType())
  519. InputDomain = AD_FP;
  520. else
  521. InputDomain = AD_Other;
  522. if (OutTy->isIntegerType() || OutTy->isPointerType())
  523. OutputDomain = AD_Int;
  524. else if (OutTy->isRealFloatingType())
  525. OutputDomain = AD_FP;
  526. else
  527. OutputDomain = AD_Other;
  528. // They are ok if they are the same size and in the same domain. This
  529. // allows tying things like:
  530. // void* to int*
  531. // void* to int if they are the same size.
  532. // double to long double if they are the same size.
  533. //
  534. uint64_t OutSize = Context.getTypeSize(OutTy);
  535. uint64_t InSize = Context.getTypeSize(InTy);
  536. if (OutSize == InSize && InputDomain == OutputDomain &&
  537. InputDomain != AD_Other)
  538. continue;
  539. // If the smaller input/output operand is not mentioned in the asm string,
  540. // then we can promote the smaller one to a larger input and the asm string
  541. // won't notice.
  542. bool SmallerValueMentioned = false;
  543. // If this is a reference to the input and if the input was the smaller
  544. // one, then we have to reject this asm.
  545. if (isOperandMentioned(InputOpNo, Pieces)) {
  546. // This is a use in the asm string of the smaller operand. Since we
  547. // codegen this by promoting to a wider value, the asm will get printed
  548. // "wrong".
  549. SmallerValueMentioned |= InSize < OutSize;
  550. }
  551. if (isOperandMentioned(TiedTo, Pieces)) {
  552. // If this is a reference to the output, and if the output is the larger
  553. // value, then it's ok because we'll promote the input to the larger type.
  554. SmallerValueMentioned |= OutSize < InSize;
  555. }
  556. // If the smaller value wasn't mentioned in the asm string, and if the
  557. // output was a register, just extend the shorter one to the size of the
  558. // larger one.
  559. if (!SmallerValueMentioned && InputDomain != AD_Other &&
  560. OutputConstraintInfos[TiedTo].allowsRegister())
  561. continue;
  562. // Either both of the operands were mentioned or the smaller one was
  563. // mentioned. One more special case that we'll allow: if the tied input is
  564. // integer, unmentioned, and is a constant, then we'll allow truncating it
  565. // down to the size of the destination.
  566. if (InputDomain == AD_Int && OutputDomain == AD_Int &&
  567. !isOperandMentioned(InputOpNo, Pieces) &&
  568. InputExpr->isEvaluatable(Context)) {
  569. CastKind castKind =
  570. (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
  571. InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get();
  572. Exprs[InputOpNo] = InputExpr;
  573. NS->setInputExpr(i, InputExpr);
  574. continue;
  575. }
  576. targetDiag(InputExpr->getBeginLoc(), diag::err_asm_tying_incompatible_types)
  577. << InTy << OutTy << OutputExpr->getSourceRange()
  578. << InputExpr->getSourceRange();
  579. return NS;
  580. }
  581. // Check for conflicts between clobber list and input or output lists
  582. SourceLocation ConstraintLoc =
  583. getClobberConflictLocation(Exprs, Constraints, Clobbers, NumClobbers,
  584. NumLabels,
  585. Context.getTargetInfo(), Context);
  586. if (ConstraintLoc.isValid())
  587. targetDiag(ConstraintLoc, diag::error_inoutput_conflict_with_clobber);
  588. // Check for duplicate asm operand name between input, output and label lists.
  589. typedef std::pair<StringRef , Expr *> NamedOperand;
  590. SmallVector<NamedOperand, 4> NamedOperandList;
  591. for (unsigned i = 0, e = NumOutputs + NumInputs + NumLabels; i != e; ++i)
  592. if (Names[i])
  593. NamedOperandList.emplace_back(
  594. std::make_pair(Names[i]->getName(), Exprs[i]));
  595. // Sort NamedOperandList.
  596. std::stable_sort(NamedOperandList.begin(), NamedOperandList.end(),
  597. [](const NamedOperand &LHS, const NamedOperand &RHS) {
  598. return LHS.first < RHS.first;
  599. });
  600. // Find adjacent duplicate operand.
  601. SmallVector<NamedOperand, 4>::iterator Found =
  602. std::adjacent_find(begin(NamedOperandList), end(NamedOperandList),
  603. [](const NamedOperand &LHS, const NamedOperand &RHS) {
  604. return LHS.first == RHS.first;
  605. });
  606. if (Found != NamedOperandList.end()) {
  607. Diag((Found + 1)->second->getBeginLoc(),
  608. diag::error_duplicate_asm_operand_name)
  609. << (Found + 1)->first;
  610. Diag(Found->second->getBeginLoc(), diag::note_duplicate_asm_operand_name)
  611. << Found->first;
  612. return StmtError();
  613. }
  614. if (NS->isAsmGoto())
  615. setFunctionHasBranchIntoScope();
  616. return NS;
  617. }
  618. void Sema::FillInlineAsmIdentifierInfo(Expr *Res,
  619. llvm::InlineAsmIdentifierInfo &Info) {
  620. QualType T = Res->getType();
  621. Expr::EvalResult Eval;
  622. if (T->isFunctionType() || T->isDependentType())
  623. return Info.setLabel(Res);
  624. if (Res->isRValue()) {
  625. if (isa<clang::EnumType>(T) && Res->EvaluateAsRValue(Eval, Context))
  626. return Info.setEnum(Eval.Val.getInt().getSExtValue());
  627. return Info.setLabel(Res);
  628. }
  629. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  630. unsigned Type = Size;
  631. if (const auto *ATy = Context.getAsArrayType(T))
  632. Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity();
  633. bool IsGlobalLV = false;
  634. if (Res->EvaluateAsLValue(Eval, Context))
  635. IsGlobalLV = Eval.isGlobalLValue();
  636. Info.setVar(Res, IsGlobalLV, Size, Type);
  637. }
  638. ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
  639. SourceLocation TemplateKWLoc,
  640. UnqualifiedId &Id,
  641. bool IsUnevaluatedContext) {
  642. if (IsUnevaluatedContext)
  643. PushExpressionEvaluationContext(
  644. ExpressionEvaluationContext::UnevaluatedAbstract,
  645. ReuseLambdaContextDecl);
  646. ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
  647. /*trailing lparen*/ false,
  648. /*is & operand*/ false,
  649. /*CorrectionCandidateCallback=*/nullptr,
  650. /*IsInlineAsmIdentifier=*/ true);
  651. if (IsUnevaluatedContext)
  652. PopExpressionEvaluationContext();
  653. if (!Result.isUsable()) return Result;
  654. Result = CheckPlaceholderExpr(Result.get());
  655. if (!Result.isUsable()) return Result;
  656. // Referring to parameters is not allowed in naked functions.
  657. if (CheckNakedParmReference(Result.get(), *this))
  658. return ExprError();
  659. QualType T = Result.get()->getType();
  660. if (T->isDependentType()) {
  661. return Result;
  662. }
  663. // Any sort of function type is fine.
  664. if (T->isFunctionType()) {
  665. return Result;
  666. }
  667. // Otherwise, it needs to be a complete type.
  668. if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) {
  669. return ExprError();
  670. }
  671. return Result;
  672. }
  673. bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
  674. unsigned &Offset, SourceLocation AsmLoc) {
  675. Offset = 0;
  676. SmallVector<StringRef, 2> Members;
  677. Member.split(Members, ".");
  678. NamedDecl *FoundDecl = nullptr;
  679. // MS InlineAsm uses 'this' as a base
  680. if (getLangOpts().CPlusPlus && Base.equals("this")) {
  681. if (const Type *PT = getCurrentThisType().getTypePtrOrNull())
  682. FoundDecl = PT->getPointeeType()->getAsTagDecl();
  683. } else {
  684. LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
  685. LookupOrdinaryName);
  686. if (LookupName(BaseResult, getCurScope()) && BaseResult.isSingleResult())
  687. FoundDecl = BaseResult.getFoundDecl();
  688. }
  689. if (!FoundDecl)
  690. return true;
  691. for (StringRef NextMember : Members) {
  692. const RecordType *RT = nullptr;
  693. if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
  694. RT = VD->getType()->getAs<RecordType>();
  695. else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) {
  696. MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
  697. // MS InlineAsm often uses struct pointer aliases as a base
  698. QualType QT = TD->getUnderlyingType();
  699. if (const auto *PT = QT->getAs<PointerType>())
  700. QT = PT->getPointeeType();
  701. RT = QT->getAs<RecordType>();
  702. } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl))
  703. RT = TD->getTypeForDecl()->getAs<RecordType>();
  704. else if (FieldDecl *TD = dyn_cast<FieldDecl>(FoundDecl))
  705. RT = TD->getType()->getAs<RecordType>();
  706. if (!RT)
  707. return true;
  708. if (RequireCompleteType(AsmLoc, QualType(RT, 0),
  709. diag::err_asm_incomplete_type))
  710. return true;
  711. LookupResult FieldResult(*this, &Context.Idents.get(NextMember),
  712. SourceLocation(), LookupMemberName);
  713. if (!LookupQualifiedName(FieldResult, RT->getDecl()))
  714. return true;
  715. if (!FieldResult.isSingleResult())
  716. return true;
  717. FoundDecl = FieldResult.getFoundDecl();
  718. // FIXME: Handle IndirectFieldDecl?
  719. FieldDecl *FD = dyn_cast<FieldDecl>(FoundDecl);
  720. if (!FD)
  721. return true;
  722. const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl());
  723. unsigned i = FD->getFieldIndex();
  724. CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
  725. Offset += (unsigned)Result.getQuantity();
  726. }
  727. return false;
  728. }
  729. ExprResult
  730. Sema::LookupInlineAsmVarDeclField(Expr *E, StringRef Member,
  731. SourceLocation AsmLoc) {
  732. QualType T = E->getType();
  733. if (T->isDependentType()) {
  734. DeclarationNameInfo NameInfo;
  735. NameInfo.setLoc(AsmLoc);
  736. NameInfo.setName(&Context.Idents.get(Member));
  737. return CXXDependentScopeMemberExpr::Create(
  738. Context, E, T, /*IsArrow=*/false, AsmLoc, NestedNameSpecifierLoc(),
  739. SourceLocation(),
  740. /*FirstQualifierFoundInScope=*/nullptr, NameInfo, /*TemplateArgs=*/nullptr);
  741. }
  742. const RecordType *RT = T->getAs<RecordType>();
  743. // FIXME: Diagnose this as field access into a scalar type.
  744. if (!RT)
  745. return ExprResult();
  746. LookupResult FieldResult(*this, &Context.Idents.get(Member), AsmLoc,
  747. LookupMemberName);
  748. if (!LookupQualifiedName(FieldResult, RT->getDecl()))
  749. return ExprResult();
  750. // Only normal and indirect field results will work.
  751. ValueDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
  752. if (!FD)
  753. FD = dyn_cast<IndirectFieldDecl>(FieldResult.getFoundDecl());
  754. if (!FD)
  755. return ExprResult();
  756. // Make an Expr to thread through OpDecl.
  757. ExprResult Result = BuildMemberReferenceExpr(
  758. E, E->getType(), AsmLoc, /*IsArrow=*/false, CXXScopeSpec(),
  759. SourceLocation(), nullptr, FieldResult, nullptr, nullptr);
  760. return Result;
  761. }
  762. StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
  763. ArrayRef<Token> AsmToks,
  764. StringRef AsmString,
  765. unsigned NumOutputs, unsigned NumInputs,
  766. ArrayRef<StringRef> Constraints,
  767. ArrayRef<StringRef> Clobbers,
  768. ArrayRef<Expr*> Exprs,
  769. SourceLocation EndLoc) {
  770. bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
  771. setFunctionHasBranchProtectedScope();
  772. MSAsmStmt *NS =
  773. new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
  774. /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
  775. Constraints, Exprs, AsmString,
  776. Clobbers, EndLoc);
  777. return NS;
  778. }
  779. LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
  780. SourceLocation Location,
  781. bool AlwaysCreate) {
  782. LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName),
  783. Location);
  784. if (Label->isMSAsmLabel()) {
  785. // If we have previously created this label implicitly, mark it as used.
  786. Label->markUsed(Context);
  787. } else {
  788. // Otherwise, insert it, but only resolve it if we have seen the label itself.
  789. std::string InternalName;
  790. llvm::raw_string_ostream OS(InternalName);
  791. // Create an internal name for the label. The name should not be a valid
  792. // mangled name, and should be unique. We use a dot to make the name an
  793. // invalid mangled name. We use LLVM's inline asm ${:uid} escape so that a
  794. // unique label is generated each time this blob is emitted, even after
  795. // inlining or LTO.
  796. OS << "__MSASMLABEL_.${:uid}__";
  797. for (char C : ExternalLabelName) {
  798. OS << C;
  799. // We escape '$' in asm strings by replacing it with "$$"
  800. if (C == '$')
  801. OS << '$';
  802. }
  803. Label->setMSAsmLabel(OS.str());
  804. }
  805. if (AlwaysCreate) {
  806. // The label might have been created implicitly from a previously encountered
  807. // goto statement. So, for both newly created and looked up labels, we mark
  808. // them as resolved.
  809. Label->setMSAsmLabelResolved();
  810. }
  811. // Adjust their location for being able to generate accurate diagnostics.
  812. Label->setLocation(Location);
  813. return Label;
  814. }