| 1 | //===------ SemaBPF.cpp ---------- BPF target-specific routines -----------===// |
| 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 functions specific to BPF. |
| 10 | // |
| 11 | //===----------------------------------------------------------------------===// |
| 12 | |
| 13 | #include "clang/Sema/SemaBPF.h" |
| 14 | #include "clang/AST/ASTDiagnostic.h" |
| 15 | #include "clang/AST/Decl.h" |
| 16 | #include "clang/AST/Expr.h" |
| 17 | #include "clang/AST/Type.h" |
| 18 | #include "clang/Basic/DiagnosticSema.h" |
| 19 | #include "clang/Basic/TargetBuiltins.h" |
| 20 | #include "clang/Basic/TargetInfo.h" |
| 21 | #include "clang/Sema/ParsedAttr.h" |
| 22 | #include "clang/Sema/Sema.h" |
| 23 | #include "llvm/ADT/APSInt.h" |
| 24 | #include <optional> |
| 25 | |
| 26 | namespace clang { |
| 27 | |
| 28 | SemaBPF::SemaBPF(Sema &S) : SemaBase(S) {} |
| 29 | |
| 30 | static bool isValidPreserveFieldInfoArg(Expr *Arg) { |
| 31 | if (Arg->getType()->getAsPlaceholderType()) |
| 32 | return false; |
| 33 | |
| 34 | // The first argument needs to be a record field access. |
| 35 | // If it is an array element access, we delay decision |
| 36 | // to BPF backend to check whether the access is a |
| 37 | // field access or not. |
| 38 | return (Arg->IgnoreParens()->getObjectKind() == OK_BitField || |
| 39 | isa<MemberExpr>(Val: Arg->IgnoreParens()) || |
| 40 | isa<ArraySubscriptExpr>(Val: Arg->IgnoreParens())); |
| 41 | } |
| 42 | |
| 43 | static bool isValidPreserveTypeInfoArg(Expr *Arg) { |
| 44 | QualType ArgType = Arg->getType(); |
| 45 | if (ArgType->getAsPlaceholderType()) |
| 46 | return false; |
| 47 | |
| 48 | // for TYPE_EXISTENCE/TYPE_MATCH/TYPE_SIZEOF reloc type |
| 49 | // format: |
| 50 | // 1. __builtin_preserve_type_info(*(<type> *)0, flag); |
| 51 | // 2. <type> var; |
| 52 | // __builtin_preserve_type_info(var, flag); |
| 53 | if (!isa<DeclRefExpr>(Val: Arg->IgnoreParens()) && |
| 54 | !isa<UnaryOperator>(Val: Arg->IgnoreParens())) |
| 55 | return false; |
| 56 | |
| 57 | // Typedef type. |
| 58 | if (ArgType->getAs<TypedefType>()) |
| 59 | return true; |
| 60 | |
| 61 | // Record type or Enum type. |
| 62 | if (const auto *RT = ArgType->getAsCanonical<TagType>()) |
| 63 | if (!RT->getDecl()->getDeclName().isEmpty()) |
| 64 | return true; |
| 65 | |
| 66 | return false; |
| 67 | } |
| 68 | |
| 69 | static bool isValidPreserveEnumValueArg(Expr *Arg) { |
| 70 | QualType ArgType = Arg->getType(); |
| 71 | if (ArgType->getAsPlaceholderType()) |
| 72 | return false; |
| 73 | |
| 74 | // for ENUM_VALUE_EXISTENCE/ENUM_VALUE reloc type |
| 75 | // format: |
| 76 | // __builtin_preserve_enum_value(*(<enum_type> *)<enum_value>, |
| 77 | // flag); |
| 78 | const auto *UO = dyn_cast<UnaryOperator>(Val: Arg->IgnoreParens()); |
| 79 | if (!UO) |
| 80 | return false; |
| 81 | |
| 82 | const auto *CE = dyn_cast<CStyleCastExpr>(Val: UO->getSubExpr()); |
| 83 | if (!CE) |
| 84 | return false; |
| 85 | if (CE->getCastKind() != CK_IntegralToPointer && |
| 86 | CE->getCastKind() != CK_NullToPointer) |
| 87 | return false; |
| 88 | |
| 89 | // The integer must be from an EnumConstantDecl. |
| 90 | const auto *DR = dyn_cast<DeclRefExpr>(Val: CE->getSubExpr()); |
| 91 | if (!DR) |
| 92 | return false; |
| 93 | |
| 94 | const EnumConstantDecl *Enumerator = |
| 95 | dyn_cast<EnumConstantDecl>(Val: DR->getDecl()); |
| 96 | if (!Enumerator) |
| 97 | return false; |
| 98 | |
| 99 | // The type must be EnumType. |
| 100 | const auto *ED = ArgType->getAsEnumDecl(); |
| 101 | if (!ED) |
| 102 | return false; |
| 103 | |
| 104 | // The enum value must be supported. |
| 105 | return llvm::is_contained(Range: ED->enumerators(), Element: Enumerator); |
| 106 | } |
| 107 | |
| 108 | // The kind of a C-style cast of the enumerator E to a pointer, as computed by |
| 109 | // Sema::PrepareScalarCast(). |
| 110 | static CastKind getEnumeratorToPointerCastKind(ASTContext &Context, |
| 111 | const Expr *E) { |
| 112 | return E->isNullPointerConstant(Ctx&: Context, NPC: Expr::NPC_ValueDependentIsNull) |
| 113 | ? CK_NullToPointer |
| 114 | : CK_IntegralToPointer; |
| 115 | } |
| 116 | |
| 117 | // In __builtin_preserve_enum_value(*(<enum_type> *)<enumerator>, flag), the |
| 118 | // enumerator names itself, not its value, so undo |
| 119 | // BuildPreserveAIEnumeratorRef() there, as if there were no attribute. |
| 120 | static void unwrapPreserveEnumValueArg(ASTContext &Context, Expr *Arg) { |
| 121 | auto *UO = dyn_cast<UnaryOperator>(Val: Arg->IgnoreParens()); |
| 122 | if (!UO || UO->getOpcode() != UO_Deref) |
| 123 | return; |
| 124 | auto *CE = dyn_cast<CStyleCastExpr>(Val: UO->getSubExpr()); |
| 125 | if (!CE || !SemaBPF::isPreserveAIEnumeratorRef(E: CE->getSubExpr())) |
| 126 | return; |
| 127 | auto *DRE = cast<DeclRefExpr>( |
| 128 | Val: cast<PseudoObjectExpr>(Val: CE->getSubExpr())->getSyntacticForm()); |
| 129 | CE->setSubExpr(DRE); |
| 130 | CE->setCastKind(getEnumeratorToPointerCastKind(Context, E: DRE)); |
| 131 | } |
| 132 | |
| 133 | bool SemaBPF::CheckBPFBuiltinFunctionCall(unsigned BuiltinID, |
| 134 | CallExpr *TheCall) { |
| 135 | assert((BuiltinID == BPF::BI__builtin_preserve_field_info || |
| 136 | BuiltinID == BPF::BI__builtin_btf_type_id || |
| 137 | BuiltinID == BPF::BI__builtin_preserve_type_info || |
| 138 | BuiltinID == BPF::BI__builtin_preserve_enum_value) && |
| 139 | "unexpected BPF builtin" ); |
| 140 | ASTContext &Context = getASTContext(); |
| 141 | if (SemaRef.checkArgCount(Call: TheCall, DesiredArgCount: 2)) |
| 142 | return true; |
| 143 | |
| 144 | // The second argument needs to be a constant int |
| 145 | Expr *Arg = TheCall->getArg(Arg: 1); |
| 146 | std::optional<llvm::APSInt> Value = Arg->getIntegerConstantExpr(Ctx: Context); |
| 147 | diag::kind kind; |
| 148 | if (!Value) { |
| 149 | if (BuiltinID == BPF::BI__builtin_preserve_field_info) |
| 150 | kind = diag::err_preserve_field_info_not_const; |
| 151 | else if (BuiltinID == BPF::BI__builtin_btf_type_id) |
| 152 | kind = diag::err_btf_type_id_not_const; |
| 153 | else if (BuiltinID == BPF::BI__builtin_preserve_type_info) |
| 154 | kind = diag::err_preserve_type_info_not_const; |
| 155 | else |
| 156 | kind = diag::err_preserve_enum_value_not_const; |
| 157 | Diag(Loc: Arg->getBeginLoc(), DiagID: kind) << 2 << Arg->getSourceRange(); |
| 158 | return true; |
| 159 | } |
| 160 | |
| 161 | // The first argument |
| 162 | Arg = TheCall->getArg(Arg: 0); |
| 163 | bool InvalidArg = false; |
| 164 | bool ReturnUnsignedInt = true; |
| 165 | if (BuiltinID == BPF::BI__builtin_preserve_field_info) { |
| 166 | if (!isValidPreserveFieldInfoArg(Arg)) { |
| 167 | InvalidArg = true; |
| 168 | kind = diag::err_preserve_field_info_not_field; |
| 169 | } |
| 170 | } else if (BuiltinID == BPF::BI__builtin_preserve_type_info) { |
| 171 | if (!isValidPreserveTypeInfoArg(Arg)) { |
| 172 | InvalidArg = true; |
| 173 | kind = diag::err_preserve_type_info_invalid; |
| 174 | } |
| 175 | } else if (BuiltinID == BPF::BI__builtin_preserve_enum_value) { |
| 176 | unwrapPreserveEnumValueArg(Context, Arg); |
| 177 | if (!isValidPreserveEnumValueArg(Arg)) { |
| 178 | InvalidArg = true; |
| 179 | kind = diag::err_preserve_enum_value_invalid; |
| 180 | } |
| 181 | ReturnUnsignedInt = false; |
| 182 | } else if (BuiltinID == BPF::BI__builtin_btf_type_id) { |
| 183 | ReturnUnsignedInt = false; |
| 184 | } |
| 185 | |
| 186 | if (InvalidArg) { |
| 187 | Diag(Loc: Arg->getBeginLoc(), DiagID: kind) << 1 << Arg->getSourceRange(); |
| 188 | return true; |
| 189 | } |
| 190 | |
| 191 | if (ReturnUnsignedInt) |
| 192 | TheCall->setType(Context.UnsignedIntTy); |
| 193 | else |
| 194 | TheCall->setType(Context.UnsignedLongTy); |
| 195 | return false; |
| 196 | } |
| 197 | |
| 198 | void SemaBPF::handlePreserveAIRecord(RecordDecl *RD) { |
| 199 | // Add preserve_access_index attribute to all fields and inner records, but |
| 200 | // not inner enums, so that their enumerators stay constants. |
| 201 | for (auto *D : RD->decls()) { |
| 202 | if (isa<EnumDecl>(Val: D) || D->hasAttr<BPFPreserveAccessIndexAttr>()) |
| 203 | continue; |
| 204 | |
| 205 | D->addAttr(A: BPFPreserveAccessIndexAttr::CreateImplicit(Ctx&: getASTContext())); |
| 206 | if (auto *Rec = dyn_cast<RecordDecl>(Val: D)) |
| 207 | handlePreserveAIRecord(RD: Rec); |
| 208 | } |
| 209 | } |
| 210 | |
| 211 | void SemaBPF::handlePreserveAccessIndexAttr(Decl *D, const ParsedAttr &AL) { |
| 212 | if (auto *Rec = dyn_cast<RecordDecl>(Val: D)) |
| 213 | handlePreserveAIRecord(RD: Rec); |
| 214 | auto *A = |
| 215 | ::new (getASTContext()) BPFPreserveAccessIndexAttr(getASTContext(), AL); |
| 216 | if (auto *ED = dyn_cast<EnumDecl>(Val: D); |
| 217 | ED && !ED->getDeclName() && !AL.isPragmaClangAttribute()) |
| 218 | AnonPreserveAIEnums.insert(KV: {ED, A}); |
| 219 | D->addAttr(A); |
| 220 | } |
| 221 | |
| 222 | void SemaBPF::DiagnoseAnonymousPreserveAIEnums() { |
| 223 | for (auto [ED, A] : AnonPreserveAIEnums) |
| 224 | if (!ED->getTypedefNameForAnonDecl()) |
| 225 | Diag(Loc: A->getLocation(), DiagID: diag::warn_preserve_access_index_anon_enum) << A; |
| 226 | AnonPreserveAIEnums.clear(); |
| 227 | } |
| 228 | |
| 229 | // Return the enum type, or its typedef name, that the enumerator E is relocated |
| 230 | // against, or a null type if E is not relocated. |
| 231 | static QualType getPreserveAIEnumType(ASTContext &Context, |
| 232 | const DeclRefExpr *E) { |
| 233 | const auto *Enumerator = dyn_cast<EnumConstantDecl>(Val: E->getDecl()); |
| 234 | if (!Enumerator) |
| 235 | return QualType(); |
| 236 | |
| 237 | // In C, an enumerator usually has type int, not the enum type, so find the |
| 238 | // enum from its context. Within the enum's definition, e.g., A in B = A + 1, |
| 239 | // the enum is incomplete and A stays a constant. |
| 240 | const auto *ED = dyn_cast<EnumDecl>(Val: Enumerator->getDeclContext()); |
| 241 | if (!ED || !ED->isCompleteDefinition() || |
| 242 | !ED->hasAttr<BPFPreserveAccessIndexAttr>()) |
| 243 | return QualType(); |
| 244 | |
| 245 | // libbpf matches relocations by type name, so an anonymous enum needs a |
| 246 | // typedef name. |
| 247 | if (ED->getDeclName()) |
| 248 | return Context.getCanonicalTagType(TD: ED); |
| 249 | if (const TypedefNameDecl *TD = ED->getTypedefNameForAnonDecl()) |
| 250 | return Context.getTypeDeclType(Decl: TD); |
| 251 | return QualType(); |
| 252 | } |
| 253 | |
| 254 | // Return the enumerator reference E, or, if it is relocated, a pseudo-object |
| 255 | // whose semantic form is a __builtin_preserve_enum_value() call. |
| 256 | Expr *SemaBPF::BuildPreserveAIEnumeratorRef(DeclRefExpr *E) { |
| 257 | if (SemaRef.isUnevaluatedContext()) |
| 258 | return E; |
| 259 | |
| 260 | ASTContext &Context = getASTContext(); |
| 261 | QualType EnumTy = getPreserveAIEnumType(Context, E); |
| 262 | if (EnumTy.isNull()) |
| 263 | return E; |
| 264 | |
| 265 | // The value cannot be relocated where a constant is required: in a constant |
| 266 | // evaluated context, e.g., an array bound or a case label, or outside of a |
| 267 | // function, e.g., a global initializer. Warn, and use the enumerator's value. |
| 268 | if (SemaRef.isConstantEvaluatedContext() || |
| 269 | SemaRef.CurContext->getRedeclContext()->isFileContext()) { |
| 270 | Diag(Loc: E->getExprLoc(), |
| 271 | DiagID: diag::warn_preserve_access_index_enumerator_not_relocated) |
| 272 | << E->getDecl() << EnumTy << E->getSourceRange(); |
| 273 | return E; |
| 274 | } |
| 275 | |
| 276 | // Keep it a constant anywhere in an unevaluated operand, e.g., in a block |
| 277 | // literal in sizeof. TransformToPotentiallyEvaluated() relocates it when it |
| 278 | // rebuilds a variably modified operand. |
| 279 | if (llvm::any_of(Range&: SemaRef.ExprEvalContexts, |
| 280 | P: [](const Sema::ExpressionEvaluationContextRecord &Rec) { |
| 281 | return Rec.isUnevaluated(); |
| 282 | })) |
| 283 | return E; |
| 284 | |
| 285 | // Build *(enum_type *)E in the form required by |
| 286 | // __builtin_preserve_enum_value(). |
| 287 | SourceLocation Loc = E->getExprLoc(); |
| 288 | auto *Ref = DeclRefExpr::Create(Context, QualifierLoc: E->getQualifierLoc(), |
| 289 | TemplateKWLoc: SourceLocation(), D: E->getDecl(), |
| 290 | /*RefersToEnclosingVariableOrCapture=*/false, |
| 291 | NameInfo: E->getNameInfo(), T: E->getType(), VK: VK_PRValue); |
| 292 | QualType PtrTy = Context.getPointerType(T: EnumTy); |
| 293 | Expr *Cast = CStyleCastExpr::Create( |
| 294 | Context, T: PtrTy, VK: VK_PRValue, K: getEnumeratorToPointerCastKind(Context, E: Ref), |
| 295 | Op: Ref, |
| 296 | /*BasePath=*/nullptr, FPO: FPOptionsOverride(), |
| 297 | WrittenTy: Context.getTrivialTypeSourceInfo(T: PtrTy, Loc), L: Loc, R: Loc); |
| 298 | Expr *Deref = UnaryOperator::Create( |
| 299 | C: Context, input: Cast, opc: UO_Deref, type: EnumTy, VK: VK_LValue, OK: OK_Ordinary, l: Loc, |
| 300 | /*CanOverflow=*/false, FPFeatures: FPOptionsOverride()); |
| 301 | |
| 302 | // Flag 1 is BPF_ENUMVAL_VALUE. |
| 303 | Expr *Flag = |
| 304 | IntegerLiteral::Create(C: Context, V: llvm::APInt(32, 1), type: Context.IntTy, l: Loc); |
| 305 | Expr *Args[] = {Deref, Flag}; |
| 306 | Expr *Conv = SemaRef.BuildBuiltinCallExpr( |
| 307 | Loc, Id: BPF::BI__builtin_preserve_enum_value, CallArgs: Args); |
| 308 | |
| 309 | // Cast the unsigned long result to the type of the enumerator, normally int, |
| 310 | // so that no type changes, e.g., hash % A stays a 32-bit unsigned remainder. |
| 311 | QualType ResultTy = E->getType(); |
| 312 | if (!Context.hasSameType(T1: Conv->getType(), T2: ResultTy)) |
| 313 | Conv = CStyleCastExpr::Create( |
| 314 | Context, T: ResultTy, VK: VK_PRValue, K: CK_IntegralCast, Op: Conv, |
| 315 | /*BasePath=*/nullptr, FPO: FPOptionsOverride(), |
| 316 | WrittenTy: Context.getTrivialTypeSourceInfo(T: ResultTy, Loc), L: Loc, R: Loc); |
| 317 | |
| 318 | // E is the syntactic form, so the AST is printed as written. |
| 319 | return PseudoObjectExpr::Create(Context, syntactic: E, semantic: {Conv}, /*resultIndex=*/0); |
| 320 | } |
| 321 | |
| 322 | // Return whether E is an enumerator reference built by |
| 323 | // BuildPreserveAIEnumeratorRef(), i.e., a pseudo-object for an enumerator whose |
| 324 | // semantic form is a __builtin_preserve_enum_value() call. |
| 325 | bool SemaBPF::isPreserveAIEnumeratorRef(const Expr *E) { |
| 326 | const auto *POE = dyn_cast<PseudoObjectExpr>(Val: E); |
| 327 | if (!POE) |
| 328 | return false; |
| 329 | const auto *DRE = dyn_cast<DeclRefExpr>(Val: POE->getSyntacticForm()); |
| 330 | if (!DRE || !isa<EnumConstantDecl>(Val: DRE->getDecl())) |
| 331 | return false; |
| 332 | const auto *Call = dyn_cast<CallExpr>(Val: POE->getResultExpr()->IgnoreCasts()); |
| 333 | return Call && |
| 334 | Call->getBuiltinCallee() == BPF::BI__builtin_preserve_enum_value; |
| 335 | } |
| 336 | |
| 337 | // If a relocated enumerator makes E non-constant, return the constant |
| 338 | // evaluator's note saying so. |
| 339 | static std::optional<PartialDiagnosticAt> |
| 340 | getPreserveAIEnumeratorNote(ASTContext &Context, const Expr *E) { |
| 341 | if (!Context.getTargetInfo().getTriple().isBPF() || E->isValueDependent()) |
| 342 | return std::nullopt; |
| 343 | SmallVector<PartialDiagnosticAt, 8> Notes; |
| 344 | Expr::EvalResult EvalResult; |
| 345 | EvalResult.Diag = &Notes; |
| 346 | if (E->EvaluateAsRValue(Result&: EvalResult, Ctx: Context, /*InConstantContext=*/true)) |
| 347 | return std::nullopt; |
| 348 | for (PartialDiagnosticAt &Note : Notes) |
| 349 | if (Note.second.getDiagID() == |
| 350 | diag::note_constexpr_bpf_preserve_ai_enumerator) |
| 351 | return std::move(Note); |
| 352 | return std::nullopt; |
| 353 | } |
| 354 | |
| 355 | // After an error that E is not a constant, emit the note if a relocated |
| 356 | // enumerator is the reason. |
| 357 | void SemaBPF::notePreserveAIEnumerator(const Expr *E) { |
| 358 | if (std::optional<PartialDiagnosticAt> Note = |
| 359 | getPreserveAIEnumeratorNote(Context&: getASTContext(), E)) |
| 360 | Diag(Loc: Note->first, PD: Note->second); |
| 361 | } |
| 362 | |
| 363 | // Replace each relocated enumerator in St with its DeclRefExpr, which has the |
| 364 | // same type and value kind, and warn that it is not relocated. |
| 365 | static Stmt *keepEnumeratorsConstant(SemaBPF &S, Stmt *St) { |
| 366 | if (!St) |
| 367 | return St; |
| 368 | if (auto *E = dyn_cast<Expr>(Val: St); |
| 369 | E && SemaBPF::isPreserveAIEnumeratorRef(E)) { |
| 370 | auto *DRE = |
| 371 | cast<DeclRefExpr>(Val: cast<PseudoObjectExpr>(Val: E)->getSyntacticForm()); |
| 372 | S.Diag(Loc: DRE->getExprLoc(), |
| 373 | DiagID: diag::warn_preserve_access_index_enumerator_not_relocated) |
| 374 | << DRE->getDecl() << getPreserveAIEnumType(Context&: S.getASTContext(), E: DRE) |
| 375 | << DRE->getSourceRange(); |
| 376 | return DRE; |
| 377 | } |
| 378 | for (Stmt *&Child : St->children()) |
| 379 | Child = keepEnumeratorsConstant(S, St: Child); |
| 380 | return St; |
| 381 | } |
| 382 | |
| 383 | // E must be a constant, e.g., an array designator, so keep its enumerators |
| 384 | // constants and warn. |
| 385 | Expr *SemaBPF::keepPreserveAIEnumeratorsConstant(Expr *E) { |
| 386 | return cast<Expr>(Val: keepEnumeratorsConstant(S&: *this, St: E)); |
| 387 | } |
| 388 | |
| 389 | // An asm operand E such as "i" must be a constant. If a relocated enumerator |
| 390 | // makes it non-constant, keep its enumerators constants and warn. |
| 391 | Expr *SemaBPF::checkAsmImmediateOperand(Expr *E) { |
| 392 | if (!getPreserveAIEnumeratorNote(Context&: getASTContext(), E)) |
| 393 | return E; |
| 394 | return keepPreserveAIEnumeratorsConstant(E); |
| 395 | } |
| 396 | |
| 397 | // The initializer of a static or constexpr local variable must be a constant, |
| 398 | // so keep its enumerators constants and warn. |
| 399 | Expr *SemaBPF::checkLocalConstantInitializer(const VarDecl *VD, Expr *Init) { |
| 400 | if (!VD->isLocalVarDecl() || (!VD->isStaticLocal() && !VD->isConstexpr())) |
| 401 | return Init; |
| 402 | return keepPreserveAIEnumeratorsConstant(E: Init); |
| 403 | } |
| 404 | |
| 405 | } // namespace clang |
| 406 | |