blob: 50366222093f7fef740cb1656abd70294ca90f33 [file] [log] [blame]
Chad Rosier571c5e92012-08-17 21:27:25 +00001//===--- SemaStmtAsm.cpp - Semantic Analysis for Asm Statements -----------===//
Chad Rosier0731aff2012-08-17 21:19:40 +00002//
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 semantic analysis for inline asm statements.
11//
12//===----------------------------------------------------------------------===//
13
Weiming Zhao71ac2402015-02-03 22:35:58 +000014#include "clang/AST/ExprCXX.h"
Chad Rosier5c563642012-10-25 21:49:22 +000015#include "clang/AST/RecordLayout.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000016#include "clang/AST/TypeLoc.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000017#include "clang/Basic/TargetInfo.h"
Ehsan Akhgari31097582014-09-22 02:21:54 +000018#include "clang/Lex/Preprocessor.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000019#include "clang/Sema/Initialization.h"
20#include "clang/Sema/Lookup.h"
21#include "clang/Sema/Scope.h"
22#include "clang/Sema/ScopeInfo.h"
Mehdi Amini9670f842016-07-18 19:02:11 +000023#include "clang/Sema/SemaInternal.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000024#include "llvm/ADT/ArrayRef.h"
Marina Yatsinac42fd032016-12-26 12:23:42 +000025#include "llvm/ADT/StringSet.h"
Alp Toker10399272014-06-08 05:11:37 +000026#include "llvm/MC/MCParser/MCAsmParser.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000027using namespace clang;
28using namespace sema;
29
30/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
31/// ignore "noop" casts in places where an lvalue is required by an inline asm.
32/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
33/// provide a strong guidance to not use it.
34///
35/// This method checks to see if the argument is an acceptable l-value and
36/// returns false if it is a case we can handle.
37static bool CheckAsmLValue(const Expr *E, Sema &S) {
38 // Type dependent expressions will be checked during instantiation.
39 if (E->isTypeDependent())
40 return false;
41
42 if (E->isLValue())
43 return false; // Cool, this is an lvalue.
44
45 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
46 // are supposed to allow.
47 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
48 if (E != E2 && E2->isLValue()) {
49 if (!S.getLangOpts().HeinousExtensions)
50 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
51 << E->getSourceRange();
52 else
53 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
54 << E->getSourceRange();
55 // Accept, even if we emitted an error diagnostic.
56 return false;
57 }
58
59 // None of the above, just randomly invalid non-lvalue.
60 return true;
61}
62
63/// isOperandMentioned - Return true if the specified operand # is mentioned
64/// anywhere in the decomposed asm string.
65static bool isOperandMentioned(unsigned OpNo,
Chad Rosierde70e0e2012-08-25 00:11:56 +000066 ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
Chad Rosier0731aff2012-08-17 21:19:40 +000067 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
Chad Rosierde70e0e2012-08-25 00:11:56 +000068 const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
Chad Rosier0731aff2012-08-17 21:19:40 +000069 if (!Piece.isOperand()) continue;
70
71 // If this is a reference to the input and if the input was the smaller
72 // one, then we have to reject this asm.
73 if (Piece.getOperandNo() == OpNo)
74 return true;
75 }
76 return false;
77}
78
Hans Wennborge9d240a2014-10-08 01:58:02 +000079static bool CheckNakedParmReference(Expr *E, Sema &S) {
80 FunctionDecl *Func = dyn_cast<FunctionDecl>(S.CurContext);
81 if (!Func)
82 return false;
83 if (!Func->hasAttr<NakedAttr>())
84 return false;
85
86 SmallVector<Expr*, 4> WorkList;
87 WorkList.push_back(E);
88 while (WorkList.size()) {
89 Expr *E = WorkList.pop_back_val();
Weiming Zhao71ac2402015-02-03 22:35:58 +000090 if (isa<CXXThisExpr>(E)) {
91 S.Diag(E->getLocStart(), diag::err_asm_naked_this_ref);
92 S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
93 return true;
94 }
Hans Wennborge9d240a2014-10-08 01:58:02 +000095 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
96 if (isa<ParmVarDecl>(DRE->getDecl())) {
97 S.Diag(DRE->getLocStart(), diag::err_asm_naked_parm_ref);
98 S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
99 return true;
100 }
101 }
102 for (Stmt *Child : E->children()) {
103 if (Expr *E = dyn_cast_or_null<Expr>(Child))
104 WorkList.push_back(E);
105 }
106 }
107 return false;
108}
109
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +0000110/// \brief Returns true if given expression is not compatible with inline
111/// assembly's memory constraint; false otherwise.
112static bool checkExprMemoryConstraintCompat(Sema &S, Expr *E,
113 TargetInfo::ConstraintInfo &Info,
114 bool is_input_expr) {
115 enum {
116 ExprBitfield = 0,
117 ExprVectorElt,
118 ExprGlobalRegVar,
119 ExprSafeType
120 } EType = ExprSafeType;
121
122 // Bitfields, vector elements and global register variables are not
123 // compatible.
124 if (E->refersToBitField())
125 EType = ExprBitfield;
126 else if (E->refersToVectorElement())
127 EType = ExprVectorElt;
128 else if (E->refersToGlobalRegisterVar())
129 EType = ExprGlobalRegVar;
130
131 if (EType != ExprSafeType) {
132 S.Diag(E->getLocStart(), diag::err_asm_non_addr_value_in_memory_constraint)
133 << EType << is_input_expr << Info.getConstraintStr()
134 << E->getSourceRange();
135 return true;
136 }
137
138 return false;
139}
140
Marina Yatsinac42fd032016-12-26 12:23:42 +0000141// Extracting the register name from the Expression value,
142// if there is no register name to extract, returns ""
143static StringRef extractRegisterName(const Expr *Expression,
144 const TargetInfo &Target) {
145 Expression = Expression->IgnoreImpCasts();
146 if (const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(Expression)) {
147 // Handle cases where the expression is a variable
148 const VarDecl *Variable = dyn_cast<VarDecl>(AsmDeclRef->getDecl());
149 if (Variable && Variable->getStorageClass() == SC_Register) {
150 if (AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>())
151 if (Target.isValidGCCRegisterName(Attr->getLabel()))
152 return Target.getNormalizedGCCRegisterName(Attr->getLabel(), true);
153 }
154 }
155 return "";
156}
157
158// Checks if there is a conflict between the input and output lists with the
159// clobbers list. If there's a conflict, returns the location of the
160// conflicted clobber, else returns nullptr
161static SourceLocation
162getClobberConflictLocation(MultiExprArg Exprs, StringLiteral **Constraints,
163 StringLiteral **Clobbers, int NumClobbers,
164 const TargetInfo &Target, ASTContext &Cont) {
165 llvm::StringSet<> InOutVars;
166 // Collect all the input and output registers from the extended asm
167 // statement
168 // in order to check for conflicts with the clobber list
169 for (int i = 0; i < Exprs.size(); ++i) {
170 StringRef Constraint = Constraints[i]->getString();
171 StringRef InOutReg = Target.getConstraintRegister(
172 Constraint, extractRegisterName(Exprs[i], Target));
173 if (InOutReg != "")
174 InOutVars.insert(InOutReg);
175 }
176 // Check for each item in the clobber list if it conflicts with the input
177 // or output
178 for (int i = 0; i < NumClobbers; ++i) {
179 StringRef Clobber = Clobbers[i]->getString();
180 // We only check registers, therefore we don't check cc and memory
181 // clobbers
182 if (Clobber == "cc" || Clobber == "memory")
183 continue;
184 Clobber = Target.getNormalizedGCCRegisterName(Clobber, true);
185 // Go over the output's registers we collected
186 if (InOutVars.count(Clobber))
187 return Clobbers[i]->getLocStart();
188 }
189 return SourceLocation();
190}
191
Chad Rosierde70e0e2012-08-25 00:11:56 +0000192StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
193 bool IsVolatile, unsigned NumOutputs,
194 unsigned NumInputs, IdentifierInfo **Names,
Dmitri Gribenkoea2d5f82013-05-10 01:14:26 +0000195 MultiExprArg constraints, MultiExprArg Exprs,
Chad Rosierde70e0e2012-08-25 00:11:56 +0000196 Expr *asmString, MultiExprArg clobbers,
197 SourceLocation RParenLoc) {
Chad Rosier0731aff2012-08-17 21:19:40 +0000198 unsigned NumClobbers = clobbers.size();
199 StringLiteral **Constraints =
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000200 reinterpret_cast<StringLiteral**>(constraints.data());
Chad Rosier0731aff2012-08-17 21:19:40 +0000201 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000202 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data());
Chad Rosier0731aff2012-08-17 21:19:40 +0000203
204 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
205
206 // The parser verifies that there is a string literal here.
David Majnemerb3e96f72014-12-11 01:00:48 +0000207 assert(AsmString->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000208
Artem Belevich5ef02c22015-08-27 19:54:21 +0000209 // If we're compiling CUDA file and function attributes indicate that it's not
210 // for this compilation side, skip all the checks.
211 if (!DeclAttrsMatchCUDAMode(getLangOpts(), getCurFunctionDecl())) {
212 GCCAsmStmt *NS = new (Context) GCCAsmStmt(
213 Context, AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs, Names,
214 Constraints, Exprs.data(), AsmString, NumClobbers, Clobbers, RParenLoc);
215 return NS;
216 }
Artem Belevich5196fe72015-03-19 18:40:25 +0000217
Chad Rosier0731aff2012-08-17 21:19:40 +0000218 for (unsigned i = 0; i != NumOutputs; i++) {
219 StringLiteral *Literal = Constraints[i];
David Majnemerb3e96f72014-12-11 01:00:48 +0000220 assert(Literal->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000221
222 StringRef OutputName;
223 if (Names[i])
224 OutputName = Names[i]->getName();
225
226 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
Artem Belevich5ef02c22015-08-27 19:54:21 +0000227 if (!Context.getTargetInfo().validateOutputConstraint(Info))
Chad Rosier0731aff2012-08-17 21:19:40 +0000228 return StmtError(Diag(Literal->getLocStart(),
229 diag::err_asm_invalid_output_constraint)
230 << Info.getConstraintStr());
231
David Majnemer0f4d6412014-12-29 09:30:33 +0000232 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
233 if (ER.isInvalid())
234 return StmtError();
235 Exprs[i] = ER.get();
236
Chad Rosier0731aff2012-08-17 21:19:40 +0000237 // Check that the output exprs are valid lvalues.
238 Expr *OutputExpr = Exprs[i];
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000239
Hans Wennborge9d240a2014-10-08 01:58:02 +0000240 // Referring to parameters is not allowed in naked functions.
241 if (CheckNakedParmReference(OutputExpr, *this))
242 return StmtError();
243
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +0000244 // Check that the output expression is compatible with memory constraint.
245 if (Info.allowsMemory() &&
246 checkExprMemoryConstraintCompat(*this, OutputExpr, Info, false))
247 return StmtError();
Alexander Musmaneae29e22015-06-05 13:40:59 +0000248
Chad Rosier0731aff2012-08-17 21:19:40 +0000249 OutputConstraintInfos.push_back(Info);
Akira Hatanaka974131e2014-09-18 18:17:18 +0000250
David Majnemer0f4d6412014-12-29 09:30:33 +0000251 // If this is dependent, just continue.
252 if (OutputExpr->isTypeDependent())
Akira Hatanaka974131e2014-09-18 18:17:18 +0000253 continue;
254
David Majnemer0f4d6412014-12-29 09:30:33 +0000255 Expr::isModifiableLvalueResult IsLV =
256 OutputExpr->isModifiableLvalue(Context, /*Loc=*/nullptr);
257 switch (IsLV) {
258 case Expr::MLV_Valid:
259 // Cool, this is an lvalue.
260 break;
David Majnemer04b78412014-12-29 10:29:53 +0000261 case Expr::MLV_ArrayType:
262 // This is OK too.
263 break;
David Majnemer0f4d6412014-12-29 09:30:33 +0000264 case Expr::MLV_LValueCast: {
265 const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Context);
266 if (!getLangOpts().HeinousExtensions) {
267 Diag(LVal->getLocStart(), diag::err_invalid_asm_cast_lvalue)
268 << OutputExpr->getSourceRange();
269 } else {
270 Diag(LVal->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
271 << OutputExpr->getSourceRange();
272 }
273 // Accept, even if we emitted an error diagnostic.
274 break;
275 }
276 case Expr::MLV_IncompleteType:
277 case Expr::MLV_IncompleteVoidType:
278 if (RequireCompleteType(OutputExpr->getLocStart(), Exprs[i]->getType(),
279 diag::err_dereference_incomplete_type))
280 return StmtError();
281 default:
282 return StmtError(Diag(OutputExpr->getLocStart(),
283 diag::err_asm_invalid_lvalue_in_output)
284 << OutputExpr->getSourceRange());
285 }
286
287 unsigned Size = Context.getTypeSize(OutputExpr->getType());
Akira Hatanaka974131e2014-09-18 18:17:18 +0000288 if (!Context.getTargetInfo().validateOutputSize(Literal->getString(),
289 Size))
290 return StmtError(Diag(OutputExpr->getLocStart(),
291 diag::err_asm_invalid_output_size)
292 << Info.getConstraintStr());
Chad Rosier0731aff2012-08-17 21:19:40 +0000293 }
294
295 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
296
297 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
298 StringLiteral *Literal = Constraints[i];
David Majnemerb3e96f72014-12-11 01:00:48 +0000299 assert(Literal->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000300
301 StringRef InputName;
302 if (Names[i])
303 InputName = Names[i]->getName();
304
305 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
Craig Topper55765ca2015-10-21 02:34:10 +0000306 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos,
307 Info)) {
Chad Rosier0731aff2012-08-17 21:19:40 +0000308 return StmtError(Diag(Literal->getLocStart(),
309 diag::err_asm_invalid_input_constraint)
310 << Info.getConstraintStr());
311 }
312
David Majnemer0f4d6412014-12-29 09:30:33 +0000313 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
314 if (ER.isInvalid())
315 return StmtError();
316 Exprs[i] = ER.get();
317
Chad Rosier0731aff2012-08-17 21:19:40 +0000318 Expr *InputExpr = Exprs[i];
319
Hans Wennborge9d240a2014-10-08 01:58:02 +0000320 // Referring to parameters is not allowed in naked functions.
321 if (CheckNakedParmReference(InputExpr, *this))
322 return StmtError();
323
Andrey Bokhankod9eab9c2015-08-03 10:38:10 +0000324 // Check that the input expression is compatible with memory constraint.
325 if (Info.allowsMemory() &&
326 checkExprMemoryConstraintCompat(*this, InputExpr, Info, true))
327 return StmtError();
Alexander Musmaneae29e22015-06-05 13:40:59 +0000328
Chad Rosier0731aff2012-08-17 21:19:40 +0000329 // Only allow void types for memory constraints.
330 if (Info.allowsMemory() && !Info.allowsRegister()) {
331 if (CheckAsmLValue(InputExpr, *this))
332 return StmtError(Diag(InputExpr->getLocStart(),
333 diag::err_asm_invalid_lvalue_in_input)
334 << Info.getConstraintStr()
335 << InputExpr->getSourceRange());
Saleem Abdulrasoola2823572015-01-06 04:26:34 +0000336 } else if (Info.requiresImmediateConstant() && !Info.allowsRegister()) {
Sunil Srivastava780e5012015-07-14 18:08:50 +0000337 if (!InputExpr->isValueDependent()) {
338 llvm::APSInt Result;
339 if (!InputExpr->EvaluateAsInt(Result, Context))
340 return StmtError(
341 Diag(InputExpr->getLocStart(), diag::err_asm_immediate_expected)
342 << Info.getConstraintStr() << InputExpr->getSourceRange());
Alexey Bataev91e58602015-07-20 12:08:00 +0000343 if (!Info.isValidAsmImmediate(Result))
Sunil Srivastava780e5012015-07-14 18:08:50 +0000344 return StmtError(Diag(InputExpr->getLocStart(),
345 diag::err_invalid_asm_value_for_constraint)
346 << Result.toString(10) << Info.getConstraintStr()
347 << InputExpr->getSourceRange());
348 }
Saleem Abdulrasoola2823572015-01-06 04:26:34 +0000349
David Majnemerade4bee2014-07-14 16:27:53 +0000350 } else {
351 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
352 if (Result.isInvalid())
353 return StmtError();
354
355 Exprs[i] = Result.get();
Chad Rosier0731aff2012-08-17 21:19:40 +0000356 }
357
358 if (Info.allowsRegister()) {
359 if (InputExpr->getType()->isVoidType()) {
360 return StmtError(Diag(InputExpr->getLocStart(),
361 diag::err_asm_invalid_type_in_input)
362 << InputExpr->getType() << Info.getConstraintStr()
363 << InputExpr->getSourceRange());
364 }
365 }
366
Chad Rosier0731aff2012-08-17 21:19:40 +0000367 InputConstraintInfos.push_back(Info);
Bill Wendling887b4852012-11-12 06:42:51 +0000368
369 const Type *Ty = Exprs[i]->getType().getTypePtr();
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000370 if (Ty->isDependentType())
Eric Christopherd41010a2012-11-12 23:13:34 +0000371 continue;
372
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000373 if (!Ty->isVoidType() || !Info.allowsMemory())
Bill Wendlingb68b7572013-03-27 06:06:26 +0000374 if (RequireCompleteType(InputExpr->getLocStart(), Exprs[i]->getType(),
375 diag::err_dereference_incomplete_type))
376 return StmtError();
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000377
Bill Wendling887b4852012-11-12 06:42:51 +0000378 unsigned Size = Context.getTypeSize(Ty);
379 if (!Context.getTargetInfo().validateInputSize(Literal->getString(),
380 Size))
381 return StmtError(Diag(InputExpr->getLocStart(),
382 diag::err_asm_invalid_input_size)
383 << Info.getConstraintStr());
Chad Rosier0731aff2012-08-17 21:19:40 +0000384 }
385
386 // Check that the clobbers are valid.
387 for (unsigned i = 0; i != NumClobbers; i++) {
388 StringLiteral *Literal = Clobbers[i];
David Majnemerb3e96f72014-12-11 01:00:48 +0000389 assert(Literal->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000390
391 StringRef Clobber = Literal->getString();
392
393 if (!Context.getTargetInfo().isValidClobber(Clobber))
394 return StmtError(Diag(Literal->getLocStart(),
395 diag::err_asm_unknown_register_name) << Clobber);
396 }
397
Chad Rosierde70e0e2012-08-25 00:11:56 +0000398 GCCAsmStmt *NS =
399 new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
Dmitri Gribenkoea2d5f82013-05-10 01:14:26 +0000400 NumInputs, Names, Constraints, Exprs.data(),
401 AsmString, NumClobbers, Clobbers, RParenLoc);
Chad Rosier0731aff2012-08-17 21:19:40 +0000402 // Validate the asm string, ensuring it makes sense given the operands we
403 // have.
Chad Rosierde70e0e2012-08-25 00:11:56 +0000404 SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
Chad Rosier0731aff2012-08-17 21:19:40 +0000405 unsigned DiagOffs;
406 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
407 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
408 << AsmString->getSourceRange();
409 return StmtError();
410 }
411
Bill Wendling9d1ee112012-10-25 23:28:48 +0000412 // Validate constraints and modifiers.
413 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
414 GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
415 if (!Piece.isOperand()) continue;
416
417 // Look for the correct constraint index.
Akira Hatanaka96a36012015-02-04 00:27:13 +0000418 unsigned ConstraintIdx = Piece.getOperandNo();
419 unsigned NumOperands = NS->getNumOutputs() + NS->getNumInputs();
Bill Wendling9d1ee112012-10-25 23:28:48 +0000420
Akira Hatanaka96a36012015-02-04 00:27:13 +0000421 // Look for the (ConstraintIdx - NumOperands + 1)th constraint with
422 // modifier '+'.
423 if (ConstraintIdx >= NumOperands) {
424 unsigned I = 0, E = NS->getNumOutputs();
425
426 for (unsigned Cnt = ConstraintIdx - NumOperands; I != E; ++I)
427 if (OutputConstraintInfos[I].isReadWrite() && Cnt-- == 0) {
428 ConstraintIdx = I;
Bill Wendling9d1ee112012-10-25 23:28:48 +0000429 break;
Akira Hatanaka96a36012015-02-04 00:27:13 +0000430 }
Bill Wendling9d1ee112012-10-25 23:28:48 +0000431
Akira Hatanaka96a36012015-02-04 00:27:13 +0000432 assert(I != E && "Invalid operand number should have been caught in "
433 " AnalyzeAsmString");
Bill Wendling9d1ee112012-10-25 23:28:48 +0000434 }
435
436 // Now that we have the right indexes go ahead and check.
437 StringLiteral *Literal = Constraints[ConstraintIdx];
438 const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
439 if (Ty->isDependentType() || Ty->isIncompleteType())
440 continue;
441
442 unsigned Size = Context.getTypeSize(Ty);
Akira Hatanaka987f1862014-08-22 06:05:21 +0000443 std::string SuggestedModifier;
444 if (!Context.getTargetInfo().validateConstraintModifier(
445 Literal->getString(), Piece.getModifier(), Size,
446 SuggestedModifier)) {
Bill Wendling9d1ee112012-10-25 23:28:48 +0000447 Diag(Exprs[ConstraintIdx]->getLocStart(),
448 diag::warn_asm_mismatched_size_modifier);
Akira Hatanaka987f1862014-08-22 06:05:21 +0000449
450 if (!SuggestedModifier.empty()) {
451 auto B = Diag(Piece.getRange().getBegin(),
452 diag::note_asm_missing_constraint_modifier)
453 << SuggestedModifier;
454 SuggestedModifier = "%" + SuggestedModifier + Piece.getString();
455 B.AddFixItHint(FixItHint::CreateReplacement(Piece.getRange(),
456 SuggestedModifier));
457 }
458 }
Bill Wendling9d1ee112012-10-25 23:28:48 +0000459 }
460
Chad Rosier0731aff2012-08-17 21:19:40 +0000461 // Validate tied input operands for type mismatches.
David Majnemerc63fa612014-12-29 04:09:59 +0000462 unsigned NumAlternatives = ~0U;
463 for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) {
464 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
465 StringRef ConstraintStr = Info.getConstraintStr();
466 unsigned AltCount = ConstraintStr.count(',') + 1;
467 if (NumAlternatives == ~0U)
468 NumAlternatives = AltCount;
469 else if (NumAlternatives != AltCount)
470 return StmtError(Diag(NS->getOutputExpr(i)->getLocStart(),
471 diag::err_asm_unexpected_constraint_alternatives)
472 << NumAlternatives << AltCount);
473 }
Alexander Musman8e261be2015-09-21 14:41:00 +0000474 SmallVector<size_t, 4> InputMatchedToOutput(OutputConstraintInfos.size(),
475 ~0U);
Chad Rosier0731aff2012-08-17 21:19:40 +0000476 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
477 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
David Majnemerc63fa612014-12-29 04:09:59 +0000478 StringRef ConstraintStr = Info.getConstraintStr();
479 unsigned AltCount = ConstraintStr.count(',') + 1;
480 if (NumAlternatives == ~0U)
481 NumAlternatives = AltCount;
482 else if (NumAlternatives != AltCount)
483 return StmtError(Diag(NS->getInputExpr(i)->getLocStart(),
484 diag::err_asm_unexpected_constraint_alternatives)
485 << NumAlternatives << AltCount);
Chad Rosier0731aff2012-08-17 21:19:40 +0000486
487 // If this is a tied constraint, verify that the output and input have
488 // either exactly the same type, or that they are int/ptr operands with the
489 // same size (int/long, int*/long, are ok etc).
490 if (!Info.hasTiedOperand()) continue;
491
492 unsigned TiedTo = Info.getTiedOperand();
493 unsigned InputOpNo = i+NumOutputs;
494 Expr *OutputExpr = Exprs[TiedTo];
495 Expr *InputExpr = Exprs[InputOpNo];
496
Alexander Musman8e261be2015-09-21 14:41:00 +0000497 // 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 Diag(NS->getInputExpr(i)->getLocStart(),
501 diag::err_asm_input_duplicate_match)
502 << TiedTo;
503 Diag(NS->getInputExpr(InputMatchedToOutput[TiedTo])->getLocStart(),
504 diag::note_asm_input_duplicate_first)
505 << TiedTo;
506 return StmtError();
507 }
508 InputMatchedToOutput[TiedTo] = i;
509
Chad Rosier0731aff2012-08-17 21:19:40 +0000510 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
511 continue;
512
513 QualType InTy = InputExpr->getType();
514 QualType OutTy = OutputExpr->getType();
515 if (Context.hasSameType(InTy, OutTy))
516 continue; // All types can be tied to themselves.
517
518 // Decide if the input and output are in the same domain (integer/ptr or
519 // floating point.
520 enum AsmDomain {
521 AD_Int, AD_FP, AD_Other
522 } InputDomain, OutputDomain;
523
524 if (InTy->isIntegerType() || InTy->isPointerType())
525 InputDomain = AD_Int;
526 else if (InTy->isRealFloatingType())
527 InputDomain = AD_FP;
528 else
529 InputDomain = AD_Other;
530
531 if (OutTy->isIntegerType() || OutTy->isPointerType())
532 OutputDomain = AD_Int;
533 else if (OutTy->isRealFloatingType())
534 OutputDomain = AD_FP;
535 else
536 OutputDomain = AD_Other;
537
538 // They are ok if they are the same size and in the same domain. This
539 // allows tying things like:
540 // void* to int*
541 // void* to int if they are the same size.
542 // double to long double if they are the same size.
543 //
544 uint64_t OutSize = Context.getTypeSize(OutTy);
545 uint64_t InSize = Context.getTypeSize(InTy);
546 if (OutSize == InSize && InputDomain == OutputDomain &&
547 InputDomain != AD_Other)
548 continue;
549
550 // If the smaller input/output operand is not mentioned in the asm string,
551 // then we can promote the smaller one to a larger input and the asm string
552 // won't notice.
553 bool SmallerValueMentioned = false;
554
555 // If this is a reference to the input and if the input was the smaller
556 // one, then we have to reject this asm.
557 if (isOperandMentioned(InputOpNo, Pieces)) {
558 // This is a use in the asm string of the smaller operand. Since we
559 // codegen this by promoting to a wider value, the asm will get printed
560 // "wrong".
561 SmallerValueMentioned |= InSize < OutSize;
562 }
563 if (isOperandMentioned(TiedTo, Pieces)) {
564 // If this is a reference to the output, and if the output is the larger
565 // value, then it's ok because we'll promote the input to the larger type.
566 SmallerValueMentioned |= OutSize < InSize;
567 }
568
569 // If the smaller value wasn't mentioned in the asm string, and if the
570 // output was a register, just extend the shorter one to the size of the
571 // larger one.
572 if (!SmallerValueMentioned && InputDomain != AD_Other &&
573 OutputConstraintInfos[TiedTo].allowsRegister())
574 continue;
575
576 // Either both of the operands were mentioned or the smaller one was
577 // mentioned. One more special case that we'll allow: if the tied input is
578 // integer, unmentioned, and is a constant, then we'll allow truncating it
579 // down to the size of the destination.
580 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
581 !isOperandMentioned(InputOpNo, Pieces) &&
582 InputExpr->isEvaluatable(Context)) {
583 CastKind castKind =
584 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000585 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get();
Chad Rosier0731aff2012-08-17 21:19:40 +0000586 Exprs[InputOpNo] = InputExpr;
587 NS->setInputExpr(i, InputExpr);
588 continue;
589 }
590
591 Diag(InputExpr->getLocStart(),
592 diag::err_asm_tying_incompatible_types)
593 << InTy << OutTy << OutputExpr->getSourceRange()
594 << InputExpr->getSourceRange();
595 return StmtError();
596 }
597
Marina Yatsinac42fd032016-12-26 12:23:42 +0000598 // Check for conflicts between clobber list and input or output lists
599 SourceLocation ConstraintLoc =
600 getClobberConflictLocation(Exprs, Constraints, Clobbers, NumClobbers,
601 Context.getTargetInfo(), Context);
602 if (ConstraintLoc.isValid())
603 return Diag(ConstraintLoc, diag::error_inoutput_conflict_with_clobber);
604
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000605 return NS;
Chad Rosier0731aff2012-08-17 21:19:40 +0000606}
607
Reid Kleckner14e96b42015-08-26 21:57:20 +0000608static void fillInlineAsmTypeInfo(const ASTContext &Context, QualType T,
609 llvm::InlineAsmIdentifierInfo &Info) {
610 // Compute the type size (and array length if applicable?).
611 Info.Type = Info.Size = Context.getTypeSizeInChars(T).getQuantity();
612 if (T->isArrayType()) {
613 const ArrayType *ATy = Context.getAsArrayType(T);
614 Info.Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity();
615 Info.Length = Info.Size / Info.Type;
616 }
617}
618
John McCallf413f5e2013-05-03 00:10:13 +0000619ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
620 SourceLocation TemplateKWLoc,
621 UnqualifiedId &Id,
Alp Toker10399272014-06-08 05:11:37 +0000622 llvm::InlineAsmIdentifierInfo &Info,
John McCallf413f5e2013-05-03 00:10:13 +0000623 bool IsUnevaluatedContext) {
Chad Rosierb18a2852013-04-22 17:01:37 +0000624 Info.clear();
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000625
John McCallf413f5e2013-05-03 00:10:13 +0000626 if (IsUnevaluatedContext)
627 PushExpressionEvaluationContext(UnevaluatedAbstract,
628 ReuseLambdaContextDecl);
629
630 ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
631 /*trailing lparen*/ false,
Chad Rosierb9aff1e2013-05-24 18:32:55 +0000632 /*is & operand*/ false,
Craig Topperc3ec1492014-05-26 06:22:03 +0000633 /*CorrectionCandidateCallback=*/nullptr,
Chad Rosierb9aff1e2013-05-24 18:32:55 +0000634 /*IsInlineAsmIdentifier=*/ true);
John McCallf413f5e2013-05-03 00:10:13 +0000635
636 if (IsUnevaluatedContext)
637 PopExpressionEvaluationContext();
638
639 if (!Result.isUsable()) return Result;
640
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000641 Result = CheckPlaceholderExpr(Result.get());
John McCallf413f5e2013-05-03 00:10:13 +0000642 if (!Result.isUsable()) return Result;
643
Hans Wennborg93dbeae2014-09-04 22:16:48 +0000644 // Referring to parameters is not allowed in naked functions.
Hans Wennborge9d240a2014-10-08 01:58:02 +0000645 if (CheckNakedParmReference(Result.get(), *this))
646 return ExprError();
Hans Wennborg93dbeae2014-09-04 22:16:48 +0000647
John McCallf413f5e2013-05-03 00:10:13 +0000648 QualType T = Result.get()->getType();
649
John McCallf413f5e2013-05-03 00:10:13 +0000650 if (T->isDependentType()) {
David Majnemerf8b569c2016-01-04 23:51:15 +0000651 return Result;
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000652 }
653
John McCallf413f5e2013-05-03 00:10:13 +0000654 // Any sort of function type is fine.
655 if (T->isFunctionType()) {
656 return Result;
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000657 }
658
John McCallf413f5e2013-05-03 00:10:13 +0000659 // Otherwise, it needs to be a complete type.
660 if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) {
661 return ExprError();
662 }
663
Reid Kleckner14e96b42015-08-26 21:57:20 +0000664 fillInlineAsmTypeInfo(Context, T, Info);
John McCallf413f5e2013-05-03 00:10:13 +0000665
666 // We can work with the expression as long as it's not an r-value.
667 if (!Result.get()->isRValue())
Chad Rosierb18a2852013-04-22 17:01:37 +0000668 Info.IsVarDecl = true;
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000669
John McCallf413f5e2013-05-03 00:10:13 +0000670 return Result;
Chad Rosier4a0054f2012-10-15 19:56:10 +0000671}
Chad Rosierd997bd12012-08-22 19:18:30 +0000672
Chad Rosier5c563642012-10-25 21:49:22 +0000673bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
674 unsigned &Offset, SourceLocation AsmLoc) {
675 Offset = 0;
Marina Yatsina71ebc692015-12-17 12:51:51 +0000676 SmallVector<StringRef, 2> Members;
677 Member.split(Members, ".");
678
Chad Rosier5c563642012-10-25 21:49:22 +0000679 LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
680 LookupOrdinaryName);
681
682 if (!LookupName(BaseResult, getCurScope()))
683 return true;
Marina Yatsinad6d8b312016-03-16 09:56:58 +0000684
685 if(!BaseResult.isSingleResult())
686 return true;
687 NamedDecl *FoundDecl = BaseResult.getFoundDecl();
Marina Yatsina71ebc692015-12-17 12:51:51 +0000688 for (StringRef NextMember : Members) {
Marina Yatsina71ebc692015-12-17 12:51:51 +0000689 const RecordType *RT = nullptr;
Marina Yatsina71ebc692015-12-17 12:51:51 +0000690 if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
691 RT = VD->getType()->getAs<RecordType>();
692 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) {
693 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
694 RT = TD->getUnderlyingType()->getAs<RecordType>();
695 } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl))
696 RT = TD->getTypeForDecl()->getAs<RecordType>();
697 else if (FieldDecl *TD = dyn_cast<FieldDecl>(FoundDecl))
698 RT = TD->getType()->getAs<RecordType>();
699 if (!RT)
700 return true;
Chad Rosier5c563642012-10-25 21:49:22 +0000701
Richard Smithdb0ac552015-12-18 22:40:25 +0000702 if (RequireCompleteType(AsmLoc, QualType(RT, 0),
703 diag::err_asm_incomplete_type))
Marina Yatsina71ebc692015-12-17 12:51:51 +0000704 return true;
Chad Rosier5c563642012-10-25 21:49:22 +0000705
Marina Yatsina71ebc692015-12-17 12:51:51 +0000706 LookupResult FieldResult(*this, &Context.Idents.get(NextMember),
707 SourceLocation(), LookupMemberName);
Chad Rosier5c563642012-10-25 21:49:22 +0000708
Marina Yatsina71ebc692015-12-17 12:51:51 +0000709 if (!LookupQualifiedName(FieldResult, RT->getDecl()))
710 return true;
711
Marina Yatsinad6d8b312016-03-16 09:56:58 +0000712 if (!FieldResult.isSingleResult())
713 return true;
714 FoundDecl = FieldResult.getFoundDecl();
715
Marina Yatsina71ebc692015-12-17 12:51:51 +0000716 // FIXME: Handle IndirectFieldDecl?
Marina Yatsinad6d8b312016-03-16 09:56:58 +0000717 FieldDecl *FD = dyn_cast<FieldDecl>(FoundDecl);
Marina Yatsina71ebc692015-12-17 12:51:51 +0000718 if (!FD)
719 return true;
720
Marina Yatsina71ebc692015-12-17 12:51:51 +0000721 const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl());
722 unsigned i = FD->getFieldIndex();
723 CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
724 Offset += (unsigned)Result.getQuantity();
725 }
Chad Rosier5c563642012-10-25 21:49:22 +0000726
727 return false;
728}
729
Reid Kleckner14e96b42015-08-26 21:57:20 +0000730ExprResult
David Majnemer758e7982016-01-05 00:08:41 +0000731Sema::LookupInlineAsmVarDeclField(Expr *E, StringRef Member,
Reid Kleckner14e96b42015-08-26 21:57:20 +0000732 llvm::InlineAsmIdentifierInfo &Info,
733 SourceLocation AsmLoc) {
734 Info.clear();
735
David Majnemerf8b569c2016-01-04 23:51:15 +0000736 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 /*FirstQualifierInScope=*/nullptr, NameInfo, /*TemplateArgs=*/nullptr);
745 }
746
747 const RecordType *RT = T->getAs<RecordType>();
Reid Kleckner14e96b42015-08-26 21:57:20 +0000748 // FIXME: Diagnose this as field access into a scalar type.
749 if (!RT)
750 return ExprResult();
751
752 LookupResult FieldResult(*this, &Context.Idents.get(Member), AsmLoc,
753 LookupMemberName);
754
755 if (!LookupQualifiedName(FieldResult, RT->getDecl()))
756 return ExprResult();
757
758 // Only normal and indirect field results will work.
759 ValueDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
760 if (!FD)
761 FD = dyn_cast<IndirectFieldDecl>(FieldResult.getFoundDecl());
762 if (!FD)
763 return ExprResult();
764
Reid Kleckner14e96b42015-08-26 21:57:20 +0000765 // Make an Expr to thread through OpDecl.
766 ExprResult Result = BuildMemberReferenceExpr(
767 E, E->getType(), AsmLoc, /*IsArrow=*/false, CXXScopeSpec(),
Aaron Ballman6924dcd2015-09-01 14:49:24 +0000768 SourceLocation(), nullptr, FieldResult, nullptr, nullptr);
Reid Kleckner14e96b42015-08-26 21:57:20 +0000769 if (Result.isInvalid())
770 return Result;
771 Info.OpDecl = Result.get();
772
773 fillInlineAsmTypeInfo(Context, Result.get()->getType(), Info);
774
775 // Fields are "variables" as far as inline assembly is concerned.
776 Info.IsVarDecl = true;
777
778 return Result;
779}
780
Chad Rosierb261a502012-09-13 00:06:55 +0000781StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
John McCallf413f5e2013-05-03 00:10:13 +0000782 ArrayRef<Token> AsmToks,
783 StringRef AsmString,
784 unsigned NumOutputs, unsigned NumInputs,
785 ArrayRef<StringRef> Constraints,
786 ArrayRef<StringRef> Clobbers,
787 ArrayRef<Expr*> Exprs,
788 SourceLocation EndLoc) {
789 bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000790 getCurFunction()->setHasBranchProtectedScope();
Chad Rosier0731aff2012-08-17 21:19:40 +0000791 MSAsmStmt *NS =
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000792 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
793 /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
John McCallf413f5e2013-05-03 00:10:13 +0000794 Constraints, Exprs, AsmString,
795 Clobbers, EndLoc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000796 return NS;
Chad Rosier0731aff2012-08-17 21:19:40 +0000797}
Ehsan Akhgari31097582014-09-22 02:21:54 +0000798
799LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
800 SourceLocation Location,
801 bool AlwaysCreate) {
802 LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName),
803 Location);
804
Ehsan Akhgari42924432014-10-08 17:28:34 +0000805 if (Label->isMSAsmLabel()) {
806 // If we have previously created this label implicitly, mark it as used.
807 Label->markUsed(Context);
808 } else {
Ehsan Akhgari31097582014-09-22 02:21:54 +0000809 // Otherwise, insert it, but only resolve it if we have seen the label itself.
810 std::string InternalName;
811 llvm::raw_string_ostream OS(InternalName);
Reid Kleckner36c201a2016-12-07 00:17:18 +0000812 // Create an internal name for the label. The name should not be a valid
813 // mangled name, and should be unique. We use a dot to make the name an
814 // invalid mangled name. We use LLVM's inline asm ${:uid} escape so that a
815 // unique label is generated each time this blob is emitted, even after
816 // inlining or LTO.
Reid Klecknerfec0f322016-11-29 00:39:37 +0000817 OS << "__MSASMLABEL_.${:uid}__";
Reid Kleckner08ebbce2016-11-28 20:52:19 +0000818 for (char C : ExternalLabelName) {
819 OS << C;
820 // We escape '$' in asm strings by replacing it with "$$"
821 if (C == '$')
Marina Yatsinaafb72f32015-12-29 08:49:34 +0000822 OS << '$';
Marina Yatsinaafb72f32015-12-29 08:49:34 +0000823 }
Ehsan Akhgari31097582014-09-22 02:21:54 +0000824 Label->setMSAsmLabel(OS.str());
825 }
826 if (AlwaysCreate) {
827 // The label might have been created implicitly from a previously encountered
828 // goto statement. So, for both newly created and looked up labels, we mark
829 // them as resolved.
830 Label->setMSAsmLabelResolved();
831 }
832 // Adjust their location for being able to generate accurate diagnostics.
833 Label->setLocation(Location);
834
835 return Label;
836}