SemaStmtAsm.cpp 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936
  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. return StmtError(
  344. Diag(InputExpr->getBeginLoc(), diag::err_asm_immediate_expected)
  345. << Info.getConstraintStr() << InputExpr->getSourceRange());
  346. // For compatibility with GCC, we also allow pointers that would be
  347. // integral constant expressions if they were cast to int.
  348. llvm::APSInt IntResult;
  349. if (!EVResult.Val.toIntegralConstant(IntResult, InputExpr->getType(),
  350. Context))
  351. return StmtError(
  352. Diag(InputExpr->getBeginLoc(), diag::err_asm_immediate_expected)
  353. << Info.getConstraintStr() << InputExpr->getSourceRange());
  354. if (!Info.isValidAsmImmediate(IntResult))
  355. return StmtError(Diag(InputExpr->getBeginLoc(),
  356. diag::err_invalid_asm_value_for_constraint)
  357. << IntResult.toString(10) << Info.getConstraintStr()
  358. << InputExpr->getSourceRange());
  359. }
  360. } else {
  361. ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
  362. if (Result.isInvalid())
  363. return StmtError();
  364. Exprs[i] = Result.get();
  365. }
  366. if (Info.allowsRegister()) {
  367. if (InputExpr->getType()->isVoidType()) {
  368. return StmtError(
  369. Diag(InputExpr->getBeginLoc(), diag::err_asm_invalid_type_in_input)
  370. << InputExpr->getType() << Info.getConstraintStr()
  371. << InputExpr->getSourceRange());
  372. }
  373. }
  374. InputConstraintInfos.push_back(Info);
  375. const Type *Ty = Exprs[i]->getType().getTypePtr();
  376. if (Ty->isDependentType())
  377. continue;
  378. if (!Ty->isVoidType() || !Info.allowsMemory())
  379. if (RequireCompleteType(InputExpr->getBeginLoc(), Exprs[i]->getType(),
  380. diag::err_dereference_incomplete_type))
  381. return StmtError();
  382. unsigned Size = Context.getTypeSize(Ty);
  383. if (!Context.getTargetInfo().validateInputSize(Literal->getString(),
  384. Size))
  385. return StmtResult(
  386. targetDiag(InputExpr->getBeginLoc(), diag::err_asm_invalid_input_size)
  387. << Info.getConstraintStr());
  388. }
  389. // Check that the clobbers are valid.
  390. for (unsigned i = 0; i != NumClobbers; i++) {
  391. StringLiteral *Literal = Clobbers[i];
  392. assert(Literal->isAscii());
  393. StringRef Clobber = Literal->getString();
  394. if (!Context.getTargetInfo().isValidClobber(Clobber)) {
  395. targetDiag(Literal->getBeginLoc(), diag::err_asm_unknown_register_name)
  396. << Clobber;
  397. return new (Context)
  398. GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
  399. NumInputs, Names, Constraints, Exprs.data(), AsmString,
  400. NumClobbers, Clobbers, NumLabels, RParenLoc);
  401. }
  402. }
  403. GCCAsmStmt *NS =
  404. new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
  405. NumInputs, Names, Constraints, Exprs.data(),
  406. AsmString, NumClobbers, Clobbers, NumLabels,
  407. RParenLoc);
  408. // Validate the asm string, ensuring it makes sense given the operands we
  409. // have.
  410. SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
  411. unsigned DiagOffs;
  412. if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
  413. targetDiag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
  414. << AsmString->getSourceRange();
  415. return NS;
  416. }
  417. // Validate constraints and modifiers.
  418. for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
  419. GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
  420. if (!Piece.isOperand()) continue;
  421. // Look for the correct constraint index.
  422. unsigned ConstraintIdx = Piece.getOperandNo();
  423. // Labels are the last in the Exprs list.
  424. if (NS->isAsmGoto() && ConstraintIdx >= NS->getNumInputs())
  425. continue;
  426. unsigned NumOperands = NS->getNumOutputs() + NS->getNumInputs();
  427. // Look for the (ConstraintIdx - NumOperands + 1)th constraint with
  428. // modifier '+'.
  429. if (ConstraintIdx >= NumOperands) {
  430. unsigned I = 0, E = NS->getNumOutputs();
  431. for (unsigned Cnt = ConstraintIdx - NumOperands; I != E; ++I)
  432. if (OutputConstraintInfos[I].isReadWrite() && Cnt-- == 0) {
  433. ConstraintIdx = I;
  434. break;
  435. }
  436. assert(I != E && "Invalid operand number should have been caught in "
  437. " AnalyzeAsmString");
  438. }
  439. // Now that we have the right indexes go ahead and check.
  440. StringLiteral *Literal = Constraints[ConstraintIdx];
  441. const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
  442. if (Ty->isDependentType() || Ty->isIncompleteType())
  443. continue;
  444. unsigned Size = Context.getTypeSize(Ty);
  445. std::string SuggestedModifier;
  446. if (!Context.getTargetInfo().validateConstraintModifier(
  447. Literal->getString(), Piece.getModifier(), Size,
  448. SuggestedModifier)) {
  449. targetDiag(Exprs[ConstraintIdx]->getBeginLoc(),
  450. diag::warn_asm_mismatched_size_modifier);
  451. if (!SuggestedModifier.empty()) {
  452. auto B = targetDiag(Piece.getRange().getBegin(),
  453. diag::note_asm_missing_constraint_modifier)
  454. << SuggestedModifier;
  455. SuggestedModifier = "%" + SuggestedModifier + Piece.getString();
  456. B << FixItHint::CreateReplacement(Piece.getRange(), SuggestedModifier);
  457. }
  458. }
  459. }
  460. // Validate tied input operands for type mismatches.
  461. unsigned NumAlternatives = ~0U;
  462. for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) {
  463. TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
  464. StringRef ConstraintStr = Info.getConstraintStr();
  465. unsigned AltCount = ConstraintStr.count(',') + 1;
  466. if (NumAlternatives == ~0U) {
  467. NumAlternatives = AltCount;
  468. } else if (NumAlternatives != AltCount) {
  469. targetDiag(NS->getOutputExpr(i)->getBeginLoc(),
  470. diag::err_asm_unexpected_constraint_alternatives)
  471. << NumAlternatives << AltCount;
  472. return NS;
  473. }
  474. }
  475. SmallVector<size_t, 4> InputMatchedToOutput(OutputConstraintInfos.size(),
  476. ~0U);
  477. for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
  478. TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
  479. StringRef ConstraintStr = Info.getConstraintStr();
  480. unsigned AltCount = ConstraintStr.count(',') + 1;
  481. if (NumAlternatives == ~0U) {
  482. NumAlternatives = AltCount;
  483. } else if (NumAlternatives != AltCount) {
  484. targetDiag(NS->getInputExpr(i)->getBeginLoc(),
  485. diag::err_asm_unexpected_constraint_alternatives)
  486. << NumAlternatives << AltCount;
  487. return NS;
  488. }
  489. // If this is a tied constraint, verify that the output and input have
  490. // either exactly the same type, or that they are int/ptr operands with the
  491. // same size (int/long, int*/long, are ok etc).
  492. if (!Info.hasTiedOperand()) continue;
  493. unsigned TiedTo = Info.getTiedOperand();
  494. unsigned InputOpNo = i+NumOutputs;
  495. Expr *OutputExpr = Exprs[TiedTo];
  496. Expr *InputExpr = Exprs[InputOpNo];
  497. // Make sure no more than one input constraint matches each output.
  498. assert(TiedTo < InputMatchedToOutput.size() && "TiedTo value out of range");
  499. if (InputMatchedToOutput[TiedTo] != ~0U) {
  500. targetDiag(NS->getInputExpr(i)->getBeginLoc(),
  501. diag::err_asm_input_duplicate_match)
  502. << TiedTo;
  503. targetDiag(NS->getInputExpr(InputMatchedToOutput[TiedTo])->getBeginLoc(),
  504. diag::note_asm_input_duplicate_first)
  505. << TiedTo;
  506. return NS;
  507. }
  508. InputMatchedToOutput[TiedTo] = i;
  509. if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
  510. continue;
  511. QualType InTy = InputExpr->getType();
  512. QualType OutTy = OutputExpr->getType();
  513. if (Context.hasSameType(InTy, OutTy))
  514. continue; // All types can be tied to themselves.
  515. // Decide if the input and output are in the same domain (integer/ptr or
  516. // floating point.
  517. enum AsmDomain {
  518. AD_Int, AD_FP, AD_Other
  519. } InputDomain, OutputDomain;
  520. if (InTy->isIntegerType() || InTy->isPointerType())
  521. InputDomain = AD_Int;
  522. else if (InTy->isRealFloatingType())
  523. InputDomain = AD_FP;
  524. else
  525. InputDomain = AD_Other;
  526. if (OutTy->isIntegerType() || OutTy->isPointerType())
  527. OutputDomain = AD_Int;
  528. else if (OutTy->isRealFloatingType())
  529. OutputDomain = AD_FP;
  530. else
  531. OutputDomain = AD_Other;
  532. // They are ok if they are the same size and in the same domain. This
  533. // allows tying things like:
  534. // void* to int*
  535. // void* to int if they are the same size.
  536. // double to long double if they are the same size.
  537. //
  538. uint64_t OutSize = Context.getTypeSize(OutTy);
  539. uint64_t InSize = Context.getTypeSize(InTy);
  540. if (OutSize == InSize && InputDomain == OutputDomain &&
  541. InputDomain != AD_Other)
  542. continue;
  543. // If the smaller input/output operand is not mentioned in the asm string,
  544. // then we can promote the smaller one to a larger input and the asm string
  545. // won't notice.
  546. bool SmallerValueMentioned = false;
  547. // If this is a reference to the input and if the input was the smaller
  548. // one, then we have to reject this asm.
  549. if (isOperandMentioned(InputOpNo, Pieces)) {
  550. // This is a use in the asm string of the smaller operand. Since we
  551. // codegen this by promoting to a wider value, the asm will get printed
  552. // "wrong".
  553. SmallerValueMentioned |= InSize < OutSize;
  554. }
  555. if (isOperandMentioned(TiedTo, Pieces)) {
  556. // If this is a reference to the output, and if the output is the larger
  557. // value, then it's ok because we'll promote the input to the larger type.
  558. SmallerValueMentioned |= OutSize < InSize;
  559. }
  560. // If the smaller value wasn't mentioned in the asm string, and if the
  561. // output was a register, just extend the shorter one to the size of the
  562. // larger one.
  563. if (!SmallerValueMentioned && InputDomain != AD_Other &&
  564. OutputConstraintInfos[TiedTo].allowsRegister())
  565. continue;
  566. // Either both of the operands were mentioned or the smaller one was
  567. // mentioned. One more special case that we'll allow: if the tied input is
  568. // integer, unmentioned, and is a constant, then we'll allow truncating it
  569. // down to the size of the destination.
  570. if (InputDomain == AD_Int && OutputDomain == AD_Int &&
  571. !isOperandMentioned(InputOpNo, Pieces) &&
  572. InputExpr->isEvaluatable(Context)) {
  573. CastKind castKind =
  574. (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
  575. InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get();
  576. Exprs[InputOpNo] = InputExpr;
  577. NS->setInputExpr(i, InputExpr);
  578. continue;
  579. }
  580. targetDiag(InputExpr->getBeginLoc(), diag::err_asm_tying_incompatible_types)
  581. << InTy << OutTy << OutputExpr->getSourceRange()
  582. << InputExpr->getSourceRange();
  583. return NS;
  584. }
  585. // Check for conflicts between clobber list and input or output lists
  586. SourceLocation ConstraintLoc =
  587. getClobberConflictLocation(Exprs, Constraints, Clobbers, NumClobbers,
  588. NumLabels,
  589. Context.getTargetInfo(), Context);
  590. if (ConstraintLoc.isValid())
  591. targetDiag(ConstraintLoc, diag::error_inoutput_conflict_with_clobber);
  592. // Check for duplicate asm operand name between input, output and label lists.
  593. typedef std::pair<StringRef , Expr *> NamedOperand;
  594. SmallVector<NamedOperand, 4> NamedOperandList;
  595. for (unsigned i = 0, e = NumOutputs + NumInputs + NumLabels; i != e; ++i)
  596. if (Names[i])
  597. NamedOperandList.emplace_back(
  598. std::make_pair(Names[i]->getName(), Exprs[i]));
  599. // Sort NamedOperandList.
  600. std::stable_sort(NamedOperandList.begin(), NamedOperandList.end(),
  601. [](const NamedOperand &LHS, const NamedOperand &RHS) {
  602. return LHS.first < RHS.first;
  603. });
  604. // Find adjacent duplicate operand.
  605. SmallVector<NamedOperand, 4>::iterator Found =
  606. std::adjacent_find(begin(NamedOperandList), end(NamedOperandList),
  607. [](const NamedOperand &LHS, const NamedOperand &RHS) {
  608. return LHS.first == RHS.first;
  609. });
  610. if (Found != NamedOperandList.end()) {
  611. Diag((Found + 1)->second->getBeginLoc(),
  612. diag::error_duplicate_asm_operand_name)
  613. << (Found + 1)->first;
  614. Diag(Found->second->getBeginLoc(), diag::note_duplicate_asm_operand_name)
  615. << Found->first;
  616. return StmtError();
  617. }
  618. if (NS->isAsmGoto())
  619. setFunctionHasBranchIntoScope();
  620. return NS;
  621. }
  622. void Sema::FillInlineAsmIdentifierInfo(Expr *Res,
  623. llvm::InlineAsmIdentifierInfo &Info) {
  624. QualType T = Res->getType();
  625. Expr::EvalResult Eval;
  626. if (T->isFunctionType() || T->isDependentType())
  627. return Info.setLabel(Res);
  628. if (Res->isRValue()) {
  629. if (isa<clang::EnumType>(T) && Res->EvaluateAsRValue(Eval, Context))
  630. return Info.setEnum(Eval.Val.getInt().getSExtValue());
  631. return Info.setLabel(Res);
  632. }
  633. unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
  634. unsigned Type = Size;
  635. if (const auto *ATy = Context.getAsArrayType(T))
  636. Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity();
  637. bool IsGlobalLV = false;
  638. if (Res->EvaluateAsLValue(Eval, Context))
  639. IsGlobalLV = Eval.isGlobalLValue();
  640. Info.setVar(Res, IsGlobalLV, Size, Type);
  641. }
  642. ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
  643. SourceLocation TemplateKWLoc,
  644. UnqualifiedId &Id,
  645. bool IsUnevaluatedContext) {
  646. if (IsUnevaluatedContext)
  647. PushExpressionEvaluationContext(
  648. ExpressionEvaluationContext::UnevaluatedAbstract,
  649. ReuseLambdaContextDecl);
  650. ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
  651. /*trailing lparen*/ false,
  652. /*is & operand*/ false,
  653. /*CorrectionCandidateCallback=*/nullptr,
  654. /*IsInlineAsmIdentifier=*/ true);
  655. if (IsUnevaluatedContext)
  656. PopExpressionEvaluationContext();
  657. if (!Result.isUsable()) return Result;
  658. Result = CheckPlaceholderExpr(Result.get());
  659. if (!Result.isUsable()) return Result;
  660. // Referring to parameters is not allowed in naked functions.
  661. if (CheckNakedParmReference(Result.get(), *this))
  662. return ExprError();
  663. QualType T = Result.get()->getType();
  664. if (T->isDependentType()) {
  665. return Result;
  666. }
  667. // Any sort of function type is fine.
  668. if (T->isFunctionType()) {
  669. return Result;
  670. }
  671. // Otherwise, it needs to be a complete type.
  672. if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) {
  673. return ExprError();
  674. }
  675. return Result;
  676. }
  677. bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
  678. unsigned &Offset, SourceLocation AsmLoc) {
  679. Offset = 0;
  680. SmallVector<StringRef, 2> Members;
  681. Member.split(Members, ".");
  682. NamedDecl *FoundDecl = nullptr;
  683. // MS InlineAsm uses 'this' as a base
  684. if (getLangOpts().CPlusPlus && Base.equals("this")) {
  685. if (const Type *PT = getCurrentThisType().getTypePtrOrNull())
  686. FoundDecl = PT->getPointeeType()->getAsTagDecl();
  687. } else {
  688. LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
  689. LookupOrdinaryName);
  690. if (LookupName(BaseResult, getCurScope()) && BaseResult.isSingleResult())
  691. FoundDecl = BaseResult.getFoundDecl();
  692. }
  693. if (!FoundDecl)
  694. return true;
  695. for (StringRef NextMember : Members) {
  696. const RecordType *RT = nullptr;
  697. if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
  698. RT = VD->getType()->getAs<RecordType>();
  699. else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) {
  700. MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
  701. // MS InlineAsm often uses struct pointer aliases as a base
  702. QualType QT = TD->getUnderlyingType();
  703. if (const auto *PT = QT->getAs<PointerType>())
  704. QT = PT->getPointeeType();
  705. RT = QT->getAs<RecordType>();
  706. } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl))
  707. RT = TD->getTypeForDecl()->getAs<RecordType>();
  708. else if (FieldDecl *TD = dyn_cast<FieldDecl>(FoundDecl))
  709. RT = TD->getType()->getAs<RecordType>();
  710. if (!RT)
  711. return true;
  712. if (RequireCompleteType(AsmLoc, QualType(RT, 0),
  713. diag::err_asm_incomplete_type))
  714. return true;
  715. LookupResult FieldResult(*this, &Context.Idents.get(NextMember),
  716. SourceLocation(), LookupMemberName);
  717. if (!LookupQualifiedName(FieldResult, RT->getDecl()))
  718. return true;
  719. if (!FieldResult.isSingleResult())
  720. return true;
  721. FoundDecl = FieldResult.getFoundDecl();
  722. // FIXME: Handle IndirectFieldDecl?
  723. FieldDecl *FD = dyn_cast<FieldDecl>(FoundDecl);
  724. if (!FD)
  725. return true;
  726. const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl());
  727. unsigned i = FD->getFieldIndex();
  728. CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
  729. Offset += (unsigned)Result.getQuantity();
  730. }
  731. return false;
  732. }
  733. ExprResult
  734. Sema::LookupInlineAsmVarDeclField(Expr *E, StringRef Member,
  735. SourceLocation AsmLoc) {
  736. QualType T = E->getType();
  737. if (T->isDependentType()) {
  738. DeclarationNameInfo NameInfo;
  739. NameInfo.setLoc(AsmLoc);
  740. NameInfo.setName(&Context.Idents.get(Member));
  741. return CXXDependentScopeMemberExpr::Create(
  742. Context, E, T, /*IsArrow=*/false, AsmLoc, NestedNameSpecifierLoc(),
  743. SourceLocation(),
  744. /*FirstQualifierFoundInScope=*/nullptr, NameInfo, /*TemplateArgs=*/nullptr);
  745. }
  746. const RecordType *RT = T->getAs<RecordType>();
  747. // FIXME: Diagnose this as field access into a scalar type.
  748. if (!RT)
  749. return ExprResult();
  750. LookupResult FieldResult(*this, &Context.Idents.get(Member), AsmLoc,
  751. LookupMemberName);
  752. if (!LookupQualifiedName(FieldResult, RT->getDecl()))
  753. return ExprResult();
  754. // Only normal and indirect field results will work.
  755. ValueDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
  756. if (!FD)
  757. FD = dyn_cast<IndirectFieldDecl>(FieldResult.getFoundDecl());
  758. if (!FD)
  759. return ExprResult();
  760. // Make an Expr to thread through OpDecl.
  761. ExprResult Result = BuildMemberReferenceExpr(
  762. E, E->getType(), AsmLoc, /*IsArrow=*/false, CXXScopeSpec(),
  763. SourceLocation(), nullptr, FieldResult, nullptr, nullptr);
  764. return Result;
  765. }
  766. StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
  767. ArrayRef<Token> AsmToks,
  768. StringRef AsmString,
  769. unsigned NumOutputs, unsigned NumInputs,
  770. ArrayRef<StringRef> Constraints,
  771. ArrayRef<StringRef> Clobbers,
  772. ArrayRef<Expr*> Exprs,
  773. SourceLocation EndLoc) {
  774. bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
  775. setFunctionHasBranchProtectedScope();
  776. MSAsmStmt *NS =
  777. new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
  778. /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
  779. Constraints, Exprs, AsmString,
  780. Clobbers, EndLoc);
  781. return NS;
  782. }
  783. LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
  784. SourceLocation Location,
  785. bool AlwaysCreate) {
  786. LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName),
  787. Location);
  788. if (Label->isMSAsmLabel()) {
  789. // If we have previously created this label implicitly, mark it as used.
  790. Label->markUsed(Context);
  791. } else {
  792. // Otherwise, insert it, but only resolve it if we have seen the label itself.
  793. std::string InternalName;
  794. llvm::raw_string_ostream OS(InternalName);
  795. // Create an internal name for the label. The name should not be a valid
  796. // mangled name, and should be unique. We use a dot to make the name an
  797. // invalid mangled name. We use LLVM's inline asm ${:uid} escape so that a
  798. // unique label is generated each time this blob is emitted, even after
  799. // inlining or LTO.
  800. OS << "__MSASMLABEL_.${:uid}__";
  801. for (char C : ExternalLabelName) {
  802. OS << C;
  803. // We escape '$' in asm strings by replacing it with "$$"
  804. if (C == '$')
  805. OS << '$';
  806. }
  807. Label->setMSAsmLabel(OS.str());
  808. }
  809. if (AlwaysCreate) {
  810. // The label might have been created implicitly from a previously encountered
  811. // goto statement. So, for both newly created and looked up labels, we mark
  812. // them as resolved.
  813. Label->setMSAsmLabelResolved();
  814. }
  815. // Adjust their location for being able to generate accurate diagnostics.
  816. Label->setLocation(Location);
  817. return Label;
  818. }