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
13#include "clang/AST/ExprCXX.h"
14#include "clang/AST/RecordLayout.h"
15#include "clang/AST/TypeLoc.h"
16#include "clang/Basic/DiagnosticLex.h"
17#include "clang/Basic/TargetInfo.h"
18#include "clang/Lex/Preprocessor.h"
19#include "clang/Lex/TextEncoding.h"
20#include "clang/Sema/Initialization.h"
21#include "clang/Sema/Lookup.h"
22#include "clang/Sema/Ownership.h"
23#include "clang/Sema/Scope.h"
24#include "clang/Sema/ScopeInfo.h"
25#include "clang/Sema/SemaBPF.h"
26#include "llvm/ADT/ArrayRef.h"
27#include "llvm/ADT/StringExtras.h"
28#include "llvm/ADT/StringSet.h"
29#include "llvm/MC/MCParser/MCAsmParser.h"
30#include "llvm/Support/TextEncoding.h"
31#include <optional>
32using namespace clang;
33using namespace sema;
34
35/// Remove the upper-level LValueToRValue cast from an expression.
36static void removeLValueToRValueCast(Expr *E) {
37 Expr *Parent = E;
38 Expr *ExprUnderCast = nullptr;
39 SmallVector<Expr *, 8> ParentsToUpdate;
40
41 while (true) {
42 ParentsToUpdate.push_back(Elt: Parent);
43 if (auto *ParenE = dyn_cast<ParenExpr>(Val: Parent)) {
44 Parent = ParenE->getSubExpr();
45 continue;
46 }
47
48 Expr *Child = nullptr;
49 CastExpr *ParentCast = dyn_cast<CastExpr>(Val: Parent);
50 if (ParentCast)
51 Child = ParentCast->getSubExpr();
52 else
53 return;
54
55 if (auto *CastE = dyn_cast<CastExpr>(Val: Child))
56 if (CastE->getCastKind() == CK_LValueToRValue) {
57 ExprUnderCast = CastE->getSubExpr();
58 // LValueToRValue cast inside GCCAsmStmt requires an explicit cast.
59 ParentCast->setSubExpr(ExprUnderCast);
60 break;
61 }
62 Parent = Child;
63 }
64
65 // Update parent expressions to have same ValueType as the underlying.
66 assert(ExprUnderCast &&
67 "Should be reachable only if LValueToRValue cast was found!");
68 auto ValueKind = ExprUnderCast->getValueKind();
69 for (Expr *E : ParentsToUpdate)
70 E->setValueKind(ValueKind);
71}
72
73/// Emit a warning about usage of "noop"-like casts for lvalues (GNU extension)
74/// and fix the argument with removing LValueToRValue cast from the expression.
75static void emitAndFixInvalidAsmCastLValue(const Expr *LVal, Expr *BadArgument,
76 Sema &S) {
77 S.Diag(Loc: LVal->getBeginLoc(), DiagID: diag::warn_invalid_asm_cast_lvalue)
78 << BadArgument->getSourceRange();
79 removeLValueToRValueCast(E: BadArgument);
80}
81
82/// CheckAsmLValue - GNU C has an extremely ugly extension whereby they silently
83/// ignore "noop" casts in places where an lvalue is required by an inline asm.
84/// We emulate this behavior when -fheinous-gnu-extensions is specified, but
85/// provide a strong guidance to not use it.
86///
87/// This method checks to see if the argument is an acceptable l-value and
88/// returns false if it is a case we can handle.
89static bool CheckAsmLValue(Expr *E, Sema &S) {
90 // Type dependent expressions will be checked during instantiation.
91 if (E->isTypeDependent())
92 return false;
93
94 if (E->isLValue())
95 return false; // Cool, this is an lvalue.
96
97 // Okay, this is not an lvalue, but perhaps it is the result of a cast that we
98 // are supposed to allow.
99 const Expr *E2 = E->IgnoreParenNoopCasts(Ctx: S.Context);
100 if (E != E2 && E2->isLValue()) {
101 emitAndFixInvalidAsmCastLValue(LVal: E2, BadArgument: E, S);
102 // Accept, even if we emitted an error diagnostic.
103 return false;
104 }
105
106 // None of the above, just randomly invalid non-lvalue.
107 return true;
108}
109
110/// isOperandMentioned - Return true if the specified operand # is mentioned
111/// anywhere in the decomposed asm string.
112static bool
113isOperandMentioned(unsigned OpNo,
114 ArrayRef<GCCAsmStmt::AsmStringPiece> AsmStrPieces) {
115 for (unsigned p = 0, e = AsmStrPieces.size(); p != e; ++p) {
116 const GCCAsmStmt::AsmStringPiece &Piece = AsmStrPieces[p];
117 if (!Piece.isOperand())
118 continue;
119
120 // If this is a reference to the input and if the input was the smaller
121 // one, then we have to reject this asm.
122 if (Piece.getOperandNo() == OpNo)
123 return true;
124 }
125 return false;
126}
127
128static bool CheckNakedParmReference(Expr *E, Sema &S) {
129 FunctionDecl *Func = dyn_cast<FunctionDecl>(Val: S.CurContext);
130 if (!Func)
131 return false;
132 if (!Func->hasAttr<NakedAttr>())
133 return false;
134
135 SmallVector<Expr*, 4> WorkList;
136 WorkList.push_back(Elt: E);
137 while (WorkList.size()) {
138 Expr *E = WorkList.pop_back_val();
139 if (isa<CXXThisExpr>(Val: E)) {
140 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_asm_naked_this_ref);
141 S.Diag(Loc: Func->getAttr<NakedAttr>()->getLocation(), DiagID: diag::note_attribute);
142 return true;
143 }
144 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(Val: E)) {
145 if (isa<ParmVarDecl>(Val: DRE->getDecl())) {
146 S.Diag(Loc: DRE->getBeginLoc(), DiagID: diag::err_asm_naked_parm_ref);
147 S.Diag(Loc: Func->getAttr<NakedAttr>()->getLocation(), DiagID: diag::note_attribute);
148 return true;
149 }
150 }
151 for (Stmt *Child : E->children()) {
152 if (Expr *E = dyn_cast_or_null<Expr>(Val: Child))
153 WorkList.push_back(Elt: E);
154 }
155 }
156 return false;
157}
158
159/// Returns true if given expression is not compatible with inline
160/// assembly's memory constraint; false otherwise.
161static bool checkExprMemoryConstraintCompat(Sema &S, Expr *E,
162 TargetInfo::ConstraintInfo &Info,
163 bool is_input_expr) {
164 enum {
165 ExprBitfield = 0,
166 ExprVectorElt,
167 ExprGlobalRegVar,
168 ExprSafeType
169 } EType = ExprSafeType;
170
171 // Bitfields, vector elements and global register variables are not
172 // compatible.
173 if (E->refersToBitField())
174 EType = ExprBitfield;
175 else if (E->refersToVectorElement())
176 EType = ExprVectorElt;
177 else if (E->refersToGlobalRegisterVar())
178 EType = ExprGlobalRegVar;
179
180 if (EType != ExprSafeType) {
181 S.Diag(Loc: E->getBeginLoc(), DiagID: diag::err_asm_non_addr_value_in_memory_constraint)
182 << EType << is_input_expr << Info.getConstraintStr()
183 << E->getSourceRange();
184 return true;
185 }
186
187 return false;
188}
189
190// Extracting the register name from the Expression value,
191// if there is no register name to extract, returns ""
192static StringRef extractRegisterName(const Expr *Expression,
193 const TargetInfo &Target) {
194 Expression = Expression->IgnoreImpCasts();
195 if (const DeclRefExpr *AsmDeclRef = dyn_cast<DeclRefExpr>(Val: Expression)) {
196 // Handle cases where the expression is a variable
197 const VarDecl *Variable = dyn_cast<VarDecl>(Val: AsmDeclRef->getDecl());
198 if (Variable && Variable->getStorageClass() == SC_Register) {
199 if (AsmLabelAttr *Attr = Variable->getAttr<AsmLabelAttr>())
200 if (Target.isValidGCCRegisterName(Name: Attr->getLabel()))
201 return Target.getNormalizedGCCRegisterName(Name: Attr->getLabel(), ReturnCanonical: true);
202 }
203 }
204 return "";
205}
206
207// Checks if there is a conflict between the input and output lists with the
208// clobbers list. If there's a conflict, returns the location of the
209// conflicted clobber, else returns nullptr
210static SourceLocation
211getClobberConflictLocation(MultiExprArg Exprs, Expr **Constraints,
212 Expr **Clobbers, int NumClobbers, unsigned NumLabels,
213 const TargetInfo &Target, ASTContext &Cont) {
214 llvm::StringSet<> InOutVars;
215 // Collect all the input and output registers from the extended asm
216 // statement in order to check for conflicts with the clobber list
217 for (unsigned int i = 0; i < Exprs.size() - NumLabels; ++i) {
218 std::string Constraint =
219 GCCAsmStmt::ExtractStringFromGCCAsmStmtComponent(E: Constraints[i]);
220 StringRef InOutReg = Target.getConstraintRegister(
221 Constraint, Expression: extractRegisterName(Expression: Exprs[i], Target));
222 if (InOutReg != "")
223 InOutVars.insert(key: InOutReg);
224 }
225 // Check for each item in the clobber list if it conflicts with the input
226 // or output
227 for (int i = 0; i < NumClobbers; ++i) {
228 std::string Clobber =
229 GCCAsmStmt::ExtractStringFromGCCAsmStmtComponent(E: Clobbers[i]);
230 // We only check registers, therefore we don't check cc and memory
231 // clobbers
232 if (Clobber == "cc" || Clobber == "memory" || Clobber == "unwind")
233 continue;
234 Clobber = Target.getNormalizedGCCRegisterName(Name: Clobber, ReturnCanonical: true);
235 // Go over the output's registers we collected
236 if (InOutVars.count(Key: Clobber))
237 return Clobbers[i]->getBeginLoc();
238 }
239 return SourceLocation();
240}
241
242ExprResult Sema::ActOnGCCAsmStmtString(Expr *Expr, bool ForAsmLabel,
243 bool IsConstexpr) {
244 if (!Expr)
245 return ExprError();
246
247 if (auto *SL = dyn_cast<StringLiteral>(Val: Expr)) {
248 assert(SL->isOrdinary());
249 if (ForAsmLabel && SL->getString().empty()) {
250 Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_asm_operand_empty_string)
251 << SL->getSourceRange();
252 }
253
254 if (!IsConstexpr &&
255 PP.getTextEncoding().getzOSFromAsmLiteralEncodingConverter() !=
256 nullptr) {
257 SmallString<16> ConvertedAsm;
258 [[maybe_unused]] std::error_code EC =
259 PP.getTextEncoding().getzOSFromAsmLiteralEncodingConverter()->convert(
260 Source: SL->getString(), Result&: ConvertedAsm);
261 assert(!EC && "This conversion should always succeed");
262 QualType StrTy = Context.getStringLiteralArrayType(EltTy: Context.CharTy,
263 Length: ConvertedAsm.size());
264 return StringLiteral::Create(Ctx: Context, Str: ConvertedAsm,
265 Kind: StringLiteralKind::Ordinary,
266 /*Pascal=*/false, Ty: StrTy, Locs: SL->getBeginLoc());
267 }
268 return SL;
269 }
270 if (DiagnoseUnexpandedParameterPack(E: Expr))
271 return ExprError();
272 if (Expr->getDependence() != ExprDependence::None)
273 return Expr;
274 APValue V;
275 if (!EvaluateAsString(Message: Expr, Result&: V, Ctx&: getASTContext(), EvalContext: StringEvaluationContext::Asm,
276 /*ErrorOnInvalid=*/ErrorOnInvalidMessage: true))
277 return ExprError();
278
279 if (ForAsmLabel && V.getArrayInitializedElts() == 0) {
280 Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_asm_operand_empty_string);
281 }
282
283 // The evaluated string is in the literal encoding (-fexec-charset).
284 // Convert it back to UTF-8.
285 if (llvm::TextEncodingConverter *FromLiteral =
286 PP.getTextEncoding().getFromLiteralEncodingConverter()) {
287 std::string Raw = V.getCharArrayAsString();
288 SmallString<16> Converted;
289 if (std::error_code EC = FromLiteral->convert(Source: Raw, Result&: Converted)) {
290 Diag(Loc: Expr->getBeginLoc(), DiagID: diag::err_exec_charset_conversion_failed)
291 << EC.message() << /*from literal encoding to UTF-8*/ 2;
292 return ExprError();
293 }
294 llvm::APSInt Proto(Context.getTypeSize(T: Context.CharTy),
295 Context.CharTy->isUnsignedIntegerType());
296 V = APValue(APValue::UninitArray{}, Converted.size(), Converted.size());
297 for (unsigned I = 0; I < Converted.size(); ++I) {
298 Proto = static_cast<unsigned char>(Converted[I]);
299 V.getArrayInitializedElt(I) = APValue(Proto);
300 }
301 }
302
303 return ConstantExpr::Create(Context: getASTContext(), E: Expr, Result: V);
304}
305
306StmtResult Sema::ActOnGCCAsmStmt(SourceLocation AsmLoc, bool IsSimple,
307 bool IsVolatile, unsigned NumOutputs,
308 unsigned NumInputs, IdentifierInfo **Names,
309 MultiExprArg constraints, MultiExprArg Exprs,
310 Expr *asmString, MultiExprArg clobbers,
311 unsigned NumLabels,
312 SourceLocation RParenLoc) {
313 unsigned NumClobbers = clobbers.size();
314
315 SmallVector<TargetInfo::ConstraintInfo, 4> OutputConstraintInfos;
316
317 FunctionDecl *FD = dyn_cast<FunctionDecl>(Val: getCurLexicalContext());
318 llvm::StringMap<bool> FeatureMap;
319 Context.getFunctionFeatureMap(FeatureMap, FD);
320
321 auto CreateGCCAsmStmt = [&] {
322 return new (Context)
323 GCCAsmStmt(Context, AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs,
324 Names, constraints.data(), Exprs.data(), asmString,
325 NumClobbers, clobbers.data(), NumLabels, RParenLoc);
326 };
327
328 if (asmString->getDependence() != ExprDependence::None ||
329 llvm::any_of(
330 Range&: constraints,
331 P: [](Expr *E) { return E->getDependence() != ExprDependence::None; }) ||
332 llvm::any_of(Range&: clobbers, P: [](Expr *E) {
333 return E->getDependence() != ExprDependence::None;
334 }))
335 return CreateGCCAsmStmt();
336
337 for (unsigned i = 0; i != NumOutputs; i++) {
338 Expr *Constraint = constraints[i];
339 StringRef OutputName;
340 if (Names[i])
341 OutputName = Names[i]->getName();
342
343 std::string ConstraintStr =
344 GCCAsmStmt::ExtractStringFromGCCAsmStmtComponent(E: Constraint);
345
346 if (ConstraintStr.find(c: '\0') != std::string::npos) {
347 Diag(Loc: Constraint->getBeginLoc(), DiagID: diag::err_asm_constraint_embedded_null)
348 << /*output*/ 0;
349 return CreateGCCAsmStmt();
350 }
351
352 TargetInfo::ConstraintInfo Info(ConstraintStr, OutputName);
353 if (!Context.getTargetInfo().validateOutputConstraint(Info) &&
354 !(LangOpts.HIPStdPar && LangOpts.CUDAIsDevice)) {
355 targetDiag(Loc: Constraint->getBeginLoc(),
356 DiagID: diag::err_asm_invalid_output_constraint)
357 << Info.getConstraintStr();
358 return CreateGCCAsmStmt();
359 }
360
361 ExprResult ER = CheckPlaceholderExpr(E: Exprs[i]);
362 if (ER.isInvalid())
363 return StmtError();
364 Exprs[i] = ER.get();
365
366 // Check that the output exprs are valid lvalues.
367 Expr *OutputExpr = Exprs[i];
368
369 // Referring to parameters is not allowed in naked functions.
370 if (CheckNakedParmReference(E: OutputExpr, S&: *this))
371 return StmtError();
372
373 // Check that the output expression is compatible with memory constraint.
374 if (Info.allowsMemory() &&
375 checkExprMemoryConstraintCompat(S&: *this, E: OutputExpr, Info, is_input_expr: false))
376 return StmtError();
377
378 // Disallow bit-precise integer types, since the backends tend to have
379 // difficulties with abnormal sizes.
380 if (OutputExpr->getType()->isBitIntType())
381 return StmtError(
382 Diag(Loc: OutputExpr->getBeginLoc(), DiagID: diag::err_asm_invalid_type)
383 << OutputExpr->getType() << 0 /*Input*/
384 << OutputExpr->getSourceRange());
385
386 OutputConstraintInfos.push_back(Elt: Info);
387
388 // If this is dependent, just continue.
389 if (OutputExpr->isTypeDependent())
390 continue;
391
392 Expr::isModifiableLvalueResult IsLV =
393 OutputExpr->isModifiableLvalue(Ctx&: Context, /*Loc=*/nullptr);
394 switch (IsLV) {
395 case Expr::MLV_Valid:
396 // Cool, this is an lvalue.
397 break;
398 case Expr::MLV_ArrayType:
399 // This is OK too.
400 break;
401 case Expr::MLV_LValueCast: {
402 const Expr *LVal = OutputExpr->IgnoreParenNoopCasts(Ctx: Context);
403 emitAndFixInvalidAsmCastLValue(LVal, BadArgument: OutputExpr, S&: *this);
404 // Accept, even if we emitted an error diagnostic.
405 break;
406 }
407 case Expr::MLV_IncompleteType:
408 case Expr::MLV_IncompleteVoidType:
409 if (RequireCompleteType(Loc: OutputExpr->getBeginLoc(), T: Exprs[i]->getType(),
410 DiagID: diag::err_dereference_incomplete_type))
411 return StmtError();
412 [[fallthrough]];
413 default:
414 return StmtError(Diag(Loc: OutputExpr->getBeginLoc(),
415 DiagID: diag::err_asm_invalid_lvalue_in_output)
416 << OutputExpr->getSourceRange());
417 }
418
419 unsigned Size = Context.getTypeSize(T: OutputExpr->getType());
420 if (!Context.getTargetInfo().validateOutputSize(
421 FeatureMap,
422 GCCAsmStmt::ExtractStringFromGCCAsmStmtComponent(E: Constraint),
423 Size)) {
424 targetDiag(Loc: OutputExpr->getBeginLoc(), DiagID: diag::err_asm_invalid_output_size)
425 << Info.getConstraintStr();
426 return CreateGCCAsmStmt();
427 }
428 }
429
430 SmallVector<TargetInfo::ConstraintInfo, 4> InputConstraintInfos;
431
432 for (unsigned i = NumOutputs, e = NumOutputs + NumInputs; i != e; i++) {
433 Expr *Constraint = constraints[i];
434
435 StringRef InputName;
436 if (Names[i])
437 InputName = Names[i]->getName();
438
439 std::string ConstraintStr =
440 GCCAsmStmt::ExtractStringFromGCCAsmStmtComponent(E: Constraint);
441
442 if (ConstraintStr.find(c: '\0') != std::string::npos) {
443 Diag(Loc: Constraint->getBeginLoc(), DiagID: diag::err_asm_constraint_embedded_null)
444 << /*input*/ 1;
445 return CreateGCCAsmStmt();
446 }
447
448 TargetInfo::ConstraintInfo Info(ConstraintStr, InputName);
449 if (!Context.getTargetInfo().validateInputConstraint(OutputConstraints: OutputConstraintInfos,
450 info&: Info)) {
451 targetDiag(Loc: Constraint->getBeginLoc(),
452 DiagID: diag::err_asm_invalid_input_constraint)
453 << Info.getConstraintStr();
454 return CreateGCCAsmStmt();
455 }
456
457 ExprResult ER = CheckPlaceholderExpr(E: Exprs[i]);
458 if (ER.isInvalid())
459 return StmtError();
460 Exprs[i] = ER.get();
461
462 Expr *InputExpr = Exprs[i];
463
464 if (InputExpr->getType()->isMemberPointerType())
465 return StmtError(Diag(Loc: InputExpr->getBeginLoc(),
466 DiagID: diag::err_asm_pmf_through_constraint_not_permitted)
467 << InputExpr->getSourceRange());
468
469 // Referring to parameters is not allowed in naked functions.
470 if (CheckNakedParmReference(E: InputExpr, S&: *this))
471 return StmtError();
472
473 // Check that the input expression is compatible with memory constraint.
474 if (Info.allowsMemory() &&
475 checkExprMemoryConstraintCompat(S&: *this, E: InputExpr, Info, is_input_expr: true))
476 return StmtError();
477
478 // Only allow void types for memory constraints.
479 if (Info.allowsMemory() && !Info.allowsRegister()) {
480 if (CheckAsmLValue(E: InputExpr, S&: *this))
481 return StmtError(Diag(Loc: InputExpr->getBeginLoc(),
482 DiagID: diag::err_asm_invalid_lvalue_in_input)
483 << Info.getConstraintStr()
484 << InputExpr->getSourceRange());
485 } else {
486 ExprResult Result = DefaultFunctionArrayLvalueConversion(E: Exprs[i]);
487 if (Result.isInvalid())
488 return StmtError();
489
490 InputExpr = Exprs[i] = Result.get();
491
492 if (!Info.allowsRegister() && !Info.allowsMemory())
493 InputExpr = Exprs[i] = BPF().checkAsmImmediateOperand(E: InputExpr);
494
495 if (Info.requiresImmediateConstant() && !Info.allowsRegister()) {
496 if (!InputExpr->isValueDependent()) {
497 Expr::EvalResult EVResult;
498 if (InputExpr->EvaluateAsRValue(Result&: EVResult, Ctx: Context, InConstantContext: true)) {
499 // For compatibility with GCC, we also allow pointers that would be
500 // integral constant expressions if they were cast to int.
501 llvm::APSInt IntResult;
502 if (EVResult.Val.toIntegralConstant(Result&: IntResult, SrcTy: InputExpr->getType(),
503 Ctx: Context))
504 if (!Info.isValidAsmImmediate(Value: IntResult))
505 return StmtError(
506 Diag(Loc: InputExpr->getBeginLoc(),
507 DiagID: diag::err_invalid_asm_value_for_constraint)
508 << toString(I: IntResult, Radix: 10) << Info.getConstraintStr()
509 << InputExpr->getSourceRange());
510 }
511 }
512 }
513 }
514
515 if (Info.allowsRegister()) {
516 if (InputExpr->getType()->isVoidType()) {
517 return StmtError(
518 Diag(Loc: InputExpr->getBeginLoc(), DiagID: diag::err_asm_invalid_type_in_input)
519 << InputExpr->getType() << Info.getConstraintStr()
520 << InputExpr->getSourceRange());
521 }
522 }
523
524 if (InputExpr->getType()->isBitIntType())
525 return StmtError(
526 Diag(Loc: InputExpr->getBeginLoc(), DiagID: diag::err_asm_invalid_type)
527 << InputExpr->getType() << 1 /*Output*/
528 << InputExpr->getSourceRange());
529
530 InputConstraintInfos.push_back(Elt: Info);
531
532 const Type *Ty = Exprs[i]->getType().getTypePtr();
533 if (Ty->isDependentType())
534 continue;
535
536 if (!Ty->isVoidType() || !Info.allowsMemory())
537 if (RequireCompleteType(Loc: InputExpr->getBeginLoc(), T: Exprs[i]->getType(),
538 DiagID: diag::err_dereference_incomplete_type))
539 return StmtError();
540
541 unsigned Size = Context.getTypeSize(T: Ty);
542 if (!Context.getTargetInfo().validateInputSize(FeatureMap, ConstraintStr,
543 Size))
544 return targetDiag(Loc: InputExpr->getBeginLoc(),
545 DiagID: diag::err_asm_invalid_input_size)
546 << Info.getConstraintStr();
547 }
548
549 std::optional<SourceLocation> UnwindClobberLoc;
550
551 // Check that the clobbers are valid.
552 for (unsigned i = 0; i != NumClobbers; i++) {
553 Expr *ClobberExpr = clobbers[i];
554
555 std::string Clobber =
556 GCCAsmStmt::ExtractStringFromGCCAsmStmtComponent(E: ClobberExpr);
557
558 if (Clobber.find(c: '\0') != std::string::npos) {
559 Diag(Loc: ClobberExpr->getBeginLoc(), DiagID: diag::err_asm_constraint_embedded_null)
560 << /*clobber*/ 2;
561 return CreateGCCAsmStmt();
562 }
563
564 if (!Context.getTargetInfo().isValidClobber(Name: Clobber)) {
565 targetDiag(Loc: ClobberExpr->getBeginLoc(),
566 DiagID: diag::err_asm_unknown_register_name)
567 << Clobber;
568 return new (Context) GCCAsmStmt(
569 Context, AsmLoc, IsSimple, IsVolatile, NumOutputs, NumInputs, Names,
570 constraints.data(), Exprs.data(), asmString, NumClobbers,
571 clobbers.data(), NumLabels, RParenLoc);
572 }
573
574 if (Clobber == "unwind") {
575 UnwindClobberLoc = ClobberExpr->getBeginLoc();
576 }
577 }
578
579 // Using unwind clobber and asm-goto together is not supported right now.
580 if (UnwindClobberLoc && NumLabels > 0) {
581 targetDiag(Loc: *UnwindClobberLoc, DiagID: diag::err_asm_unwind_and_goto);
582 return CreateGCCAsmStmt();
583 }
584
585 GCCAsmStmt *NS = CreateGCCAsmStmt();
586 // Validate the asm string, ensuring it makes sense given the operands we
587 // have.
588
589 auto GetLocation = [this](const Expr *Str, unsigned Offset) {
590 if (auto *SL = dyn_cast<StringLiteral>(Val: Str))
591 return getLocationOfStringLiteralByte(SL, ByteNo: Offset);
592 return Str->getBeginLoc();
593 };
594
595 SmallVector<GCCAsmStmt::AsmStringPiece, 8> Pieces;
596 unsigned DiagOffs;
597 if (unsigned DiagID = NS->AnalyzeAsmString(Pieces, C: Context, DiagOffs)) {
598 targetDiag(Loc: GetLocation(asmString, DiagOffs), DiagID)
599 << asmString->getSourceRange();
600 return NS;
601 }
602
603 // Validate constraints and modifiers.
604 for (unsigned i = 0, e = Pieces.size(); i != e; ++i) {
605 GCCAsmStmt::AsmStringPiece &Piece = Pieces[i];
606 if (!Piece.isOperand()) continue;
607
608 // Look for the correct constraint index.
609 unsigned ConstraintIdx = Piece.getOperandNo();
610 unsigned NumOperands = NS->getNumOutputs() + NS->getNumInputs();
611 // Labels are the last in the Exprs list.
612 if (NS->isAsmGoto() && ConstraintIdx >= NumOperands)
613 continue;
614 // Look for the (ConstraintIdx - NumOperands + 1)th constraint with
615 // modifier '+'.
616 if (ConstraintIdx >= NumOperands) {
617 unsigned I = 0, E = NS->getNumOutputs();
618
619 for (unsigned Cnt = ConstraintIdx - NumOperands; I != E; ++I)
620 if (OutputConstraintInfos[I].isReadWrite() && Cnt-- == 0) {
621 ConstraintIdx = I;
622 break;
623 }
624
625 assert(I != E && "Invalid operand number should have been caught in "
626 " AnalyzeAsmString");
627 }
628
629 // Now that we have the right indexes go ahead and check.
630 Expr *Constraint = constraints[ConstraintIdx];
631 const Type *Ty = Exprs[ConstraintIdx]->getType().getTypePtr();
632 if (Ty->isDependentType() || Ty->isIncompleteType())
633 continue;
634
635 unsigned Size = Context.getTypeSize(T: Ty);
636 std::string SuggestedModifier;
637 if (!Context.getTargetInfo().validateConstraintModifier(
638 GCCAsmStmt::ExtractStringFromGCCAsmStmtComponent(E: Constraint),
639 Piece.getModifier(), Size, SuggestedModifier)) {
640 targetDiag(Loc: Exprs[ConstraintIdx]->getBeginLoc(),
641 DiagID: diag::warn_asm_mismatched_size_modifier);
642
643 if (!SuggestedModifier.empty()) {
644 auto B = targetDiag(Loc: Piece.getRange().getBegin(),
645 DiagID: diag::note_asm_missing_constraint_modifier)
646 << SuggestedModifier;
647 if (isa<StringLiteral>(Val: Constraint)) {
648 SuggestedModifier = "%" + SuggestedModifier + Piece.getString();
649 B << FixItHint::CreateReplacement(RemoveRange: Piece.getRange(),
650 Code: SuggestedModifier);
651 }
652 }
653 }
654 }
655
656 // Validate tied input operands for type mismatches.
657 unsigned NumAlternatives = ~0U;
658 for (unsigned i = 0, e = OutputConstraintInfos.size(); i != e; ++i) {
659 TargetInfo::ConstraintInfo &Info = OutputConstraintInfos[i];
660 StringRef ConstraintStr = Info.getConstraintStr();
661 unsigned AltCount = ConstraintStr.count(C: ',') + 1;
662 if (NumAlternatives == ~0U) {
663 NumAlternatives = AltCount;
664 } else if (NumAlternatives != AltCount) {
665 targetDiag(Loc: NS->getOutputExpr(i)->getBeginLoc(),
666 DiagID: diag::err_asm_unexpected_constraint_alternatives)
667 << NumAlternatives << AltCount;
668 return NS;
669 }
670 }
671 SmallVector<size_t, 4> InputMatchedToOutput(OutputConstraintInfos.size(),
672 ~0U);
673 for (unsigned i = 0, e = InputConstraintInfos.size(); i != e; ++i) {
674 TargetInfo::ConstraintInfo &Info = InputConstraintInfos[i];
675 StringRef ConstraintStr = Info.getConstraintStr();
676 unsigned AltCount = ConstraintStr.count(C: ',') + 1;
677 if (NumAlternatives == ~0U) {
678 NumAlternatives = AltCount;
679 } else if (NumAlternatives != AltCount) {
680 targetDiag(Loc: NS->getInputExpr(i)->getBeginLoc(),
681 DiagID: diag::err_asm_unexpected_constraint_alternatives)
682 << NumAlternatives << AltCount;
683 return NS;
684 }
685
686 // If this is a tied constraint, verify that the output and input have
687 // either exactly the same type, or that they are int/ptr operands with the
688 // same size (int/long, int*/long, are ok etc).
689 if (!Info.hasTiedOperand()) continue;
690
691 unsigned TiedTo = Info.getTiedOperand();
692 unsigned InputOpNo = i+NumOutputs;
693 Expr *OutputExpr = Exprs[TiedTo];
694 Expr *InputExpr = Exprs[InputOpNo];
695
696 // Make sure no more than one input constraint matches each output.
697 assert(TiedTo < InputMatchedToOutput.size() && "TiedTo value out of range");
698 if (InputMatchedToOutput[TiedTo] != ~0U) {
699 targetDiag(Loc: NS->getInputExpr(i)->getBeginLoc(),
700 DiagID: diag::err_asm_input_duplicate_match)
701 << TiedTo;
702 targetDiag(Loc: NS->getInputExpr(i: InputMatchedToOutput[TiedTo])->getBeginLoc(),
703 DiagID: diag::note_asm_input_duplicate_first)
704 << TiedTo;
705 return NS;
706 }
707 InputMatchedToOutput[TiedTo] = i;
708
709 if (OutputExpr->isTypeDependent() || InputExpr->isTypeDependent())
710 continue;
711
712 QualType InTy = InputExpr->getType();
713 QualType OutTy = OutputExpr->getType();
714 if (Context.hasSameType(T1: InTy, T2: OutTy))
715 continue; // All types can be tied to themselves.
716
717 // Decide if the input and output are in the same domain (integer/ptr or
718 // floating point.
719 enum AsmDomain {
720 AD_Int, AD_FP, AD_Other
721 } InputDomain, OutputDomain;
722
723 if (InTy->isIntegerType() || InTy->isPointerType())
724 InputDomain = AD_Int;
725 else if (InTy->isRealFloatingType())
726 InputDomain = AD_FP;
727 else
728 InputDomain = AD_Other;
729
730 if (OutTy->isIntegerType() || OutTy->isPointerType())
731 OutputDomain = AD_Int;
732 else if (OutTy->isRealFloatingType())
733 OutputDomain = AD_FP;
734 else
735 OutputDomain = AD_Other;
736
737 // They are ok if they are the same size and in the same domain. This
738 // allows tying things like:
739 // void* to int*
740 // void* to int if they are the same size.
741 // double to long double if they are the same size.
742 //
743 uint64_t OutSize = Context.getTypeSize(T: OutTy);
744 uint64_t InSize = Context.getTypeSize(T: InTy);
745 if (OutSize == InSize && InputDomain == OutputDomain &&
746 InputDomain != AD_Other)
747 continue;
748
749 // If the smaller input/output operand is not mentioned in the asm string,
750 // then we can promote the smaller one to a larger input and the asm string
751 // won't notice.
752 bool SmallerValueMentioned = false;
753
754 // If this is a reference to the input and if the input was the smaller
755 // one, then we have to reject this asm.
756 if (isOperandMentioned(OpNo: InputOpNo, AsmStrPieces: Pieces)) {
757 // This is a use in the asm string of the smaller operand. Since we
758 // codegen this by promoting to a wider value, the asm will get printed
759 // "wrong".
760 SmallerValueMentioned |= InSize < OutSize;
761 }
762 if (isOperandMentioned(OpNo: TiedTo, AsmStrPieces: Pieces)) {
763 // If this is a reference to the output, and if the output is the larger
764 // value, then it's ok because we'll promote the input to the larger type.
765 SmallerValueMentioned |= OutSize < InSize;
766 }
767
768 // If the input is an integer register while the output is floating point,
769 // or vice-versa, there is no way they can work together.
770 bool FPTiedToInt = (InputDomain == AD_FP) ^ (OutputDomain == AD_FP);
771
772 // If the smaller value wasn't mentioned in the asm string, and if the
773 // output was a register, just extend the shorter one to the size of the
774 // larger one.
775 if (!SmallerValueMentioned && !FPTiedToInt && InputDomain != AD_Other &&
776 OutputConstraintInfos[TiedTo].allowsRegister()) {
777
778 // FIXME: GCC supports some non-scalar register outputs. Currently
779 // codegen crashes when the size cannot be represented by an integer type
780 // that fits in a general-purpose register.
781 bool FitsInGeneralPurposeRegister =
782 OutSize <= Context.getTargetInfo().getRegisterWidth() &&
783 !Context.getIntTypeForBitwidth(DestWidth: OutSize, /*Signed*/ false).isNull();
784 if (OutputDomain == AD_Other && !FitsInGeneralPurposeRegister) {
785 targetDiag(Loc: OutputExpr->getExprLoc(), DiagID: diag::err_store_value_to_reg);
786 return NS;
787 }
788
789 continue;
790 }
791
792 // Either both of the operands were mentioned or the smaller one was
793 // mentioned. One more special case that we'll allow: if the tied input is
794 // integer, unmentioned, and is a constant, then we'll allow truncating it
795 // down to the size of the destination.
796 if (InputDomain == AD_Int && OutputDomain == AD_Int &&
797 !isOperandMentioned(OpNo: InputOpNo, AsmStrPieces: Pieces) &&
798 InputExpr->isEvaluatable(Ctx: Context)) {
799 CastKind castKind =
800 (OutTy->isBooleanType() ? CK_IntegralToBoolean : CK_IntegralCast);
801 InputExpr = ImpCastExprToType(E: InputExpr, Type: OutTy, CK: castKind).get();
802 Exprs[InputOpNo] = InputExpr;
803 NS->setInputExpr(i, E: InputExpr);
804 continue;
805 }
806
807 targetDiag(Loc: InputExpr->getBeginLoc(), DiagID: diag::err_asm_tying_incompatible_types)
808 << InTy << OutTy << OutputExpr->getSourceRange()
809 << InputExpr->getSourceRange();
810 return NS;
811 }
812
813 // Check for conflicts between clobber list and input or output lists
814 SourceLocation ConstraintLoc = getClobberConflictLocation(
815 Exprs, Constraints: constraints.data(), Clobbers: clobbers.data(), NumClobbers, NumLabels,
816 Target: Context.getTargetInfo(), Cont&: Context);
817 if (ConstraintLoc.isValid())
818 targetDiag(Loc: ConstraintLoc, DiagID: diag::error_inoutput_conflict_with_clobber);
819
820 // Check for duplicate asm operand name between input, output and label lists.
821 typedef std::pair<StringRef , Expr *> NamedOperand;
822 SmallVector<NamedOperand, 4> NamedOperandList;
823 for (unsigned i = 0, e = NumOutputs + NumInputs + NumLabels; i != e; ++i)
824 if (Names[i])
825 NamedOperandList.emplace_back(
826 Args: std::make_pair(x: Names[i]->getName(), y&: Exprs[i]));
827 // Sort NamedOperandList.
828 llvm::stable_sort(Range&: NamedOperandList, C: llvm::less_first());
829 // Find adjacent duplicate operand.
830 SmallVector<NamedOperand, 4>::iterator Found =
831 std::adjacent_find(first: begin(cont&: NamedOperandList), last: end(cont&: NamedOperandList),
832 binary_pred: [](const NamedOperand &LHS, const NamedOperand &RHS) {
833 return LHS.first == RHS.first;
834 });
835 if (Found != NamedOperandList.end()) {
836 Diag(Loc: (Found + 1)->second->getBeginLoc(),
837 DiagID: diag::error_duplicate_asm_operand_name)
838 << (Found + 1)->first;
839 Diag(Loc: Found->second->getBeginLoc(), DiagID: diag::note_duplicate_asm_operand_name)
840 << Found->first;
841 return StmtError();
842 }
843 if (NS->isAsmGoto())
844 setFunctionHasBranchIntoScope();
845
846 CleanupVarDeclMarking();
847 DiscardCleanupsInEvaluationContext();
848 return NS;
849}
850
851void Sema::FillInlineAsmIdentifierInfo(Expr *Res,
852 llvm::InlineAsmIdentifierInfo &Info) {
853 QualType T = Res->getType();
854 Expr::EvalResult Eval;
855 if (T->isFunctionType() || T->isDependentType())
856 return Info.setLabel(Res);
857 if (Res->isPRValue()) {
858 bool IsEnum = isa<clang::EnumType>(Val: T);
859 if (DeclRefExpr *DRE = dyn_cast<clang::DeclRefExpr>(Val: Res))
860 if (DRE->getDecl()->getKind() == Decl::EnumConstant)
861 IsEnum = true;
862 if (IsEnum && Res->EvaluateAsRValue(Result&: Eval, Ctx: Context))
863 return Info.setEnum(Eval.Val.getInt().getSExtValue());
864
865 return Info.setLabel(Res);
866 }
867 unsigned Size = Context.getTypeSizeInChars(T).getQuantity();
868 unsigned Type = Size;
869 if (const auto *ATy = Context.getAsArrayType(T))
870 Type = Context.getTypeSizeInChars(T: ATy->getElementType()).getQuantity();
871 bool IsGlobalLV = false;
872 if (Res->EvaluateAsLValue(Result&: Eval, Ctx: Context))
873 IsGlobalLV = Eval.isGlobalLValue();
874 Info.setVar(decl: Res, isGlobalLV: IsGlobalLV, size: Size, type: Type);
875}
876
877ExprResult Sema::LookupInlineAsmIdentifier(CXXScopeSpec &SS,
878 SourceLocation TemplateKWLoc,
879 UnqualifiedId &Id,
880 bool IsUnevaluatedContext) {
881
882 if (IsUnevaluatedContext)
883 PushExpressionEvaluationContext(
884 NewContext: ExpressionEvaluationContext::UnevaluatedAbstract,
885 ReuseLambdaContextDecl);
886
887 ExprResult Result = ActOnIdExpression(S: getCurScope(), SS, TemplateKWLoc, Id,
888 /*IsCall=*/false,
889 /*is & operand*/ IsAddressOfOperand: false,
890 /*CorrectionCandidateCallback=*/CCC: nullptr,
891 /*IsInlineAsmIdentifier=*/true);
892
893 if (IsUnevaluatedContext)
894 PopExpressionEvaluationContext();
895
896 if (!Result.isUsable()) return Result;
897
898 Result = CheckPlaceholderExpr(E: Result.get());
899 if (!Result.isUsable()) return Result;
900
901 // Referring to parameters is not allowed in naked functions.
902 if (CheckNakedParmReference(E: Result.get(), S&: *this))
903 return ExprError();
904
905 QualType T = Result.get()->getType();
906
907 if (T->isDependentType()) {
908 return Result;
909 }
910
911 // Any sort of function type is fine.
912 if (T->isFunctionType()) {
913 return Result;
914 }
915
916 // Otherwise, it needs to be a complete type.
917 if (RequireCompleteExprType(E: Result.get(), DiagID: diag::err_asm_incomplete_type)) {
918 return ExprError();
919 }
920
921 return Result;
922}
923
924bool Sema::LookupInlineAsmField(StringRef Base, StringRef Member,
925 unsigned &Offset, SourceLocation AsmLoc) {
926 Offset = 0;
927 SmallVector<StringRef, 2> Members;
928 Member.split(A&: Members, Separator: ".");
929
930 NamedDecl *FoundDecl = nullptr;
931
932 // MS InlineAsm uses 'this' as a base
933 if (getLangOpts().CPlusPlus && Base == "this") {
934 if (const Type *PT = getCurrentThisType().getTypePtrOrNull())
935 FoundDecl = PT->getPointeeType()->getAsTagDecl();
936 } else {
937 LookupResult BaseResult(*this, &Context.Idents.get(Name: Base), SourceLocation(),
938 LookupOrdinaryName);
939 if (LookupName(R&: BaseResult, S: getCurScope()) && BaseResult.isSingleResult())
940 FoundDecl = BaseResult.getFoundDecl();
941 }
942
943 if (!FoundDecl)
944 return true;
945
946 for (StringRef NextMember : Members) {
947 const RecordType *RT = nullptr;
948 if (VarDecl *VD = dyn_cast<VarDecl>(Val: FoundDecl))
949 RT = VD->getType()->getAsCanonical<RecordType>();
950 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Val: FoundDecl)) {
951 MarkAnyDeclReferenced(Loc: TD->getLocation(), D: TD, /*OdrUse=*/MightBeOdrUse: false);
952 // MS InlineAsm often uses struct pointer aliases as a base
953 QualType QT = TD->getUnderlyingType();
954 if (const auto *PT = QT->getAs<PointerType>())
955 QT = PT->getPointeeType();
956 RT = QT->getAsCanonical<RecordType>();
957 } else if (TypeDecl *TD = dyn_cast<TypeDecl>(Val: FoundDecl))
958 RT = QualType(Context.getCanonicalTypeDeclType(TD))
959 ->getAsCanonical<RecordType>();
960 else if (FieldDecl *TD = dyn_cast<FieldDecl>(Val: FoundDecl))
961 RT = TD->getType()->getAsCanonical<RecordType>();
962 if (!RT)
963 return true;
964
965 if (RequireCompleteType(Loc: AsmLoc, T: QualType(RT, 0),
966 DiagID: diag::err_asm_incomplete_type))
967 return true;
968
969 LookupResult FieldResult(*this, &Context.Idents.get(Name: NextMember),
970 SourceLocation(), LookupMemberName);
971
972 RecordDecl *RD = RT->getDecl()->getDefinitionOrSelf();
973 if (!LookupQualifiedName(R&: FieldResult, LookupCtx: RD))
974 return true;
975
976 if (!FieldResult.isSingleResult())
977 return true;
978 FoundDecl = FieldResult.getFoundDecl();
979
980 // FIXME: Handle IndirectFieldDecl?
981 FieldDecl *FD = dyn_cast<FieldDecl>(Val: FoundDecl);
982 if (!FD)
983 return true;
984
985 const ASTRecordLayout &RL = Context.getASTRecordLayout(D: RD);
986 unsigned i = FD->getFieldIndex();
987 CharUnits Result = Context.toCharUnitsFromBits(BitSize: RL.getFieldOffset(FieldNo: i));
988 Offset += (unsigned)Result.getQuantity();
989 }
990
991 return false;
992}
993
994ExprResult
995Sema::LookupInlineAsmVarDeclField(Expr *E, StringRef Member,
996 SourceLocation AsmLoc) {
997
998 QualType T = E->getType();
999 if (T->isDependentType()) {
1000 DeclarationNameInfo NameInfo;
1001 NameInfo.setLoc(AsmLoc);
1002 NameInfo.setName(&Context.Idents.get(Name: Member));
1003 return CXXDependentScopeMemberExpr::Create(
1004 Ctx: Context, Base: E, BaseType: T, /*IsArrow=*/false, OperatorLoc: AsmLoc, QualifierLoc: NestedNameSpecifierLoc(),
1005 TemplateKWLoc: SourceLocation(),
1006 /*FirstQualifierFoundInScope=*/nullptr, MemberNameInfo: NameInfo, /*TemplateArgs=*/nullptr);
1007 }
1008
1009 auto *RD = T->getAsRecordDecl();
1010 // FIXME: Diagnose this as field access into a scalar type.
1011 if (!RD)
1012 return ExprResult();
1013
1014 LookupResult FieldResult(*this, &Context.Idents.get(Name: Member), AsmLoc,
1015 LookupMemberName);
1016
1017 if (!LookupQualifiedName(R&: FieldResult, LookupCtx: RD))
1018 return ExprResult();
1019
1020 // Only normal and indirect field results will work.
1021 ValueDecl *FD = dyn_cast<FieldDecl>(Val: FieldResult.getFoundDecl());
1022 if (!FD)
1023 FD = dyn_cast<IndirectFieldDecl>(Val: FieldResult.getFoundDecl());
1024 if (!FD)
1025 return ExprResult();
1026
1027 // Make an Expr to thread through OpDecl.
1028 ExprResult Result = BuildMemberReferenceExpr(
1029 Base: E, BaseType: E->getType(), OpLoc: AsmLoc, /*IsArrow=*/false, SS: CXXScopeSpec(),
1030 TemplateKWLoc: SourceLocation(), FirstQualifierInScope: nullptr, R&: FieldResult, TemplateArgs: nullptr, S: nullptr);
1031
1032 return Result;
1033}
1034
1035StmtResult Sema::ActOnMSAsmStmt(SourceLocation AsmLoc, SourceLocation LBraceLoc,
1036 ArrayRef<Token> AsmToks,
1037 StringRef AsmString,
1038 unsigned NumOutputs, unsigned NumInputs,
1039 ArrayRef<StringRef> Constraints,
1040 ArrayRef<StringRef> Clobbers,
1041 ArrayRef<Expr*> Exprs,
1042 SourceLocation EndLoc) {
1043 bool IsSimple = (NumOutputs != 0 || NumInputs != 0);
1044 setFunctionHasBranchProtectedScope();
1045
1046 bool InvalidOperand = false;
1047 for (uint64_t I = 0; I < NumOutputs + NumInputs; ++I) {
1048 Expr *E = Exprs[I];
1049 if (E->getType()->isBitIntType()) {
1050 InvalidOperand = true;
1051 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_asm_invalid_type)
1052 << E->getType() << (I < NumOutputs)
1053 << E->getSourceRange();
1054 } else if (E->refersToBitField()) {
1055 InvalidOperand = true;
1056 FieldDecl *BitField = E->getSourceBitField();
1057 Diag(Loc: E->getBeginLoc(), DiagID: diag::err_ms_asm_bitfield_unsupported)
1058 << E->getSourceRange();
1059 Diag(Loc: BitField->getLocation(), DiagID: diag::note_bitfield_decl);
1060 }
1061 }
1062 if (InvalidOperand)
1063 return StmtError();
1064
1065 MSAsmStmt *NS =
1066 new (Context) MSAsmStmt(Context, AsmLoc, LBraceLoc, IsSimple,
1067 /*IsVolatile*/ true, AsmToks, NumOutputs, NumInputs,
1068 Constraints, Exprs, AsmString,
1069 Clobbers, EndLoc);
1070 return NS;
1071}
1072
1073LabelDecl *Sema::GetOrCreateMSAsmLabel(StringRef ExternalLabelName,
1074 SourceLocation Location,
1075 bool AlwaysCreate) {
1076 LabelDecl* Label = LookupOrCreateLabel(II: PP.getIdentifierInfo(Name: ExternalLabelName),
1077 IdentLoc: Location);
1078
1079 if (Label->isMSAsmLabel()) {
1080 // If we have previously created this label implicitly, mark it as used.
1081 Label->markUsed(C&: Context);
1082 } else {
1083 // Otherwise, insert it, but only resolve it if we have seen the label itself.
1084 std::string InternalName;
1085 llvm::raw_string_ostream OS(InternalName);
1086 // Create an internal name for the label. The name should not be a valid
1087 // mangled name, and should be unique. We use a dot to make the name an
1088 // invalid mangled name. We use LLVM's inline asm ${:uid} escape so that a
1089 // unique label is generated each time this blob is emitted, even after
1090 // inlining or LTO.
1091 OS << "__MSASMLABEL_.${:uid}__";
1092 for (char C : ExternalLabelName) {
1093 OS << C;
1094 // We escape '$' in asm strings by replacing it with "$$"
1095 if (C == '$')
1096 OS << '$';
1097 }
1098 Label->setMSAsmLabel(OS.str());
1099 }
1100 if (AlwaysCreate) {
1101 // The label might have been created implicitly from a previously encountered
1102 // goto statement. So, for both newly created and looked up labels, we mark
1103 // them as resolved.
1104 Label->setMSAsmLabelResolved();
1105 }
1106 // Adjust their location for being able to generate accurate diagnostics.
1107 Label->setLocation(Location);
1108
1109 return Label;
1110}
1111