1 //===--- SemaStmtAttr.cpp - Statement Attribute Handling ------------------===// 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 stmt-related attribute processing. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "clang/AST/ASTContext.h" 14 #include "clang/AST/EvaluatedExprVisitor.h" 15 #include "clang/Basic/SourceManager.h" 16 #include "clang/Basic/TargetInfo.h" 17 #include "clang/Sema/DelayedDiagnostic.h" 18 #include "clang/Sema/Lookup.h" 19 #include "clang/Sema/ScopeInfo.h" 20 #include "clang/Sema/SemaInternal.h" 21 #include "llvm/ADT/StringExtras.h" 22 23 using namespace clang; 24 using namespace sema; 25 26 static Attr *handleFallThroughAttr(Sema &S, Stmt *St, const ParsedAttr &A, 27 SourceRange Range) { 28 FallThroughAttr Attr(S.Context, A); 29 if (isa<SwitchCase>(St)) { 30 S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_wrong_target) 31 << A << St->getBeginLoc(); 32 SourceLocation L = S.getLocForEndOfToken(Range.getEnd()); 33 S.Diag(L, diag::note_fallthrough_insert_semi_fixit) 34 << FixItHint::CreateInsertion(L, ";"); 35 return nullptr; 36 } 37 auto *FnScope = S.getCurFunction(); 38 if (FnScope->SwitchStack.empty()) { 39 S.Diag(A.getRange().getBegin(), diag::err_fallthrough_attr_outside_switch); 40 return nullptr; 41 } 42 43 // If this is spelled as the standard C++17 attribute, but not in C++17, warn 44 // about using it as an extension. 45 if (!S.getLangOpts().CPlusPlus17 && A.isCXX11Attribute() && 46 !A.getScopeName()) 47 S.Diag(A.getLoc(), diag::ext_cxx17_attr) << A; 48 49 FnScope->setHasFallthroughStmt(); 50 return ::new (S.Context) FallThroughAttr(S.Context, A); 51 } 52 53 static Attr *handleSuppressAttr(Sema &S, Stmt *St, const ParsedAttr &A, 54 SourceRange Range) { 55 std::vector<StringRef> DiagnosticIdentifiers; 56 for (unsigned I = 0, E = A.getNumArgs(); I != E; ++I) { 57 StringRef RuleName; 58 59 if (!S.checkStringLiteralArgumentAttr(A, I, RuleName, nullptr)) 60 return nullptr; 61 62 // FIXME: Warn if the rule name is unknown. This is tricky because only 63 // clang-tidy knows about available rules. 64 DiagnosticIdentifiers.push_back(RuleName); 65 } 66 67 return ::new (S.Context) SuppressAttr( 68 S.Context, A, DiagnosticIdentifiers.data(), DiagnosticIdentifiers.size()); 69 } 70 71 static Attr *handleLoopHintAttr(Sema &S, Stmt *St, const ParsedAttr &A, 72 SourceRange) { 73 IdentifierLoc *PragmaNameLoc = A.getArgAsIdent(0); 74 IdentifierLoc *OptionLoc = A.getArgAsIdent(1); 75 IdentifierLoc *StateLoc = A.getArgAsIdent(2); 76 Expr *ValueExpr = A.getArgAsExpr(3); 77 78 StringRef PragmaName = 79 llvm::StringSwitch<StringRef>(PragmaNameLoc->Ident->getName()) 80 .Cases("unroll", "nounroll", "unroll_and_jam", "nounroll_and_jam", 81 PragmaNameLoc->Ident->getName()) 82 .Default("clang loop"); 83 84 // This could be handled automatically by adding a Subjects definition in 85 // Attr.td, but that would make the diagnostic behavior worse in this case 86 // because the user spells this attribute as a pragma. 87 if (!isa<DoStmt, ForStmt, CXXForRangeStmt, WhileStmt>(St)) { 88 std::string Pragma = "#pragma " + std::string(PragmaName); 89 S.Diag(St->getBeginLoc(), diag::err_pragma_loop_precedes_nonloop) << Pragma; 90 return nullptr; 91 } 92 93 LoopHintAttr::OptionType Option; 94 LoopHintAttr::LoopHintState State; 95 96 auto SetHints = [&Option, &State](LoopHintAttr::OptionType O, 97 LoopHintAttr::LoopHintState S) { 98 Option = O; 99 State = S; 100 }; 101 102 if (PragmaName == "nounroll") { 103 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Disable); 104 } else if (PragmaName == "unroll") { 105 // #pragma unroll N 106 if (ValueExpr) 107 SetHints(LoopHintAttr::UnrollCount, LoopHintAttr::Numeric); 108 else 109 SetHints(LoopHintAttr::Unroll, LoopHintAttr::Enable); 110 } else if (PragmaName == "nounroll_and_jam") { 111 SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Disable); 112 } else if (PragmaName == "unroll_and_jam") { 113 // #pragma unroll_and_jam N 114 if (ValueExpr) 115 SetHints(LoopHintAttr::UnrollAndJamCount, LoopHintAttr::Numeric); 116 else 117 SetHints(LoopHintAttr::UnrollAndJam, LoopHintAttr::Enable); 118 } else { 119 // #pragma clang loop ... 120 assert(OptionLoc && OptionLoc->Ident && 121 "Attribute must have valid option info."); 122 Option = llvm::StringSwitch<LoopHintAttr::OptionType>( 123 OptionLoc->Ident->getName()) 124 .Case("vectorize", LoopHintAttr::Vectorize) 125 .Case("vectorize_width", LoopHintAttr::VectorizeWidth) 126 .Case("interleave", LoopHintAttr::Interleave) 127 .Case("vectorize_predicate", LoopHintAttr::VectorizePredicate) 128 .Case("interleave_count", LoopHintAttr::InterleaveCount) 129 .Case("unroll", LoopHintAttr::Unroll) 130 .Case("unroll_count", LoopHintAttr::UnrollCount) 131 .Case("pipeline", LoopHintAttr::PipelineDisabled) 132 .Case("pipeline_initiation_interval", 133 LoopHintAttr::PipelineInitiationInterval) 134 .Case("distribute", LoopHintAttr::Distribute) 135 .Default(LoopHintAttr::Vectorize); 136 if (Option == LoopHintAttr::VectorizeWidth) { 137 assert((ValueExpr || (StateLoc && StateLoc->Ident)) && 138 "Attribute must have a valid value expression or argument."); 139 if (ValueExpr && S.CheckLoopHintExpr(ValueExpr, St->getBeginLoc())) 140 return nullptr; 141 if (StateLoc && StateLoc->Ident && StateLoc->Ident->isStr("scalable")) 142 State = LoopHintAttr::ScalableWidth; 143 else 144 State = LoopHintAttr::FixedWidth; 145 } else if (Option == LoopHintAttr::InterleaveCount || 146 Option == LoopHintAttr::UnrollCount || 147 Option == LoopHintAttr::PipelineInitiationInterval) { 148 assert(ValueExpr && "Attribute must have a valid value expression."); 149 if (S.CheckLoopHintExpr(ValueExpr, St->getBeginLoc())) 150 return nullptr; 151 State = LoopHintAttr::Numeric; 152 } else if (Option == LoopHintAttr::Vectorize || 153 Option == LoopHintAttr::Interleave || 154 Option == LoopHintAttr::VectorizePredicate || 155 Option == LoopHintAttr::Unroll || 156 Option == LoopHintAttr::Distribute || 157 Option == LoopHintAttr::PipelineDisabled) { 158 assert(StateLoc && StateLoc->Ident && "Loop hint must have an argument"); 159 if (StateLoc->Ident->isStr("disable")) 160 State = LoopHintAttr::Disable; 161 else if (StateLoc->Ident->isStr("assume_safety")) 162 State = LoopHintAttr::AssumeSafety; 163 else if (StateLoc->Ident->isStr("full")) 164 State = LoopHintAttr::Full; 165 else if (StateLoc->Ident->isStr("enable")) 166 State = LoopHintAttr::Enable; 167 else 168 llvm_unreachable("bad loop hint argument"); 169 } else 170 llvm_unreachable("bad loop hint"); 171 } 172 173 return LoopHintAttr::CreateImplicit(S.Context, Option, State, ValueExpr, A); 174 } 175 176 namespace { 177 class CallExprFinder : public ConstEvaluatedExprVisitor<CallExprFinder> { 178 bool FoundCallExpr = false; 179 180 public: 181 typedef ConstEvaluatedExprVisitor<CallExprFinder> Inherited; 182 183 CallExprFinder(Sema &S, const Stmt *St) : Inherited(S.Context) { Visit(St); } 184 185 bool foundCallExpr() { return FoundCallExpr; } 186 187 void VisitCallExpr(const CallExpr *E) { FoundCallExpr = true; } 188 void VisitAsmStmt(const AsmStmt *S) { FoundCallExpr = true; } 189 190 void Visit(const Stmt *St) { 191 if (!St) 192 return; 193 ConstEvaluatedExprVisitor<CallExprFinder>::Visit(St); 194 } 195 }; 196 } // namespace 197 198 static Attr *handleNoMergeAttr(Sema &S, Stmt *St, const ParsedAttr &A, 199 SourceRange Range) { 200 NoMergeAttr NMA(S.Context, A); 201 CallExprFinder CEF(S, St); 202 203 if (!CEF.foundCallExpr()) { 204 S.Diag(St->getBeginLoc(), diag::warn_nomerge_attribute_ignored_in_stmt) 205 << NMA.getSpelling(); 206 return nullptr; 207 } 208 209 return ::new (S.Context) NoMergeAttr(S.Context, A); 210 } 211 212 static Attr *handleMustTailAttr(Sema &S, Stmt *St, const ParsedAttr &A, 213 SourceRange Range) { 214 // Validation is in Sema::ActOnAttributedStmt(). 215 return ::new (S.Context) MustTailAttr(S.Context, A); 216 } 217 218 static Attr *handleLikely(Sema &S, Stmt *St, const ParsedAttr &A, 219 SourceRange Range) { 220 221 if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && !A.getScopeName()) 222 S.Diag(A.getLoc(), diag::ext_cxx20_attr) << A << Range; 223 224 return ::new (S.Context) LikelyAttr(S.Context, A); 225 } 226 227 static Attr *handleUnlikely(Sema &S, Stmt *St, const ParsedAttr &A, 228 SourceRange Range) { 229 230 if (!S.getLangOpts().CPlusPlus20 && A.isCXX11Attribute() && !A.getScopeName()) 231 S.Diag(A.getLoc(), diag::ext_cxx20_attr) << A << Range; 232 233 return ::new (S.Context) UnlikelyAttr(S.Context, A); 234 } 235 236 #define WANT_STMT_MERGE_LOGIC 237 #include "clang/Sema/AttrParsedAttrImpl.inc" 238 #undef WANT_STMT_MERGE_LOGIC 239 240 static void 241 CheckForIncompatibleAttributes(Sema &S, 242 const SmallVectorImpl<const Attr *> &Attrs) { 243 // The vast majority of attributed statements will only have one attribute 244 // on them, so skip all of the checking in the common case. 245 if (Attrs.size() < 2) 246 return; 247 248 // First, check for the easy cases that are table-generated for us. 249 if (!DiagnoseMutualExclusions(S, Attrs)) 250 return; 251 252 // There are 6 categories of loop hints attributes: vectorize, interleave, 253 // unroll, unroll_and_jam, pipeline and distribute. Except for distribute they 254 // come in two variants: a state form and a numeric form. The state form 255 // selectively defaults/enables/disables the transformation for the loop 256 // (for unroll, default indicates full unrolling rather than enabling the 257 // transformation). The numeric form form provides an integer hint (for 258 // example, unroll count) to the transformer. The following array accumulates 259 // the hints encountered while iterating through the attributes to check for 260 // compatibility. 261 struct { 262 const LoopHintAttr *StateAttr; 263 const LoopHintAttr *NumericAttr; 264 } HintAttrs[] = {{nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr}, 265 {nullptr, nullptr}, {nullptr, nullptr}, {nullptr, nullptr}, 266 {nullptr, nullptr}}; 267 268 for (const auto *I : Attrs) { 269 const LoopHintAttr *LH = dyn_cast<LoopHintAttr>(I); 270 271 // Skip non loop hint attributes 272 if (!LH) 273 continue; 274 275 LoopHintAttr::OptionType Option = LH->getOption(); 276 enum { 277 Vectorize, 278 Interleave, 279 Unroll, 280 UnrollAndJam, 281 Distribute, 282 Pipeline, 283 VectorizePredicate 284 } Category; 285 switch (Option) { 286 case LoopHintAttr::Vectorize: 287 case LoopHintAttr::VectorizeWidth: 288 Category = Vectorize; 289 break; 290 case LoopHintAttr::Interleave: 291 case LoopHintAttr::InterleaveCount: 292 Category = Interleave; 293 break; 294 case LoopHintAttr::Unroll: 295 case LoopHintAttr::UnrollCount: 296 Category = Unroll; 297 break; 298 case LoopHintAttr::UnrollAndJam: 299 case LoopHintAttr::UnrollAndJamCount: 300 Category = UnrollAndJam; 301 break; 302 case LoopHintAttr::Distribute: 303 // Perform the check for duplicated 'distribute' hints. 304 Category = Distribute; 305 break; 306 case LoopHintAttr::PipelineDisabled: 307 case LoopHintAttr::PipelineInitiationInterval: 308 Category = Pipeline; 309 break; 310 case LoopHintAttr::VectorizePredicate: 311 Category = VectorizePredicate; 312 break; 313 }; 314 315 assert(Category < sizeof(HintAttrs) / sizeof(HintAttrs[0])); 316 auto &CategoryState = HintAttrs[Category]; 317 const LoopHintAttr *PrevAttr; 318 if (Option == LoopHintAttr::Vectorize || 319 Option == LoopHintAttr::Interleave || Option == LoopHintAttr::Unroll || 320 Option == LoopHintAttr::UnrollAndJam || 321 Option == LoopHintAttr::VectorizePredicate || 322 Option == LoopHintAttr::PipelineDisabled || 323 Option == LoopHintAttr::Distribute) { 324 // Enable|Disable|AssumeSafety hint. For example, vectorize(enable). 325 PrevAttr = CategoryState.StateAttr; 326 CategoryState.StateAttr = LH; 327 } else { 328 // Numeric hint. For example, vectorize_width(8). 329 PrevAttr = CategoryState.NumericAttr; 330 CategoryState.NumericAttr = LH; 331 } 332 333 PrintingPolicy Policy(S.Context.getLangOpts()); 334 SourceLocation OptionLoc = LH->getRange().getBegin(); 335 if (PrevAttr) 336 // Cannot specify same type of attribute twice. 337 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility) 338 << /*Duplicate=*/true << PrevAttr->getDiagnosticName(Policy) 339 << LH->getDiagnosticName(Policy); 340 341 if (CategoryState.StateAttr && CategoryState.NumericAttr && 342 (Category == Unroll || Category == UnrollAndJam || 343 CategoryState.StateAttr->getState() == LoopHintAttr::Disable)) { 344 // Disable hints are not compatible with numeric hints of the same 345 // category. As a special case, numeric unroll hints are also not 346 // compatible with enable or full form of the unroll pragma because these 347 // directives indicate full unrolling. 348 S.Diag(OptionLoc, diag::err_pragma_loop_compatibility) 349 << /*Duplicate=*/false 350 << CategoryState.StateAttr->getDiagnosticName(Policy) 351 << CategoryState.NumericAttr->getDiagnosticName(Policy); 352 } 353 } 354 } 355 356 static Attr *handleOpenCLUnrollHint(Sema &S, Stmt *St, const ParsedAttr &A, 357 SourceRange Range) { 358 // Although the feature was introduced only in OpenCL C v2.0 s6.11.5, it's 359 // useful for OpenCL 1.x too and doesn't require HW support. 360 // opencl_unroll_hint can have 0 arguments (compiler 361 // determines unrolling factor) or 1 argument (the unroll factor provided 362 // by the user). 363 unsigned UnrollFactor = 0; 364 if (A.getNumArgs() == 1) { 365 Expr *E = A.getArgAsExpr(0); 366 Optional<llvm::APSInt> ArgVal; 367 368 if (!(ArgVal = E->getIntegerConstantExpr(S.Context))) { 369 S.Diag(A.getLoc(), diag::err_attribute_argument_type) 370 << A << AANT_ArgumentIntegerConstant << E->getSourceRange(); 371 return nullptr; 372 } 373 374 int Val = ArgVal->getSExtValue(); 375 if (Val <= 0) { 376 S.Diag(A.getRange().getBegin(), 377 diag::err_attribute_requires_positive_integer) 378 << A << /* positive */ 0; 379 return nullptr; 380 } 381 UnrollFactor = static_cast<unsigned>(Val); 382 } 383 384 return ::new (S.Context) OpenCLUnrollHintAttr(S.Context, A, UnrollFactor); 385 } 386 387 static Attr *ProcessStmtAttribute(Sema &S, Stmt *St, const ParsedAttr &A, 388 SourceRange Range) { 389 if (A.isInvalid() || A.getKind() == ParsedAttr::IgnoredAttribute) 390 return nullptr; 391 392 // Unknown attributes are automatically warned on. Target-specific attributes 393 // which do not apply to the current target architecture are treated as 394 // though they were unknown attributes. 395 const TargetInfo *Aux = S.Context.getAuxTargetInfo(); 396 if (A.getKind() == ParsedAttr::UnknownAttribute || 397 !(A.existsInTarget(S.Context.getTargetInfo()) || 398 (S.Context.getLangOpts().SYCLIsDevice && Aux && 399 A.existsInTarget(*Aux)))) { 400 S.Diag(A.getLoc(), A.isDeclspecAttribute() 401 ? (unsigned)diag::warn_unhandled_ms_attribute_ignored 402 : (unsigned)diag::warn_unknown_attribute_ignored) 403 << A << A.getRange(); 404 return nullptr; 405 } 406 407 if (S.checkCommonAttributeFeatures(St, A)) 408 return nullptr; 409 410 switch (A.getKind()) { 411 case ParsedAttr::AT_FallThrough: 412 return handleFallThroughAttr(S, St, A, Range); 413 case ParsedAttr::AT_LoopHint: 414 return handleLoopHintAttr(S, St, A, Range); 415 case ParsedAttr::AT_OpenCLUnrollHint: 416 return handleOpenCLUnrollHint(S, St, A, Range); 417 case ParsedAttr::AT_Suppress: 418 return handleSuppressAttr(S, St, A, Range); 419 case ParsedAttr::AT_NoMerge: 420 return handleNoMergeAttr(S, St, A, Range); 421 case ParsedAttr::AT_MustTail: 422 return handleMustTailAttr(S, St, A, Range); 423 case ParsedAttr::AT_Likely: 424 return handleLikely(S, St, A, Range); 425 case ParsedAttr::AT_Unlikely: 426 return handleUnlikely(S, St, A, Range); 427 default: 428 // N.B., ClangAttrEmitter.cpp emits a diagnostic helper that ensures a 429 // declaration attribute is not written on a statement, but this code is 430 // needed for attributes in Attr.td that do not list any subjects. 431 S.Diag(A.getRange().getBegin(), diag::err_decl_attribute_invalid_on_stmt) 432 << A << St->getBeginLoc(); 433 return nullptr; 434 } 435 } 436 437 void Sema::ProcessStmtAttributes(Stmt *S, 438 const ParsedAttributesWithRange &InAttrs, 439 SmallVectorImpl<const Attr *> &OutAttrs) { 440 for (const ParsedAttr &AL : InAttrs) { 441 if (const Attr *A = ProcessStmtAttribute(*this, S, AL, InAttrs.Range)) 442 OutAttrs.push_back(A); 443 } 444 445 CheckForIncompatibleAttributes(*this, OutAttrs); 446 } 447