blob: afd785c5dfb4bb1aec48596e481f4faa13ba47a3 [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
14#include "clang/Sema/SemaInternal.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"
Chad Rosier0731aff2012-08-17 21:19:40 +000023#include "llvm/ADT/ArrayRef.h"
24#include "llvm/ADT/BitVector.h"
Alp Toker10399272014-06-08 05:11:37 +000025#include "llvm/MC/MCParser/MCAsmParser.h"
Chad Rosier0731aff2012-08-17 21:19:40 +000026using namespace clang;
27using namespace sema;
28
29/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
30/// ignore "noop" casts in places where an lvalue is required by an inline asm.
31/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
32/// provide a strong guidance to not use it.
33///
34/// This method checks to see if the argument is an acceptable l-value and
35/// returns false if it is a case we can handle.
36static bool CheckAsmLValue(const Expr *E, Sema &S) {
37 // Type dependent expressions will be checked during instantiation.
38 if (E->isTypeDependent())
39 return false;
40
41 if (E->isLValue())
42 return false; // Cool, this is an lvalue.
43
44 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
45 // are supposed to allow.
46 const Expr *E2 = E->IgnoreParenNoopCasts(S.Context);
47 if (E != E2 && E2->isLValue()) {
48 if (!S.getLangOpts().HeinousExtensions)
49 S.Diag(E2->getLocStart(), diag::err_invalid_asm_cast_lvalue)
50 << E->getSourceRange();
51 else
52 S.Diag(E2->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
53 << E->getSourceRange();
54 // Accept, even if we emitted an error diagnostic.
55 return false;
56 }
57
58 // None of the above, just randomly invalid non-lvalue.
59 return true;
60}
61
62/// isOperandMentioned - Return true if the specified operand # is mentioned
63/// anywhere in the decomposed asm string.
64static bool isOperandMentioned(unsigned OpNo,
Chad Rosierde70e0e2012-08-25 00:11:56 +000065 ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
Chad Rosier0731aff2012-08-17 21:19:40 +000066 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
Chad Rosierde70e0e2012-08-25 00:11:56 +000067 const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
Chad Rosier0731aff2012-08-17 21:19:40 +000068 if (!Piece.isOperand()) continue;
69
70 // If this is a reference to the input and if the input was the smaller
71 // one, then we have to reject this asm.
72 if (Piece.getOperandNo() == OpNo)
73 return true;
74 }
75 return false;
76}
77
Hans Wennborge9d240a2014-10-08 01:58:02 +000078static bool CheckNakedParmReference(Expr *E, Sema &S) {
79 FunctionDecl *Func = dyn_cast<FunctionDecl>(S.CurContext);
80 if (!Func)
81 return false;
82 if (!Func->hasAttr<NakedAttr>())
83 return false;
84
85 SmallVector<Expr*, 4> WorkList;
86 WorkList.push_back(E);
87 while (WorkList.size()) {
88 Expr *E = WorkList.pop_back_val();
89 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(E)) {
90 if (isa<ParmVarDecl>(DRE->getDecl())) {
91 S.Diag(DRE->getLocStart(), diag::err_asm_naked_parm_ref);
92 S.Diag(Func->getAttr<NakedAttr>()->getLocation(), diag::note_attribute);
93 return true;
94 }
95 }
96 for (Stmt *Child : E->children()) {
97 if (Expr *E = dyn_cast_or_null<Expr>(Child))
98 WorkList.push_back(E);
99 }
100 }
101 return false;
102}
103
Chad Rosierde70e0e2012-08-25 00:11:56 +0000104StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
105 bool IsVolatile, unsigned NumOutputs,
106 unsigned NumInputs, IdentifierInfo **Names,
Dmitri Gribenkoea2d5f82013-05-10 01:14:26 +0000107 MultiExprArg constraints, MultiExprArg Exprs,
Chad Rosierde70e0e2012-08-25 00:11:56 +0000108 Expr *asmString, MultiExprArg clobbers,
109 SourceLocation RParenLoc) {
Chad Rosier0731aff2012-08-17 21:19:40 +0000110 unsigned NumClobbers = clobbers.size();
111 StringLiteral **Constraints =
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000112 reinterpret_cast<StringLiteral**>(constraints.data());
Chad Rosier0731aff2012-08-17 21:19:40 +0000113 StringLiteral *AsmString = cast<StringLiteral>(asmString);
Benjamin Kramercc4c49d2012-08-23 23:38:35 +0000114 StringLiteral **Clobbers = reinterpret_cast<StringLiteral**>(clobbers.data());
Chad Rosier0731aff2012-08-17 21:19:40 +0000115
116 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
117
118 // The parser verifies that there is a string literal here.
David Majnemerb3e96f72014-12-11 01:00:48 +0000119 assert(AsmString->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000120
121 for (unsigned i = 0; i != NumOutputs; i++) {
122 StringLiteral *Literal = Constraints[i];
David Majnemerb3e96f72014-12-11 01:00:48 +0000123 assert(Literal->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000124
125 StringRef OutputName;
126 if (Names[i])
127 OutputName = Names[i]->getName();
128
129 TargetInfo::ConstraintInfo Info(Literal->getString(), OutputName);
130 if (!Context.getTargetInfo().validateOutputConstraint(Info))
131 return StmtError(Diag(Literal->getLocStart(),
132 diag::err_asm_invalid_output_constraint)
133 << Info.getConstraintStr());
134
David Majnemer0f4d6412014-12-29 09:30:33 +0000135 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
136 if (ER.isInvalid())
137 return StmtError();
138 Exprs[i] = ER.get();
139
Chad Rosier0731aff2012-08-17 21:19:40 +0000140 // Check that the output exprs are valid lvalues.
141 Expr *OutputExpr = Exprs[i];
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000142
Hans Wennborge9d240a2014-10-08 01:58:02 +0000143 // Referring to parameters is not allowed in naked functions.
144 if (CheckNakedParmReference(OutputExpr, *this))
145 return StmtError();
146
Chad Rosier0731aff2012-08-17 21:19:40 +0000147 OutputConstraintInfos.push_back(Info);
Akira Hatanaka974131e2014-09-18 18:17:18 +0000148
David Majnemer0f4d6412014-12-29 09:30:33 +0000149 // If this is dependent, just continue.
150 if (OutputExpr->isTypeDependent())
Akira Hatanaka974131e2014-09-18 18:17:18 +0000151 continue;
152
David Majnemer0f4d6412014-12-29 09:30:33 +0000153 Expr::isModifiableLvalueResult IsLV =
154 OutputExpr->isModifiableLvalue(Context, /*Loc=*/nullptr);
155 switch (IsLV) {
156 case Expr::MLV_Valid:
157 // Cool, this is an lvalue.
158 break;
David Majnemer04b78412014-12-29 10:29:53 +0000159 case Expr::MLV_ArrayType:
160 // This is OK too.
161 break;
David Majnemer0f4d6412014-12-29 09:30:33 +0000162 case Expr::MLV_LValueCast: {
163 const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Context);
164 if (!getLangOpts().HeinousExtensions) {
165 Diag(LVal->getLocStart(), diag::err_invalid_asm_cast_lvalue)
166 << OutputExpr->getSourceRange();
167 } else {
168 Diag(LVal->getLocStart(), diag::warn_invalid_asm_cast_lvalue)
169 << OutputExpr->getSourceRange();
170 }
171 // Accept, even if we emitted an error diagnostic.
172 break;
173 }
174 case Expr::MLV_IncompleteType:
175 case Expr::MLV_IncompleteVoidType:
176 if (RequireCompleteType(OutputExpr->getLocStart(), Exprs[i]->getType(),
177 diag::err_dereference_incomplete_type))
178 return StmtError();
179 default:
180 return StmtError(Diag(OutputExpr->getLocStart(),
181 diag::err_asm_invalid_lvalue_in_output)
182 << OutputExpr->getSourceRange());
183 }
184
185 unsigned Size = Context.getTypeSize(OutputExpr->getType());
Akira Hatanaka974131e2014-09-18 18:17:18 +0000186 if (!Context.getTargetInfo().validateOutputSize(Literal->getString(),
187 Size))
188 return StmtError(Diag(OutputExpr->getLocStart(),
189 diag::err_asm_invalid_output_size)
190 << Info.getConstraintStr());
Chad Rosier0731aff2012-08-17 21:19:40 +0000191 }
192
193 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
194
195 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
196 StringLiteral *Literal = Constraints[i];
David Majnemerb3e96f72014-12-11 01:00:48 +0000197 assert(Literal->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000198
199 StringRef InputName;
200 if (Names[i])
201 InputName = Names[i]->getName();
202
203 TargetInfo::ConstraintInfo Info(Literal->getString(), InputName);
204 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraintInfos.data(),
205 NumOutputs, Info)) {
206 return StmtError(Diag(Literal->getLocStart(),
207 diag::err_asm_invalid_input_constraint)
208 << Info.getConstraintStr());
209 }
210
David Majnemer0f4d6412014-12-29 09:30:33 +0000211 ExprResult ER = CheckPlaceholderExpr(Exprs[i]);
212 if (ER.isInvalid())
213 return StmtError();
214 Exprs[i] = ER.get();
215
Chad Rosier0731aff2012-08-17 21:19:40 +0000216 Expr *InputExpr = Exprs[i];
217
Hans Wennborge9d240a2014-10-08 01:58:02 +0000218 // Referring to parameters is not allowed in naked functions.
219 if (CheckNakedParmReference(InputExpr, *this))
220 return StmtError();
221
Chad Rosier0731aff2012-08-17 21:19:40 +0000222 // Only allow void types for memory constraints.
223 if (Info.allowsMemory() && !Info.allowsRegister()) {
224 if (CheckAsmLValue(InputExpr, *this))
225 return StmtError(Diag(InputExpr->getLocStart(),
226 diag::err_asm_invalid_lvalue_in_input)
227 << Info.getConstraintStr()
228 << InputExpr->getSourceRange());
David Majnemerade4bee2014-07-14 16:27:53 +0000229 } else {
230 ExprResult Result = DefaultFunctionArrayLvalueConversion(Exprs[i]);
231 if (Result.isInvalid())
232 return StmtError();
233
234 Exprs[i] = Result.get();
Chad Rosier0731aff2012-08-17 21:19:40 +0000235 }
236
237 if (Info.allowsRegister()) {
238 if (InputExpr->getType()->isVoidType()) {
239 return StmtError(Diag(InputExpr->getLocStart(),
240 diag::err_asm_invalid_type_in_input)
241 << InputExpr->getType() << Info.getConstraintStr()
242 << InputExpr->getSourceRange());
243 }
244 }
245
Chad Rosier0731aff2012-08-17 21:19:40 +0000246 InputConstraintInfos.push_back(Info);
Bill Wendling887b4852012-11-12 06:42:51 +0000247
248 const Type *Ty = Exprs[i]->getType().getTypePtr();
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000249 if (Ty->isDependentType())
Eric Christopherd41010a2012-11-12 23:13:34 +0000250 continue;
251
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000252 if (!Ty->isVoidType() || !Info.allowsMemory())
Bill Wendlingb68b7572013-03-27 06:06:26 +0000253 if (RequireCompleteType(InputExpr->getLocStart(), Exprs[i]->getType(),
254 diag::err_dereference_incomplete_type))
255 return StmtError();
Bill Wendlingc4fc3a22013-03-25 21:09:49 +0000256
Bill Wendling887b4852012-11-12 06:42:51 +0000257 unsigned Size = Context.getTypeSize(Ty);
258 if (!Context.getTargetInfo().validateInputSize(Literal->getString(),
259 Size))
260 return StmtError(Diag(InputExpr->getLocStart(),
261 diag::err_asm_invalid_input_size)
262 << Info.getConstraintStr());
Chad Rosier0731aff2012-08-17 21:19:40 +0000263 }
264
265 // Check that the clobbers are valid.
266 for (unsigned i = 0; i != NumClobbers; i++) {
267 StringLiteral *Literal = Clobbers[i];
David Majnemerb3e96f72014-12-11 01:00:48 +0000268 assert(Literal->isAscii());
Chad Rosier0731aff2012-08-17 21:19:40 +0000269
270 StringRef Clobber = Literal->getString();
271
272 if (!Context.getTargetInfo().isValidClobber(Clobber))
273 return StmtError(Diag(Literal->getLocStart(),
274 diag::err_asm_unknown_register_name) << Clobber);
275 }
276
Chad Rosierde70e0e2012-08-25 00:11:56 +0000277 GCCAsmStmt *NS =
278 new (Context) GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs,
Dmitri Gribenkoea2d5f82013-05-10 01:14:26 +0000279 NumInputs, Names, Constraints, Exprs.data(),
280 AsmString, NumClobbers, Clobbers, RParenLoc);
Chad Rosier0731aff2012-08-17 21:19:40 +0000281 // Validate the asm string, ensuring it makes sense given the operands we
282 // have.
Chad Rosierde70e0e2012-08-25 00:11:56 +0000283 SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
Chad Rosier0731aff2012-08-17 21:19:40 +0000284 unsigned DiagOffs;
285 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, Context, DiagOffs)) {
286 Diag(getLocationOfStringLiteralByte(AsmString, DiagOffs), DiagID)
287 << AsmString->getSourceRange();
288 return StmtError();
289 }
290
Bill Wendling9d1ee112012-10-25 23:28:48 +0000291 // Validate constraints and modifiers.
292 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
293 GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
294 if (!Piece.isOperand()) continue;
295
296 // Look for the correct constraint index.
297 unsigned Idx = 0;
298 unsigned ConstraintIdx = 0;
299 for (unsigned i = 0, e = NS->getNumOutputs(); i != e; ++i, ++ConstraintIdx) {
300 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
301 if (Idx == Piece.getOperandNo())
302 break;
303 ++Idx;
304
305 if (Info.isReadWrite()) {
306 if (Idx == Piece.getOperandNo())
307 break;
308 ++Idx;
309 }
310 }
311
312 for (unsigned i = 0, e = NS->getNumInputs(); i != e; ++i, ++ConstraintIdx) {
313 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
314 if (Idx == Piece.getOperandNo())
315 break;
316 ++Idx;
317
318 if (Info.isReadWrite()) {
319 if (Idx == Piece.getOperandNo())
320 break;
321 ++Idx;
322 }
323 }
324
325 // Now that we have the right indexes go ahead and check.
326 StringLiteral *Literal = Constraints[ConstraintIdx];
327 const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
328 if (Ty->isDependentType() || Ty->isIncompleteType())
329 continue;
330
331 unsigned Size = Context.getTypeSize(Ty);
Akira Hatanaka987f1862014-08-22 06:05:21 +0000332 std::string SuggestedModifier;
333 if (!Context.getTargetInfo().validateConstraintModifier(
334 Literal->getString(), Piece.getModifier(), Size,
335 SuggestedModifier)) {
Bill Wendling9d1ee112012-10-25 23:28:48 +0000336 Diag(Exprs[ConstraintIdx]->getLocStart(),
337 diag::warn_asm_mismatched_size_modifier);
Akira Hatanaka987f1862014-08-22 06:05:21 +0000338
339 if (!SuggestedModifier.empty()) {
340 auto B = Diag(Piece.getRange().getBegin(),
341 diag::note_asm_missing_constraint_modifier)
342 << SuggestedModifier;
343 SuggestedModifier = "%" + SuggestedModifier + Piece.getString();
344 B.AddFixItHint(FixItHint::CreateReplacement(Piece.getRange(),
345 SuggestedModifier));
346 }
347 }
Bill Wendling9d1ee112012-10-25 23:28:48 +0000348 }
349
Chad Rosier0731aff2012-08-17 21:19:40 +0000350 // Validate tied input operands for type mismatches.
David Majnemerc63fa612014-12-29 04:09:59 +0000351 unsigned NumAlternatives = ~0U;
352 for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) {
353 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
354 StringRef ConstraintStr = Info.getConstraintStr();
355 unsigned AltCount = ConstraintStr.count(',') + 1;
356 if (NumAlternatives == ~0U)
357 NumAlternatives = AltCount;
358 else if (NumAlternatives != AltCount)
359 return StmtError(Diag(NS->getOutputExpr(i)->getLocStart(),
360 diag::err_asm_unexpected_constraint_alternatives)
361 << NumAlternatives << AltCount);
362 }
Chad Rosier0731aff2012-08-17 21:19:40 +0000363 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
364 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
David Majnemerc63fa612014-12-29 04:09:59 +0000365 StringRef ConstraintStr = Info.getConstraintStr();
366 unsigned AltCount = ConstraintStr.count(',') + 1;
367 if (NumAlternatives == ~0U)
368 NumAlternatives = AltCount;
369 else if (NumAlternatives != AltCount)
370 return StmtError(Diag(NS->getInputExpr(i)->getLocStart(),
371 diag::err_asm_unexpected_constraint_alternatives)
372 << NumAlternatives << AltCount);
Chad Rosier0731aff2012-08-17 21:19:40 +0000373
374 // If this is a tied constraint, verify that the output and input have
375 // either exactly the same type, or that they are int/ptr operands with the
376 // same size (int/long, int*/long, are ok etc).
377 if (!Info.hasTiedOperand()) continue;
378
379 unsigned TiedTo = Info.getTiedOperand();
380 unsigned InputOpNo = i+NumOutputs;
381 Expr *OutputExpr = Exprs[TiedTo];
382 Expr *InputExpr = Exprs[InputOpNo];
383
384 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
385 continue;
386
387 QualType InTy = InputExpr->getType();
388 QualType OutTy = OutputExpr->getType();
389 if (Context.hasSameType(InTy, OutTy))
390 continue; // All types can be tied to themselves.
391
392 // Decide if the input and output are in the same domain (integer/ptr or
393 // floating point.
394 enum AsmDomain {
395 AD_Int, AD_FP, AD_Other
396 } InputDomain, OutputDomain;
397
398 if (InTy->isIntegerType() || InTy->isPointerType())
399 InputDomain = AD_Int;
400 else if (InTy->isRealFloatingType())
401 InputDomain = AD_FP;
402 else
403 InputDomain = AD_Other;
404
405 if (OutTy->isIntegerType() || OutTy->isPointerType())
406 OutputDomain = AD_Int;
407 else if (OutTy->isRealFloatingType())
408 OutputDomain = AD_FP;
409 else
410 OutputDomain = AD_Other;
411
412 // They are ok if they are the same size and in the same domain. This
413 // allows tying things like:
414 // void* to int*
415 // void* to int if they are the same size.
416 // double to long double if they are the same size.
417 //
418 uint64_t OutSize = Context.getTypeSize(OutTy);
419 uint64_t InSize = Context.getTypeSize(InTy);
420 if (OutSize == InSize && InputDomain == OutputDomain &&
421 InputDomain != AD_Other)
422 continue;
423
424 // If the smaller input/output operand is not mentioned in the asm string,
425 // then we can promote the smaller one to a larger input and the asm string
426 // won't notice.
427 bool SmallerValueMentioned = false;
428
429 // If this is a reference to the input and if the input was the smaller
430 // one, then we have to reject this asm.
431 if (isOperandMentioned(InputOpNo, Pieces)) {
432 // This is a use in the asm string of the smaller operand. Since we
433 // codegen this by promoting to a wider value, the asm will get printed
434 // "wrong".
435 SmallerValueMentioned |= InSize < OutSize;
436 }
437 if (isOperandMentioned(TiedTo, Pieces)) {
438 // If this is a reference to the output, and if the output is the larger
439 // value, then it's ok because we'll promote the input to the larger type.
440 SmallerValueMentioned |= OutSize < InSize;
441 }
442
443 // If the smaller value wasn't mentioned in the asm string, and if the
444 // output was a register, just extend the shorter one to the size of the
445 // larger one.
446 if (!SmallerValueMentioned && InputDomain != AD_Other &&
447 OutputConstraintInfos[TiedTo].allowsRegister())
448 continue;
449
450 // Either both of the operands were mentioned or the smaller one was
451 // mentioned. One more special case that we'll allow: if the tied input is
452 // integer, unmentioned, and is a constant, then we'll allow truncating it
453 // down to the size of the destination.
454 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
455 !isOperandMentioned(InputOpNo, Pieces) &&
456 InputExpr->isEvaluatable(Context)) {
457 CastKind castKind =
458 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000459 InputExpr = ImpCastExprToType(InputExpr, OutTy, castKind).get();
Chad Rosier0731aff2012-08-17 21:19:40 +0000460 Exprs[InputOpNo] = InputExpr;
461 NS->setInputExpr(i, InputExpr);
462 continue;
463 }
464
465 Diag(InputExpr->getLocStart(),
466 diag::err_asm_tying_incompatible_types)
467 << InTy << OutTy << OutputExpr->getSourceRange()
468 << InputExpr->getSourceRange();
469 return StmtError();
470 }
471
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000472 return NS;
Chad Rosier0731aff2012-08-17 21:19:40 +0000473}
474
John McCallf413f5e2013-05-03 00:10:13 +0000475ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
476 SourceLocation TemplateKWLoc,
477 UnqualifiedId &Id,
Alp Toker10399272014-06-08 05:11:37 +0000478 llvm::InlineAsmIdentifierInfo &Info,
John McCallf413f5e2013-05-03 00:10:13 +0000479 bool IsUnevaluatedContext) {
Chad Rosierb18a2852013-04-22 17:01:37 +0000480 Info.clear();
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000481
John McCallf413f5e2013-05-03 00:10:13 +0000482 if (IsUnevaluatedContext)
483 PushExpressionEvaluationContext(UnevaluatedAbstract,
484 ReuseLambdaContextDecl);
485
486 ExprResult Result = ActOnIdExpression(getCurScope(), SS, TemplateKWLoc, Id,
487 /*trailing lparen*/ false,
Chad Rosierb9aff1e2013-05-24 18:32:55 +0000488 /*is & operand*/ false,
Craig Topperc3ec1492014-05-26 06:22:03 +0000489 /*CorrectionCandidateCallback=*/nullptr,
Chad Rosierb9aff1e2013-05-24 18:32:55 +0000490 /*IsInlineAsmIdentifier=*/ true);
John McCallf413f5e2013-05-03 00:10:13 +0000491
492 if (IsUnevaluatedContext)
493 PopExpressionEvaluationContext();
494
495 if (!Result.isUsable()) return Result;
496
Nikola Smiljanic01a75982014-05-29 10:55:11 +0000497 Result = CheckPlaceholderExpr(Result.get());
John McCallf413f5e2013-05-03 00:10:13 +0000498 if (!Result.isUsable()) return Result;
499
Hans Wennborg93dbeae2014-09-04 22:16:48 +0000500 // Referring to parameters is not allowed in naked functions.
Hans Wennborge9d240a2014-10-08 01:58:02 +0000501 if (CheckNakedParmReference(Result.get(), *this))
502 return ExprError();
Hans Wennborg93dbeae2014-09-04 22:16:48 +0000503
John McCallf413f5e2013-05-03 00:10:13 +0000504 QualType T = Result.get()->getType();
505
506 // For now, reject dependent types.
507 if (T->isDependentType()) {
508 Diag(Id.getLocStart(), diag::err_asm_incomplete_type) << T;
509 return ExprError();
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000510 }
511
John McCallf413f5e2013-05-03 00:10:13 +0000512 // Any sort of function type is fine.
513 if (T->isFunctionType()) {
514 return Result;
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000515 }
516
John McCallf413f5e2013-05-03 00:10:13 +0000517 // Otherwise, it needs to be a complete type.
518 if (RequireCompleteExprType(Result.get(), diag::err_asm_incomplete_type)) {
519 return ExprError();
520 }
521
522 // Compute the type size (and array length if applicable?).
523 Info.Type = Info.Size = Context.getTypeSizeInChars(T).getQuantity();
524 if (T->isArrayType()) {
525 const ArrayType *ATy = Context.getAsArrayType(T);
526 Info.Type = Context.getTypeSizeInChars(ATy->getElementType()).getQuantity();
527 Info.Length = Info.Size / Info.Type;
528 }
529
530 // We can work with the expression as long as it's not an r-value.
531 if (!Result.get()->isRValue())
Chad Rosierb18a2852013-04-22 17:01:37 +0000532 Info.IsVarDecl = true;
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000533
John McCallf413f5e2013-05-03 00:10:13 +0000534 return Result;
Chad Rosier4a0054f2012-10-15 19:56:10 +0000535}
Chad Rosierd997bd12012-08-22 19:18:30 +0000536
Chad Rosier5c563642012-10-25 21:49:22 +0000537bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
538 unsigned &Offset, SourceLocation AsmLoc) {
539 Offset = 0;
540 LookupResult BaseResult(*this, &Context.Idents.get(Base), SourceLocation(),
541 LookupOrdinaryName);
542
543 if (!LookupName(BaseResult, getCurScope()))
544 return true;
545
546 if (!BaseResult.isSingleResult())
547 return true;
548
Craig Topperc3ec1492014-05-26 06:22:03 +0000549 const RecordType *RT = nullptr;
Chad Rosier10230d42013-04-01 17:58:03 +0000550 NamedDecl *FoundDecl = BaseResult.getFoundDecl();
551 if (VarDecl *VD = dyn_cast<VarDecl>(FoundDecl))
Chad Rosier5c563642012-10-25 21:49:22 +0000552 RT = VD->getType()->getAs<RecordType>();
Nico Weber72889432014-09-06 01:25:55 +0000553 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(FoundDecl)) {
554 MarkAnyDeclReferenced(TD->getLocation(), TD, /*OdrUse=*/false);
Chad Rosier5c563642012-10-25 21:49:22 +0000555 RT = TD->getUnderlyingType()->getAs<RecordType>();
Nico Weber72889432014-09-06 01:25:55 +0000556 } else if (TypeDecl *TD = dyn_cast<TypeDecl>(FoundDecl))
Nico Weber9ef9ca42014-05-06 03:13:27 +0000557 RT = TD->getTypeForDecl()->getAs<RecordType>();
Chad Rosier5c563642012-10-25 21:49:22 +0000558 if (!RT)
559 return true;
560
561 if (RequireCompleteType(AsmLoc, QualType(RT, 0), 0))
562 return true;
563
564 LookupResult FieldResult(*this, &Context.Idents.get(Member), SourceLocation(),
565 LookupMemberName);
566
567 if (!LookupQualifiedName(FieldResult, RT->getDecl()))
568 return true;
569
570 // FIXME: Handle IndirectFieldDecl?
571 FieldDecl *FD = dyn_cast<FieldDecl>(FieldResult.getFoundDecl());
572 if (!FD)
573 return true;
574
575 const ASTRecordLayout &RL = Context.getASTRecordLayout(RT->getDecl());
576 unsigned i = FD->getFieldIndex();
577 CharUnits Result = Context.toCharUnitsFromBits(RL.getFieldOffset(i));
578 Offset = (unsigned)Result.getQuantity();
579
580 return false;
581}
582
Chad Rosierb261a502012-09-13 00:06:55 +0000583StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
John McCallf413f5e2013-05-03 00:10:13 +0000584 ArrayRef<Token> AsmToks,
585 StringRef AsmString,
586 unsigned NumOutputs, unsigned NumInputs,
587 ArrayRef<StringRef> Constraints,
588 ArrayRef<StringRef> Clobbers,
589 ArrayRef<Expr*> Exprs,
590 SourceLocation EndLoc) {
591 bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
Ehsan Akhgari31097582014-09-22 02:21:54 +0000592 getCurFunction()->setHasBranchProtectedScope();
Chad Rosier0731aff2012-08-17 21:19:40 +0000593 MSAsmStmt *NS =
Chad Rosierce2bcbf2012-10-18 15:49:40 +0000594 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
595 /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
John McCallf413f5e2013-05-03 00:10:13 +0000596 Constraints, Exprs, AsmString,
597 Clobbers, EndLoc);
Nikola Smiljanic03ff2592014-05-29 14:05:12 +0000598 return NS;
Chad Rosier0731aff2012-08-17 21:19:40 +0000599}
Ehsan Akhgari31097582014-09-22 02:21:54 +0000600
601LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
602 SourceLocation Location,
603 bool AlwaysCreate) {
604 LabelDecl* Label = LookupOrCreateLabel(PP.getIdentifierInfo(ExternalLabelName),
605 Location);
606
Ehsan Akhgari42924432014-10-08 17:28:34 +0000607 if (Label->isMSAsmLabel()) {
608 // If we have previously created this label implicitly, mark it as used.
609 Label->markUsed(Context);
610 } else {
Ehsan Akhgari31097582014-09-22 02:21:54 +0000611 // Otherwise, insert it, but only resolve it if we have seen the label itself.
612 std::string InternalName;
613 llvm::raw_string_ostream OS(InternalName);
614 // Create an internal name for the label. The name should not be a valid mangled
615 // name, and should be unique. We use a dot to make the name an invalid mangled
616 // name.
617 OS << "__MSASMLABEL_." << MSAsmLabelNameCounter++ << "__" << ExternalLabelName;
618 Label->setMSAsmLabel(OS.str());
619 }
620 if (AlwaysCreate) {
621 // The label might have been created implicitly from a previously encountered
622 // goto statement. So, for both newly created and looked up labels, we mark
623 // them as resolved.
624 Label->setMSAsmLabelResolved();
625 }
626 // Adjust their location for being able to generate accurate diagnostics.
627 Label->setLocation(Location);
628
629 return Label;
630}