clang 24.0.0git
CIRGenExpr.cpp
Go to the documentation of this file.
1//===----------------------------------------------------------------------===//
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 contains code to emit Expr nodes as CIR code.
10//
11//===----------------------------------------------------------------------===//
12
13#include "Address.h"
15#include "CIRGenFunction.h"
16#include "CIRGenModule.h"
17#include "CIRGenValue.h"
18#include "TargetInfo.h"
19#include "mlir/Dialect/Ptr/IR/MemorySpaceInterfaces.h"
20#include "mlir/IR/BuiltinAttributes.h"
21#include "mlir/IR/Value.h"
22#include "clang/AST/ASTLambda.h"
23#include "clang/AST/Attr.h"
24#include "clang/AST/CharUnits.h"
25#include "clang/AST/Decl.h"
26#include "clang/AST/Expr.h"
27#include "clang/AST/ExprCXX.h"
38#include <optional>
39
40using namespace clang;
41using namespace clang::CIRGen;
42using namespace cir;
43
44/// Get the address of a zero-sized field within a record. Zero-sized fields
45/// (e.g. empty bases with [[no_unique_address]]) don't appear in the CIR
46/// record layout, so we compute their address using the ASTContext field
47/// offset and byte-level pointer arithmetic instead of cir.get_member.
49 const FieldDecl *field) {
50 CIRGenBuilderTy &builder = cgf.getBuilder();
52 cgf.getContext().getFieldOffset(field));
53 mlir::Type fieldType = cgf.convertType(field->getType());
54
55 if (offset.isZero()) {
56 return Address(builder.createPtrBitcast(base.getPointer(), fieldType),
57 base.getAlignment());
58 }
59
60 // Cast to byte pointer, stride by the field offset, then cast to the
61 // field pointer type (CIR pointers are typed, so we need explicit casts
62 // unlike OG's opaque-pointer GEP).
63 mlir::Location loc = cgf.getLoc(field->getLocation());
64 mlir::Value addr =
65 builder.createPtrBitcast(base.getPointer(), builder.getUInt8Ty());
66 addr = builder.createPtrStride(loc, addr,
67 builder.getUInt64(offset.getQuantity(), loc));
68 addr = builder.createPtrBitcast(addr, fieldType);
69 return Address(addr, base.getAlignment().alignmentAtOffset(offset));
70}
71
73 const FieldDecl *field,
74 llvm::StringRef fieldName,
75 unsigned fieldIndex) {
76 // Retrieve layout information for both type resolution and alignment.
77 const RecordDecl *rec = field->getParent();
78 const CIRGenRecordLayout &layout = cgm.getTypes().getCIRGenRecordLayout(rec);
79
80 bool addressedByFieldIndex =
82 ? layout.hasCIRField(field)
84 if (!addressedByFieldIndex)
85 return emitAddrOfZeroSizeField(*this, base, field);
86
87 mlir::Location loc = getLoc(field->getLocation());
88 unsigned idx = layout.getCIRFieldNo(field);
89
90 // For potentially-overlapping fields (e.g. [[no_unique_address]]), the
91 // record stores the base subobject type (without tail padding) rather than
92 // the complete object type. Use the record's member type for get_member,
93 // then bitcast to the complete type for downstream use.
94 //
95 // For unions, all fields map to index 0, so we use the field's declared type
96 // directly instead of looking up the member type from the layout.
97 mlir::Type fieldType = convertType(field->getType());
98 // A member lives in the same address space as its record.
99 mlir::ptr::MemorySpaceAttrInterface addrSpace = base.getAddressSpace();
100 auto fieldPtr = cir::PointerType::get(fieldType, addrSpace);
101 bool needsBitcast = false;
102
103 if (!rec->isUnion() && field->isPotentiallyOverlapping()) {
104 mlir::Type memberType = layout.getCIRType().getMembers()[idx];
105 fieldPtr = cir::PointerType::get(memberType, addrSpace);
106 needsBitcast = true;
107 }
108
109 // For most cases fieldName is the same as field->getName() but for lambdas,
110 // which do not currently carry the name, so it can be passed down from the
111 // CaptureStmt.
112 mlir::Value addr = builder.createGetMember(loc, fieldPtr, base.getPointer(),
113 fieldName, fieldIndex);
114
115 // If the field is potentially overlapping, the record member uses the base
116 // subobject type. Cast to the complete object pointer type expected by
117 // callers (analogous to OG's opaque pointer behavior).
118 if (needsBitcast)
119 addr = builder.createPtrBitcast(addr, fieldType);
120
122 layout.getCIRType().getElementOffset(cgm.getDataLayout().layout, idx));
123 return Address(addr, base.getAlignment().alignmentAtOffset(offset));
124}
125
126/// Given an expression of pointer type, try to
127/// derive a more accurate bound on the alignment of the pointer.
129 LValueBaseInfo *baseInfo) {
130 // We allow this with ObjC object pointers because of fragile ABIs.
131 assert(expr->getType()->isPointerType() ||
132 expr->getType()->isObjCObjectPointerType());
133 expr = expr->IgnoreParens();
134
135 // Casts:
136 if (auto const *ce = dyn_cast<CastExpr>(expr)) {
137 if (const auto *ece = dyn_cast<ExplicitCastExpr>(ce))
138 cgm.emitExplicitCastExprType(ece);
139
140 switch (ce->getCastKind()) {
141 // Non-converting casts (but not C's implicit conversion from void*).
142 case CK_BitCast:
143 case CK_NoOp:
144 case CK_AddressSpaceConversion: {
145 if (const auto *ptrTy =
146 ce->getSubExpr()->getType()->getAs<PointerType>()) {
147 if (ptrTy->getPointeeType()->isVoidType())
148 break;
149
150 LValueBaseInfo innerBaseInfo;
152 Address addr =
153 emitPointerWithAlignment(ce->getSubExpr(), &innerBaseInfo);
154 if (baseInfo)
155 *baseInfo = innerBaseInfo;
156
157 if (isa<ExplicitCastExpr>(ce)) {
158 LValueBaseInfo targetTypeBaseInfo;
159
160 const QualType pointeeType = expr->getType()->getPointeeType();
161 const CharUnits align =
162 cgm.getNaturalTypeAlignment(pointeeType, &targetTypeBaseInfo);
163
164 // If the source l-value is opaque, honor the alignment of the
165 // casted-to type.
166 if (innerBaseInfo.getAlignmentSource() != AlignmentSource::Decl) {
167 if (baseInfo)
168 baseInfo->mergeForCast(targetTypeBaseInfo);
169 addr = Address(addr.getPointer(), addr.getElementType(), align);
170 }
171 }
172
174
175 const mlir::Type eltTy =
176 convertTypeForMem(expr->getType()->getPointeeType());
177 addr = getBuilder().createElementBitCast(getLoc(expr->getSourceRange()),
178 addr, eltTy);
179 if (ce->getCastKind() == CK_AddressSpaceConversion)
181 addr.getPointer(), convertType(expr->getType())));
182
183 return addr;
184 }
185 break;
186 }
187
188 // Array-to-pointer decay. TODO(cir): BaseInfo and TBAAInfo.
189 case CK_ArrayToPointerDecay:
190 return emitArrayToPointerDecay(ce->getSubExpr(), baseInfo);
191
192 case CK_UncheckedDerivedToBase:
193 case CK_DerivedToBase: {
196 Address addr = emitPointerWithAlignment(ce->getSubExpr(), baseInfo);
197 const CXXRecordDecl *derived =
198 ce->getSubExpr()->getType()->getPointeeCXXRecordDecl();
199 return getAddressOfBaseClass(addr, derived, ce->path(),
201 ce->getExprLoc());
202 }
203
204 case CK_AnyPointerToBlockPointerCast:
205 case CK_BaseToDerived:
206 case CK_BaseToDerivedMemberPointer:
207 case CK_BlockPointerToObjCPointerCast:
208 case CK_BuiltinFnToFnPtr:
209 case CK_CPointerToObjCPointerCast:
210 case CK_DerivedToBaseMemberPointer:
211 case CK_Dynamic:
212 case CK_FunctionToPointerDecay:
213 case CK_IntegralToPointer:
214 case CK_LValueToRValue:
215 case CK_LValueToRValueBitCast:
216 case CK_NullToMemberPointer:
217 case CK_NullToPointer:
218 case CK_ReinterpretMemberPointer:
219 case CK_UserDefinedConversion:
220 // Common pointer conversions, nothing to do here.
221 // TODO: Is there any reason to treat base-to-derived conversions
222 // specially?
223 break;
224
225 case CK_ARCConsumeObject:
226 case CK_ARCExtendBlockObject:
227 case CK_ARCProduceObject:
228 case CK_ARCReclaimReturnedObject:
229 case CK_AtomicToNonAtomic:
230 case CK_BooleanToSignedIntegral:
231 case CK_ConstructorConversion:
232 case CK_CopyAndAutoreleaseBlockObject:
233 case CK_Dependent:
234 case CK_FixedPointCast:
235 case CK_FixedPointToBoolean:
236 case CK_FixedPointToFloating:
237 case CK_FixedPointToIntegral:
238 case CK_FloatingCast:
239 case CK_FloatingComplexCast:
240 case CK_FloatingComplexToBoolean:
241 case CK_FloatingComplexToIntegralComplex:
242 case CK_FloatingComplexToReal:
243 case CK_FloatingRealToComplex:
244 case CK_FloatingToBoolean:
245 case CK_FloatingToFixedPoint:
246 case CK_FloatingToIntegral:
247 case CK_HLSLAggregateSplatCast:
248 case CK_HLSLArrayRValue:
249 case CK_HLSLElementwiseCast:
250 case CK_HLSLVectorTruncation:
251 case CK_HLSLMatrixTruncation:
252 case CK_IntToOCLSampler:
253 case CK_IntegralCast:
254 case CK_IntegralComplexCast:
255 case CK_IntegralComplexToBoolean:
256 case CK_IntegralComplexToFloatingComplex:
257 case CK_IntegralComplexToReal:
258 case CK_IntegralRealToComplex:
259 case CK_IntegralToBoolean:
260 case CK_IntegralToFixedPoint:
261 case CK_IntegralToFloating:
262 case CK_LValueBitCast:
263 case CK_MatrixCast:
264 case CK_MemberPointerToBoolean:
265 case CK_NonAtomicToAtomic:
266 case CK_ObjCObjectLValueCast:
267 case CK_PointerToBoolean:
268 case CK_PointerToIntegral:
269 case CK_ToUnion:
270 case CK_ToVoid:
271 case CK_VectorSplat:
272 case CK_ZeroToOCLOpaqueType:
273 // Classic codegen has a default that does nothing. In CIR, we are issuing
274 // a diagnostic so we can examine casts that are reached here to be sure
275 // no action is needed. If nothing is needed, the cast can be moved to the
276 // group above that does nothing.
277 cgm.errorNYI(ce->getSourceRange(),
278 "unexpected cast for emitPointerWithAlignment: ",
279 ce->getCastKindName());
280 break;
281 }
282 }
283
284 // Unary &
285 if (const UnaryOperator *uo = dyn_cast<UnaryOperator>(expr)) {
286 // TODO(cir): maybe we should use a CIR unary op for pointers here instead.
287 if (uo->getOpcode() == UO_AddrOf) {
288 LValue lv = emitLValue(uo->getSubExpr());
289 if (baseInfo)
290 *baseInfo = lv.getBaseInfo();
292 return lv.getAddress();
293 }
294 }
295
296 // std::addressof and variants.
297 if (auto const *call = dyn_cast<CallExpr>(expr)) {
298 switch (call->getBuiltinCallee()) {
299 default:
300 break;
301 case Builtin::BIaddressof:
302 case Builtin::BI__addressof:
303 case Builtin::BI__builtin_addressof: {
304 LValue lv = emitLValue(call->getArg(0));
305 if (baseInfo)
306 *baseInfo = lv.getBaseInfo();
308 return lv.getAddress();
309 }
310 }
311 }
312
313 // Otherwise, use the alignment of the type.
315 emitScalarExpr(expr), expr->getType()->getPointeeType(), CharUnits(),
316 /*forPointeeType=*/true, baseInfo);
317}
318
320 LValue dst) {
321 auto getScalarSizeInBits = [&](mlir::Type ty) -> unsigned {
322 mlir::Type scalarTy = mlir::isa<cir::VectorType>(ty)
323 ? mlir::cast<cir::VectorType>(ty).getElementType()
324 : ty;
325 const cir::CIRDataLayout &dl = cgm.getDataLayout();
326 return dl.getTypeSizeInBits(scalarTy).getFixedValue();
327 };
328
329 mlir::Value srcVal = src.getValue();
330 Address dstAddr = dst.getExtVectorAddress();
331 if (getScalarSizeInBits(dstAddr.getElementType()) >
332 getScalarSizeInBits(srcVal.getType())) {
333 cgm.errorNYI(
334 dst.getPointer().getLoc(),
335 "emitStoreThroughExtVectorComponentLValue: dstTySize > srcTysize");
336 return;
337 }
338
339 if (getLangOpts().HLSL) {
340 cgm.errorNYI(dst.getPointer().getLoc(),
341 "emitStoreThroughExtVectorComponentLValue: HLSL");
342 return;
343 }
344
345 // This access turns into a read/modify/write of the vector. Load the input
346 // value now.
347 mlir::Location loc = dst.getExtVectorPointer().getLoc();
348
349 mlir::ArrayAttr elts = dst.getExtVectorElts();
350
351 mlir::Value vec = builder.createLoad(loc, dstAddr, dst.isVolatile());
352 if (const auto *vecTy = dst.getType()->getAs<clang::VectorType>()) {
353 unsigned numSrcElts = vecTy->getNumElements();
354 unsigned numDstElts = cast<cir::VectorType>(vec.getType()).getFixedSize();
355 if (numDstElts == numSrcElts) {
356 // Use shuffle vector is the src and destination are the same number of
357 // elements and restore the vector mask since it is on the side it will be
358 // stored.
359 SmallVector<int64_t> mask(numDstElts);
360 for (unsigned i = 0; i != numDstElts; ++i)
361 mask[getAccessedFieldNo(i, elts)] = i;
362
363 vec = builder.createVecShuffle(loc, srcVal, mask);
364 } else if (numDstElts > numSrcElts) {
365 // Extended the source vector to the same length and then shuffle it
366 // into the destination.
367 // FIXME: since we're shuffling with undef, can we just use the indices
368 // into that? This could be simpler.
369 SmallVector<int64_t> extMask(numDstElts, -1);
370 std::iota(extMask.begin(), extMask.begin() + numSrcElts, 0);
371
372 mlir::Value extSrcVal = builder.createVecShuffle(loc, srcVal, extMask);
373
374 // build identity
375 SmallVector<int64_t> mask(numDstElts);
376 std::iota(mask.begin(), mask.begin() + numDstElts, 0);
377
378 // When the vector size is odd and .odd or .hi is used, the last element
379 // of the Elts constant array will be one past the size of the vector.
380 // Ignore the last element here, if it is greater than the mask size.
381 if ((unsigned)getAccessedFieldNo(numSrcElts - 1, elts) == mask.size())
382 numSrcElts--;
383
384 // modify when what gets shuffled in
385 for (unsigned i = 0; i != numSrcElts; ++i)
386 mask[getAccessedFieldNo(i, elts)] = i + numDstElts;
387
388 vec = builder.createVecShuffle(loc, vec, extSrcVal, mask);
389 } else {
390 // We should never shorten the vector
391 llvm_unreachable("unexpected shorten vector length");
392 }
393 } else {
394 // If the Src is a scalar (not a vector), and the target is a vector it
395 // must be updating one element.
396 unsigned inIdx = getAccessedFieldNo(0, elts);
397 cir::ConstantOp elt = builder.getSInt64(inIdx, loc);
398 vec = cir::VecInsertOp::create(builder, loc, vec, srcVal, elt);
399 }
400
401 builder.createStore(loc, vec, dst.getExtVectorAddress(),
402 dst.isVolatileQualified());
403}
404
406 bool isInit) {
407 if (!dst.isSimple()) {
408 if (dst.isVectorElt()) {
409 // Read/modify/write the vector, inserting the new element
410 const mlir::Location loc = dst.getVectorPointer().getLoc();
411 const mlir::Value vector =
412 builder.createLoad(loc, dst.getVectorAddress());
413 const mlir::Value newVector = cir::VecInsertOp::create(
414 builder, loc, vector, src.getValue(), dst.getVectorIdx());
415 builder.createStore(loc, newVector, dst.getVectorAddress());
416 return;
417 }
418
419 if (dst.isExtVectorElt())
421
422 if (dst.isMatrixElt()) {
423 // Read/modify/write the matrix, inserting the new element.
424 const mlir::Location loc = dst.getPointer().getLoc();
425
426 // In Opt-level >1, we emit an assume here.
428
429 const mlir::Value matrix =
430 builder.createLoad(loc, dst.getMatrixAddress());
431 const mlir::Value newMatrix = builder.createMatrixInsert(
432 loc, src.getValue(), matrix, dst.getMatrixRowIdx(),
433 dst.getMatrixColumnIdx());
434 builder.createStore(loc, newMatrix, dst.getMatrixAddress(),
435 dst.isVolatileQualified());
436 return;
437 }
438
439 if (dst.isMatrixRow()) {
440 cgm.errorNYI("emitStoreThroughLValue: !dst.isSimple() && isMatrixRow");
441 return;
442 }
443
444 assert(dst.isBitField() && "Unknown LValue type");
446 return;
447 }
448
451
452 assert(src.isScalar() && "Can't emit an aggregate store with this method");
453 emitStoreOfScalar(src.getValue(), dst, isInit);
454}
455
456static std::optional<LValue> emitDeclTargetVarDeclLValue(CIRGenFunction &cgf,
457 const Expr *e,
458 const VarDecl *vd) {
459 std::optional<OMPDeclareTargetDeclAttr::MapTypeTy> res =
460 OMPDeclareTargetDeclAttr::isDeclareTargetDeclaration(vd);
461 if (!res)
462 return std::nullopt;
463 // MT_Local uses direct access.
464 if (*res == OMPDeclareTargetDeclAttr::MT_Local)
465 return std::nullopt;
466 // MT_To/MT_Enter without unified memory use direct access.
467 if ((*res == OMPDeclareTargetDeclAttr::MT_To ||
468 *res == OMPDeclareTargetDeclAttr::MT_Enter) &&
470 return std::nullopt;
471 cgf.cgm.errorNYI(e->getSourceRange(),
472 "emitDeclTargetVarDeclLValue: indirect access");
473 return std::nullopt;
474}
475
476static LValue emitGlobalVarDeclLValue(CIRGenFunction &cgf, const Expr *e,
477 const VarDecl *vd) {
478 QualType t = e->getType();
479
480 // In classic codegen, thread-locals get a wrapper function here. Rather than
481 // doing that, we instead treat this as a normal 'global', and leave it to
482 // lowerng-prepare to correctly generate the wrapper/etc.
483
484 // Check if the variable is marked as declare target with link clause in
485 // device codegen.
486 if (cgf.getLangOpts().OpenMPIsTargetDevice)
487 if (std::optional<LValue> lv = emitDeclTargetVarDeclLValue(cgf, e, vd))
488 return *lv;
489
490 // Traditional LLVM codegen handles thread local separately, CIR handles
491 // as part of getAddrOfGlobalVar.
492 mlir::Value v = cgf.cgm.getAddrOfGlobalVar(vd);
493
494 mlir::Type realVarTy = cgf.convertTypeForMem(vd->getType());
495 cir::PointerType realPtrTy = cir::PointerType::get(
496 realVarTy, mlir::cast<cir::PointerType>(v.getType()).getAddrSpace());
497 if (realPtrTy != v.getType())
498 v = cgf.getBuilder().createBitcast(v.getLoc(), v, realPtrTy);
499
500 CharUnits alignment = cgf.getContext().getDeclAlign(vd);
501 Address addr(v, realVarTy, alignment);
502 LValue lv;
503 if (vd->getType()->isReferenceType())
504 lv = cgf.emitLoadOfReferenceLValue(addr, cgf.getLoc(e->getSourceRange()),
506 else
507 lv = cgf.makeAddrLValue(addr, t, AlignmentSource::Decl);
509 return lv;
510}
511
512void CIRGenFunction::emitStoreOfScalar(mlir::Value value, Address addr,
513 bool isVolatile, QualType ty,
514 LValueBaseInfo baseInfo, bool isInit,
515 bool isNontemporal) {
516
517 if (const auto *clangVecTy = ty->getAs<clang::VectorType>()) {
518 // Handle vectors of size 3 like size 4 for better performance.
519 // TODO(CIR): Use `ABIInfo::getOptimalVectorMemoryType` once it upstreamed
521 if (clangVecTy->getNumElements() == 3 && !getLangOpts().PreserveVec3Type)
522 cgm.errorNYI(addr.getPointer().getLoc(),
523 "emitStoreOfScalar Vec3 & PreserveVec3Type disabled");
524 }
525
526 value = emitToMemory(value, ty);
527
529 LValue atomicLValue = LValue::makeAddr(addr, ty, baseInfo);
530 if (ty->isAtomicType() ||
531 (!isInit && isLValueSuitableForInlineAtomic(atomicLValue))) {
532 emitAtomicStore(RValue::get(value), atomicLValue, isInit);
533 return;
534 }
535
536 // Update the alloca with more info on initialization.
537 assert(addr.getPointer() && "expected pointer to exist");
538 cir::AllocaOp srcAlloca = addr.getUnderlyingAllocaOp();
539 if (currVarDecl && srcAlloca) {
540 const VarDecl *vd = currVarDecl;
541 assert(vd && "VarDecl expected");
542 if (vd->hasInit())
543 srcAlloca.setInitAttr(mlir::UnitAttr::get(&getMLIRContext()));
544 }
545
546 assert(currSrcLoc && "must pass in source location");
547 builder.createStore(getLoc(*currSrcLoc), value, addr, isVolatile,
548 isNontemporal);
549
551}
552
554 LValue dst) {
555
556 const CIRGenBitFieldInfo &info = dst.getBitFieldInfo();
557 mlir::Type resLTy = convertTypeForMem(dst.getType());
558 Address ptr = dst.getBitFieldAddress();
559
560 bool useVoaltile =
561 cgm.getCodeGenOpts().AAPCSBitfieldWidth && dst.isVolatileQualified() &&
562 info.volatileStorageSize != 0 && CodeGenUtils::isAAPCS(cgm.getTarget());
563
564 assert(currSrcLoc && "must pass in source location");
565
566 return builder.createSetBitfield(getLoc(*currSrcLoc), resLTy, ptr,
567 ptr.getElementType(), src.getValue(), info,
568 dst.isVolatileQualified(), useVoaltile);
569}
570
572 const CIRGenBitFieldInfo &info = lv.getBitFieldInfo();
573
574 // Get the output type.
575 mlir::Type resLTy = convertType(lv.getType());
576 Address ptr = lv.getBitFieldAddress();
577
578 bool useVoaltile = lv.isVolatileQualified() && info.volatileOffset != 0 &&
579 CodeGenUtils::isAAPCS(cgm.getTarget());
580
581 mlir::Value field =
582 builder.createGetBitfield(getLoc(loc), resLTy, ptr, ptr.getElementType(),
583 info, lv.isVolatile(), useVoaltile);
585 return RValue::get(field);
586}
587
589 const FieldDecl *field,
590 mlir::Type fieldType,
591 unsigned index) {
592 mlir::Location loc = getLoc(field->getLocation());
593 cir::PointerType fieldPtr =
594 cir::PointerType::get(fieldType, base.getAddress().getAddressSpace());
596 cir::GetMemberOp sea = getBuilder().createGetMember(
597 loc, fieldPtr, base.getPointer(), field->getName(),
598 mlir::isa<cir::UnionType>(rec) ? field->getFieldIndex() : index);
600 rec.getElementOffset(cgm.getDataLayout().layout, index));
601 return Address(sea, base.getAlignment().alignmentAtOffset(offset));
602}
603
605 const FieldDecl *field) {
606 LValueBaseInfo baseInfo = base.getBaseInfo();
607 const CIRGenRecordLayout &layout =
608 cgm.getTypes().getCIRGenRecordLayout(field->getParent());
609 const CIRGenBitFieldInfo &info = layout.getBitFieldInfo(field);
610
612
613 unsigned idx = layout.getCIRFieldNo(field);
614 Address addr = getAddrOfBitFieldStorage(base, field, info.storageType, idx);
615
616 mlir::Location loc = getLoc(field->getLocation());
617 if (addr.getElementType() != info.storageType)
618 addr = builder.createElementBitCast(loc, addr, info.storageType);
619
620 QualType fieldType =
622 // TODO(cir): Support TBAA for bit fields.
624 LValueBaseInfo fieldBaseInfo(baseInfo.getAlignmentSource());
625 return LValue::makeBitfield(addr, info, fieldType, fieldBaseInfo);
626}
627
629 LValueBaseInfo baseInfo = base.getBaseInfo();
630
631 if (field->isBitField())
632 return emitLValueForBitField(base, field);
633
634 QualType fieldType = field->getType();
635 const RecordDecl *rec = field->getParent();
636 AlignmentSource baseAlignSource = baseInfo.getAlignmentSource();
637 LValueBaseInfo fieldBaseInfo(getFieldAlignmentSource(baseAlignSource));
639
640 Address addr = base.getAddress();
641 if (auto *classDecl = dyn_cast<CXXRecordDecl>(rec)) {
642 if (cgm.getCodeGenOpts().StrictVTablePointers &&
643 classDecl->isDynamicClass()) {
644 cgm.errorNYI(field->getSourceRange(),
645 "emitLValueForField: strict vtable for dynamic class");
646 }
647 }
648
649 unsigned recordCVR = base.getVRQualifiers();
650
651 llvm::StringRef fieldName = field->getName();
652 unsigned fieldIndex;
653 if (cgm.lambdaFieldToName.count(field))
654 fieldName = cgm.lambdaFieldToName[field];
655
656 // Fields with no CIR field index (e.g. a [[no_unique_address]] field that
657 // is empty for both layout and the ABI) aren't in the record layout, so
658 // handle them separately: use the base address directly with the right
659 // type instead of get_member.
660 const CIRGenRecordLayout &layout =
661 cgm.getTypes().getCIRGenRecordLayout(field->getParent());
662 if (!rec->isUnion() && !layout.hasCIRField(field)) {
663 addr = emitAddrOfZeroSizeField(*this, addr, field);
664 LValue lv = makeAddrLValue(addr, fieldType, fieldBaseInfo);
665 lv.getQuals().addCVRQualifiers(recordCVR);
666 return lv;
667 }
668
669 if (rec->isUnion())
670 fieldIndex = field->getFieldIndex();
671 else
672 fieldIndex = layout.getCIRFieldNo(field);
673
674 addr = emitAddrOfFieldStorage(addr, field, fieldName, fieldIndex);
676
677 // If this is a reference field, load the reference right now.
678 if (fieldType->isReferenceType()) {
680 LValue refLVal = makeAddrLValue(addr, fieldType, fieldBaseInfo);
681 if (recordCVR & Qualifiers::Volatile)
682 refLVal.getQuals().addVolatile();
683 addr = emitLoadOfReference(refLVal, getLoc(field->getSourceRange()),
684 &fieldBaseInfo);
685
686 // Qualifiers on the struct don't apply to the referencee.
687 recordCVR = 0;
688 fieldType = fieldType->getPointeeType();
689 }
690
691 if (field->hasAttr<AnnotateAttr>())
692 addr = emitFieldAnnotations(field, addr);
693
694 LValue lv = makeAddrLValue(addr, fieldType, fieldBaseInfo);
695 lv.getQuals().addCVRQualifiers(recordCVR);
696
697 // __weak attribute on a field is ignored.
699 cgm.errorNYI(field->getSourceRange(),
700 "emitLValueForField: __weak attribute");
701 return LValue();
702 }
703
704 return lv;
705}
706
708 LValue base, const clang::FieldDecl *field, llvm::StringRef fieldName) {
709 QualType fieldType = field->getType();
710
711 if (!fieldType->isReferenceType())
712 return emitLValueForField(base, field);
713
714 Address v = base.getAddress();
715 const CIRGenRecordLayout &layout =
716 cgm.getTypes().getCIRGenRecordLayout(field->getParent());
717 if (!layout.hasCIRField(field)) {
718 v = emitAddrOfZeroSizeField(*this, v, field);
719 } else {
720 unsigned fieldIndex = layout.getCIRFieldNo(field);
721 v = emitAddrOfFieldStorage(v, field, fieldName, fieldIndex);
722 }
723
724 // Make sure that the address is pointing to the right type.
725 mlir::Type memTy = convertTypeForMem(fieldType);
726 v = builder.createElementBitCast(getLoc(field->getSourceRange()), v, memTy);
727
728 // TODO: Generate TBAA information that describes this access as a structure
729 // member access and not just an access to an object of the field's type. This
730 // should be similar to what we do in EmitLValueForField().
731 LValueBaseInfo baseInfo = base.getBaseInfo();
732 AlignmentSource fieldAlignSource = baseInfo.getAlignmentSource();
733 LValueBaseInfo fieldBaseInfo(getFieldAlignmentSource(fieldAlignSource));
735 return makeAddrLValue(v, fieldType, fieldBaseInfo);
736}
737
738/// Converts a scalar value from its primary IR type (as returned
739/// by ConvertType) to its load/store type.
740mlir::Value CIRGenFunction::emitToMemory(mlir::Value value, QualType ty) {
741 if (auto *atomicTy = ty->getAs<AtomicType>())
742 ty = atomicTy->getValueType();
743
744 if (ty->isConstantMatrixBoolType()) {
745 cgm.errorNYI("emitToMemory: ConstantMatrixBoolType");
746 return {};
747 }
748
749 // Unlike in classic codegen CIR, bools are kept as `cir.bool` and BitInts are
750 // kept as `cir.int<N>` until further lowering
751 return value;
752}
753
754mlir::Value CIRGenFunction::emitFromMemory(mlir::Value value, QualType ty) {
755 if (auto *atomicTy = ty->getAs<AtomicType>())
756 ty = atomicTy->getValueType();
757
759 cgm.errorNYI("emitFromMemory: PackedVectorBoolType");
760 }
761
762 return value;
763}
764
765void CIRGenFunction::emitStoreOfScalar(mlir::Value value, LValue lvalue,
766 bool isInit) {
767 emitStoreOfScalar(value, lvalue.getAddress(), lvalue.isVolatile(),
768 lvalue.getType(), lvalue.getBaseInfo(), isInit,
769 lvalue.isNontemporal());
770}
771
772mlir::Value CIRGenFunction::emitLoadOfScalar(Address addr, bool isVolatile,
773 QualType ty, SourceLocation loc,
774 LValueBaseInfo baseInfo,
775 bool isNontemporal) {
776 // Traditional LLVM codegen handles thread local separately, CIR handles
777 // as part of getAddrOfGlobalVar (GetGlobalOp).
778 mlir::Type eltTy = addr.getElementType();
779 if (const auto *clangVecTy = ty->getAs<clang::VectorType>()) {
780 // Handle vectors of size 3 like size 4 for better performance.
782 if (clangVecTy->getNumElements() == 3 && !getLangOpts().PreserveVec3Type)
783 cgm.errorNYI(addr.getPointer().getLoc(),
784 "emitLoadOfScalar Vec3 & PreserveVec3Type disabled");
785 }
786
788 LValue atomicLValue = LValue::makeAddr(addr, ty, baseInfo);
789 if (ty->isAtomicType() || isLValueSuitableForInlineAtomic(atomicLValue))
790 return emitAtomicLoad(atomicLValue, loc).getValue();
791
792 if (mlir::isa<cir::VoidType>(eltTy))
793 cgm.errorNYI(loc, "emitLoadOfScalar: void type");
794
796
797 mlir::Value loadOp =
798 builder.createLoad(getLoc(loc), addr, isVolatile, isNontemporal);
799
800 // Types with a boolean representation that are not the builtin bool (an enum
801 // whose underlying type is bool, or a _BitInt(1)) need no register/memory
802 // conversion here: like bool and _BitInt(N), CIR keeps them in their literal
803 // type until LowerToLLVM widens them to the in-memory integer type (see
804 // emitToMemory).
805 return loadOp;
806}
807
809 SourceLocation loc) {
811 return emitLoadOfScalar(lvalue.getAddress(), lvalue.isVolatile(),
812 lvalue.getType(), loc, lvalue.getBaseInfo(),
813 lvalue.isNontemporal());
814}
815
817 CIRGenFunction &cgf) {
818 if (cgf.getLangOpts().HLSL &&
819 lv.getType().getAddressSpace() == LangAS::hlsl_constant) {
820 cgf.cgm.errorNYI(
821 loc, "emitLoadOfMatrixLValue: HLSL & hlsl_constant address space");
822 return {};
823 }
824
825 return RValue::get(cgf.emitLoadOfScalar(lv, loc));
826}
827
828/// Given an expression that represents a value lvalue, this
829/// method emits the address of the lvalue, then loads the result as an rvalue,
830/// returning the rvalue.
832 assert(!lv.getType()->isFunctionType());
833
834 if (lv.isBitField())
835 return emitLoadOfBitfieldLValue(lv, loc);
836
837 if (lv.isSimple()) {
838 if (lv.getType()->isConstantMatrixType())
839 return emitLoadOfMatrixLValue(lv, loc, *this);
840
841 return RValue::get(emitLoadOfScalar(lv, loc));
842 }
843
844 if (lv.isVectorElt()) {
845 const mlir::Value load =
846 builder.createLoad(getLoc(loc), lv.getVectorAddress());
847 return RValue::get(cir::VecExtractOp::create(builder, getLoc(loc), load,
848 lv.getVectorIdx()));
849 }
850
851 if (lv.isExtVectorElt())
853
854 if (lv.isMatrixElt()) {
855 // In Opt-level >1, we emit an assume here.
857 const mlir::Location mlirLoc = getLoc(loc);
858 const mlir::Value matrix =
859 builder.createLoad(mlirLoc, lv.getMatrixAddress(), lv.isVolatile());
860 return RValue::get(builder.createMatrixExtract(
861 mlirLoc, matrix, lv.getMatrixRowIdx(), lv.getMatrixColumnIdx()));
862 }
863
864 cgm.errorNYI(loc, "emitLoadOfLValue");
865 return RValue::get(nullptr);
866}
867
868int64_t CIRGenFunction::getAccessedFieldNo(unsigned int idx,
869 const mlir::ArrayAttr elts) {
870 auto elt = mlir::cast<mlir::IntegerAttr>(elts[idx]);
871 return elt.getInt();
872}
873
874// If this is a reference to a subset of the elements of a vector, create an
875// appropriate shufflevector.
877 mlir::Location loc = lv.getExtVectorPointer().getLoc();
878 mlir::Value vec =
879 builder.createLoad(loc, lv.getExtVectorAddress(), lv.isVolatile());
880
881 // HLSL allows treating scalars as one-element vectors. Converting the scalar
882 // IR value to a vector here allows the rest of codegen to behave as normal.
883 if (getLangOpts().HLSL &&
884 !mlir::isa<cir::VectorType, cir::MatrixType>(vec.getType())) {
885 auto dstTy = cir::VectorType::get(
886 vec.getType(), llvm::ElementCount::get(1, /*Scalable=*/false));
887 cir::ConstantOp poison =
888 builder.getConstant(loc, cir::PoisonAttr::get(dstTy));
889 vec = builder.createInsertElement(loc, poison, vec, /*idx=*/0);
890 }
891
892 assert((mlir::isa<cir::VectorType, cir::MatrixType>(vec.getType())) &&
893 "ExtVecElement with non vector or matrix type on non-HLSL mode");
894
895 const mlir::ArrayAttr elts = lv.getExtVectorElts();
896
897 // If the result of the expression is a non-vector type, we must be extracting
898 // a single element. Just codegen as an extractelement.
899 const auto *exprVecTy = lv.getType()->getAs<clang::VectorType>();
900 if (!exprVecTy) {
901 int64_t indexValue = getAccessedFieldNo(0, elts);
902 cir::ConstantOp index =
903 builder.getConstInt(loc, builder.getSInt64Ty(), indexValue);
904 if (mlir::isa<cir::VectorType>(vec.getType()))
905 return RValue::get(cir::VecExtractOp::create(builder, loc, vec, index));
906
907 cir::ConstantOp columnIdx =
908 builder.getConstInt(loc, builder.getSInt64Ty(), 0);
909 mlir::Value element =
910 cir::MatrixExtractOp::create(builder, loc, vec, index, columnIdx);
911 return RValue::get(element);
912 }
913
914 // Always use shuffle vector to try to retain the original program structure
916 for (auto i : llvm::seq<unsigned>(0, exprVecTy->getNumElements()))
917 mask.push_back(getAccessedFieldNo(i, elts));
918
919 cir::VecShuffleOp resultVec = builder.createVecShuffle(loc, vec, mask);
920 if (lv.getType()->isExtVectorBoolType()) {
921 cgm.errorNYI(loc, "emitLoadOfExtVectorElementLValue: ExtVectorBoolType");
922 return {};
923 }
924
925 return RValue::get(resultVec);
926}
927
928LValue
930 assert((e->getOpcode() == BO_PtrMemD || e->getOpcode() == BO_PtrMemI) &&
931 "unexpected binary operator opcode");
932
933 Address baseAddr = Address::invalid();
934 if (e->getOpcode() == BO_PtrMemD)
935 baseAddr = emitLValue(e->getLHS()).getAddress();
936 else
937 baseAddr = emitPointerWithAlignment(e->getLHS());
938
939 const auto *memberPtrTy = e->getRHS()->getType()->castAs<MemberPointerType>();
940
941 mlir::Value memberPtr = emitScalarExpr(e->getRHS());
942
943 LValueBaseInfo baseInfo;
945 Address memberAddr = emitCXXMemberDataPointerAddress(e, baseAddr, memberPtr,
946 memberPtrTy, &baseInfo);
947
948 return makeAddrLValue(memberAddr, memberPtrTy->getPointeeType(), baseInfo);
949}
950
951/// Generates lvalue for partial ext_vector access.
953 mlir::Location loc) {
954 Address vectorAddress = lv.getExtVectorAddress();
955 QualType elementTy = lv.getType()->castAs<VectorType>()->getElementType();
956 mlir::Type vectorElementTy = cgm.getTypes().convertType(elementTy);
957 Address castToPointerElement =
958 vectorAddress.withElementType(builder, vectorElementTy);
959
960 mlir::ArrayAttr extVecElts = lv.getExtVectorElts();
961 unsigned idx = getAccessedFieldNo(0, extVecElts);
962 mlir::Value idxValue =
963 builder.getConstInt(loc, mlir::cast<cir::IntType>(ptrDiffTy), idx);
964
965 mlir::Value elementValue = builder.getArrayElement(
966 loc, loc, castToPointerElement.getPointer(), vectorElementTy, idxValue,
967 /*shouldDecay=*/false);
968
969 const CharUnits eltSize = getContext().getTypeSizeInChars(elementTy);
970 const CharUnits alignment =
971 castToPointerElement.getAlignment().alignmentAtOffset(idx * eltSize);
972 return Address(elementValue, vectorElementTy, alignment);
973}
974
976 const auto *fd = cast<FunctionDecl>(gd.getDecl());
977 if (fd->hasAttr<WeakRefAttr>())
978 return cast_or_null<cir::FuncOp>(getWeakRefReference(fd));
979 return getAddrOfFunction(gd);
980}
981
983 mlir::Value thisValue) {
984 return cgf.emitLValueForLambdaField(fd, thisValue);
985}
986
987/// Given that we are currently emitting a lambda, emit an l-value for
988/// one of its members.
989///
991 mlir::Value thisValue) {
992 bool hasExplicitObjectParameter = false;
993 const auto *md = dyn_cast_if_present<CXXMethodDecl>(curCodeDecl);
994 LValue lambdaLV;
995 if (md) {
996 hasExplicitObjectParameter = md->isExplicitObjectMemberFunction();
997 assert(md->getParent()->isLambda());
998 assert(md->getParent() == field->getParent());
999 }
1000
1001 if (hasExplicitObjectParameter) {
1002 const VarDecl *d = cast<CXXMethodDecl>(curCodeDecl)->getParamDecl(0);
1003 auto it = localDeclMap.find(d);
1004 assert(it != localDeclMap.end() && "explicit parameter not loaded?");
1005 Address addrOfExplicitObject = it->second;
1006 if (d->getType()->isReferenceType())
1007 lambdaLV = emitLoadOfReferenceLValue(addrOfExplicitObject,
1008 getLoc(field->getSourceRange()),
1010 else
1011 lambdaLV = makeAddrLValue(addrOfExplicitObject,
1013
1014 // Make sure we have an lvalue to the lambda itself and not a derived class.
1015 auto *thisTy = d->getType().getNonReferenceType()->getAsCXXRecordDecl();
1016 auto *lambdaTy = cast<CXXRecordDecl>(field->getParent());
1017 if (thisTy != lambdaTy) {
1018 const CXXCastPath &basePathArray = getContext().LambdaCastPaths.at(md);
1020 lambdaLV.getAddress(), thisTy,
1021 llvm::make_range(basePathArray.begin(), basePathArray.end()),
1022 /*nullCheckValue=*/false, SourceLocation());
1024 lambdaLV = makeAddrLValue(base, t);
1025 }
1026 } else {
1027 CanQualType lambdaTagType =
1029 lambdaLV = makeNaturalAlignAddrLValue(thisValue, lambdaTagType);
1030 }
1031 return emitLValueForField(lambdaLV, field);
1032}
1033
1037
1038static LValue emitFunctionDeclLValue(CIRGenFunction &cgf, const Expr *e,
1039 GlobalDecl gd) {
1040 const FunctionDecl *fd = cast<FunctionDecl>(gd.getDecl());
1041 cir::FuncOp funcOp = cgf.cgm.getFunctionPointer(gd);
1042 mlir::Location loc = cgf.getLoc(e->getSourceRange());
1043 CharUnits align = cgf.getContext().getDeclAlign(fd);
1044
1046
1047 mlir::Type fnTy = funcOp.getFunctionType();
1048 mlir::ptr::MemorySpaceAttrInterface fnAddrSpace =
1050 mlir::Type ptrTy = cir::PointerType::get(fnTy, fnAddrSpace);
1051 mlir::Value addr;
1052
1053 // On the HIP host, a reference to a __global__ kernel must resolve to the
1054 // address of the kernel handle registered with the offload runtime, not
1055 // the device stub's own address. CUDA uses the device stub itself as the
1056 // kernel handle.
1057 if (cgf.cgm.getLangOpts().HIP && !cgf.cgm.getLangOpts().CUDAIsDevice &&
1058 fd->hasAttr<CUDAGlobalAttr>()) {
1059 auto handle = mlir::cast<cir::GlobalOp>(
1060 cgf.cgm.getCUDARuntime().getKernelHandle(funcOp, gd));
1061 cir::PointerType handlePtrTy = cir::PointerType::get(handle.getSymType());
1062 mlir::Value handleAddr = cir::GetGlobalOp::create(
1063 cgf.getBuilder(), loc, handlePtrTy, handle.getSymName());
1064 addr = cir::CastOp::create(cgf.getBuilder(), loc, ptrTy,
1065 cir::CastKind::bitcast, handleAddr);
1066 }
1067
1068 if (!addr)
1069 addr = cir::GetGlobalOp::create(cgf.getBuilder(), loc, ptrTy,
1070 funcOp.getSymName());
1071
1072 if (funcOp.getFunctionType() != cgf.convertType(fd->getType())) {
1073 fnTy = cgf.convertType(fd->getType());
1074 ptrTy = cir::PointerType::get(fnTy, fnAddrSpace);
1075
1076 addr = cir::CastOp::create(cgf.getBuilder(), addr.getLoc(), ptrTy,
1077 cir::CastKind::bitcast, addr);
1078 }
1079
1080 return cgf.makeAddrLValue(Address(addr, fnTy, align), e->getType(),
1082}
1083
1084/// Determine whether we can emit a reference to \p vd from the current
1085/// context, despite not necessarily having seen an odr-use of the variable in
1086/// this context.
1087/// TODO(cir): This could be shared with classic codegen.
1089 const DeclRefExpr *e,
1090 const VarDecl *vd) {
1091 // For a variable declared in an enclosing scope, do not emit a spurious
1092 // reference even if we have a capture, as that will emit an unwarranted
1093 // reference to our capture state, and will likely generate worse code than
1094 // emitting a local copy.
1096 return false;
1097
1098 // For a local declaration declared in this function, we can always reference
1099 // it even if we don't have an odr-use.
1100 if (vd->hasLocalStorage()) {
1101 return vd->getDeclContext() ==
1102 dyn_cast_or_null<DeclContext>(cgf.curCodeDecl);
1103 }
1104
1105 // For a global declaration, we can emit a reference to it if we know
1106 // for sure that we are able to emit a definition of it.
1107 vd = vd->getDefinition(cgf.getContext());
1108 if (!vd)
1109 return false;
1110
1111 // Don't emit a spurious reference if it might be to a variable that only
1112 // exists on a different device / target.
1113 // FIXME: This is unnecessarily broad. Check whether this would actually be a
1114 // cross-target reference.
1115 if (cgf.getLangOpts().OpenMP || cgf.getLangOpts().CUDA ||
1116 cgf.getLangOpts().OpenCL) {
1117 return false;
1118 }
1119
1120 // We can emit a spurious reference only if the linkage implies that we'll
1121 // be emitting a non-interposable symbol that will be retained until link
1122 // time.
1123 switch (cgf.cgm.getCIRLinkageVarDefinition(vd)) {
1124 case cir::GlobalLinkageKind::ExternalLinkage:
1125 case cir::GlobalLinkageKind::LinkOnceODRLinkage:
1126 case cir::GlobalLinkageKind::WeakODRLinkage:
1127 case cir::GlobalLinkageKind::InternalLinkage:
1128 case cir::GlobalLinkageKind::PrivateLinkage:
1129 return true;
1130 default:
1131 return false;
1132 }
1133}
1134
1136 const NamedDecl *nd = e->getDecl();
1137 QualType ty = e->getType();
1138
1139 assert(e->isNonOdrUse() != NOUR_Unevaluated &&
1140 "should not emit an unevaluated operand");
1141
1142 if (const auto *vd = dyn_cast<VarDecl>(nd)) {
1143 // Global Named registers access via intrinsics only
1144 if (vd->getStorageClass() == SC_Register && vd->hasAttr<AsmLabelAttr>() &&
1145 !vd->isLocalVarDecl()) {
1146 cgm.errorNYI(e->getSourceRange(),
1147 "emitDeclRefLValue: Global Named registers access");
1148 return LValue();
1149 }
1150
1151 if (e->isNonOdrUse() == NOUR_Constant &&
1152 (vd->getType()->isReferenceType() ||
1153 !canEmitSpuriousReferenceToVariable(*this, e, vd))) {
1154 vd->getAnyInitializer(vd);
1155 mlir::Attribute val = ConstantEmitter(*this).emitAbstract(
1156 e->getLocation(), *vd->evaluateValue(), vd->getType());
1157 assert(val && "failed to emit constant expression");
1158
1159 Address addr = Address::invalid();
1160 if (!vd->getType()->isReferenceType()) {
1161 // Spill the constant value to a global.
1162 addr = cgm.createUnnamedGlobalFrom(*vd, val,
1163 getContext().getDeclAlign(vd));
1164 mlir::Type varTy = getTypes().convertTypeForMem(vd->getType());
1165 auto ptrTy = mlir::cast<cir::PointerType>(addr.getPointer().getType());
1166 if (ptrTy.getPointee() != varTy) {
1167 addr = addr.withElementType(builder, varTy);
1168 }
1169 } else {
1170 // Should we be using the alignment of the constant pointer we emitted?
1171 CharUnits alignment = cgm.getNaturalTypeAlignment(
1172 e->getType(), /*baseInfo=*/nullptr, /*forPointeeType=*/true);
1173 // Classic codegen passes TBAA as null-ptr to the above function, so it
1174 // probably needs to deal with that.
1176 mlir::Value ptrVal = getBuilder().getConstant(
1177 getLoc(e->getSourceRange()), mlir::cast<mlir::TypedAttr>(val));
1178 addr = makeNaturalAddressForPointer(ptrVal, ty, alignment);
1179 }
1180 return makeAddrLValue(addr, ty, AlignmentSource::Decl);
1181 }
1182
1183 // Check for captured variables.
1185 vd = vd->getCanonicalDecl();
1186 if (FieldDecl *fd = lambdaCaptureFields.lookup(vd))
1187 return emitCapturedFieldLValue(*this, fd, cxxabiThisValue);
1190 }
1191 }
1192
1193 // FIXME: We should be able to assert this for FunctionDecls as well!
1194 // FIXME: We should be able to assert this for all DeclRefExprs, not just
1195 // those with a valid source location.
1196 assert((nd->isUsed(false) || !isa<VarDecl>(nd) || e->isNonOdrUse() ||
1197 !e->getLocation().isValid()) &&
1198 "Should not use decl without marking it used!");
1199
1200 // A weakref variable refers to its alias target. Weakref functions are
1201 // handled by getRawFunctionPointer.
1202 if (const auto *vd = dyn_cast<VarDecl>(nd);
1203 vd && vd->hasAttr<WeakRefAttr>()) {
1204 auto aliasee =
1205 mlir::cast_or_null<cir::GlobalOp>(cgm.getWeakRefReference(vd));
1206 if (!aliasee)
1207 return LValue();
1208 mlir::Value v =
1209 builder.createGetGlobal(getLoc(e->getSourceRange()), aliasee);
1210 Address addr(v, convertTypeForMem(vd->getType()),
1211 getContext().getDeclAlign(vd));
1212 return makeAddrLValue(addr, ty, AlignmentSource::Decl);
1213 }
1214
1215 if (const auto *vd = dyn_cast<VarDecl>(nd)) {
1216 // Checks for omitted feature handling
1223
1224 // Check if this is a global variable
1225 if (vd->hasLinkage() || vd->isStaticDataMember())
1226 return emitGlobalVarDeclLValue(*this, e, vd);
1227
1228 Address addr = Address::invalid();
1229
1230 // The variable should generally be present in the local decl map.
1231 auto iter = localDeclMap.find(vd);
1232 if (iter != localDeclMap.end()) {
1233 addr = iter->second;
1234
1235 } else if (vd->isStaticLocal()) {
1236 // Otherwise, it might be static local we haven't emitted yet for some
1237 // reason; most likely, because it's in an outer function.
1238 cir::GlobalOp var =
1239 cgm.getOrCreateStaticVarDecl(*vd, cgm.getCIRLinkageVarDefinition(vd));
1240 mlir::Value getGlobVal = builder.createGetGlobal(var);
1241 auto getGlob = getGlobVal.getDefiningOp<cir::GetGlobalOp>();
1242 getGlob.setStaticLocal(var.getDynamicInitGuard().has_value());
1243 getGlob.setTls(vd->getTLSKind() != VarDecl::TLS_None);
1244 addr = Address(cgm.castGlobalToDeclAddrSpace(getGlob, *vd),
1245 convertTypeForMem(vd->getType()),
1246 getContext().getDeclAlign(vd));
1247 } else {
1248 llvm_unreachable("DeclRefExpr for Decl not entered in localDeclMap?");
1249 }
1250
1251 // Drill into reference types.
1252 LValue lv =
1253 vd->getType()->isReferenceType()
1257
1258 // Statics are defined as globals, so they are not include in the function's
1259 // symbol table.
1260 assert((vd->isStaticLocal() || symbolTable.count(vd)) &&
1261 "non-static locals should be already mapped");
1262
1263 return lv;
1264 }
1265
1266 if (const auto *bd = dyn_cast<BindingDecl>(nd)) {
1268 FieldDecl *fd = lambdaCaptureFields.lookup(bd);
1269 return emitCapturedFieldLValue(*this, fd, cxxabiThisValue);
1270 }
1271 return emitLValue(bd->getBinding());
1272 }
1273
1274 if (const auto *fd = dyn_cast<FunctionDecl>(nd)) {
1275 LValue lv = emitFunctionDeclLValue(*this, e, fd);
1276
1277 // Emit debuginfo for the function declaration if the target wants to.
1278 if (getContext().getTargetInfo().allowDebugInfoForExternalRef())
1280
1281 return lv;
1282 }
1283 if (isa<MSGuidDecl>(nd))
1284 cgm.errorNYI(e->getSourceRange(),
1285 "emitDeclRefLValue: unhandled MS Guid Decl");
1286
1287 if (const auto *tpo = dyn_cast<TemplateParamObjectDecl>(nd)) {
1288 CharUnits alignment = cgm.getNaturalTypeAlignment(tpo->getType());
1289 cir::GetGlobalOp atpo =
1290 builder.createGetGlobal(cgm.getAddrOfTemplateParamObject(tpo));
1292 "Do an address space conversion if necessary");
1293
1294 return makeAddrLValue(
1295 Address(atpo, convertTypeForMem(tpo->getType()), alignment), ty,
1297 }
1298
1299 llvm_unreachable("Unhandled DeclRefExpr");
1300}
1301
1303 QualType boolTy = getContext().BoolTy;
1304 SourceLocation loc = e->getExprLoc();
1305
1307 if (e->getType()->getAs<MemberPointerType>()) {
1308 cgm.errorNYI(e->getSourceRange(),
1309 "evaluateExprAsBool: member pointer type");
1310 return createDummyValue(getLoc(loc), boolTy);
1311 }
1312
1313 CIRGenFunction::CIRGenFPOptionsRAII FPOptsRAII(*this, e);
1314 if (!e->getType()->isAnyComplexType())
1315 return emitScalarConversion(emitScalarExpr(e), e->getType(), boolTy, loc);
1316
1318 loc);
1319}
1320
1322 UnaryOperatorKind op = e->getOpcode();
1323
1324 // __extension__ doesn't affect lvalue-ness.
1325 if (op == UO_Extension)
1326 return emitLValue(e->getSubExpr());
1327
1328 switch (op) {
1329 case UO_Deref: {
1331 assert(!t.isNull() && "CodeGenFunction::EmitUnaryOpLValue: Illegal type");
1332
1334 LValueBaseInfo baseInfo;
1335 Address addr = emitPointerWithAlignment(e->getSubExpr(), &baseInfo);
1336
1337 // Tag 'load' with deref attribute.
1338 // FIXME: This misses some derefence cases and has problematic interactions
1339 // with other operators.
1340 if (auto loadOp = addr.getDefiningOp<cir::LoadOp>())
1341 loadOp.setIsDerefAttr(mlir::UnitAttr::get(&getMLIRContext()));
1342
1343 LValue lv = makeAddrLValue(addr, t, baseInfo);
1346 return lv;
1347 }
1348 case UO_Real:
1349 case UO_Imag: {
1350 LValue lv = emitLValue(e->getSubExpr());
1351 assert(lv.isSimple() && "real/imag on non-ordinary l-value");
1352
1353 // __real is valid on scalars. This is a faster way of testing that.
1354 // __imag can only produce an rvalue on scalars.
1355 if (e->getOpcode() == UO_Real &&
1356 !mlir::isa<cir::ComplexType>(lv.getAddress().getElementType())) {
1357 assert(e->getSubExpr()->getType()->isArithmeticType());
1358 return lv;
1359 }
1360
1362 QualType elemTy = exprTy->castAs<clang::ComplexType>()->getElementType();
1363 mlir::Location loc = getLoc(e->getExprLoc());
1364 Address component =
1365 e->getOpcode() == UO_Real
1366 ? builder.createComplexRealPtr(loc, lv.getAddress())
1367 : builder.createComplexImagPtr(loc, lv.getAddress());
1369 LValue elemLV = makeAddrLValue(component, elemTy);
1370 elemLV.getQuals().addQualifiers(lv.getQuals());
1371 return elemLV;
1372 }
1373 case UO_PreInc:
1374 case UO_PreDec: {
1375 LValue lv = emitLValue(e->getSubExpr());
1376
1377 assert(e->isPrefix() && "Prefix operator in unexpected state!");
1378
1379 if (e->getType()->isAnyComplexType())
1381 else
1383
1384 return lv;
1385 }
1386 case UO_Extension:
1387 llvm_unreachable("UnaryOperator extension should be handled above!");
1388 case UO_Plus:
1389 case UO_Minus:
1390 case UO_Not:
1391 case UO_LNot:
1392 case UO_AddrOf:
1393 case UO_PostInc:
1394 case UO_PostDec:
1395 case UO_Coawait:
1396 llvm_unreachable("UnaryOperator of non-lvalue kind!");
1397 }
1398 llvm_unreachable("Unknown unary operator kind!");
1399}
1400
1401/// If the specified expr is a simple decay from an array to pointer,
1402/// return the array subexpression.
1403/// FIXME: this could be abstracted into a common AST helper.
1404static const Expr *getSimpleArrayDecayOperand(const Expr *e) {
1405 // If this isn't just an array->pointer decay, bail out.
1406 const auto *castExpr = dyn_cast<CastExpr>(e);
1407 if (!castExpr || castExpr->getCastKind() != CK_ArrayToPointerDecay)
1408 return nullptr;
1409
1410 // If this is a decay from variable width array, bail out.
1411 const Expr *subExpr = castExpr->getSubExpr();
1412 if (subExpr->getType()->isVariableArrayType())
1413 return nullptr;
1414
1415 return subExpr;
1416}
1417
1418static cir::IntAttr getConstantIndexOrNull(mlir::Value idx) {
1419 // TODO(cir): should we consider using MLIRs IndexType instead of IntegerAttr?
1420 if (auto constantOp = idx.getDefiningOp<cir::ConstantOp>())
1421 return constantOp.getValueAttr<cir::IntAttr>();
1422 return {};
1423}
1424
1425static CharUnits getArrayElementAlign(CharUnits arrayAlign, mlir::Value idx,
1426 CharUnits eltSize) {
1427 // If we have a constant index, we can use the exact offset of the
1428 // element we're accessing.
1429 if (const cir::IntAttr constantIdx = getConstantIndexOrNull(idx)) {
1430 const CharUnits offset = constantIdx.getValue().getZExtValue() * eltSize;
1431 return arrayAlign.alignmentAtOffset(offset);
1432 }
1433 // Otherwise, use the worst-case alignment for any element.
1434 return arrayAlign.alignmentOfArrayElement(eltSize);
1435}
1436
1437/// Return true if \p ptr is derived from a cir.alloca through cir.get_element,
1438/// cir.ptr_stride, or a cir.cast that is array_to_ptrdecay or for which
1439/// isAllocaPreservingCast() holds, so the alloca is its underlying object.
1440static bool isBasedOnAlloca(mlir::Value ptr) {
1441 while (mlir::Operation *op = ptr.getDefiningOp()) {
1442 if (mlir::isa<cir::AllocaOp>(op))
1443 return true;
1444 if (auto elementOp = mlir::dyn_cast<cir::GetElementOp>(op))
1445 ptr = elementOp.getBase();
1446 else if (auto strideOp = mlir::dyn_cast<cir::PtrStrideOp>(op))
1447 ptr = strideOp.getBase();
1448 else if (auto castOp = mlir::dyn_cast<cir::CastOp>(op);
1449 castOp && (castOp.isAllocaPreservingCast() ||
1450 castOp.getKind() == cir::CastKind::array_to_ptrdecay))
1451 ptr = castOp.getSrc();
1452 else
1453 return false;
1454 }
1455 return false;
1456}
1457
1458/// Return the no-wrap flags for an array subscript of \p ptr: none when
1459/// pointer overflow is defined, otherwise inbounds unless \p ptr may come from
1460/// an OpenMP section map, plus nuw unless \p signedIndices.
1462 mlir::Value ptr,
1463 bool signedIndices) {
1464 if (cgf.getLangOpts().PointerOverflowDefined)
1466
1467 // An OpenMP section map passes `section - host_offset`, which can point
1468 // outside the mapped allocation, so a subscript of an array of arrays based
1469 // on it cannot be marked inbounds. A base derived from a cir.alloca is
1470 // never such a pointer.
1471 auto arrayTy = mlir::dyn_cast<cir::ArrayType>(
1472 mlir::cast<cir::PointerType>(ptr.getType()).getPointee());
1473 bool isSectionSubscript =
1474 cgf.getLangOpts().OpenMPIsTargetDevice && arrayTy &&
1475 mlir::isa<cir::ArrayType>(arrayTy.getElementType()) &&
1476 !isBasedOnAlloca(ptr);
1477
1479 if (!isSectionSubscript)
1481 if (!signedIndices)
1483 return flags;
1484}
1485
1487 mlir::Location beginLoc,
1488 mlir::Location endLoc, mlir::Value ptr,
1489 mlir::Type eltTy, mlir::Value idx,
1490 bool signedIndices, bool shouldDecay) {
1491 CIRGenModule &cgm = cgf.getCIRGenModule();
1493 return cgm.getBuilder().getArrayElement(
1494 beginLoc, endLoc, ptr, eltTy, idx, shouldDecay,
1495 getArraySubscriptFlags(cgf, ptr, signedIndices));
1496}
1497
1499 mlir::Location beginLoc,
1500 mlir::Location endLoc, Address addr,
1501 QualType eltType, mlir::Value idx,
1502 mlir::Location loc, bool signedIndices,
1503 bool shouldDecay) {
1504
1505 // Determine the element size of the statically-sized base. This is
1506 // the thing that the indices are expressed in terms of.
1507 if (const VariableArrayType *vla =
1508 cgf.getContext().getAsVariableArrayType(eltType)) {
1510 }
1511
1512 // We can use that to compute the best alignment of the element.
1513 const CharUnits eltSize = cgf.getContext().getTypeSizeInChars(eltType);
1514 const CharUnits eltAlign =
1515 getArrayElementAlign(addr.getAlignment(), idx, eltSize);
1516
1518 const mlir::Value eltPtr = emitArraySubscriptPtr(
1519 cgf, beginLoc, endLoc, addr.getPointer(), addr.getElementType(), idx,
1520 signedIndices, shouldDecay);
1521 const mlir::Type elementType = cgf.convertTypeForMem(eltType);
1522 return Address(eltPtr, elementType, eltAlign);
1523}
1524
1525LValue
1527 if (e->getType()->getAs<ObjCObjectType>()) {
1528 cgm.errorNYI(e->getSourceRange(), "emitArraySubscriptExpr: ObjCObjectType");
1530 }
1531
1532 // The index must always be an integer, which is not an aggregate. Emit it
1533 // in lexical order (this complexity is, sadly, required by C++17).
1534 mlir::Value idxPre = (e->getLHS() == e->getIdx())
1535 ? emitScalarExpr(e->getIdx())
1536 : mlir::Value();
1537 const bool signedIndices =
1539
1540 auto emitIdxAfterBase = [&, idxPre](bool promote) -> mlir::Value {
1541 mlir::Value idx = idxPre;
1542 if (e->getLHS() != e->getIdx()) {
1543 assert(e->getRHS() == e->getIdx() && "index was neither LHS nor RHS");
1544 idx = emitScalarExpr(e->getIdx());
1545 }
1546
1548
1549 // Extend or truncate the index type to pointer-sized integer.
1550 if (promote) {
1551 // Choose the type we extend or truncate to based on the signedness of the
1552 // index type.
1553 mlir::Type desiredIdxTy = signedIndices ? ptrDiffTy : uIntPtrTy;
1554
1555 if (idx.getType() != desiredIdxTy) {
1556 cir::CastKind kind = mlir::isa<cir::BoolType>(idx.getType())
1557 ? cir::CastKind::bool_to_int
1558 : cir::CastKind::integral;
1559 idx = builder.createOrFold<cir::CastOp>(idx.getLoc(), desiredIdxTy,
1560 kind, idx);
1561 }
1562 }
1563
1564 return idx;
1565 };
1566 // This is captured by value above, using it after this is an error, so clear
1567 // it to make sure no one is depending on it (mirrors classic codegen).
1568 idxPre = mlir::Value();
1569
1570 // If the base is a vector type, then we are forming a vector element
1571 // with this subscript.
1572 if (e->getBase()->getType()->isSubscriptableVectorType() &&
1574 const LValue lv = emitLValue(e->getBase());
1575 const mlir::Value idx = emitIdxAfterBase(/*promote=*/false);
1576 return LValue::makeVectorElt(lv.getAddress(), idx, e->getBase()->getType(),
1577 lv.getBaseInfo());
1578 }
1579
1580 // The HLSL runtime handles subscript expressions on global resource arrays
1581 // and objects with HLSL buffer layouts.
1582 if (getLangOpts().HLSL) {
1583 cgm.errorNYI(e->getSourceRange(), "emitArraySubscriptExpr: HLSL");
1584 return {};
1585 }
1586
1587 // Handle the extvector case we ignored above.
1589 const LValue lv = emitLValue(e->getBase());
1590 const mlir::Value idx = emitIdxAfterBase(/*promote=*/true);
1591 Address addr = emitExtVectorElementLValue(lv, cgm.getLoc(e->getExprLoc()));
1592
1593 QualType elementType = lv.getType()->castAs<VectorType>()->getElementType();
1594 addr = emitArraySubscriptPtr(*this, cgm.getLoc(e->getBeginLoc()),
1595 cgm.getLoc(e->getEndLoc()), addr, e->getType(),
1596 idx, cgm.getLoc(e->getExprLoc()),
1597 signedIndices, /*shouldDecay=*/false);
1598
1599 return makeAddrLValue(addr, elementType, lv.getBaseInfo());
1600 }
1601
1602 if (const VariableArrayType *vla =
1603 getContext().getAsVariableArrayType(e->getType())) {
1604 // The base must be a pointer, which is not an aggregate. Emit
1605 // it. It needs to be emitted first in case it's what captures
1606 // the VLA bounds.
1608 mlir::Value idx = emitIdxAfterBase(/*promote=*/true);
1609
1610 // The element count here is the total number of non-VLA elements.
1611 mlir::Value numElements = getVLASize(vla).numElts;
1612 idx = builder.createIntCast(idx, numElements.getType());
1613
1614 // Effectively, the multiply by the VLA size is part of the GEP.
1615 // GEP indexes are signed, and scaling an index isn't permitted to
1616 // signed-overflow, so we use the same semantics for our explicit
1617 // multiply. We suppress this if overflow is not undefined behavior.
1618 cir::OverflowFlags overflowFlags = getLangOpts().PointerOverflowDefined
1619 ? cir::OverflowFlags::None
1620 : cir::OverflowFlags::NoSignedWrap;
1621 idx = builder.createMul(cgm.getLoc(e->getExprLoc()), idx, numElements,
1622 overflowFlags);
1623
1624 addr = emitArraySubscriptPtr(*this, cgm.getLoc(e->getBeginLoc()),
1625 cgm.getLoc(e->getEndLoc()), addr, e->getType(),
1626 idx, cgm.getLoc(e->getExprLoc()),
1627 signedIndices, /*shouldDecay=*/false);
1628
1629 return makeAddrLValue(addr, vla->getElementType(), LValueBaseInfo());
1630 }
1631
1632 if (const Expr *array = getSimpleArrayDecayOperand(e->getBase())) {
1633 LValue arrayLV;
1634 if (const auto *ase = dyn_cast<ArraySubscriptExpr>(array))
1635 arrayLV = emitArraySubscriptExpr(ase);
1636 else
1637 arrayLV = emitLValue(array);
1638 mlir::Value idx = emitIdxAfterBase(/*promote=*/true);
1639
1640 // Propagate the alignment from the array itself to the result.
1641 const Address addr = emitArraySubscriptPtr(
1642 *this, cgm.getLoc(array->getBeginLoc()), cgm.getLoc(array->getEndLoc()),
1643 arrayLV.getAddress(), e->getType(), idx, cgm.getLoc(e->getExprLoc()),
1644 signedIndices, /*shouldDecay=*/true);
1645
1646 const LValue lv = LValue::makeAddr(addr, e->getType(), LValueBaseInfo());
1647
1648 if (getLangOpts().ObjC && getLangOpts().getGC() != LangOptions::NonGC) {
1649 cgm.errorNYI(e->getSourceRange(), "emitArraySubscriptExpr: ObjC with GC");
1650 }
1651
1652 return lv;
1653 }
1654
1655 // The base must be a pointer; emit it with an estimate of its alignment.
1656 assert(e->getBase()->getType()->isPointerType() &&
1657 "The base must be a pointer");
1658
1659 LValueBaseInfo eltBaseInfo;
1660 const Address ptrAddr = emitPointerWithAlignment(e->getBase(), &eltBaseInfo);
1661 const mlir::Value idx = emitIdxAfterBase(/*promote=*/true);
1662 // Propagate the alignment from the array itself to the result.
1663 const Address addxr = emitArraySubscriptPtr(
1664 *this, cgm.getLoc(e->getBeginLoc()), cgm.getLoc(e->getEndLoc()), ptrAddr,
1665 e->getType(), idx, cgm.getLoc(e->getExprLoc()), signedIndices,
1666 /*shouldDecay=*/false);
1667
1668 const LValue lv = LValue::makeAddr(addxr, e->getType(), eltBaseInfo);
1669
1670 if (getLangOpts().ObjC && getLangOpts().getGC() != LangOptions::NonGC) {
1671 cgm.errorNYI(e->getSourceRange(), "emitArraySubscriptExpr: ObjC with GC");
1672 }
1673
1674 return lv;
1675}
1676
1678 assert(!e->isIncomplete() &&
1679 "incomplete matrix subscript expressions should be rejected in Sema");
1680 LValue base = emitLValue(e->getBase());
1681 mlir::Value rowIdx = emitScalarExpr(e->getRowIdx());
1682 mlir::Value colIdx = emitScalarExpr(e->getColumnIdx());
1683
1685 cgm.errorNYI(e->getSourceRange(),
1686 "emitMatrixSubscriptExpr: row-major matrix");
1687
1688 return LValue::makeMatrixElt(base.getAddress(), rowIdx, colIdx,
1689 e->getBase()->getType(), base.getBaseInfo());
1690}
1691
1693 // Emit the base vector as an l-value.
1694 LValue base;
1695
1696 // ExtVectorElementExpr's base can either be a vector or pointer to vector.
1697 if (e->isArrow()) {
1698 // If it is a pointer to a vector, emit the address and form an lvalue with
1699 // it.
1700 LValueBaseInfo baseInfo;
1701 Address ptr = emitPointerWithAlignment(e->getBase(), &baseInfo);
1702 const auto *clangPtrTy =
1704 base = makeAddrLValue(ptr, clangPtrTy->getPointeeType(), baseInfo);
1705 base.getQuals().removeObjCGCAttr();
1706 } else if (e->getBase()->isGLValue()) {
1707 // Otherwise, if the base is an lvalue ( as in the case of foo.x.x),
1708 // emit the base as an lvalue.
1709 assert(e->getBase()->getType()->isVectorType());
1710 base = emitLValue(e->getBase());
1711 } else {
1712 // Otherwise, the base is a normal rvalue (as in (V+V).x), emit it as such.
1713 assert(e->getBase()->getType()->isVectorType() &&
1714 "Result must be a vector");
1715 mlir::Value vec = emitScalarExpr(e->getBase());
1716
1717 // Store the vector to memory (because LValue wants an address).
1718 QualType baseTy = e->getBase()->getType();
1719 Address vecMem = createMemTemp(baseTy, vec.getLoc(), "tmp");
1720 if (!getLangOpts().HLSL && baseTy->isExtVectorBoolType()) {
1721 cgm.errorNYI(e->getSourceRange(),
1722 "emitExtVectorElementExpr: ExtVectorBoolType & !HLSL");
1723 return {};
1724 }
1725 builder.createStore(vec.getLoc(), vec, vecMem);
1726 base = makeAddrLValue(vecMem, baseTy, AlignmentSource::Decl);
1727 }
1728
1729 QualType type =
1731
1732 // Encode the element access list into a vector of unsigned indices.
1734 e->getEncodedElementAccess(indices);
1735
1736 if (base.isSimple()) {
1737 SmallVector<int64_t> attrElts(indices.begin(), indices.end());
1738 mlir::ArrayAttr elts = builder.getI64ArrayAttr(attrElts);
1739 return LValue::makeExtVectorElt(base.getAddress(), elts, type,
1740 base.getBaseInfo());
1741 }
1742
1743 if (base.isMatrixRow()) {
1744 cgm.errorNYI(e->getSourceRange(), "emitExtVectorElementExpr: isMatrixRow");
1745 return {};
1746 }
1747
1748 assert(base.isExtVectorElt() && "Can only subscript lvalue vec elts here!");
1749 mlir::ArrayAttr baseElts = base.getExtVectorElts();
1751 for (unsigned idx : indices)
1752 elts.push_back(getAccessedFieldNo(idx, baseElts));
1753 mlir::ArrayAttr cv = builder.getI64ArrayAttr(elts);
1754 return LValue::makeExtVectorElt(base.getAddress(), cv, type,
1755 base.getBaseInfo());
1756}
1757
1759 LValue base;
1760 if (e->getBase()->isGLValue()) {
1761 base = emitLValue(e->getBase());
1762 } else {
1763 cgm.errorNYI(e->getSourceRange(), "emitMatrixElementExpr base not GLValue");
1764 return {};
1765 }
1766
1767 QualType resultType =
1769
1770 // Encode the element access list into a vector of unsigned indices.
1771 // getEncodedElementAccess returns row-major linearized indices.
1773 e->getEncodedElementAccess(indices);
1774
1775 // getEncodedElementAccess returns row-major linearized indices
1776 // If the matrix memory layout is column-major, convert indices
1777 // to column-major indices.
1778 bool isRowMajor = isMatrixRowMajor(getLangOpts(), e->getBase()->getType());
1779 if (!isRowMajor) {
1780 const auto *matrixTy =
1782 unsigned numCols = matrixTy->getNumColumns();
1783 for (uint32_t &idx : indices) {
1784 // Decompose row-major index: Row = Idx / NumCols, Col = Idx % NumCols
1785 unsigned row = idx / numCols;
1786 unsigned column = idx % numCols;
1787 // Re-linearize as column-major
1788 idx = matrixTy->getColumnMajorFlattenedIndex(row, column);
1789 }
1790 }
1791
1792 if (base.isSimple()) {
1793 Address matrixAddr = base.getAddress();
1794 if (getLangOpts().HLSL &&
1796 cgm.errorNYI(
1797 e->getSourceRange(),
1798 "emitMatrixElementExpr simple & HLSL address space hlsl_constant");
1799 return {};
1800 }
1801
1802 SmallVector<int64_t> attrElts(indices.begin(), indices.end());
1803 mlir::ArrayAttr elts = builder.getI64ArrayAttr(attrElts);
1804 return LValue::makeExtVectorElt(matrixAddr, elts, resultType,
1805 base.getBaseInfo());
1806 }
1807
1808 cgm.errorNYI(e->getSourceRange(), "emitMatrixElementExpr not simple");
1809 return {};
1810}
1811
1813 llvm::StringRef name) {
1814 cir::GlobalOp globalOp = cgm.getGlobalForStringLiteral(e, name);
1815 assert(globalOp.getAlignment() && "expected alignment for string literal");
1816 unsigned align = *(globalOp.getAlignment());
1817 mlir::Value addr =
1818 builder.createGetGlobal(getLoc(e->getSourceRange()), globalOp);
1819 mlir::ptr::MemorySpaceAttrInterface destAS =
1820 cgm.getTypes().getPointerAddressSpace(e->getType());
1821 if (mlir::cast<cir::PointerType>(addr.getType()).getAddrSpace() != destAS)
1822 addr = performAddrSpaceCast(
1823 addr, builder.getPointerTo(globalOp.getSymType(), destAS));
1824 return makeAddrLValue(
1825 Address(addr, globalOp.getSymType(), CharUnits::fromQuantity(align)),
1827}
1828
1829/// Casts are never lvalues unless that cast is to a reference type. If the cast
1830/// is to a reference, we can have the usual lvalue result, otherwise if a cast
1831/// is needed by the code generator in an lvalue context, then it must mean that
1832/// we need the address of an aggregate in order to access one of its members.
1833/// This can happen for all the reasons that casts are permitted with aggregate
1834/// result, including noop aggregate casts, and cast from scalar to union.
1836 switch (e->getCastKind()) {
1837 case CK_ToVoid:
1838 case CK_BitCast:
1839 case CK_LValueToRValueBitCast:
1840 case CK_ArrayToPointerDecay:
1841 case CK_FunctionToPointerDecay:
1842 case CK_NullToMemberPointer:
1843 case CK_NullToPointer:
1844 case CK_IntegralToPointer:
1845 case CK_PointerToIntegral:
1846 case CK_PointerToBoolean:
1847 case CK_IntegralCast:
1848 case CK_BooleanToSignedIntegral:
1849 case CK_IntegralToBoolean:
1850 case CK_IntegralToFloating:
1851 case CK_FloatingToIntegral:
1852 case CK_FloatingToBoolean:
1853 case CK_FloatingCast:
1854 case CK_FloatingRealToComplex:
1855 case CK_FloatingComplexToReal:
1856 case CK_FloatingComplexToBoolean:
1857 case CK_FloatingComplexCast:
1858 case CK_FloatingComplexToIntegralComplex:
1859 case CK_IntegralRealToComplex:
1860 case CK_IntegralComplexToReal:
1861 case CK_IntegralComplexToBoolean:
1862 case CK_IntegralComplexCast:
1863 case CK_IntegralComplexToFloatingComplex:
1864 case CK_DerivedToBaseMemberPointer:
1865 case CK_BaseToDerivedMemberPointer:
1866 case CK_MemberPointerToBoolean:
1867 case CK_ReinterpretMemberPointer:
1868 case CK_AnyPointerToBlockPointerCast:
1869 case CK_ARCProduceObject:
1870 case CK_ARCConsumeObject:
1871 case CK_ARCReclaimReturnedObject:
1872 case CK_ARCExtendBlockObject:
1873 case CK_CopyAndAutoreleaseBlockObject:
1874 case CK_IntToOCLSampler:
1875 case CK_FloatingToFixedPoint:
1876 case CK_FixedPointToFloating:
1877 case CK_FixedPointCast:
1878 case CK_FixedPointToBoolean:
1879 case CK_FixedPointToIntegral:
1880 case CK_IntegralToFixedPoint:
1881 case CK_MatrixCast:
1882 case CK_HLSLVectorTruncation:
1883 case CK_HLSLMatrixTruncation:
1884 case CK_HLSLArrayRValue:
1885 case CK_HLSLElementwiseCast:
1886 case CK_HLSLAggregateSplatCast:
1887 llvm_unreachable("unexpected cast lvalue");
1888
1889 case CK_Dependent:
1890 llvm_unreachable("dependent cast kind in IR gen!");
1891
1892 case CK_BuiltinFnToFnPtr:
1893 llvm_unreachable("builtin functions are handled elsewhere");
1894
1895 case CK_Dynamic: {
1896 LValue lv = emitLValue(e->getSubExpr());
1897 Address v = lv.getAddress();
1898 const auto *dce = cast<CXXDynamicCastExpr>(e);
1900 }
1901
1902 // These are never l-values; just use the aggregate emission code.
1903 case CK_ToUnion:
1904 return emitAggExprToLValue(e);
1905
1906 case CK_ConstructorConversion:
1907 case CK_UserDefinedConversion:
1908 case CK_CPointerToObjCPointerCast:
1909 case CK_BlockPointerToObjCPointerCast:
1910 case CK_LValueToRValue:
1911 return emitLValue(e->getSubExpr());
1912
1913 case CK_NonAtomicToAtomic:
1914 case CK_AtomicToNonAtomic:
1915 case CK_ObjCObjectLValueCast:
1916 case CK_VectorSplat: {
1917 return emitLValue(e->getSubExpr());
1918 }
1919
1920 case CK_AddressSpaceConversion: {
1921 LValue lv = emitLValue(e->getSubExpr());
1922 QualType destTy = getContext().getPointerType(e->getType());
1923
1924 mlir::Value v = performAddrSpaceCast(lv.getPointer(), convertType(destTy));
1925
1927 lv.getAddress().getAlignment()),
1928 e->getType(), lv.getBaseInfo());
1929 }
1930
1931 case CK_LValueBitCast: {
1932 // This must be a reinterpret_cast (or c-style equivalent).
1933 const auto *ce = cast<ExplicitCastExpr>(e);
1934
1935 cgm.emitExplicitCastExprType(ce, this);
1936 LValue LV = emitLValue(e->getSubExpr());
1938 builder, convertTypeForMem(ce->getTypeAsWritten()->getPointeeType()));
1939
1940 return makeAddrLValue(V, e->getType(), LV.getBaseInfo());
1941 }
1942
1943 case CK_NoOp: {
1944 // CK_NoOp can model a qualification conversion, which can remove an array
1945 // bound and change the IR type.
1946 LValue lv = emitLValue(e->getSubExpr());
1947 // Propagate the volatile qualifier to LValue, if exists in e.
1949 lv.getQuals() = e->getType().getQualifiers();
1950 if (lv.isSimple()) {
1951 Address v = lv.getAddress();
1952 if (v.isValid()) {
1953 mlir::Type ty = convertTypeForMem(e->getType());
1954 if (v.getElementType() != ty) {
1955 // We have only inspected/reproduced this with complete to incomplete
1956 // array types, so we do an NYI for other cases, so we can make sure
1957 // we're doing a conversion we want to be making.
1958 auto fromTy = dyn_cast<cir::ArrayType>(v.getElementType());
1959 auto toTy = dyn_cast<cir::ArrayType>(ty);
1960 if (!fromTy || !toTy ||
1961 fromTy.getElementType() != toTy.getElementType() ||
1962 toTy.getSize() != 0)
1963 cgm.errorNYI(e->getSourceRange(),
1964 "emitCastLValue NoOp not array-shrink case");
1965
1966 lv = makeAddrLValue(v.withElementType(builder, ty), e->getType(),
1967 lv.getBaseInfo());
1968 }
1969 }
1970 }
1971 return lv;
1972 }
1973
1974 case CK_UncheckedDerivedToBase:
1975 case CK_DerivedToBase: {
1976 auto *derivedClassDecl = e->getSubExpr()->getType()->castAsCXXRecordDecl();
1977
1978 LValue lv = emitLValue(e->getSubExpr());
1979 Address thisAddr = lv.getAddress();
1980
1981 // Perform the derived-to-base conversion
1982 Address baseAddr =
1983 getAddressOfBaseClass(thisAddr, derivedClassDecl, e->path(),
1984 /*NullCheckValue=*/false, e->getExprLoc());
1985
1986 // TODO: Support accesses to members of base classes in TBAA. For now, we
1987 // conservatively pretend that the complete object is of the base class
1988 // type.
1990 return makeAddrLValue(baseAddr, e->getType(), lv.getBaseInfo());
1991 }
1992
1993 case CK_BaseToDerived: {
1994 const auto *derivedClassDecl = e->getType()->castAsCXXRecordDecl();
1995 LValue lv = emitLValue(e->getSubExpr());
1996
1997 // Perform the base-to-derived conversion
1999 getLoc(e->getSourceRange()), lv.getAddress(), derivedClassDecl,
2000 e->path(), /*NullCheckValue=*/false);
2001 // C++11 [expr.static.cast]p2: Behavior is undefined if a downcast is
2002 // performed and the object is not of the derived type.
2004
2006 return makeAddrLValue(derived, e->getType(), lv.getBaseInfo());
2007 }
2008
2009 case CK_ZeroToOCLOpaqueType:
2010 llvm_unreachable("NULL to OpenCL opaque type lvalue cast is not valid");
2011 }
2012
2013 llvm_unreachable("Invalid cast kind");
2014}
2015
2017 const MemberExpr *me) {
2018 if (auto *vd = dyn_cast<VarDecl>(me->getMemberDecl())) {
2019 // Try to emit static variable member expressions as DREs.
2020 return DeclRefExpr::Create(
2022 /*RefersToEnclosingVariableOrCapture=*/false, me->getExprLoc(),
2023 me->getType(), me->getValueKind(), nullptr, nullptr, me->isNonOdrUse());
2024 }
2025 return nullptr;
2026}
2027
2029 if (DeclRefExpr *dre = tryToConvertMemberExprToDeclRefExpr(*this, e)) {
2031 return emitDeclRefLValue(dre);
2032 }
2033
2034 Expr *baseExpr = e->getBase();
2035 // If this is s.x, emit s as an lvalue. If it is s->x, emit s as a scalar.
2036 LValue baseLV;
2037 if (e->isArrow()) {
2038 LValueBaseInfo baseInfo;
2040 Address addr = emitPointerWithAlignment(baseExpr, &baseInfo);
2041 QualType ptrTy = baseExpr->getType()->getPointeeType();
2043 baseLV = makeAddrLValue(addr, ptrTy, baseInfo);
2044 } else {
2046 baseLV = emitLValue(baseExpr);
2047 }
2048
2049 const NamedDecl *nd = e->getMemberDecl();
2050 if (auto *field = dyn_cast<FieldDecl>(nd)) {
2051 LValue lv = emitLValueForField(baseLV, field);
2053 if (getLangOpts().OpenMP) {
2054 // If the member was explicitly marked as nontemporal, mark it as
2055 // nontemporal. If the base lvalue is marked as nontemporal, mark access
2056 // to children as nontemporal too.
2058 if (baseLV.isNontemporal())
2059 lv.setNontemporal(true);
2060 }
2061 return lv;
2062 }
2063
2064 if (const auto *fd = dyn_cast<FunctionDecl>(nd))
2065 return emitFunctionDeclLValue(*this, e, fd);
2066
2067 llvm_unreachable("Unhandled member declaration!");
2068}
2069
2070/// Evaluate an expression into a given memory location.
2072 Qualifiers quals, bool isInit) {
2073 // FIXME: This function should take an LValue as an argument.
2074 switch (getEvaluationKind(e->getType())) {
2075 case cir::TEK_Complex: {
2076 LValue lv = makeAddrLValue(location, e->getType());
2077 emitComplexExprIntoLValue(e, lv, isInit);
2078 return;
2079 }
2080
2081 case cir::TEK_Aggregate: {
2082 emitAggExpr(e, AggValueSlot::forAddr(location, quals,
2086 return;
2087 }
2088
2089 case cir::TEK_Scalar: {
2091 LValue lv = makeAddrLValue(location, e->getType());
2092 emitStoreThroughLValue(rv, lv);
2093 return;
2094 }
2095 }
2096
2097 llvm_unreachable("bad evaluation kind");
2098}
2099
2101 const MaterializeTemporaryExpr *m,
2102 const Expr *inner) {
2103 // TODO(cir): cgf.getTargetHooks();
2104 switch (m->getStorageDuration()) {
2105 case SD_FullExpression:
2106 case SD_Automatic: {
2107 QualType ty = inner->getType();
2108
2110
2111 // The temporary memory should be created in the same scope as the extending
2112 // declaration of the temporary materialization expression.
2113 cir::AllocaOp extDeclAlloca;
2114 if (const ValueDecl *extDecl = m->getExtendingDecl()) {
2115 auto extDeclAddrIter = cgf.localDeclMap.find(extDecl);
2116 if (extDeclAddrIter != cgf.localDeclMap.end())
2117 extDeclAlloca = extDeclAddrIter->second.getUnderlyingAllocaOp();
2118 }
2119 mlir::OpBuilder::InsertPoint ip;
2120 if (extDeclAlloca) {
2121 ip = {extDeclAlloca->getBlock(), extDeclAlloca->getIterator()};
2122 } else if (cgf.isInConditionalBranch() &&
2124 // Place in the function entry block so the alloca dominates both
2125 // regions of any enclosing cir.cleanup.scope. The default path
2126 // would use curLexScope which may be a ternary branch.
2129 }
2130 return cgf.createMemTemp(ty, cgf.getLoc(m->getSourceRange()),
2131 cgf.getCounterRefTmpAsString(), /*alloca=*/nullptr,
2132 ip);
2133 }
2134 case SD_Thread:
2135 case SD_Static: {
2136 auto addr =
2137 mlir::cast<cir::GlobalOp>(cgf.cgm.getAddrOfGlobalTemporary(m, inner));
2138 auto getGlobal = cgf.cgm.getBuilder().createGetGlobal(addr);
2139 assert(addr.getAlignment().has_value() &&
2140 "This should always have an alignment");
2141 return Address(getGlobal,
2142 clang::CharUnits::fromQuantity(addr.getAlignment().value()));
2143 }
2144
2145 case SD_Dynamic:
2146 llvm_unreachable("temporary can't have dynamic storage duration");
2147 }
2148 llvm_unreachable("unknown storage duration");
2149}
2150
2152 const MaterializeTemporaryExpr *m,
2153 const Expr *e, Address referenceTemporary) {
2154 // Objective-C++ ARC:
2155 // If we are binding a reference to a temporary that has ownership, we
2156 // need to perform retain/release operations on the temporary.
2157 //
2158 // FIXME(ogcg): This should be looking at e, not m.
2159 if (m->getType().getObjCLifetime()) {
2160 cgf.cgm.errorNYI(e->getSourceRange(), "pushTemporaryCleanup: ObjCLifetime");
2161 return;
2162 }
2163
2165 if (dk == QualType::DK_none)
2166 return;
2167
2168 switch (m->getStorageDuration()) {
2169 case SD_Static:
2170 case SD_Thread: {
2171 CXXDestructorDecl *referenceTemporaryDtor = nullptr;
2172 if (const auto *classDecl =
2174 classDecl && !classDecl->hasTrivialDestructor())
2175 // Get the destructor for the reference temporary.
2176 referenceTemporaryDtor = classDecl->getDestructor();
2177
2178 if (!referenceTemporaryDtor)
2179 return;
2180
2181 CIRGenModule &cgm = cgf.cgm;
2182 auto globalOp =
2183 mlir::cast<cir::GlobalOp>(cgm.getAddrOfGlobalTemporary(m, e));
2184
2185 CIRGenBuilderTy &builder = cgm.getBuilder();
2186 mlir::Location loc = cgm.getLoc(m->getSourceRange());
2187 auto registerOp = cir::RegisterExitDtorOp::create(
2188 builder, loc, globalOp.getSymNameAttr().getValue());
2189 mlir::OpBuilder::InsertionGuard guard(builder);
2190 builder.setInsertionPointToStart(
2191 builder.createBlock(&registerOp.getBody()));
2192
2193 mlir::Value tempAddr = builder.createGetGlobal(globalOp);
2194 if (e->getType()->isArrayType()) {
2195 Address addr{tempAddr, cgf.convertTypeForMem(e->getType()),
2196 referenceTemporary.getAlignment()};
2198 } else {
2199 GlobalDecl gd(referenceTemporaryDtor, Dtor_Complete);
2200 cir::FuncOp dtorFn = cgm.getAddrAndTypeOfCXXStructor(gd).second;
2201 // Make sure the call and the callee agree on calling convention.
2202 builder.createCallOp(loc, dtorFn, mlir::ValueRange{tempAddr},
2203 /*attrs=*/{}, /*argAttrs=*/{}, /*resAttrs=*/{},
2204 dtorFn.getCallingConv());
2205 }
2206 cir::YieldOp::create(builder, loc);
2207 break;
2208 }
2209
2210 case SD_FullExpression:
2211 cgf.pushDestroy(NormalAndEHCleanup, referenceTemporary, e->getType(),
2213 break;
2214
2215 case SD_Automatic:
2217 NormalAndEHCleanup, referenceTemporary, e->getType(),
2219 m->getExtendingDecl());
2220 break;
2221
2222 case SD_Dynamic:
2223 llvm_unreachable("temporary cannot have dynamic storage duration");
2224 }
2225}
2226
2228 const MaterializeTemporaryExpr *m) {
2229 const Expr *e = m->getSubExpr();
2230
2231 assert((!m->getExtendingDecl() || !isa<VarDecl>(m->getExtendingDecl()) ||
2232 !cast<VarDecl>(m->getExtendingDecl())->isARCPseudoStrong()) &&
2233 "Reference should never be pseudo-strong!");
2234
2235 // FIXME: ideally this would use emitAnyExprToMem, however, we cannot do so
2236 // as that will cause the lifetime adjustment to be lost for ARC
2237 auto ownership = m->getType().getObjCLifetime();
2238 if (ownership != Qualifiers::OCL_None &&
2239 ownership != Qualifiers::OCL_ExplicitNone) {
2240 cgm.errorNYI(e->getSourceRange(),
2241 "emitMaterializeTemporaryExpr: ObjCLifetime");
2242 return {};
2243 }
2244
2247 e = e->skipRValueSubobjectAdjustments(commaLHSs, adjustments);
2248
2249 for (const Expr *ignored : commaLHSs)
2250 emitIgnoredExpr(ignored);
2251
2252 if (isa<OpaqueValueExpr>(e)) {
2253 cgm.errorNYI(e->getSourceRange(),
2254 "emitMaterializeTemporaryExpr: OpaqueValueExpr");
2255 return {};
2256 }
2257
2258 // Create and initialize the reference temporary.
2259 Address object = createReferenceTemporary(*this, m, e);
2260 cir::GlobalOp var = nullptr;
2261 if (auto getGlobalOp = object.getPointer().getDefiningOp<cir::GetGlobalOp>())
2262 var = mlir::dyn_cast_or_null<cir::GlobalOp>(
2263 cgm.getGlobalValue(getGlobalOp.getName()));
2264
2265 if (var) {
2266 if (!var.getInitialValue().has_value()) {
2267 var.setInitialValueAttr(builder.getZeroInitAttr(var.getSymType()));
2269 emitAnyExprToMem(e, object, Qualifiers(), /*isInitializer=*/true);
2270 }
2271 } else {
2273 emitAnyExprToMem(e, object, Qualifiers(), /*isInitializer=*/true);
2274 }
2275 pushTemporaryCleanup(*this, m, e, object);
2276
2277 // Perform derived-to-base casts and/or field accesses, to get from the
2278 // temporary object we created (and, potentially, for which we extended
2279 // the lifetime) to the subobject we're binding the reference to.
2280 for (SubobjectAdjustment &adjustment : llvm::reverse(adjustments)) {
2281 switch (adjustment.Kind) {
2283 object =
2284 getAddressOfBaseClass(object, adjustment.DerivedToBase.DerivedClass,
2285 adjustment.DerivedToBase.BasePath->path(),
2286 /*nullCheckValue=*/false, e->getExprLoc());
2287 break;
2290 lv = emitLValueForField(lv, adjustment.Field);
2291 assert(lv.isSimple() &&
2292 "materialized temporary field is not a simple lvalue");
2293 object = lv.getAddress();
2294 break;
2295 }
2297 mlir::Value ptr = emitScalarExpr(adjustment.Ptr.RHS);
2299 e, object, ptr, adjustment.Ptr.MPT, /*baseInfo=*/nullptr);
2300 break;
2301 }
2302 }
2303 }
2304
2305 return makeAddrLValue(object, m->getType(), AlignmentSource::Decl);
2306}
2307
2308LValue
2311
2312 auto it = opaqueLValues.find(e);
2313 if (it != opaqueLValues.end())
2314 return it->second;
2315
2316 assert(e->isUnique() && "LValue for a nonunique OVE hasn't been emitted");
2317 return emitLValue(e->getSourceExpr());
2318}
2319
2320RValue
2323
2324 auto it = opaqueRValues.find(e);
2325 if (it != opaqueRValues.end())
2326 return it->second;
2327
2328 assert(e->isUnique() && "RValue for a nonunique OVE hasn't been emitted");
2329 return emitAnyExpr(e->getSourceExpr());
2330}
2331
2333 if (e->isFileScope()) {
2334 cgm.errorNYI(e->getSourceRange(), "emitCompoundLiteralLValue: FileScope");
2335 return {};
2336 }
2337
2338 if (e->getType()->isVariablyModifiedType())
2340
2341 Address declPtr = createMemTemp(e->getType(), getLoc(e->getSourceRange()),
2342 ".compoundliteral");
2343 const Expr *initExpr = e->getInitializer();
2344 LValue result = makeAddrLValue(declPtr, e->getType(), AlignmentSource::Decl);
2345
2346 emitAnyExprToMem(initExpr, declPtr, e->getType().getQualifiers(),
2347 /*Init*/ true);
2348
2349 // Block-scope compound literals are destroyed at the end of the enclosing
2350 // scope in C.
2351 if (!getLangOpts().CPlusPlus && e->getType().isDestructedType()) {
2352 cgm.errorNYI(e->getSourceRange(),
2353 "emitCompoundLiteralLValue: non C++ DestructedType");
2354 return {};
2355 }
2356
2357 return result;
2358}
2359
2361 RValue rv = emitCallExpr(e);
2362
2363 if (!rv.isScalar())
2364 return makeAddrLValue(rv.getAggregateAddress(), e->getType(),
2366
2367 assert(e->getCallReturnType(getContext())->isReferenceType() &&
2368 "Can't have a scalar return unless the return type is a "
2369 "reference type!");
2370
2372}
2373
2374LValue
2383
2386 "binding l-value to type which needs a temporary");
2388 emitCXXConstructExpr(e, slot);
2390}
2391
2393 // Comma expressions just emit their LHS then their RHS as an l-value.
2394 if (e->getOpcode() == BO_Comma) {
2395 emitIgnoredExpr(e->getLHS());
2396 return emitLValue(e->getRHS());
2397 }
2398
2399 if (e->getOpcode() == BO_PtrMemD || e->getOpcode() == BO_PtrMemI)
2401
2402 assert(e->getOpcode() == BO_Assign && "unexpected binary l-value");
2403
2404 // Note that in all of these cases, __block variables need the RHS
2405 // evaluated first just in case the variable gets moved by the RHS.
2406
2408 case cir::TEK_Scalar: {
2410 if (e->getLHS()->getType().getObjCLifetime() !=
2412 cgm.errorNYI(e->getSourceRange(), "objc lifetimes");
2413 return {};
2414 }
2415
2416 RValue rv = emitAnyExpr(e->getRHS());
2417 LValue lv = emitLValue(e->getLHS());
2418
2419 SourceLocRAIIObject loc{*this, e->getSourceRange()};
2420 if (lv.isBitField())
2422 else
2423 emitStoreThroughLValue(rv, lv);
2424
2426
2427 return lv;
2428 }
2429
2430 case cir::TEK_Complex: {
2432 }
2433
2434 case cir::TEK_Aggregate:
2435 cgm.errorNYI(e->getSourceRange(), "aggregate lvalues");
2436 return {};
2437 }
2438 llvm_unreachable("bad evaluation kind");
2439}
2440
2441/// Emit code to compute the specified expression which
2442/// can have any type. The result is returned as an RValue struct.
2444 bool ignoreResult) {
2446 case cir::TEK_Scalar:
2447 return RValue::get(emitScalarExpr(e, ignoreResult));
2448 case cir::TEK_Complex:
2450 case cir::TEK_Aggregate: {
2451 if (!ignoreResult && aggSlot.isIgnored())
2452 aggSlot = createAggTemp(e->getType(), getLoc(e->getSourceRange()),
2454 emitAggExpr(e, aggSlot);
2455 return aggSlot.asRValue();
2456 }
2457 }
2458 llvm_unreachable("bad evaluation kind");
2459}
2460
2461// Returns whether \p fn disables the builtin \p name with no_builtin. An empty
2462// list disables all builtins.
2463static bool hasNoBuiltinAttr(cir::FuncOp fn, StringRef name) {
2464 auto noBuiltins = fn->getAttrOfType<mlir::ArrayAttr>(
2465 cir::CIRDialect::getNoBuiltinsAttrName());
2466 if (!noBuiltins)
2467 return false;
2468 return noBuiltins.empty() ||
2469 llvm::is_contained(noBuiltins,
2470 mlir::StringAttr::get(fn.getContext(), name));
2471}
2472
2473CIRGenCallee CIRGenFunction::emitDirectCallee(const GlobalDecl &gd) {
2474 const auto *fd = cast<FunctionDecl>(gd.getDecl());
2475
2476 if (unsigned builtinID = fd->getBuiltinID()) {
2477 StringRef ident = cgm.getMangledName(gd);
2478 std::string fdInlineName = (ident + ".inline").str();
2479
2480 bool isPredefinedLibFunction =
2481 cgm.getASTContext().BuiltinInfo.isPredefinedLibFunction(builtinID);
2482 auto fn = dyn_cast<cir::FuncOp>(curFn);
2483 bool hasAttributeNoBuiltin = fn && hasNoBuiltinAttr(fn, fd->getName());
2484
2485 // When directly calling an inline builtin, call it through it's mangled
2486 // name to make it clear it's not the actual builtin.
2487 if ((!fn || fn.getName() != fdInlineName) &&
2489 cir::FuncOp clone =
2490 mlir::cast_or_null<cir::FuncOp>(cgm.getGlobalValue(fdInlineName));
2491
2492 if (!clone) {
2493 // Create a forward declaration - the body will be generated in
2494 // generateCode when the function definition is processed
2495 cir::FuncOp calleeFunc = cgm.getRawFunctionPointer(gd);
2496 mlir::OpBuilder::InsertionGuard guard(builder);
2497 builder.setInsertionPointToStart(cgm.getModule().getBody());
2498
2499 clone = cir::FuncOp::create(builder, calleeFunc.getLoc(), fdInlineName,
2500 calleeFunc.getFunctionType());
2501 cgm.insertGlobalSymbol(clone);
2502 clone.setLinkageAttr(cir::GlobalLinkageKindAttr::get(
2503 &cgm.getMLIRContext(), cir::GlobalLinkageKind::InternalLinkage));
2504 clone.setSymVisibility("private");
2505 clone.setInlineKind(cir::InlineKind::AlwaysInline);
2506 }
2507 return CIRGenCallee::forDirect(clone, gd);
2508 }
2509
2510 // Replaceable builtins provide their own implementation of a builtin. If we
2511 // are in an inline builtin implementation, avoid trivial infinite
2512 // recursion. Honor __attribute__((no_builtin("foo"))) or
2513 // __attribute__((no_builtin)) on the current function unless foo is
2514 // not a predefined library function which means we must generate the
2515 // builtin no matter what.
2516 else if (!isPredefinedLibFunction || !hasAttributeNoBuiltin)
2517 return CIRGenCallee::forBuiltin(builtinID, fd);
2518 }
2519
2520 cir::FuncOp callee = cgm.getRawFunctionPointer(gd);
2521 if (!callee)
2522 return CIRGenCallee();
2523
2524 if ((cgm.getLangOpts().CUDA || cgm.getLangOpts().HIP) &&
2525 !cgm.getLangOpts().CUDAIsDevice && fd->hasAttr<CUDAGlobalAttr>()) {
2526 mlir::Operation *handle = cgm.getCUDARuntime().getKernelHandle(callee, gd);
2527 callee =
2528 mlir::cast<cir::FuncOp>(*cgm.getCUDARuntime().getKernelStub(handle));
2529 }
2530
2531 return CIRGenCallee::forDirect(callee, gd);
2532}
2533
2534mlir::Value CIRGenFunction::getUndefConstant(mlir::Location loc,
2535 mlir::Type cirTy) {
2536 return builder.getConstant(loc, cir::UndefAttr::get(cirTy));
2537}
2538
2540 if (ty->isVoidType())
2541 return RValue::get(nullptr);
2542
2543 mlir::Location loc = builder.getUnknownLoc();
2544
2545 switch (getEvaluationKind(ty)) {
2546 case cir::TEK_Complex: {
2547 QualType elemTy = ty->castAs<ComplexType>()->getElementType();
2548 mlir::Type elemCirTy = convertType(elemTy);
2549 mlir::Value undefElem = getUndefConstant(loc, elemCirTy);
2550 mlir::Value v = builder.createComplexCreate(loc, undefElem, undefElem);
2551 return RValue::getComplex(v);
2552 }
2553
2554 // If this is a use of an undefined aggregate type, the aggregate must have
2555 // an identifiable address. Just because the contents of the value are
2556 // undefined doesn't mean that the address can't be taken and compared.
2557 case cir::TEK_Aggregate: {
2558 Address destPtr = createMemTempWithoutCast(ty, loc, "undef.agg.tmp");
2559 return RValue::getAggregate(destPtr);
2560 }
2561
2562 case cir::TEK_Scalar:
2563 return RValue::get(getUndefConstant(loc, convertType(ty)));
2564 }
2565 llvm_unreachable("bad evaluation kind");
2566}
2567
2569 const CIRGenCallee &origCallee,
2570 const clang::CallExpr *e,
2572 // Get the actual function type. The callee type will always be a pointer to
2573 // function type or a block pointer type.
2574 assert(calleeTy->isFunctionPointerType() &&
2575 "Callee must have function pointer type!");
2576
2577 calleeTy = getContext().getCanonicalType(calleeTy);
2578 auto pointeeTy = cast<PointerType>(calleeTy)->getPointeeType();
2579
2580 CIRGenCallee callee = origCallee;
2581
2582 if (getLangOpts().CPlusPlus)
2584
2585 const auto *fnType = cast<FunctionType>(pointeeTy);
2586
2588
2589 CallArgList args;
2591
2592 // C++23 static-member operators (`static operator()` /
2593 // `static operator[]`) produce a CXXOperatorCallExpr whose first argument
2594 // is the object expression even though the operator is static. Emit the
2595 // object for its side effects and drop it before walking the parameter
2596 // arguments.
2597 auto arguments = e->arguments();
2598 if (const auto *oce = dyn_cast<CXXOperatorCallExpr>(e)) {
2599 if (const auto *md =
2600 dyn_cast_if_present<CXXMethodDecl>(oce->getCalleeDecl());
2601 md && md->isStatic()) {
2602 emitIgnoredExpr(e->getArg(0));
2603 arguments = llvm::drop_begin(arguments, 1);
2604 }
2605 }
2606
2607 emitCallArgs(args, dyn_cast<FunctionProtoType>(fnType), arguments,
2608 e->getDirectCallee(), /*paramsToSkip=*/0, order);
2609
2610 const CIRGenFunctionInfo &funcInfo =
2611 cgm.getTypes().arrangeFreeFunctionCall(args, fnType);
2612
2613 // C99 6.5.2.2p6:
2614 // If the expression that denotes the called function has a type that does
2615 // not include a prototype, [the default argument promotions are performed].
2616 // If the number of arguments does not equal the number of parameters, the
2617 // behavior is undefined. If the function is defined with a type that
2618 // includes a prototype, and either the prototype ends with an ellipsis (,
2619 // ...) or the types of the arguments after promotion are not compatible
2620 // with the types of the parameters, the behavior is undefined. If the
2621 // function is defined with a type that does not include a prototype, and
2622 // the types of the arguments after promotion are not compatible with those
2623 // of the parameters after promotion, the behavior is undefined [except in
2624 // some trivial cases].
2625 // That is, in the general case, we should assume that a call through an
2626 // unprototyped function type works like a *non-variadic* call. The way we
2627 // make this work is to cast to the exxact type fo the promoted arguments.
2628 if (isa<FunctionNoProtoType>(fnType)) {
2631 cir::FuncType calleeTy = getTypes().getFunctionType(funcInfo);
2632 // get non-variadic function type
2633 calleeTy = cir::FuncType::get(calleeTy.getInputs(),
2634 calleeTy.getReturnType(), false);
2635 auto calleePtrTy = cir::PointerType::get(calleeTy);
2636
2637 mlir::Operation *fn = callee.getFunctionPointer();
2638 mlir::Value addr;
2639 if (auto funcOp = mlir::dyn_cast<cir::FuncOp>(fn)) {
2640 addr = cir::GetGlobalOp::create(
2641 builder, getLoc(e->getSourceRange()),
2642 cir::PointerType::get(funcOp.getFunctionType()), funcOp.getSymName());
2643 } else {
2644 addr = fn->getResult(0);
2645 }
2646
2647 fn = builder.createBitcast(addr, calleePtrTy).getDefiningOp();
2648 callee.setFunctionPointer(fn);
2649 }
2650
2652
2653 // HIP function pointer contains kernel handle when it is used in triple
2654 // chevron. The kernel stub needs to be loaded from kernel handle and used
2655 // as callee.
2656 const clang::Decl *targetDecl =
2657 origCallee.getAbstractInfo().getCalleeDecl().getDecl();
2658 if (getLangOpts().HIP && !getLangOpts().CUDAIsDevice &&
2660 (!targetDecl || !isa<FunctionDecl>(targetDecl))) {
2661 mlir::Value handleAddr = callee.getFunctionPointer()->getResult(0);
2662 mlir::Location loc = getLoc(e->getSourceRange());
2663 auto handlePtrTy = mlir::cast<cir::PointerType>(handleAddr.getType());
2664 mlir::Value handleAddrAddr =
2665 builder.createBitcast(handleAddr, cir::PointerType::get(handlePtrTy));
2666 cir::LoadOp stub = builder.createLoad(
2667 loc, Address(handleAddrAddr, handlePtrTy, getPointerAlign()));
2668 callee.setFunctionPointer(stub.getOperation());
2669 }
2670
2671 cir::CIRCallOpInterface callOp;
2672 RValue callResult = emitCall(funcInfo, callee, returnValue, args, &callOp,
2673 e == mustTailCall, e->getSourceRange());
2674
2676
2677 return callResult;
2678}
2679
2681 e = e->IgnoreParens();
2682
2683 // Look through function-to-pointer decay.
2684 if (const auto *implicitCast = dyn_cast<ImplicitCastExpr>(e)) {
2685 if (implicitCast->getCastKind() == CK_FunctionToPointerDecay ||
2686 implicitCast->getCastKind() == CK_BuiltinFnToFnPtr) {
2687 return emitCallee(implicitCast->getSubExpr());
2688 }
2689 // Classic codegen has some handling here for ptr-auth (as a part of the
2690 // large ptr-auth-qualifier PR (#100830)). In the meantime, other cast kinds
2691 // can fall-through and be handled by the indirect call work below,
2692 // including L-to-R value conversions and atomic conversions.
2694
2695 } else if (const auto *declRef = dyn_cast<DeclRefExpr>(e)) {
2696 // Resolve direct calls.
2697 if (const auto *funcDecl = dyn_cast<FunctionDecl>(declRef->getDecl()))
2698 return emitDirectCallee(funcDecl);
2699 } else if (auto me = dyn_cast<MemberExpr>(e)) {
2700 if (const auto *fd = dyn_cast<FunctionDecl>(me->getMemberDecl())) {
2701 emitIgnoredExpr(me->getBase());
2702 return emitDirectCallee(fd);
2703 }
2704 // Else fall through to the indirect reference handling below.
2705 } else if (auto *pde = dyn_cast<CXXPseudoDestructorExpr>(e)) {
2707 }
2708
2709 // Otherwise, we have an indirect reference.
2710 mlir::Value calleePtr;
2712 if (const auto *ptrType = e->getType()->getAs<clang::PointerType>()) {
2713 calleePtr = emitScalarExpr(e);
2714 functionType = ptrType->getPointeeType();
2715 } else {
2716 functionType = e->getType();
2717 calleePtr = emitLValue(e).getPointer();
2718 }
2719 assert(functionType->isFunctionType());
2720
2721 GlobalDecl gd;
2722 if (const auto *vd =
2723 dyn_cast_or_null<VarDecl>(e->getReferencedDeclOfCallee()))
2724 gd = GlobalDecl(vd);
2725
2726 CIRGenCalleeInfo calleeInfo(functionType->getAs<FunctionProtoType>(), gd);
2727 CIRGenCallee callee(calleeInfo, calleePtr.getDefiningOp());
2728 return callee;
2729}
2730
2734
2735 // Builtins never have block type.
2736 if (e->getCallee()->getType()->isBlockPointerType()) {
2737 cgm.errorNYI(e->getSourceRange(),
2738 std::string("emitCallExpr: block pointer type"));
2739 return getUndefRValue(e->getType());
2740 }
2741
2742 if (const auto *ce = dyn_cast<CXXMemberCallExpr>(e))
2744
2745 if (const auto *cudaKernelCallExpr = dyn_cast<CUDAKernelCallExpr>(e))
2747
2748 // A CXXOperatorCallExpr is created even for explicit-object methods or
2749 // static member operators (C++23 `static operator()` / `static
2750 // operator[]`), but those should be treated like ordinary static function
2751 // calls. Only route through the member-call path for ordinary instance
2752 // operators.
2753 if (const auto *operatorCall = dyn_cast<CXXOperatorCallExpr>(e)) {
2754 if (const auto *md =
2755 dyn_cast_if_present<CXXMethodDecl>(operatorCall->getCalleeDecl());
2756 md && md->isImplicitObjectMemberFunction())
2757 return emitCXXOperatorMemberCallExpr(operatorCall, md, returnValue);
2758 }
2759
2760 CIRGenCallee callee = emitCallee(e->getCallee());
2761
2762 // emitCallee has already diagnosed (errorNYI) why there is no callee.
2763 if (callee.isInvalid())
2764 return getUndefRValue(e->getType());
2765
2766 if (callee.isBuiltin())
2767 return emitBuiltinExpr(callee.getBuiltinDecl(), callee.getBuiltinID(), e,
2768 returnValue);
2769
2770 if (callee.isPseudoDestructor())
2772
2773 return emitCall(e->getCallee()->getType(), callee, e, returnValue);
2774}
2775
2776/// Emit code to compute the specified expression, ignoring the result.
2778 if (e->isPRValue()) {
2779 emitAnyExpr(e, AggValueSlot::ignored(), /*ignoreResult=*/true);
2780 return;
2781 }
2782
2783 // Just emit it as an l-value and drop the result.
2784 emitLValue(e);
2785}
2786
2788 LValueBaseInfo *baseInfo) {
2790 assert(e->getType()->isArrayType() &&
2791 "Array to pointer decay must have array source type!");
2792
2793 // Expressions of array type can't be bitfields or vector elements.
2794 LValue lv = emitLValue(e);
2795 Address addr = lv.getAddress();
2796
2797 if (e->getType()->isVariableArrayType())
2798 return addr;
2799
2800 // If the array type was an incomplete type, we need to make sure
2801 // the decay ends up being the right type.
2802 mlir::Type arrayTy = convertType(e->getType());
2803 assert(mlir::isa<cir::ArrayType>(arrayTy) && "expected array");
2804 addr = addr.withElementType(builder, arrayTy);
2805
2806 // The result of this decay conversion points to an array element within the
2807 // base lvalue. However, since TBAA currently does not support representing
2808 // accesses to elements of member arrays, we conservatively represent accesses
2809 // to the pointee object as if it had no any base lvalue specified.
2810 // TODO: Support TBAA for member arrays.
2813
2814 mlir::Value ptr = builder.maybeBuildArrayDecay(
2815 cgm.getLoc(e->getSourceRange()), addr.getPointer(),
2816 convertTypeForMem(eltType));
2817 return Address(ptr, addr.getAlignment());
2818}
2819
2820/// Given the address of a temporary variable, produce an r-value of its type.
2824 switch (getEvaluationKind(type)) {
2825 case cir::TEK_Complex:
2826 return RValue::getComplex(emitLoadOfComplex(lvalue, loc));
2827 case cir::TEK_Aggregate:
2828 return lvalue.asAggregateRValue();
2829 case cir::TEK_Scalar:
2830 return RValue::get(emitLoadOfScalar(lvalue, loc));
2831 }
2832 llvm_unreachable("bad evaluation kind");
2833}
2834
2835/// Emit an `if` on a boolean condition, filling `then` and `else` into
2836/// appropriated regions.
2837mlir::LogicalResult CIRGenFunction::emitIfOnBoolExpr(const Expr *cond,
2838 const Stmt *thenS,
2839 const Stmt *elseS) {
2840 mlir::Location thenLoc = getLoc(thenS->getSourceRange());
2841 std::optional<mlir::Location> elseLoc;
2842 if (elseS)
2843 elseLoc = getLoc(elseS->getSourceRange());
2844
2845 mlir::LogicalResult resThen = mlir::success(), resElse = mlir::success();
2847 cond, /*thenBuilder=*/
2848 [&](mlir::OpBuilder &, mlir::Location) {
2849 LexicalScope lexScope{*this, thenLoc, builder.getInsertionBlock()};
2850 resThen = emitStmt(thenS, /*useCurrentScope=*/true);
2851 },
2852 thenLoc,
2853 /*elseBuilder=*/
2854 [&](mlir::OpBuilder &, mlir::Location) {
2855 assert(elseLoc && "Invalid location for elseS.");
2856 LexicalScope lexScope{*this, *elseLoc, builder.getInsertionBlock()};
2857 resElse = emitStmt(elseS, /*useCurrentScope=*/true);
2858 },
2859 elseLoc);
2860
2861 return mlir::LogicalResult::success(resThen.succeeded() &&
2862 resElse.succeeded());
2863}
2864
2865/// Emit an `if` on a boolean condition, filling `then` and `else` into
2866/// appropriated regions.
2868 const clang::Expr *cond, BuilderCallbackRef thenBuilder,
2869 mlir::Location thenLoc, BuilderCallbackRef elseBuilder,
2870 std::optional<mlir::Location> elseLoc) {
2871 // Attempt to be as accurate as possible with IfOp location, generate
2872 // one fused location that has either 2 or 4 total locations, depending
2873 // on else's availability.
2874 SmallVector<mlir::Location, 2> ifLocs{thenLoc};
2875 if (elseLoc)
2876 ifLocs.push_back(*elseLoc);
2877 mlir::Location loc = mlir::FusedLoc::get(&getMLIRContext(), ifLocs);
2878
2879 // Emit the code with the fully general case.
2880 mlir::Value condV = emitOpOnBoolExpr(loc, cond);
2881 return emitIfOnBoolValue(condV, loc, thenBuilder, thenLoc, elseBuilder,
2882 elseLoc);
2883}
2884
2886 mlir::Value condV, mlir::Location loc, BuilderCallbackRef thenBuilder,
2887 mlir::Location thenLoc, BuilderCallbackRef elseBuilder,
2888 std::optional<mlir::Location> elseLoc) {
2889 cir::IfOp ifOp = cir::IfOp::create(builder, loc, condV, elseLoc.has_value(),
2890 /*thenBuilder=*/thenBuilder,
2891 /*elseBuilder=*/elseBuilder);
2892 terminateStructuredRegionBody(ifOp.getThenRegion(), thenLoc);
2893 assert((elseLoc.has_value() || ifOp.getElseRegion().empty()) &&
2894 "else region created with no else location");
2895 if (elseLoc.has_value())
2896 terminateStructuredRegionBody(ifOp.getElseRegion(), *elseLoc);
2897 return ifOp;
2898}
2899
2900/// TODO(cir): see EmitBranchOnBoolExpr for extra ideas).
2901mlir::Value CIRGenFunction::emitOpOnBoolExpr(mlir::Location loc,
2902 const Expr *cond) {
2905 cond = cond->IgnoreParens();
2906
2907 // In LLVM the condition is reversed here for efficient codegen.
2908 // This should be done in CIR prior to LLVM lowering, if we do now
2909 // we can make CIR based diagnostics misleading.
2910 // cir.ternary(!x, t, f) -> cir.ternary(x, f, t)
2912
2913 if (const ConditionalOperator *condOp = dyn_cast<ConditionalOperator>(cond)) {
2914 Expr *trueExpr = condOp->getTrueExpr();
2915 Expr *falseExpr = condOp->getFalseExpr();
2916 mlir::Value condV = emitOpOnBoolExpr(loc, condOp->getCond());
2917
2918 mlir::Value ternaryOpRes =
2919 cir::TernaryOp::create(
2920 builder, loc, condV, /*thenBuilder=*/
2921 [this, trueExpr](mlir::OpBuilder &b, mlir::Location loc) {
2922 mlir::Value lhs = emitScalarExpr(trueExpr);
2923 cir::YieldOp::create(b, loc, lhs);
2924 },
2925 /*elseBuilder=*/
2926 [this, falseExpr](mlir::OpBuilder &b, mlir::Location loc) {
2927 mlir::Value rhs = emitScalarExpr(falseExpr);
2928 cir::YieldOp::create(b, loc, rhs);
2929 })
2930 .getResult();
2931
2932 return emitScalarConversion(ternaryOpRes, condOp->getType(),
2933 getContext().BoolTy, condOp->getExprLoc());
2934 }
2935
2936 if (isa<CXXThrowExpr>(cond)) {
2937 cgm.errorNYI("NYI");
2938 return createDummyValue(loc, cond->getType());
2939 }
2940
2941 // If the branch has a condition wrapped by __builtin_unpredictable,
2942 // create metadata that specifies that the branch is unpredictable.
2943 // Don't bother if not optimizing because that metadata would not be used.
2945
2946 // Emit the code with the fully general case.
2947 return evaluateExprAsBool(cond);
2948}
2949
2950mlir::Value CIRGenFunction::emitAlloca(StringRef name, mlir::Type ty,
2951 mlir::Location loc, CharUnits alignment,
2952 bool insertIntoFnEntryBlock,
2953 mlir::Value arraySize) {
2954 mlir::Block *entryBlock = insertIntoFnEntryBlock
2956 : curLexScope->getEntryBlock();
2957
2958 // If this is an alloca in the entry basic block of a cir.try and there's
2959 // a surrounding cir.scope, make sure the alloca ends up in the surrounding
2960 // scope instead. This is necessary in order to guarantee all SSA values are
2961 // reachable during cleanups.
2962 if (auto tryOp =
2963 llvm::dyn_cast_if_present<cir::TryOp>(entryBlock->getParentOp())) {
2964 if (auto scopeOp = llvm::dyn_cast<cir::ScopeOp>(tryOp->getParentOp()))
2965 entryBlock = &scopeOp.getScopeRegion().front();
2966 }
2967
2968 return emitAlloca(name, ty, loc, alignment,
2969 builder.getBestAllocaInsertPoint(entryBlock), arraySize);
2970}
2971
2972mlir::Value CIRGenFunction::emitAlloca(StringRef name, mlir::Type ty,
2973 mlir::Location loc, CharUnits alignment,
2974 mlir::OpBuilder::InsertPoint ip,
2975 mlir::Value arraySize) {
2976 // CIR uses its own alloca address space rather than follow the target data
2977 // layout like original CodeGen. The data layout awareness should be done in
2978 // the lowering pass instead.
2979 cir::PointerType localVarPtrTy =
2981 mlir::IntegerAttr alignIntAttr = cgm.getSize(alignment);
2982
2983 mlir::Value addr;
2984 {
2985 mlir::OpBuilder::InsertionGuard guard(builder);
2986 builder.restoreInsertionPoint(ip);
2987 addr = builder.createAlloca(loc, /*addr type*/ localVarPtrTy, name,
2988 alignIntAttr, arraySize);
2990 }
2991 return addr;
2992}
2993
2994// Note: this function also emit constructor calls to support a MSVC extensions
2995// allowing explicit constructor function call.
2998 const Expr *callee = ce->getCallee()->IgnoreParens();
2999
3000 if (isa<BinaryOperator>(callee))
3002
3003 const auto *me = cast<MemberExpr>(callee);
3004 const auto *md = cast<CXXMethodDecl>(me->getMemberDecl());
3005
3006 // Sema represents calls to static member functions as ordinary CallExpr
3007 // nodes rather than CXXMemberCallExpr.
3008 assert(!md->isStatic() &&
3009 "static member call is unexpected in emitCXXMemberCallExpr");
3010
3011 bool hasQualifier = me->hasQualifier();
3012 NestedNameSpecifier qualifier = me->getQualifier();
3013 bool isArrow = me->isArrow();
3014 const Expr *base = me->getBase();
3015
3017 ce, md, returnValue, hasQualifier, qualifier, isArrow, base);
3018}
3019
3021 // Emit the expression as an lvalue.
3022 LValue lv = emitLValue(e);
3023 assert(lv.isSimple());
3024 mlir::Value value = lv.getPointer();
3025
3027
3028 return RValue::get(value);
3029}
3030
3032 LValueBaseInfo *pointeeBaseInfo) {
3033 if (refLVal.isVolatile())
3034 cgm.errorNYI(loc, "load of volatile reference");
3035
3036 cir::LoadOp load =
3037 cir::LoadOp::create(builder, loc, refLVal.getAddress().getElementType(),
3038 refLVal.getAddress().getPointer());
3039
3041
3043 CharUnits align = cgm.getNaturalTypeAlignment(pointeeType, pointeeBaseInfo);
3044 return Address(load, convertTypeForMem(pointeeType), align);
3045}
3046
3048 mlir::Location loc,
3049 QualType refTy,
3050 AlignmentSource source) {
3051 LValue refLVal = makeAddrLValue(refAddr, refTy, LValueBaseInfo(source));
3052 LValueBaseInfo pointeeBaseInfo;
3054 Address pointeeAddr = emitLoadOfReference(refLVal, loc, &pointeeBaseInfo);
3055 return makeAddrLValue(pointeeAddr, refLVal.getType()->getPointeeType(),
3056 pointeeBaseInfo);
3057}
3058
3059void CIRGenFunction::emitTrap(mlir::Location loc, bool createNewBlock) {
3060 cir::TrapOp::create(builder, loc);
3061 if (createNewBlock)
3062 builder.createBlock(builder.getBlock()->getParent());
3063}
3064
3066 bool createNewBlock) {
3068 cir::UnreachableOp::create(builder, getLoc(loc));
3069 if (createNewBlock)
3070 builder.createBlock(builder.getBlock()->getParent());
3071}
3072
3073mlir::Value CIRGenFunction::createDummyValue(mlir::Location loc,
3074 clang::QualType qt) {
3075 mlir::Type t = convertType(qt);
3076 CharUnits alignment = getContext().getTypeAlignInChars(qt);
3077 return builder.createDummyValue(loc, t, alignment);
3078}
3079
3080//===----------------------------------------------------------------------===//
3081// CIR builder helpers
3082//===----------------------------------------------------------------------===//
3083
3085 mlir::Location loc,
3086 const Twine &name) {
3088 convertTypeForMem(ty), getContext().getTypeAlignInChars(ty), loc, name);
3089}
3090
3092 const Twine &name, Address *alloca,
3093 mlir::OpBuilder::InsertPoint ip) {
3094 // FIXME: Should we prefer the preferred type alignment here?
3095 return createMemTemp(ty, getContext().getTypeAlignInChars(ty), loc, name,
3096 alloca, ip);
3097}
3098
3100 mlir::Location loc, const Twine &name,
3101 Address *alloca,
3102 mlir::OpBuilder::InsertPoint ip) {
3103 Address result =
3104 createTempAlloca(convertTypeForMem(ty), /*destAddrSpace=*/{}, align, loc,
3105 name, /*arraySize=*/nullptr, alloca, ip);
3106 return result;
3107}
3108
3109/// This creates a alloca and inserts it into the entry block of the
3110/// current region.
3112 mlir::Type ty, CharUnits align, mlir::Location loc, const Twine &name,
3113 mlir::Value arraySize, mlir::OpBuilder::InsertPoint ip) {
3114 cir::AllocaOp alloca = ip.isSet()
3115 ? createTempAlloca(ty, loc, name, ip, arraySize)
3116 : createTempAlloca(ty, loc, name, arraySize);
3117 alloca.setAlignmentAttr(cgm.getSize(align));
3118 return Address(alloca, ty, align);
3119}
3120
3122 mlir::Location loc, const Twine &name,
3123 mlir::Value arraySize,
3124 Address *allocaAddr,
3125 mlir::OpBuilder::InsertPoint ip) {
3126 return createTempAlloca(ty, /*destAddrSpace=*/{}, align, loc, name, arraySize,
3127 allocaAddr, ip);
3128}
3129
3131 Address alloca, mlir::ptr::MemorySpaceAttrInterface destAddrSpace,
3132 mlir::Value arraySize) {
3133 if (!destAddrSpace)
3134 destAddrSpace = cir::toCIRAddressSpaceAttr(
3135 getMLIRContext(), cgm.getLangTempAllocaAddressSpace());
3136
3137 // Resolve the default address space through getTargetAddressSpace, as
3138 // classic CodeGen does and as CIRGenTypes::getPointerAddressSpace does for
3139 // default pointer types. This is only non-zero for targets where the default
3140 // address space is not 0 (e.g. generic for SYCL device code).
3141 if (!cir::normalizeDefaultAddressSpace(destAddrSpace))
3142 if (unsigned targetAS = getContext().getTargetAddressSpace(LangAS::Default))
3143 destAddrSpace =
3144 cir::TargetAddressSpaceAttr::get(&getMLIRContext(), targetAS);
3145
3146 mlir::ptr::MemorySpaceAttrInterface srcAddrSpace = getCIRAllocaAddressSpace();
3147 // Alloca always returns a pointer in alloca address space, which may
3148 // be different from the type defined by the language. For example,
3149 // in C++ the auto variables are in the default address space. Therefore
3150 // cast alloca to the default address space when necessary.
3151 if (srcAddrSpace == destAddrSpace)
3152 return alloca;
3153
3154 mlir::OpBuilder::InsertionGuard guard(builder);
3155 if (cir::AllocaOp allocaOp = alloca.getUnderlyingAllocaOp()) {
3156 builder.setInsertionPointAfter(allocaOp);
3157 } else if (!arraySize) {
3158 mlir::Block *entryBlock = getCurFunctionEntryBlock();
3159 builder.restoreInsertionPoint(builder.getBestAllocaInsertPoint(entryBlock));
3160 }
3161
3162 mlir::Type destPtrTy =
3163 builder.getPointerTo(alloca.getElementType(), destAddrSpace);
3164 mlir::Value casted = performAddrSpaceCast(alloca.getPointer(), destPtrTy);
3165 return Address(casted, alloca.getElementType(), alloca.getAlignment(),
3166 /*isKnownNonNull=*/true);
3167}
3168
3169/// This creates a alloca and inserts it into the entry block. The alloca is
3170/// casted to the requested language address space if necessary.
3172 mlir::Type ty, mlir::ptr::MemorySpaceAttrInterface destAddrSpace,
3173 CharUnits align, mlir::Location loc, const Twine &name,
3174 mlir::Value arraySize, Address *allocaAddr,
3175 mlir::OpBuilder::InsertPoint ip) {
3176 Address alloca =
3177 createTempAllocaWithoutCast(ty, align, loc, name, arraySize, ip);
3178 if (allocaAddr)
3179 *allocaAddr = alloca;
3180 return maybeCastStackAddressSpace(alloca, destAddrSpace, arraySize);
3181}
3182
3183/// This creates an alloca and inserts it into the entry block if \p ArraySize
3184/// is nullptr, otherwise inserts it at the current insertion point of the
3185/// builder.
3186cir::AllocaOp CIRGenFunction::createTempAlloca(mlir::Type ty,
3187 mlir::Location loc,
3188 const Twine &name,
3189 mlir::Value arraySize,
3190 bool insertIntoFnEntryBlock) {
3191 return mlir::cast<cir::AllocaOp>(emitAlloca(name.str(), ty, loc, CharUnits(),
3192 insertIntoFnEntryBlock, arraySize)
3193 .getDefiningOp());
3194}
3195
3196/// This creates an alloca and inserts it into the provided insertion point
3197cir::AllocaOp CIRGenFunction::createTempAlloca(mlir::Type ty,
3198 mlir::Location loc,
3199 const Twine &name,
3200 mlir::OpBuilder::InsertPoint ip,
3201 mlir::Value arraySize) {
3202 assert(ip.isSet() && "Insertion point is not set");
3203 return mlir::cast<cir::AllocaOp>(
3204 emitAlloca(name.str(), ty, loc, CharUnits(), ip, arraySize)
3205 .getDefiningOp());
3206}
3207
3208/// CreateDefaultAlignTempAlloca - This creates an alloca with the
3209/// default alignment of the corresponding LLVM type, which is *not*
3210/// guaranteed to be related in any way to the expected alignment of
3211/// an AST type that might have been lowered to Ty.
3213 mlir::Location loc,
3214 const Twine &name) {
3215 CharUnits align =
3216 CharUnits::fromQuantity(cgm.getDataLayout().getABITypeAlign(ty));
3217 return createTempAlloca(ty, align, loc, name);
3218}
3219
3220/// Try to emit a reference to the given value without producing it as
3221/// an l-value. This is just an optimization, but it avoids us needing
3222/// to emit global copies of variables if they're named without triggering
3223/// a formal use in a context where we can't emit a direct reference to them,
3224/// for instance if a block or lambda or a member of a local class uses a
3225/// const int variable or constexpr variable from an enclosing function.
3228 const ValueDecl *value = refExpr->getDecl();
3229
3230 // The value needs to be an enum constant or a constant variable.
3232 if (isa<ParmVarDecl>(value))
3234 else if (const auto *var = dyn_cast<VarDecl>(value))
3236 else if (isa<EnumConstantDecl>(value))
3238 else
3240 if (cek == CodeGenUtils::CEK_None)
3241 return ConstantEmission();
3242
3243 Expr::EvalResult result;
3244 bool resultIsReference;
3245 QualType resultType;
3246
3247 // It's best to evaluate all the way as an r-value if that's permitted.
3249 refExpr->EvaluateAsRValue(result, getContext())) {
3250 resultIsReference = false;
3251 resultType = refExpr->getType().getUnqualifiedType();
3252 } else if (cek != CodeGenUtils::CEK_AsValueOnly &&
3253 refExpr->EvaluateAsLValue(result, getContext())) {
3254 resultIsReference = true;
3255 resultType = value->getType();
3256 } else {
3257 return ConstantEmission();
3258 }
3259
3260 // In any case, if the initializer has side-effects, abandon ship.
3261 if (result.HasSideEffects)
3262 return ConstantEmission();
3263
3264 // In CUDA/HIP device compilation, a lambda may capture a reference variable
3265 // referencing a global host variable by copy. In this case the lambda should
3266 // make a copy of the value of the global host variable. The DRE of the
3267 // captured reference variable cannot be emitted as load from the host
3268 // global variable as compile time constant, since the host variable is not
3269 // accessible on device. The DRE of the captured reference variable has to be
3270 // loaded from captures.
3271 if (cgm.getLangOpts().CUDAIsDevice && result.Val.isLValue() &&
3273 auto *md = dyn_cast_or_null<CXXMethodDecl>(curCodeDecl);
3274 if (isLambdaMethod(md) && md->getOverloadedOperator() == OO_Call) {
3275 const APValue::LValueBase &base = result.Val.getLValueBase();
3276 if (const ValueDecl *d = base.dyn_cast<const ValueDecl *>()) {
3277 if (const auto *vd = dyn_cast<const VarDecl>(d)) {
3278 if (!vd->hasAttr<CUDADeviceAttr>())
3279 return ConstantEmission();
3280 }
3281 }
3282 }
3283 }
3284
3285 // Emit as a constant.
3286 // FIXME(cir): have emitAbstract build a TypedAttr instead (this requires
3287 // somewhat heavy refactoring...)
3288 mlir::Attribute c = ConstantEmitter(*this).emitAbstract(
3289 refExpr->getLocation(), result.Val, resultType);
3290 mlir::TypedAttr cstToEmit = mlir::dyn_cast_if_present<mlir::TypedAttr>(c);
3291 if (!cstToEmit)
3292 return ConstantEmission();
3293
3294 // Make sure we emit a debug reference to the global variable.
3296
3297 // If we emitted a reference constant, we need to dereference that.
3298 if (resultIsReference)
3299 return ConstantEmission::forReference(cstToEmit);
3300
3301 return ConstantEmission::forValue(cstToEmit);
3302}
3303
3307 return tryEmitAsConstant(dre);
3308 return ConstantEmission();
3309}
3310
3312 const CIRGenFunction::ConstantEmission &constant, Expr *e) {
3313 assert(constant && "not a constant");
3314 if (constant.isReference())
3315 return emitLoadOfLValue(constant.getReferenceLValue(*this, e),
3316 e->getExprLoc())
3317 .getValue();
3318 return builder.getConstant(getLoc(e->getSourceRange()), constant.getValue());
3319}
3320
3322 const StringLiteral *sl = e->getFunctionName();
3323 assert(sl != nullptr && "No StringLiteral name in PredefinedExpr");
3324 auto fn = cast<cir::FuncOp>(curFn);
3325 StringRef fnName = fn.getName();
3326 fnName.consume_front("\01");
3327 std::array<StringRef, 2> nameItems = {
3329 std::string gvName = llvm::join(nameItems, ".");
3330 if (isa_and_nonnull<BlockDecl>(curCodeDecl))
3331 cgm.errorNYI(e->getSourceRange(), "predefined lvalue in block");
3332
3333 return emitStringLiteralLValue(sl, gvName);
3334}
3335
3340
3341namespace {
3342// Handle the case where the condition is a constant evaluatable simple integer,
3343// which means we don't have to separately handle the true/false blocks.
3344std::optional<LValue> handleConditionalOperatorLValueSimpleCase(
3346 const Expr *condExpr = e->getCond();
3347 llvm::APSInt condExprVal;
3348 if (!cgf.constantFoldsToSimpleInteger(condExpr, condExprVal))
3349 return std::nullopt;
3350
3351 const Expr *live = e->getTrueExpr(), *dead = e->getFalseExpr();
3352 if (!condExprVal.getBoolValue())
3353 std::swap(live, dead);
3354
3355 if (cgf.containsLabel(dead))
3356 return std::nullopt;
3357
3358 // If the true case is live, we need to track its region.
3361 // If a throw expression we emit it and return an undefined lvalue
3362 // because it can't be used.
3363 if (auto *throwExpr = dyn_cast<CXXThrowExpr>(live->IgnoreParens())) {
3364 cgf.emitCXXThrowExpr(throwExpr);
3365 // Return an undefined lvalue - the throw terminates execution
3366 // so this value will never actually be used
3367 mlir::Type elemTy = cgf.convertType(dead->getType());
3368 mlir::Value undefPtr =
3369 cgf.getBuilder().getNullPtr(cgf.getBuilder().getPointerTo(elemTy),
3370 cgf.getLoc(throwExpr->getSourceRange()));
3371 return cgf.makeAddrLValue(Address(undefPtr, elemTy, CharUnits::One()),
3372 dead->getType());
3373 }
3374 return cgf.emitLValue(live);
3375}
3376
3377/// Emit the operand of a glvalue conditional operator. This is either a glvalue
3378/// or a (possibly-parenthesized) throw-expression. If this is a throw, no
3379/// LValue is returned and the current block has been terminated.
3380static std::optional<LValue> emitLValueOrThrowExpression(CIRGenFunction &cgf,
3381 const Expr *operand) {
3382 if (auto *throwExpr = dyn_cast<CXXThrowExpr>(operand->IgnoreParens())) {
3383 cgf.emitCXXThrowExpr(throwExpr);
3384 return std::nullopt;
3385 }
3386
3387 return cgf.emitLValue(operand);
3388}
3389} // namespace
3390
3391// Create and generate the 3 blocks for a conditional operator.
3392// Leaves the 'current block' in the continuation basic block.
3393template <typename FuncTy>
3396 const FuncTy &branchGenFunc) {
3397 ConditionalInfo info;
3398 mlir::Location loc = getLoc(e->getSourceRange());
3399 CIRGenBuilderTy &builder = getBuilder();
3400
3401 mlir::Value condV = emitOpOnBoolExpr(loc, e->getCond());
3402
3403 ConditionalEvaluation eval(*this, loc);
3404
3405 auto emitBranch = [&](mlir::OpBuilder &b, mlir::Location loc,
3406 const Expr *expr, std::optional<LValue> &resultLV) {
3407 CIRGenFunction::LexicalScope lexScope{*this, loc, b.getInsertionBlock()};
3408 curLexScope->setAsTernary();
3409
3410 mlir::Value resultPtr;
3411 {
3412 // Emit any cleanups that were needed on this branch so we can spill
3413 // and reload the return value.
3414 CIRGenFunction::RunCleanupsScope branchCleanups(*this);
3416 eval.beginEvaluation();
3417 resultLV = branchGenFunc(*this, expr);
3418 resultPtr = resultLV ? resultLV->getPointer() : mlir::Value();
3419 eval.endEvaluation();
3420 branchCleanups.forceCleanup({&resultPtr});
3421 }
3422
3423 // A branch that produced no result is a throw-expression; its region is
3424 // already terminated by cir.unreachable and needs no yield.
3425 if (resultPtr)
3426 cir::YieldOp::create(b, loc, resultPtr);
3427 };
3428
3429 cir::TernaryOp ternary = cir::TernaryOp::create(
3430 builder, loc, condV,
3431 /*trueBuilder=*/
3432 [&](mlir::OpBuilder &b, mlir::Location loc) {
3433 emitBranch(b, loc, e->getTrueExpr(), info.lhs);
3434 },
3435 /*falseBuilder=*/
3436 [&](mlir::OpBuilder &b, mlir::Location loc) {
3437 emitBranch(b, loc, e->getFalseExpr(), info.rhs);
3438 });
3439
3440 // Arms end with a yield or cir.unreachable (throw); this is a backstop
3441 // for error (NYI) paths that leave a region open.
3442 terminateStructuredRegionBody(ternary.getTrueRegion(), loc);
3443 terminateStructuredRegionBody(ternary.getFalseRegion(), loc);
3444
3445 info.result = ternary.getResult();
3446 return info;
3447}
3448
3451 if (!expr->isGLValue()) {
3452 // ?: here should be an aggregate.
3453 assert(hasAggregateEvaluationKind(expr->getType()) &&
3454 "Unexpected conditional operator!");
3455 return emitAggExprToLValue(expr);
3456 }
3457
3458 OpaqueValueMapping binding(*this, expr);
3459 if (std::optional<LValue> res =
3460 handleConditionalOperatorLValueSimpleCase(*this, expr))
3461 return *res;
3462
3463 ConditionalInfo info =
3464 emitConditionalBlocks(expr, [](CIRGenFunction &cgf, const Expr *e) {
3465 return emitLValueOrThrowExpression(cgf, e);
3466 });
3467
3468 if ((info.lhs && !info.lhs->isSimple()) ||
3469 (info.rhs && !info.rhs->isSimple())) {
3470 cgm.errorNYI(expr->getSourceRange(),
3471 "unsupported conditional operator with non-simple lvalue");
3472 return LValue();
3473 }
3474
3475 if (info.lhs && info.rhs) {
3476 Address lhsAddr = info.lhs->getAddress();
3477 Address rhsAddr = info.rhs->getAddress();
3478 Address result(info.result, lhsAddr.getElementType(),
3479 std::min(lhsAddr.getAlignment(), rhsAddr.getAlignment()));
3480 AlignmentSource alignSource =
3481 std::max(info.lhs->getBaseInfo().getAlignmentSource(),
3482 info.rhs->getBaseInfo().getAlignmentSource());
3484 return makeAddrLValue(result, expr->getType(), LValueBaseInfo(alignSource));
3485 }
3486
3487 assert((info.lhs || info.rhs) &&
3488 "both operands of glvalue conditional are throw-expressions?");
3489
3490 // One arm threw; the surviving arm's pointer is local to the ternary's
3491 // region, so address the result through the ternary's result value.
3492 const LValue &survivingLV = info.lhs ? *info.lhs : *info.rhs;
3493 Address survivingAddr = survivingLV.getAddress();
3494 Address result(info.result, survivingAddr.getElementType(),
3495 survivingAddr.getAlignment());
3497 return makeAddrLValue(result, expr->getType(), survivingLV.getBaseInfo());
3498}
3499
3500/// An LValue is a candidate for having its loads and stores be made atomic if
3501/// we are operating under /volatile:ms *and* the LValue itself is volatile and
3502/// performing such an operation can be performed without a libcall.
3504 if (!cgm.getLangOpts().MSVolatile)
3505 return false;
3506
3507 cgm.errorNYI("LValueSuitableForInlineAtomic LangOpts MSVolatile");
3508 return false;
3509}
3510
#define V(N, I)
This file provides some common utility functions for processing Lambda related AST Constructs.
Provides definitions for the various language-specific address spaces.
llvm::function_ref< void(mlir::OpBuilder &, mlir::Location)> BuilderCallbackRef
Definition CIRDialect.h:34
static cir::PtrOffsetFlags getArraySubscriptFlags(CIRGenFunction &cgf, mlir::Value ptr, bool signedIndices)
Return the no-wrap flags for an array subscript of ptr: none when pointer overflow is defined,...
static std::optional< LValue > emitDeclTargetVarDeclLValue(CIRGenFunction &cgf, const Expr *e, const VarDecl *vd)
static Address createReferenceTemporary(CIRGenFunction &cgf, const MaterializeTemporaryExpr *m, const Expr *inner)
static LValue emitFunctionDeclLValue(CIRGenFunction &cgf, const Expr *e, GlobalDecl gd)
static bool isBasedOnAlloca(mlir::Value ptr)
Return true if ptr is derived from a cir.alloca through cir.get_element, cir.ptr_stride,...
static CharUnits getArrayElementAlign(CharUnits arrayAlign, mlir::Value idx, CharUnits eltSize)
static void pushTemporaryCleanup(CIRGenFunction &cgf, const MaterializeTemporaryExpr *m, const Expr *e, Address referenceTemporary)
static RValue emitLoadOfMatrixLValue(LValue lv, SourceLocation loc, CIRGenFunction &cgf)
static cir::IntAttr getConstantIndexOrNull(mlir::Value idx)
static bool hasNoBuiltinAttr(cir::FuncOp fn, StringRef name)
static const Expr * getSimpleArrayDecayOperand(const Expr *e)
If the specified expr is a simple decay from an array to pointer, return the array subexpression.
static mlir::Value emitArraySubscriptPtr(CIRGenFunction &cgf, mlir::Location beginLoc, mlir::Location endLoc, mlir::Value ptr, mlir::Type eltTy, mlir::Value idx, bool signedIndices, bool shouldDecay)
static bool canEmitSpuriousReferenceToVariable(CIRGenFunction &cgf, const DeclRefExpr *e, const VarDecl *vd)
Determine whether we can emit a reference to vd from the current context, despite not necessarily hav...
static DeclRefExpr * tryToConvertMemberExprToDeclRefExpr(CIRGenFunction &cgf, const MemberExpr *me)
static LValue emitGlobalVarDeclLValue(CIRGenFunction &cgf, const Expr *e, const VarDecl *vd)
static LValue emitCapturedFieldLValue(CIRGenFunction &cgf, const FieldDecl *fd, mlir::Value thisValue)
static Address emitAddrOfZeroSizeField(CIRGenFunction &cgf, Address base, const FieldDecl *field)
Get the address of a zero-sized field within a record.
Defines the clang::Expr interface and subclasses for C++ expressions.
Defines AST-level helper utilities for matrix types.
*collection of selector each with an associated kind and an ordered *collection of selectors A selector has a kind
cir::ConstantOp getConstant(mlir::Location loc, mlir::TypedAttr attr)
cir::PtrStrideOp createPtrStride(mlir::Location loc, mlir::Value base, mlir::Value stride)
static OpBuilder::InsertPoint getBestAllocaInsertPoint(mlir::Block *block)
cir::PointerType getPointerTo(mlir::Type ty)
cir::CallOp createCallOp(mlir::Location loc, mlir::SymbolRefAttr callee, mlir::Type returnType, mlir::ValueRange operands, llvm::ArrayRef< mlir::NamedAttribute > attrs={}, llvm::ArrayRef< mlir::NamedAttrList > argAttrs={}, llvm::ArrayRef< mlir::NamedAttribute > resAttrs={}, cir::CallingConv callingConv=cir::CallingConv::C)
cir::ConstantOp getNullPtr(mlir::Type ty, mlir::Location loc)
mlir::Value createPtrBitcast(mlir::Value src, mlir::Type newPointeeTy)
cir::GetGlobalOp createGetGlobal(mlir::Location loc, cir::GlobalOp global, bool threadLocal=false)
mlir::Value createAlloca(mlir::Location loc, cir::PointerType addrType, llvm::StringRef name, mlir::IntegerAttr alignment, mlir::Value dynAllocSize)
mlir::Value createBitcast(mlir::Value src, mlir::Type newTy)
llvm::TypeSize getTypeSizeInBits(mlir::Type ty) const
llvm::ArrayRef< mlir::Type > getMembers() const
Definition CIRTypes.cpp:648
uint64_t getElementOffset(const mlir::DataLayout &dataLayout, unsigned idx) const
Definition CIRTypes.cpp:706
const LValueBase getLValueBase() const
Definition APValue.cpp:1137
bool isLValue() const
Definition APValue.h:554
CharUnits getTypeAlignInChars(QualType T) const
Return the ABI-specified alignment of a (complete) type T, in characters.
uint64_t getFieldOffset(const ValueDecl *FD) const
Get the offset of a FieldDecl or IndirectFieldDecl, in bits.
static CanQualType getCanonicalType(QualType T)
Return the canonical (structural) type corresponding to the specified potentially non-canonical type ...
QualType getPointerType(QualType T) const
Return the uniqued reference to the type for a pointer to the specified type.
CanQualType BoolTy
llvm::DenseMap< const CXXMethodDecl *, CXXCastPath > LambdaCastPaths
For capturing lambdas with an explicit object parameter whose type is derived from the lambda type,...
CharUnits getDeclAlign(const Decl *D, bool ForAlignof=false) const
Return a conservative estimate of the alignment of the specified decl D.
CharUnits getTypeSizeInChars(QualType T) const
Return the size of the specified (complete) type T, in characters.
const VariableArrayType * getAsVariableArrayType(QualType T) const
CharUnits toCharUnitsFromBits(int64_t BitSize) const
Convert a size in bits to a size in characters.
CanQualType getCanonicalTagType(const TagDecl *TD) const
AbstractConditionalOperator - An abstract base class for ConditionalOperator and BinaryConditionalOpe...
Definition Expr.h:4422
Expr * getCond() const
getCond - Return the expression representing the condition for the ?
Definition Expr.h:4600
Expr * getTrueExpr() const
getTrueExpr - Return the subexpression representing the value of the expression if the condition eval...
Definition Expr.h:4606
Expr * getFalseExpr() const
getFalseExpr - Return the subexpression representing the value of the expression if the condition eva...
Definition Expr.h:4612
ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
Definition Expr.h:2790
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:2845
Expr * getLHS()
An array access can be written A[4] or 4[A] (both are equivalent).
Definition Expr.h:2819
SourceLocation getBeginLoc() const LLVM_READONLY
Definition Expr.h:2833
SourceLocation getEndLoc() const
Definition Expr.h:2836
QualType getElementType() const
Definition TypeBase.h:3832
A builtin binary operation expression such as "x + y" or "x <= y".
Definition Expr.h:4107
Expr * getLHS() const
Definition Expr.h:4157
Expr * getRHS() const
Definition Expr.h:4159
Opcode getOpcode() const
Definition Expr.h:4152
Address withPointer(mlir::Value newPtr) const
Return address with different pointer, but same element type and alignment.
Definition Address.h:83
mlir::ptr::MemorySpaceAttrInterface getAddressSpace() const
Definition Address.h:133
mlir::Value getPointer() const
Definition Address.h:98
mlir::Type getElementType() const
Definition Address.h:125
static Address invalid()
Definition Address.h:76
Address withElementType(CIRGenBuilderTy &builder, mlir::Type ElemTy) const
Return address with different element type, a bitcast pointer, and the same alignment.
clang::CharUnits getAlignment() const
Definition Address.h:138
mlir::Type getType() const
Definition Address.h:117
bool isValid() const
Definition Address.h:77
cir::AllocaOp getUnderlyingAllocaOp() const
Return the underlying alloca for this address, if any.
Definition Address.h:152
mlir::Operation * getDefiningOp() const
Get the operation which defines this address.
Definition Address.h:141
An aggregate value slot.
IsDestructed_t
This is set to true if the slot might be aliased and it's not undefined behavior to access it through...
static AggValueSlot forAddr(Address addr, clang::Qualifiers quals, IsDestructed_t isDestructed, IsAliased_t isAliased, Overlap_t mayOverlap, IsZeroed_t isZeroed=IsNotZeroed)
void setExternallyDestructed(bool destructed=true)
static AggValueSlot ignored()
Returns an aggregate value slot indicating that the aggregate value is being ignored.
cir::ConstantOp getUInt64(uint64_t c, mlir::Location loc)
Address createGetMember(mlir::Location loc, Address base, llvm::StringRef name, unsigned index, const cir::CIRDataLayout &layout)
Address createElementBitCast(mlir::Location loc, Address addr, mlir::Type destType)
Cast the element type of the given address to a different type, preserving information like the align...
mlir::Value getArrayElement(mlir::Location arrayLocBegin, mlir::Location arrayLocEnd, mlir::Value arrayPtr, mlir::Type eltTy, mlir::Value idx, bool shouldDecay, cir::PtrOffsetFlags flags=cir::PtrOffsetFlags::None)
Create a cir.get_element or cir.ptr_stride operation to get access to an array element.
virtual mlir::Operation * getKernelHandle(cir::FuncOp fn, GlobalDecl gd)=0
Abstract information about a function or function prototype.
Definition CIRGenCall.h:27
clang::GlobalDecl getCalleeDecl() const
Definition CIRGenCall.h:44
bool isPseudoDestructor() const
Definition CIRGenCall.h:125
void setFunctionPointer(mlir::Operation *functionPtr)
Definition CIRGenCall.h:187
const clang::FunctionDecl * getBuiltinDecl() const
Definition CIRGenCall.h:101
const CXXPseudoDestructorExpr * getPseudoDestructorExpr() const
Definition CIRGenCall.h:129
static CIRGenCallee forDirect(mlir::Operation *funcPtr, const CIRGenCalleeInfo &abstractInfo=CIRGenCalleeInfo())
Definition CIRGenCall.h:92
unsigned getBuiltinID() const
Definition CIRGenCall.h:105
CIRGenCalleeInfo getAbstractInfo() const
Definition CIRGenCall.h:142
static CIRGenCallee forBuiltin(unsigned builtinID, const clang::FunctionDecl *builtinDecl)
Definition CIRGenCall.h:110
mlir::Operation * getFunctionPointer() const
Definition CIRGenCall.h:149
static CIRGenCallee forPseudoDestructor(const clang::CXXPseudoDestructorExpr *expr)
Definition CIRGenCall.h:119
An object to manage conditionally-evaluated expressions.
static ConstantEmission forReference(mlir::TypedAttr c)
static ConstantEmission forValue(mlir::TypedAttr c)
LValue getReferenceLValue(CIRGenFunction &cgf, const Expr *refExpr) const
An RAII object to set (and then clear) a mapping for an OpaqueValueExpr.
Enters a new scope for capturing cleanups, all of which will be executed once the scope is exited.
void forceCleanup(ArrayRef< mlir::Value * > valuesToReload={})
Force the emission of cleanups now, instead of waiting until this object is destroyed.
mlir::Value emitComplexToScalarConversion(mlir::Value src, QualType srcTy, QualType dstTy, SourceLocation loc)
Emit a conversion from the specified complex type to the specified destination type,...
mlir::Type convertType(clang::QualType t)
LValue emitCXXBindTemporaryLValue(const CXXBindTemporaryExpr *e)
LValue emitOpaqueValueLValue(const OpaqueValueExpr *e)
static cir::TypeEvaluationKind getEvaluationKind(clang::QualType type)
Return the cir::TypeEvaluationKind of QualType type.
RValue convertTempToRValue(Address addr, clang::QualType type, clang::SourceLocation loc)
Given the address of a temporary variable, produce an r-value of its type.
Address emitCXXMemberDataPointerAddress(const Expr *e, Address base, mlir::Value memberPtr, const MemberPointerType *memberPtrType, LValueBaseInfo *baseInfo)
Address emitFieldAnnotations(const clang::FieldDecl *field, Address addr)
Annotate the address of field; accesses must use the result.
CIRGenTypes & getTypes() const
Address emitPointerWithAlignment(const clang::Expr *expr, LValueBaseInfo *baseInfo=nullptr)
Given an expression with a pointer type, emit the value and compute our best estimate of the alignmen...
void emitVariablyModifiedType(QualType ty)
RValue emitLoadOfLValue(LValue lv, SourceLocation loc)
Given an expression that represents a value lvalue, this method emits the address of the lvalue,...
const clang::LangOptions & getLangOpts() const
cir::AllocaOp createTempAlloca(mlir::Type ty, mlir::Location loc, const Twine &name="tmp", mlir::Value arraySize=nullptr, bool insertIntoFnEntryBlock=false)
This creates an alloca and inserts it into the entry block if ArraySize is nullptr,...
void emitTrap(mlir::Location loc, bool createNewBlock)
Emit a trap instruction, which is used to abort the program in an abnormal way, usually for debugging...
mlir::Block * getCurFunctionEntryBlock()
RValue emitCXXMemberCallExpr(const clang::CXXMemberCallExpr *e, ReturnValueSlot returnValue)
RValue emitCXXMemberPointerCallExpr(const CXXMemberCallExpr *ce, ReturnValueSlot returnValue)
LValue emitLValueForBitField(LValue base, const FieldDecl *field)
mlir::LogicalResult emitIfOnBoolExpr(const clang::Expr *cond, const clang::Stmt *thenS, const clang::Stmt *elseS)
Emit an if on a boolean condition to the specified blocks.
VlaSizePair getVLASize(const VariableArrayType *type)
Returns an MLIR::Value+QualType pair that corresponds to the size, in non-variably-sized elements,...
cir::IfOp emitIfOnBoolValue(mlir::Value condV, mlir::Location loc, BuilderCallbackRef thenBuilder, mlir::Location thenLoc, BuilderCallbackRef elseBuilder, std::optional< mlir::Location > elseLoc={})
Build the cir.if for an already-emitted condition value.
mlir::Value emitComplexExpr(const Expr *e)
Emit the computation of the specified expression of complex type, returning the result.
LValue makeNaturalAlignPointeeAddrLValue(mlir::Value v, clang::QualType t)
Given a value of type T* that may not be to a complete object, construct an l-vlaue withi the natural...
RValue emitCallExpr(const clang::CallExpr *e, ReturnValueSlot returnValue=ReturnValueSlot())
LValue emitMemberExpr(const MemberExpr *e)
LValue emitConditionalOperatorLValue(const AbstractConditionalOperator *expr)
LValue emitLValue(const clang::Expr *e)
Emit code to compute a designator that specifies the location of the expression.
Address makeNaturalAddressForPointer(mlir::Value ptr, QualType t, CharUnits alignment, bool forPointeeType=false, LValueBaseInfo *baseInfo=nullptr)
Construct an address with the natural alignment of T.
LValue emitLValueForLambdaField(const FieldDecl *field)
mlir::Value evaluateExprAsBool(const clang::Expr *e)
Perform the usual unary conversions on the specified expression and compare the result against zero,...
LValue makeNaturalAlignAddrLValue(mlir::Value val, QualType ty)
bool constantFoldsToSimpleInteger(const clang::Expr *cond, llvm::APSInt &resultInt, bool allowLabels=false)
If the specified expression does not fold to a constant, or if it does fold but contains a label,...
mlir::Location getLoc(clang::SourceLocation srcLoc)
Helpers to convert Clang's SourceLocation to a MLIR Location.
mlir::Value emitOpOnBoolExpr(mlir::Location loc, const clang::Expr *cond)
TODO(cir): see EmitBranchOnBoolExpr for extra ideas).
void emitStoreThroughExtVectorComponentLValue(RValue src, LValue dst)
CodeGenUtils::EvaluationOrder EvaluationOrder
void emitCallArgs(CallArgList &args, PrototypeWrapper prototype, llvm::iterator_range< clang::CallExpr::const_arg_iterator > argRange, AbstractCallee callee=AbstractCallee(), unsigned paramsToSkip=0, EvaluationOrder order=EvaluationOrder::Default)
Address getAddressOfBaseClass(Address value, const CXXRecordDecl *derived, llvm::iterator_range< CastExpr::path_const_iterator > path, bool nullCheckValue, SourceLocation loc)
LValue emitLoadOfReferenceLValue(Address refAddr, mlir::Location loc, QualType refTy, AlignmentSource source)
void emitAnyExprToMem(const Expr *e, Address location, Qualifiers quals, bool isInitializer)
Emits the code necessary to evaluate an arbitrary expression into the given memory location.
LValue getOrCreateOpaqueLValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its LValue mapping if it exists, otherwise create one.
mlir::Value performAddrSpaceCast(mlir::Value v, mlir::Type destTy) const
RValue emitReferenceBindingToExpr(const Expr *e)
Emits a reference binding to the passed in expression.
LValue emitArraySubscriptExpr(const clang::ArraySubscriptExpr *e)
RValue emitCUDAKernelCallExpr(const CUDAKernelCallExpr *expr, ReturnValueSlot returnValue)
mlir::Operation * curFn
The current function or global initializer that is generated code for.
Address emitExtVectorElementLValue(LValue lv, mlir::Location loc)
Generates lvalue for partial ext_vector access.
mlir::Value emitScalarConversion(mlir::Value src, clang::QualType srcType, clang::QualType dstType, clang::SourceLocation loc)
Emit a conversion from the specified type to the specified destination type, both of which are CIR sc...
Address getAddressOfDerivedClass(mlir::Location loc, Address baseAddr, const CXXRecordDecl *derived, llvm::iterator_range< CastExpr::path_const_iterator > path, bool nullCheckValue)
Address maybeCastStackAddressSpace(Address alloca, mlir::ptr::MemorySpaceAttrInterface destAddrSpace, mlir::Value arraySize=nullptr)
RValue emitAtomicLoad(LValue lvalue, SourceLocation loc, AggValueSlot slot=AggValueSlot::ignored())
AggValueSlot createAggTemp(QualType ty, mlir::Location loc, const Twine &name="tmp", Address *alloca=nullptr)
Create a temporary memory object for the given aggregate type.
RValue emitLoadOfExtVectorElementLValue(LValue lv)
mlir::Value emitCXXTypeidExpr(const CXXTypeidExpr *e)
mlir::Type convertTypeForMem(QualType t)
mlir::Value emitAlloca(llvm::StringRef name, mlir::Type ty, mlir::Location loc, clang::CharUnits alignment, bool insertIntoFnEntryBlock, mlir::Value arraySize=nullptr)
mlir::Value emitComplexPrePostIncDec(const UnaryOperator *e, LValue lv)
void emitUnreachable(clang::SourceLocation loc, bool createNewBlock)
Emit a reached-unreachable diagnostic if loc is valid and runtime checking is enabled.
mlir::Value createDummyValue(mlir::Location loc, clang::QualType qt)
void emitCXXConstructExpr(const clang::CXXConstructExpr *e, AggValueSlot dest)
mlir::Value emitLoadOfComplex(LValue src, SourceLocation loc)
Load a complex number from the specified l-value.
LValue emitAggExprToLValue(const Expr *e)
void emitStoreOfScalar(mlir::Value value, Address addr, bool isVolatile, clang::QualType ty, LValueBaseInfo baseInfo, bool isInit=false, bool isNontemporal=false)
void pushDestroy(QualType::DestructionKind dtorKind, Address addr, QualType type)
Push the standard destructor for the given type as at least a normal cleanup.
RValue getUndefRValue(clang::QualType ty)
Get an appropriate 'undef' rvalue for the given type.
Address returnValue
The temporary alloca to hold the return value.
static bool hasAggregateEvaluationKind(clang::QualType type)
LValue emitPointerToDataMemberBinaryExpr(const BinaryOperator *e)
LValue emitUnaryOpLValue(const clang::UnaryOperator *e)
LValue emitMatrixSubscriptExpr(const MatrixSubscriptExpr *e)
RValue emitLoadOfBitfieldLValue(LValue lv, SourceLocation loc)
LValue emitComplexAssignmentLValue(const BinaryOperator *e)
const clang::Decl * curCodeDecl
This is the inner-most code context, which includes blocks.
LValue emitLValueForFieldInitialization(LValue base, const clang::FieldDecl *field, llvm::StringRef fieldName)
Like emitLValueForField, excpet that if the Field is a reference, this will return the address of the...
LValue emitCallExprLValue(const clang::CallExpr *e)
void emitCXXTemporary(const CXXTemporary *temporary, QualType tempType, Address ptr)
Emits all the code to cause the given temporary to be cleaned up.
LValue emitStringLiteralLValue(const StringLiteral *e, llvm::StringRef name=".str")
mlir::Value getUndefConstant(mlir::Location loc, mlir::Type cirTy)
Return a CIR constant for an undefined value of cirTy.
mlir::Value emitToMemory(mlir::Value value, clang::QualType ty)
Given a value and its clang type, returns the value casted to its memory representation.
LValue emitLValueForField(LValue base, const clang::FieldDecl *field)
mlir::Value emitScalarExpr(const clang::Expr *e, bool ignoreResultAssign=false)
Emit the computation of the specified expression of scalar type.
void pushLifetimeExtendedDestroy(CleanupKind kind, Address addr, QualType type, Destroyer *destroyer, bool useEHCleanupForArray, const clang::ValueDecl *extendingDecl)
Address emitLoadOfReference(LValue refLVal, mlir::Location loc, LValueBaseInfo *pointeeBaseInfo)
bool shouldNullCheckClassCastValue(const CastExpr *ce)
CIRGenBuilderTy & getBuilder()
LValue emitBinaryOperatorLValue(const BinaryOperator *e)
Address getAddrOfBitFieldStorage(LValue base, const clang::FieldDecl *field, mlir::Type fieldType, unsigned index)
void emitDestroy(Address addr, QualType type, Destroyer *destroyer)
Immediately perform the destruction of the given object.
mlir::MLIRContext & getMLIRContext()
std::optional< SourceRange > currSrcLoc
Use to track source locations across nested visitor traversals.
LValue emitCastLValue(const CastExpr *e)
Casts are never lvalues unless that cast is to a reference type.
LValue emitCXXTypeidLValue(const CXXTypeidExpr *e)
mlir::Value emitLoadOfScalar(LValue lvalue, SourceLocation loc)
EmitLoadOfScalar - Load a scalar value from an address, taking care to appropriately convert from the...
mlir::Value emitScalarPrePostIncDec(const UnaryOperator *e, LValue lv)
bool containsLabel(const clang::Stmt *s, bool ignoreCaseStmts=false)
Return true if the statement contains a label in it.
DeclMapTy localDeclMap
This keeps track of the CIR allocas or globals for local C declarations.
LValue emitDeclRefLValue(const clang::DeclRefExpr *e)
void emitComplexExprIntoLValue(const Expr *e, LValue dest, bool isInit)
llvm::DenseMap< const clang::ValueDecl *, clang::FieldDecl * > lambdaCaptureFields
ConstantEmission tryEmitAsConstant(const DeclRefExpr *refExpr)
Try to emit a reference to the given value without producing it as an l-value.
RValue emitCall(const CIRGenFunctionInfo &funcInfo, const CIRGenCallee &callee, ReturnValueSlot returnValue, const CallArgList &args, cir::CIRCallOpInterface *callOp, bool isMustTail, SourceRange clangLoc)
void emitCXXThrowExpr(const CXXThrowExpr *e)
LValue makeAddrLValue(Address addr, QualType ty, AlignmentSource source=AlignmentSource::Type)
LValue emitMatrixElementExpr(const MatrixElementExpr *e)
int64_t getAccessedFieldNo(unsigned idx, mlir::ArrayAttr elts)
LValue emitPredefinedLValue(const PredefinedExpr *e)
RValue emitAnyExpr(const clang::Expr *e, AggValueSlot aggSlot=AggValueSlot::ignored(), bool ignoreResult=false)
Emit code to compute the specified expression which can have any type.
llvm::DenseMap< const OpaqueValueExpr *, RValue > opaqueRValues
Address emitArrayToPointerDecay(const Expr *e, LValueBaseInfo *baseInfo=nullptr)
void emitAtomicStore(RValue rvalue, LValue dest, bool isInit)
mlir::Value emitStoreThroughBitfieldLValue(RValue src, LValue dstresult)
llvm::DenseMap< const OpaqueValueExpr *, LValue > opaqueLValues
Keeps track of the current set of opaque value expressions.
CIRGenFunction(CIRGenModule &cgm, CIRGenBuilderTy &builder, bool suppressNewContext=false)
void terminateStructuredRegionBody(mlir::Region &r, mlir::Location loc)
Address createMemTempWithoutCast(QualType t, mlir::Location loc, const Twine &name="tmp")
LValue emitMaterializeTemporaryExpr(const MaterializeTemporaryExpr *e)
LValue emitExtVectorElementExpr(const ExtVectorElementExpr *e)
clang::ASTContext & getContext() const
RValue emitCXXMemberOrOperatorMemberCallExpr(const clang::CallExpr *ce, const clang::CXXMethodDecl *md, ReturnValueSlot returnValue, bool hasQualifier, clang::NestedNameSpecifier qualifier, bool isArrow, const clang::Expr *base)
mlir::Value emitScalarConstant(const ConstantEmission &constant, Expr *e)
RValue emitBuiltinExpr(const clang::GlobalDecl &gd, unsigned builtinID, const clang::CallExpr *e, ReturnValueSlot returnValue)
RValue emitCXXOperatorMemberCallExpr(const CXXOperatorCallExpr *e, const CXXMethodDecl *md, ReturnValueSlot returnValue)
void emitStoreThroughLValue(RValue src, LValue dst, bool isInit=false)
Store the specified rvalue into the specified lvalue, where both are guaranteed to the have the same ...
bool isLValueSuitableForInlineAtomic(LValue lv)
An LValue is a candidate for having its loads and stores be made atomic if we are operating under /vo...
mlir::LogicalResult emitStmt(const clang::Stmt *s, bool useCurrentScope, llvm::ArrayRef< const Attr * > attrs={})
RValue getOrCreateOpaqueRValueMapping(const OpaqueValueExpr *e)
Given an opaque value expression, return its RValue mapping if it exists, otherwise create one.
Address createTempAllocaWithoutCast(mlir::Type ty, CharUnits align, mlir::Location loc, const Twine &name="tmp", mlir::Value arraySize=nullptr, mlir::OpBuilder::InsertPoint ip={})
This creates a alloca and inserts it into the entry block of the current region.
mlir::Value emitFromMemory(mlir::Value value, clang::QualType ty)
EmitFromMemory - Change a scalar value from its memory representation to its value representation.
void emitIgnoredExpr(const clang::Expr *e)
Emit code to compute the specified expression, ignoring the result.
Address createMemTemp(QualType t, mlir::Location loc, const Twine &name="tmp", Address *alloca=nullptr, mlir::OpBuilder::InsertPoint ip={})
Create a temporary memory object of the given type, with appropriate alignmen and cast it to the defa...
mlir::Value emitDynamicCast(Address thisAddr, const CXXDynamicCastExpr *dce)
void emitAggExpr(const clang::Expr *e, AggValueSlot slot)
ConditionalInfo emitConditionalBlocks(const AbstractConditionalOperator *e, const FuncTy &branchGenFunc)
Address createDefaultAlignTempAlloca(mlir::Type ty, mlir::Location loc, const Twine &name)
CreateDefaultAlignTempAlloca - This creates an alloca with the default alignment of the corresponding...
LValue emitCXXConstructLValue(const CXXConstructExpr *e)
RValue emitCXXPseudoDestructorExpr(const CXXPseudoDestructorExpr *expr)
LValue emitCompoundLiteralLValue(const CompoundLiteralExpr *e)
CIRGenCallee emitCallee(const clang::Expr *e)
Address emitAddrOfFieldStorage(Address base, const FieldDecl *field, llvm::StringRef fieldName, unsigned fieldIndex)
This class organizes the cross-function state that is used while generating CIR code.
DiagnosticBuilder errorNYI(SourceLocation, llvm::StringRef)
Helpers to emit "not yet implemented" error diagnostics.
cir::GlobalLinkageKind getCIRLinkageVarDefinition(const VarDecl *vd)
mlir::Operation * getWeakRefReference(const clang::ValueDecl *vd)
Return the symbol that a weakref declaration refers to: the cir.func or cir.global named by its alias...
CIRGenCUDARuntime & getCUDARuntime()
mlir::IntegerAttr getSize(CharUnits size)
CIRGenBuilderTy & getBuilder()
std::pair< cir::FuncType, cir::FuncOp > getAddrAndTypeOfCXXStructor(clang::GlobalDecl gd, const CIRGenFunctionInfo *fnInfo=nullptr, cir::FuncType fnType=nullptr, bool dontDefer=false, ForDefinition_t isForDefinition=NotForDefinition)
cir::FuncOp getRawFunctionPointer(GlobalDecl GD)
Return a function pointer for a reference to the given function.
cir::FuncOp getAddrOfFunction(clang::GlobalDecl gd, mlir::Type funcType=nullptr, bool forVTable=false, bool dontDefer=false, ForDefinition_t isForDefinition=NotForDefinition)
Return the address of the given function.
mlir::Operation * getAddrOfGlobalTemporary(const MaterializeTemporaryExpr *mte, const Expr *init)
Returns a pointer to a global variable representing a temporary with static or thread storage duratio...
mlir::Value getAddrOfGlobalVar(const VarDecl *d, mlir::Type ty={}, ForDefinition_t isForDefinition=NotForDefinition)
Return the mlir::Value for the address of the given global variable.
const clang::LangOptions & getLangOpts() const
mlir::Location getLoc(clang::SourceLocation cLoc)
Helpers to convert the presumed location of Clang's SourceLocation to an MLIR Location.
cir::FuncOp getFunctionPointer(GlobalDecl GD)
Return the ABI-correct function pointer value for a reference to the given function.
CIRGenOpenMPRuntime & getOpenMPRuntime()
bool hasRequiresUnifiedSharedMemory() const
Return whether unified shared memory is required.
This class handles record and union layout info while lowering AST types to CIR types.
cir::RecordType getCIRType() const
Return the "complete object" LLVM type associated with this record.
const CIRGenBitFieldInfo & getBitFieldInfo(const clang::FieldDecl *fd) const
Return the BitFieldInfo that corresponds to the field FD.
unsigned getCIRFieldNo(const clang::FieldDecl *fd) const
Return cir::RecordType element number that corresponds to the field FD.
bool hasCIRField(const clang::FieldDecl *fd) const
mlir::ptr::MemorySpaceAttrInterface getPointerAddressSpace(clang::QualType pointeeTy) const
Returns the CIR address space for a pointer/reference to pointeeTy, or a null attribute for the defau...
cir::FuncType getFunctionType(const CIRGenFunctionInfo &info)
Get the CIR function type for.
mlir::Type convertTypeForMem(clang::QualType, bool forBitField=false)
Convert type T into an mlir::Type.
mlir::Attribute emitAbstract(const Expr *e, QualType destType)
Emit the result of the given expression as an abstract constant, asserting that it succeeded.
AlignmentSource getAlignmentSource() const
void mergeForCast(const LValueBaseInfo &info)
bool isExtVectorElt() const
mlir::Value getVectorPointer() const
const clang::Qualifiers & getQuals() const
mlir::Value getExtVectorPointer() const
bool isMatrixRow() const
static LValue makeExtVectorElt(Address vecAddress, mlir::ArrayAttr elts, clang::QualType type, LValueBaseInfo baseInfo)
mlir::Value getVectorIdx() const
bool isVectorElt() const
Address getAddress() const
static LValue makeAddr(Address address, clang::QualType t, LValueBaseInfo baseInfo)
mlir::ArrayAttr getExtVectorElts() const
bool isMatrixElt() const
static LValue makeVectorElt(Address vecAddress, mlir::Value index, clang::QualType t, LValueBaseInfo baseInfo)
RValue asAggregateRValue() const
unsigned getVRQualifiers() const
clang::QualType getType() const
static LValue makeBitfield(Address addr, const CIRGenBitFieldInfo &info, clang::QualType type, LValueBaseInfo baseInfo)
Create a new object to represent a bit-field access.
mlir::Value getPointer() const
Address getMatrixAddress() const
void setNontemporal(bool v)
bool isVolatileQualified() const
bool isBitField() const
Address getVectorAddress() const
clang::CharUnits getAlignment() const
LValueBaseInfo getBaseInfo() const
mlir::Value getMatrixColumnIdx() const
bool isNontemporal() const
bool isVolatile() const
static LValue makeMatrixElt(Address matAddress, mlir::Value rowIdx, mlir::Value colIdx, clang::QualType t, LValueBaseInfo baseInfo)
const CIRGenBitFieldInfo & getBitFieldInfo() const
Address getBitFieldAddress() const
Address getExtVectorAddress() const
mlir::Value getMatrixRowIdx() const
bool isSimple() const
This trivial value class is used to represent the result of an expression that is evaluated.
Definition CIRGenValue.h:33
Address getAggregateAddress() const
Return the value of the address of the aggregate.
Definition CIRGenValue.h:69
static RValue get(mlir::Value v)
Definition CIRGenValue.h:83
static RValue getAggregate(Address addr, bool isVolatile=false)
Convert an Address to an RValue.
static RValue getComplex(mlir::Value v)
Definition CIRGenValue.h:91
mlir::Value getValue() const
Return the value of this scalar value.
Definition CIRGenValue.h:57
bool isScalar() const
Definition CIRGenValue.h:49
Contains the address where the return value of a function can be stored, and whether the address is v...
Definition CIRGenCall.h:262
Represents binding an expression to a temporary.
Definition ExprCXX.h:1498
CXXTemporary * getTemporary()
Definition ExprCXX.h:1516
const Expr * getSubExpr() const
Definition ExprCXX.h:1520
Represents a call to a C++ constructor.
Definition ExprCXX.h:1553
Represents a C++ destructor within a class.
Definition DeclCXX.h:2924
Represents a call to a member function that may be written either with member call syntax (e....
Definition ExprCXX.h:184
Represents a C++ struct/union/class.
Definition DeclCXX.h:258
bool hasTrivialDestructor() const
Determine whether this class has a trivial destructor (C++ [class.dtor]p3)
Definition DeclCXX.h:1382
A C++ typeid expression (C++ [expr.typeid]), which gets the type_info that corresponds to the supplie...
Definition ExprCXX.h:853
CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
Definition Expr.h:3012
Expr * getArg(unsigned Arg)
getArg - Return the specified argument.
Definition Expr.h:3216
FunctionDecl * getDirectCallee()
If the callee is a FunctionDecl, return it. Otherwise return null.
Definition Expr.h:3195
Expr * getCallee()
Definition Expr.h:3159
arg_range arguments()
Definition Expr.h:3264
QualType getCallReturnType(const ASTContext &Ctx) const
getCallReturnType - Get the return type of the call expr.
Definition Expr.cpp:1635
CastExpr - Base class for type casts, including both implicit casts (ImplicitCastExpr) and explicit c...
Definition Expr.h:3745
CastKind getCastKind() const
Definition Expr.h:3789
llvm::iterator_range< path_iterator > path()
Path through the class hierarchy taken by casts between base and derived classes (see implementation ...
Definition Expr.h:3832
bool changesVolatileQualification() const
Return.
Definition Expr.h:3879
Expr * getSubExpr()
Definition Expr.h:3795
This is an opaque type for sizes expressed in character units.
Definition CharUnits.h:38
CharUnits alignmentAtOffset(CharUnits offset) const
Given that this is a non-zero alignment value, what is the alignment at the given offset?
Definition CharUnits.h:177
bool isZero() const
Test whether the quantity equals zero.
Definition CharUnits.h:101
QuantityType getQuantity() const
Get the raw integer representation of this quantity.
Definition CharUnits.h:155
static CharUnits One()
Construct a CharUnits quantity of one.
Definition CharUnits.h:55
CharUnits alignmentOfArrayElement(CharUnits elementSize) const
Given that this is the alignment of the first element of an array, return the minimum alignment of an...
Definition CharUnits.h:184
static CharUnits fromQuantity(QuantityType Quantity)
Construct a CharUnits quantity from a raw integer type.
Definition CharUnits.h:58
Complex values, per C99 6.2.5p11.
Definition TypeBase.h:3362
CompoundLiteralExpr - [C99 6.5.2.5].
Definition Expr.h:3674
bool isFileScope() const
Definition Expr.h:3706
const Expr * getInitializer() const
Definition Expr.h:3702
ConditionalOperator - The ?
Definition Expr.h:4460
Represents a concrete matrix type with constant number of rows and columns.
Definition TypeBase.h:4622
unsigned getNumColumns() const
Returns the number of columns in the matrix.
Definition TypeBase.h:4644
A reference to a declared variable, function, enum, etc.
Definition Expr.h:1315
bool refersToEnclosingVariableOrCapture() const
Does this DeclRefExpr refer to an enclosing local or a captured variable?
Definition Expr.h:1519
static DeclRefExpr * Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc, SourceLocation TemplateKWLoc, ValueDecl *D, bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc, QualType T, ExprValueKind VK, NamedDecl *FoundD=nullptr, const TemplateArgumentListInfo *TemplateArgs=nullptr, NonOdrUseReason NOUR=NOUR_None)
Definition Expr.cpp:498
ValueDecl * getDecl()
Definition Expr.h:1383
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:1513
SourceLocation getLocation() const
Definition Expr.h:1391
Decl - This represents one declaration (or definition), e.g.
Definition DeclBase.h:86
SourceLocation getLocation() const
Definition DeclBase.h:448
bool isUsed(bool CheckUsedAttr=true) const
Whether any (re-)declaration of the entity was used, meaning that a definition is required.
Definition DeclBase.cpp:579
DeclContext * getDeclContext()
Definition DeclBase.h:457
bool hasAttr() const
Definition DeclBase.h:586
const Expr * getBase() const
Definition Expr.h:6667
This represents one expression.
Definition Expr.h:114
const Expr * skipRValueSubobjectAdjustments(SmallVectorImpl< const Expr * > &CommaLHS, SmallVectorImpl< SubobjectAdjustment > &Adjustments) const
Walk outwards from an expression we want to bind a reference to and find the expression whose lifetim...
Definition Expr.cpp:85
bool isGLValue() const
Definition Expr.h:289
ExprValueKind getValueKind() const
getValueKind - The value kind that this expression produces.
Definition Expr.h:449
Expr * IgnoreParens() LLVM_READONLY
Skip past any parentheses which might surround this expression until reaching a fixed point.
Definition Expr.cpp:3125
bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsLValue - Evaluate an expression to see if we can fold it to an lvalue with link time known ...
bool isPRValue() const
Definition Expr.h:287
bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx, bool InConstantContext=false) const
EvaluateAsRValue - Return true if this is a constant which we can fold to an rvalue using any crazy t...
Decl * getReferencedDeclOfCallee()
Definition Expr.cpp:1578
SourceLocation getExprLoc() const LLVM_READONLY
getExprLoc - Return the preferred location for the arrow when diagnosing a problem with a generic exp...
Definition Expr.cpp:283
QualType getType() const
Definition Expr.h:146
ExtVectorElementExpr - This represents access to specific elements of a vector, and may occur on the ...
Definition Expr.h:6696
bool isArrow() const
isArrow - Return true if the base expression is a pointer to vector, return false if the base express...
Definition Expr.cpp:4485
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4598
Represents a member of a struct/union/class.
Definition Decl.h:3341
bool isBitField() const
Determines whether this field is a bitfield.
Definition Decl.h:3444
SourceRange getSourceRange() const override LLVM_READONLY
Source range that this declaration covers.
Definition Decl.cpp:4929
unsigned getFieldIndex() const
Returns the index of this field within its record, as appropriate for passing to ASTRecordLayout::get...
Definition Decl.h:3426
const RecordDecl * getParent() const
Returns the parent of this field declaration, which is the struct in which this field is defined.
Definition Decl.h:3577
bool isPotentiallyOverlapping() const
Determine if this field is of potentially-overlapping class type, that is, subobject with the [[no_un...
Definition Decl.cpp:4907
Represents a function declaration or definition.
Definition Decl.h:2082
Represents a prototype with parameter type info, e.g.
Definition TypeBase.h:5548
GlobalDecl - represents a global declaration.
Definition GlobalDecl.h:60
const Decl * getDecl() const
Definition GlobalDecl.h:115
Represents a prvalue temporary that is written into memory so that a reference can bind to it.
Definition ExprCXX.h:4974
StorageDuration getStorageDuration() const
Retrieve the storage duration for the materialized temporary.
Definition ExprCXX.h:4999
Expr * getSubExpr() const
Retrieve the temporary-generating subexpression whose value will be materialized into a glvalue.
Definition ExprCXX.h:4991
ValueDecl * getExtendingDecl()
Get the declaration which triggered the lifetime-extension of this temporary, if any.
Definition ExprCXX.h:5024
void getEncodedElementAccess(SmallVectorImpl< uint32_t > &Elts) const
getEncodedElementAccess - Encode the elements accessed into an llvm aggregate Constant of ConstantInt...
Definition Expr.cpp:4630
MatrixSubscriptExpr - Matrix subscript expression for the MatrixType extension.
Definition Expr.h:2934
bool isIncomplete() const
Definition Expr.h:2954
MemberExpr - [C99 6.5.2.3] Structure and Union Members.
Definition Expr.h:3433
ValueDecl * getMemberDecl() const
Retrieve the member declaration to which this expression refers.
Definition Expr.h:3516
NonOdrUseReason isNonOdrUse() const
Is this expression a non-odr-use reference, and if so, why?
Definition Expr.h:3657
Expr * getBase() const
Definition Expr.h:3510
bool isArrow() const
Definition Expr.h:3617
SourceLocation getExprLoc() const LLVM_READONLY
Definition Expr.h:3628
A pointer to member type per C++ 8.3.3 - Pointers to members.
Definition TypeBase.h:3751
This represents a decl that may have a name.
Definition Decl.h:276
StringRef getName() const
Get the name of identifier for this declaration as a StringRef.
Definition Decl.h:303
A C++ nested-name-specifier augmented with source location information.
Represents a C++ nested name specifier, such as "\::std::vector<int>::".
OpaqueValueExpr - An expression referring to an opaque object of a fixed type and value class.
Definition Expr.h:1223
Expr * getSourceExpr() const
The source expression of an opaque value expression is the expression which originally generated the ...
Definition Expr.h:1273
bool isUnique() const
Definition Expr.h:1281
PointerType - C99 6.7.5.1 - Pointer Declarators.
Definition TypeBase.h:3403
[C99 6.4.2.2] - A predefined identifier such as func.
Definition Expr.h:2074
StringRef getIdentKindName() const
Definition Expr.h:2131
PredefinedIdentKind getIdentKind() const
Definition Expr.h:2109
StringLiteral * getFunctionName()
Definition Expr.h:2118
A (possibly-)qualified type.
Definition TypeBase.h:938
bool isNull() const
Return true if this QualType doesn't point to a type yet.
Definition TypeBase.h:1005
LangAS getAddressSpace() const
Return the address space of this type.
Definition TypeBase.h:8704
Qualifiers getQualifiers() const
Retrieve the set of qualifiers applied to this type.
Definition TypeBase.h:8618
Qualifiers::ObjCLifetime getObjCLifetime() const
Returns lifetime attribute of this type.
Definition TypeBase.h:1454
QualType getNonReferenceType() const
If Type is a reference type (e.g., const int&), returns the type that the reference refers to ("const...
Definition TypeBase.h:8763
QualType getUnqualifiedType() const
Retrieve the unqualified variant of the given type, removing as little sugar as possible.
Definition TypeBase.h:8672
QualType withCVRQualifiers(unsigned CVR) const
Definition TypeBase.h:1195
DestructionKind isDestructedType() const
Returns a nonzero value if objects of this type require non-trivial work to clean up after.
Definition TypeBase.h:1561
The collection of all-type qualifiers we support.
Definition TypeBase.h:332
unsigned getCVRQualifiers() const
Definition TypeBase.h:489
GC getObjCGCAttr() const
Definition TypeBase.h:520
@ OCL_ExplicitNone
This object can be modified without requiring retains or releases.
Definition TypeBase.h:355
@ OCL_None
There is no lifetime qualification on this type.
Definition TypeBase.h:351
void addCVRQualifiers(unsigned mask)
Definition TypeBase.h:503
void addQualifiers(Qualifiers Q)
Add the qualifiers from the given set to this set.
Definition TypeBase.h:651
Represents a struct/union/class.
Definition Decl.h:4506
Encodes a location in the source.
bool isValid() const
Return true if this is a valid SourceLocation object.
Stmt - This represents one statement.
Definition Stmt.h:85
SourceRange getSourceRange() const LLVM_READONLY
SourceLocation tokens are not useful in isolation - they are low level value objects created/interpre...
Definition Stmt.cpp:343
StringLiteral - This represents a string literal expression, e.g.
Definition Expr.h:1844
bool isUnion() const
Definition Decl.h:4109
bool isBlockPointerType() const
Definition TypeBase.h:8835
bool isVoidType() const
Definition TypeBase.h:9200
bool isSignedIntegerOrEnumerationType() const
Determines whether this is an integer type that is signed or an enumeration types whose underlying ty...
Definition Type.cpp:2417
bool isPackedVectorBoolType(const ASTContext &ctx) const
Definition Type.cpp:542
const ArrayType * castAsArrayTypeUnsafe() const
A variant of castAs<> for array type which silently discards qualifiers from the outermost type.
Definition TypeBase.h:9507
CXXRecordDecl * getAsCXXRecordDecl() const
Retrieves the CXXRecordDecl that this type refers to, either because the type is a RecordType or beca...
Definition Type.h:26
bool isArrayType() const
Definition TypeBase.h:8914
bool isFunctionPointerType() const
Definition TypeBase.h:8882
CXXRecordDecl * castAsCXXRecordDecl() const
Definition Type.h:36
bool isArithmeticType() const
Definition Type.cpp:2552
bool isConstantMatrixType() const
Definition TypeBase.h:8982
bool isPointerType() const
Definition TypeBase.h:8815
const T * castAs() const
Member-template castAs<specific type>.
Definition TypeBase.h:9498
bool isReferenceType() const
Definition TypeBase.h:8839
bool isVariableArrayType() const
Definition TypeBase.h:8926
QualType getPointeeType() const
If this is a pointer, ObjC object pointer, or block pointer, this returns the respective pointee.
Definition Type.cpp:885
bool isExtVectorBoolType() const
Definition TypeBase.h:8962
bool isConstantMatrixBoolType() const
Definition TypeBase.h:8968
bool isAnyComplexType() const
Definition TypeBase.h:8950
const Type * getBaseElementTypeUnsafe() const
Get the base element type of this type, potentially discarding type qualifiers.
Definition TypeBase.h:9384
bool isAtomicType() const
Definition TypeBase.h:9007
bool isVariablyModifiedType() const
Whether this type is a variably-modified type (C99 6.7.5).
Definition TypeBase.h:2881
bool isFunctionType() const
Definition TypeBase.h:8811
bool isVectorType() const
Definition TypeBase.h:8954
bool isSubscriptableVectorType() const
Definition TypeBase.h:8974
const T * getAs() const
Member-template getAs<specific type>'.
Definition TypeBase.h:9431
UnaryOperator - This represents the unary-expression's (except sizeof and alignof),...
Definition Expr.h:2313
SourceLocation getExprLoc() const
Definition Expr.h:2437
Expr * getSubExpr() const
Definition Expr.h:2354
Opcode getOpcode() const
Definition Expr.h:2349
static bool isPrefix(Opcode Op)
isPrefix - Return true if this is a prefix operation, like –x.
Definition Expr.h:2388
Represent the declaration of a variable (in which case it is an lvalue) a function (in which case it ...
Definition Decl.h:714
QualType getType() const
Definition Decl.h:725
Represents a variable declaration or definition.
Definition Decl.h:934
bool hasInit() const
Definition Decl.cpp:2400
VarDecl * getDefinition(ASTContext &)
Get the real (not just tentative) definition for this declaration.
Definition Decl.cpp:2368
bool hasLocalStorage() const
Returns true if a variable with function scope is a non-static local variable.
Definition Decl.h:1192
@ TLS_None
Not a TLS variable.
Definition Decl.h:954
Represents a C array with a specified size that is not an integer-constant-expression.
Definition TypeBase.h:4064
Represents a GCC generic vector type.
Definition TypeBase.h:4398
Defines the clang::TargetInfo interface.
mlir::ptr::MemorySpaceAttrInterface toCIRAddressSpaceAttr(mlir::MLIRContext &ctx, clang::LangAS langAS)
Convert an AST LangAS to the appropriate CIR address space attribute interface.
mlir::ptr::MemorySpaceAttrInterface normalizeDefaultAddressSpace(mlir::ptr::MemorySpaceAttrInterface addrSpace)
Normalize LangAddressSpace::Default to null (empty attribute).
PtrOffsetFlags
No-wrap flags of a pointer offset computation: the subset of llvm::GEPNoWrapFlags that cir....
AlignmentSource
The source of the alignment of an l-value; an expression of confidence in the alignment actually matc...
@ Decl
The l-value was an access to a declared entity or something equivalently strong, like the address of ...
static AlignmentSource getFieldAlignmentSource(AlignmentSource source)
Given that the base address has the given alignment source, what's our confidence in the alignment of...
bool isAAPCS(const TargetInfo &TargetInfo)
Helper method to check if the underlying ABI is AAPCS.
QualType getFixedSizeElementType(const ASTContext &Ctx, const VariableArrayType *VLA)
Strip off the variably-modified array types wrapping VLA and return the first element type that has a...
Definition ExprUtils.cpp:15
bool onlyHasInlineBuiltinDeclaration(const FunctionDecl *FD)
Detect the unusual situation where an inline version of a builtin is shadowed by a non-inline version...
EvaluationOrder getCallArgEvaluationOrder(const CallExpr *E)
Returns the argument evaluation order the language requires for the given call.
Definition CallUtils.cpp:51
ConstantEmissionKind checkVarTypeForConstantEmission(QualType Type)
Can we constant-emit a load of a reference to a variable of the given type?
bool isEmptyFieldForLayout(const ASTContext &Ctx, const FieldDecl *FD)
Return true iff the field is "empty", that is, either a zero-width bit-field or an isEmptyRecordForLa...
ConstantEmissionKind
How a reference to a variable can be emitted as a constant.
Definition ExprUtils.h:159
const internal::VariadicAllOfMatcher< Type > type
Matches Types in the clang AST.
const AstTypeMatcher< FunctionType > functionType
const internal::VariadicDynCastAllOfMatcher< Stmt, CUDAKernelCallExpr > cudaKernelCallExpr
const internal::VariadicDynCastAllOfMatcher< Stmt, Expr > expr
Matches expressions.
const internal::VariadicDynCastAllOfMatcher< Stmt, CastExpr > castExpr
Matches any cast nodes of Clang's AST.
Top level wrappers for InstallAPI frontend operations.
CanQual< Type > CanQualType
Represents a canonical, potentially-qualified type.
bool isa(CodeGen::Address addr)
Definition Address.h:330
@ CPlusPlus
QualType pointeeType(QualType T)
bool isMatrixRowMajor(const LangOptions &LangOpts, QualType T)
Returns true if matrices of T should be laid out in row-major order.
Definition MatrixUtils.h:25
@ SC_Register
Definition Specifiers.h:261
@ SD_Thread
Thread storage duration.
Definition Specifiers.h:344
@ SD_Static
Static storage duration.
Definition Specifiers.h:345
@ SD_FullExpression
Full-expression storage duration (for temporaries).
Definition Specifiers.h:342
@ SD_Automatic
Automatic storage duration (most local variables).
Definition Specifiers.h:343
@ SD_Dynamic
Dynamic storage duration.
Definition Specifiers.h:346
@ Dtor_Complete
Complete object dtor.
Definition ABI.h:36
SmallVector< CXXBaseSpecifier *, 4 > CXXCastPath
A simple array of base specifiers.
Definition ASTContext.h:147
U cast(CodeGen::Address addr)
Definition Address.h:327
bool isLambdaMethod(const DeclContext *DC)
Definition ASTLambda.h:39
@ NOUR_Unevaluated
This name appears in an unevaluated operand.
Definition Specifiers.h:181
@ NOUR_Constant
This name appears as a potential result of an lvalue-to-rvalue conversion that is a constant expressi...
Definition Specifiers.h:184
static bool objCLifetime()
static bool emitLifetimeMarkers()
static bool opLoadEmitScalarRangeCheck()
static bool addressSpace()
static bool opAllocaNonGC()
static bool opAllocaOpenMPThreadPrivate()
static bool preservedAccessIndexRegion()
static bool mergeAllConstants()
static bool opLoadStoreTbaa()
static bool opCallChain()
static bool opAllocaImpreciseLifetime()
static bool opAllocaStaticLocal()
static bool opAllocaTLS()
static bool emitCheckedInBoundsGEP()
static bool openMPNontemporalDecl()
static bool setObjCGCLValueClass()
static bool cirgenABIInfo()
static bool opLoadStoreObjC()
static bool pointerAuthentication()
static bool insertBuiltinUnpredictable()
static bool matrixTypeIndexAssumption()
static bool shouldReverseUnaryCondOnBoolExpr()
static bool addressIsKnownNonNull()
static bool openMPLastprivateConditional()
static bool astVarDeclInterface()
static bool cgCapturedStmtInfo()
static bool opAllocaEscapeByReference()
static bool opCallFnInfoOpts()
static bool generateDebugInfo()
static bool incrementProfileCounter()
Record with information about how a bitfield should be accessed.
Represents a scope, including function bodies, compound statements, and the substatements of if/while...
clang::CharUnits getPointerAlign() const
mlir::ptr::MemorySpaceAttrInterface getCIRAllocaAddressSpace() const
EvalResult is a struct with detailed info about an evaluated expression.
Definition Expr.h:667
APValue Val
Val - This is the value the expression can be folded to.
Definition Expr.h:669
bool HasSideEffects
Whether the evaluated expression has side effects.
Definition Expr.h:626
An adjustment to be made to the temporary created when emitting a reference binding,...
Definition Expr.h:70