1 //===--- CGExprConstant.cpp - Emit LLVM Code from Constant Expressions ----===// 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 Constant Expr nodes as LLVM code. 10 // 11 //===----------------------------------------------------------------------===// 12 13 #include "CGCXXABI.h" 14 #include "CGObjCRuntime.h" 15 #include "CGRecordLayout.h" 16 #include "CodeGenFunction.h" 17 #include "CodeGenModule.h" 18 #include "ConstantEmitter.h" 19 #include "TargetInfo.h" 20 #include "clang/AST/APValue.h" 21 #include "clang/AST/ASTContext.h" 22 #include "clang/AST/Attr.h" 23 #include "clang/AST/RecordLayout.h" 24 #include "clang/AST/StmtVisitor.h" 25 #include "clang/Basic/Builtins.h" 26 #include "llvm/ADT/STLExtras.h" 27 #include "llvm/ADT/Sequence.h" 28 #include "llvm/IR/Constants.h" 29 #include "llvm/IR/DataLayout.h" 30 #include "llvm/IR/Function.h" 31 #include "llvm/IR/GlobalVariable.h" 32 using namespace clang; 33 using namespace CodeGen; 34 35 //===----------------------------------------------------------------------===// 36 // ConstantAggregateBuilder 37 //===----------------------------------------------------------------------===// 38 39 namespace { 40 class ConstExprEmitter; 41 42 struct ConstantAggregateBuilderUtils { 43 CodeGenModule &CGM; 44 45 ConstantAggregateBuilderUtils(CodeGenModule &CGM) : CGM(CGM) {} 46 47 CharUnits getAlignment(const llvm::Constant *C) const { 48 return CharUnits::fromQuantity( 49 CGM.getDataLayout().getABITypeAlignment(C->getType())); 50 } 51 52 CharUnits getSize(llvm::Type *Ty) const { 53 return CharUnits::fromQuantity(CGM.getDataLayout().getTypeAllocSize(Ty)); 54 } 55 56 CharUnits getSize(const llvm::Constant *C) const { 57 return getSize(C->getType()); 58 } 59 60 llvm::Constant *getPadding(CharUnits PadSize) const { 61 llvm::Type *Ty = CGM.Int8Ty; 62 if (PadSize > CharUnits::One()) 63 Ty = llvm::ArrayType::get(Ty, PadSize.getQuantity()); 64 return llvm::UndefValue::get(Ty); 65 } 66 67 llvm::Constant *getZeroes(CharUnits ZeroSize) const { 68 llvm::Type *Ty = llvm::ArrayType::get(CGM.Int8Ty, ZeroSize.getQuantity()); 69 return llvm::ConstantAggregateZero::get(Ty); 70 } 71 }; 72 73 /// Incremental builder for an llvm::Constant* holding a struct or array 74 /// constant. 75 class ConstantAggregateBuilder : private ConstantAggregateBuilderUtils { 76 /// The elements of the constant. These two arrays must have the same size; 77 /// Offsets[i] describes the offset of Elems[i] within the constant. The 78 /// elements are kept in increasing offset order, and we ensure that there 79 /// is no overlap: Offsets[i+1] >= Offsets[i] + getSize(Elemes[i]). 80 /// 81 /// This may contain explicit padding elements (in order to create a 82 /// natural layout), but need not. Gaps between elements are implicitly 83 /// considered to be filled with undef. 84 llvm::SmallVector<llvm::Constant*, 32> Elems; 85 llvm::SmallVector<CharUnits, 32> Offsets; 86 87 /// The size of the constant (the maximum end offset of any added element). 88 /// May be larger than the end of Elems.back() if we split the last element 89 /// and removed some trailing undefs. 90 CharUnits Size = CharUnits::Zero(); 91 92 /// This is true only if laying out Elems in order as the elements of a 93 /// non-packed LLVM struct will give the correct layout. 94 bool NaturalLayout = true; 95 96 bool split(size_t Index, CharUnits Hint); 97 Optional<size_t> splitAt(CharUnits Pos); 98 99 static llvm::Constant *buildFrom(CodeGenModule &CGM, 100 ArrayRef<llvm::Constant *> Elems, 101 ArrayRef<CharUnits> Offsets, 102 CharUnits StartOffset, CharUnits Size, 103 bool NaturalLayout, llvm::Type *DesiredTy, 104 bool AllowOversized); 105 106 public: 107 ConstantAggregateBuilder(CodeGenModule &CGM) 108 : ConstantAggregateBuilderUtils(CGM) {} 109 110 /// Update or overwrite the value starting at \p Offset with \c C. 111 /// 112 /// \param AllowOverwrite If \c true, this constant might overwrite (part of) 113 /// a constant that has already been added. This flag is only used to 114 /// detect bugs. 115 bool add(llvm::Constant *C, CharUnits Offset, bool AllowOverwrite); 116 117 /// Update or overwrite the bits starting at \p OffsetInBits with \p Bits. 118 bool addBits(llvm::APInt Bits, uint64_t OffsetInBits, bool AllowOverwrite); 119 120 /// Attempt to condense the value starting at \p Offset to a constant of type 121 /// \p DesiredTy. 122 void condense(CharUnits Offset, llvm::Type *DesiredTy); 123 124 /// Produce a constant representing the entire accumulated value, ideally of 125 /// the specified type. If \p AllowOversized, the constant might be larger 126 /// than implied by \p DesiredTy (eg, if there is a flexible array member). 127 /// Otherwise, the constant will be of exactly the same size as \p DesiredTy 128 /// even if we can't represent it as that type. 129 llvm::Constant *build(llvm::Type *DesiredTy, bool AllowOversized) const { 130 return buildFrom(CGM, Elems, Offsets, CharUnits::Zero(), Size, 131 NaturalLayout, DesiredTy, AllowOversized); 132 } 133 }; 134 135 template<typename Container, typename Range = std::initializer_list< 136 typename Container::value_type>> 137 static void replace(Container &C, size_t BeginOff, size_t EndOff, Range Vals) { 138 assert(BeginOff <= EndOff && "invalid replacement range"); 139 llvm::replace(C, C.begin() + BeginOff, C.begin() + EndOff, Vals); 140 } 141 142 bool ConstantAggregateBuilder::add(llvm::Constant *C, CharUnits Offset, 143 bool AllowOverwrite) { 144 // Common case: appending to a layout. 145 if (Offset >= Size) { 146 CharUnits Align = getAlignment(C); 147 CharUnits AlignedSize = Size.alignTo(Align); 148 if (AlignedSize > Offset || Offset.alignTo(Align) != Offset) 149 NaturalLayout = false; 150 else if (AlignedSize < Offset) { 151 Elems.push_back(getPadding(Offset - Size)); 152 Offsets.push_back(Size); 153 } 154 Elems.push_back(C); 155 Offsets.push_back(Offset); 156 Size = Offset + getSize(C); 157 return true; 158 } 159 160 // Uncommon case: constant overlaps what we've already created. 161 llvm::Optional<size_t> FirstElemToReplace = splitAt(Offset); 162 if (!FirstElemToReplace) 163 return false; 164 165 CharUnits CSize = getSize(C); 166 llvm::Optional<size_t> LastElemToReplace = splitAt(Offset + CSize); 167 if (!LastElemToReplace) 168 return false; 169 170 assert((FirstElemToReplace == LastElemToReplace || AllowOverwrite) && 171 "unexpectedly overwriting field"); 172 173 replace(Elems, *FirstElemToReplace, *LastElemToReplace, {C}); 174 replace(Offsets, *FirstElemToReplace, *LastElemToReplace, {Offset}); 175 Size = std::max(Size, Offset + CSize); 176 NaturalLayout = false; 177 return true; 178 } 179 180 bool ConstantAggregateBuilder::addBits(llvm::APInt Bits, uint64_t OffsetInBits, 181 bool AllowOverwrite) { 182 const ASTContext &Context = CGM.getContext(); 183 const uint64_t CharWidth = CGM.getContext().getCharWidth(); 184 185 // Offset of where we want the first bit to go within the bits of the 186 // current char. 187 unsigned OffsetWithinChar = OffsetInBits % CharWidth; 188 189 // We split bit-fields up into individual bytes. Walk over the bytes and 190 // update them. 191 for (CharUnits OffsetInChars = 192 Context.toCharUnitsFromBits(OffsetInBits - OffsetWithinChar); 193 /**/; ++OffsetInChars) { 194 // Number of bits we want to fill in this char. 195 unsigned WantedBits = 196 std::min((uint64_t)Bits.getBitWidth(), CharWidth - OffsetWithinChar); 197 198 // Get a char containing the bits we want in the right places. The other 199 // bits have unspecified values. 200 llvm::APInt BitsThisChar = Bits; 201 if (BitsThisChar.getBitWidth() < CharWidth) 202 BitsThisChar = BitsThisChar.zext(CharWidth); 203 if (CGM.getDataLayout().isBigEndian()) { 204 // Figure out how much to shift by. We may need to left-shift if we have 205 // less than one byte of Bits left. 206 int Shift = Bits.getBitWidth() - CharWidth + OffsetWithinChar; 207 if (Shift > 0) 208 BitsThisChar.lshrInPlace(Shift); 209 else if (Shift < 0) 210 BitsThisChar = BitsThisChar.shl(-Shift); 211 } else { 212 BitsThisChar = BitsThisChar.shl(OffsetWithinChar); 213 } 214 if (BitsThisChar.getBitWidth() > CharWidth) 215 BitsThisChar = BitsThisChar.trunc(CharWidth); 216 217 if (WantedBits == CharWidth) { 218 // Got a full byte: just add it directly. 219 add(llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar), 220 OffsetInChars, AllowOverwrite); 221 } else { 222 // Partial byte: update the existing integer if there is one. If we 223 // can't split out a 1-CharUnit range to update, then we can't add 224 // these bits and fail the entire constant emission. 225 llvm::Optional<size_t> FirstElemToUpdate = splitAt(OffsetInChars); 226 if (!FirstElemToUpdate) 227 return false; 228 llvm::Optional<size_t> LastElemToUpdate = 229 splitAt(OffsetInChars + CharUnits::One()); 230 if (!LastElemToUpdate) 231 return false; 232 assert(*LastElemToUpdate - *FirstElemToUpdate < 2 && 233 "should have at most one element covering one byte"); 234 235 // Figure out which bits we want and discard the rest. 236 llvm::APInt UpdateMask(CharWidth, 0); 237 if (CGM.getDataLayout().isBigEndian()) 238 UpdateMask.setBits(CharWidth - OffsetWithinChar - WantedBits, 239 CharWidth - OffsetWithinChar); 240 else 241 UpdateMask.setBits(OffsetWithinChar, OffsetWithinChar + WantedBits); 242 BitsThisChar &= UpdateMask; 243 244 if (*FirstElemToUpdate == *LastElemToUpdate || 245 Elems[*FirstElemToUpdate]->isNullValue() || 246 isa<llvm::UndefValue>(Elems[*FirstElemToUpdate])) { 247 // All existing bits are either zero or undef. 248 add(llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar), 249 OffsetInChars, /*AllowOverwrite*/ true); 250 } else { 251 llvm::Constant *&ToUpdate = Elems[*FirstElemToUpdate]; 252 // In order to perform a partial update, we need the existing bitwise 253 // value, which we can only extract for a constant int. 254 auto *CI = dyn_cast<llvm::ConstantInt>(ToUpdate); 255 if (!CI) 256 return false; 257 // Because this is a 1-CharUnit range, the constant occupying it must 258 // be exactly one CharUnit wide. 259 assert(CI->getBitWidth() == CharWidth && "splitAt failed"); 260 assert((!(CI->getValue() & UpdateMask) || AllowOverwrite) && 261 "unexpectedly overwriting bitfield"); 262 BitsThisChar |= (CI->getValue() & ~UpdateMask); 263 ToUpdate = llvm::ConstantInt::get(CGM.getLLVMContext(), BitsThisChar); 264 } 265 } 266 267 // Stop if we've added all the bits. 268 if (WantedBits == Bits.getBitWidth()) 269 break; 270 271 // Remove the consumed bits from Bits. 272 if (!CGM.getDataLayout().isBigEndian()) 273 Bits.lshrInPlace(WantedBits); 274 Bits = Bits.trunc(Bits.getBitWidth() - WantedBits); 275 276 // The remanining bits go at the start of the following bytes. 277 OffsetWithinChar = 0; 278 } 279 280 return true; 281 } 282 283 /// Returns a position within Elems and Offsets such that all elements 284 /// before the returned index end before Pos and all elements at or after 285 /// the returned index begin at or after Pos. Splits elements as necessary 286 /// to ensure this. Returns None if we find something we can't split. 287 Optional<size_t> ConstantAggregateBuilder::splitAt(CharUnits Pos) { 288 if (Pos >= Size) 289 return Offsets.size(); 290 291 while (true) { 292 auto FirstAfterPos = llvm::upper_bound(Offsets, Pos); 293 if (FirstAfterPos == Offsets.begin()) 294 return 0; 295 296 // If we already have an element starting at Pos, we're done. 297 size_t LastAtOrBeforePosIndex = FirstAfterPos - Offsets.begin() - 1; 298 if (Offsets[LastAtOrBeforePosIndex] == Pos) 299 return LastAtOrBeforePosIndex; 300 301 // We found an element starting before Pos. Check for overlap. 302 if (Offsets[LastAtOrBeforePosIndex] + 303 getSize(Elems[LastAtOrBeforePosIndex]) <= Pos) 304 return LastAtOrBeforePosIndex + 1; 305 306 // Try to decompose it into smaller constants. 307 if (!split(LastAtOrBeforePosIndex, Pos)) 308 return None; 309 } 310 } 311 312 /// Split the constant at index Index, if possible. Return true if we did. 313 /// Hint indicates the location at which we'd like to split, but may be 314 /// ignored. 315 bool ConstantAggregateBuilder::split(size_t Index, CharUnits Hint) { 316 NaturalLayout = false; 317 llvm::Constant *C = Elems[Index]; 318 CharUnits Offset = Offsets[Index]; 319 320 if (auto *CA = dyn_cast<llvm::ConstantAggregate>(C)) { 321 replace(Elems, Index, Index + 1, 322 llvm::map_range(llvm::seq(0u, CA->getNumOperands()), 323 [&](unsigned Op) { return CA->getOperand(Op); })); 324 if (auto *Seq = dyn_cast<llvm::SequentialType>(CA->getType())) { 325 // Array or vector. 326 CharUnits ElemSize = getSize(Seq->getElementType()); 327 replace( 328 Offsets, Index, Index + 1, 329 llvm::map_range(llvm::seq(0u, CA->getNumOperands()), 330 [&](unsigned Op) { return Offset + Op * ElemSize; })); 331 } else { 332 // Must be a struct. 333 auto *ST = cast<llvm::StructType>(CA->getType()); 334 const llvm::StructLayout *Layout = 335 CGM.getDataLayout().getStructLayout(ST); 336 replace(Offsets, Index, Index + 1, 337 llvm::map_range( 338 llvm::seq(0u, CA->getNumOperands()), [&](unsigned Op) { 339 return Offset + CharUnits::fromQuantity( 340 Layout->getElementOffset(Op)); 341 })); 342 } 343 return true; 344 } 345 346 if (auto *CDS = dyn_cast<llvm::ConstantDataSequential>(C)) { 347 // FIXME: If possible, split into two ConstantDataSequentials at Hint. 348 CharUnits ElemSize = getSize(CDS->getElementType()); 349 replace(Elems, Index, Index + 1, 350 llvm::map_range(llvm::seq(0u, CDS->getNumElements()), 351 [&](unsigned Elem) { 352 return CDS->getElementAsConstant(Elem); 353 })); 354 replace(Offsets, Index, Index + 1, 355 llvm::map_range( 356 llvm::seq(0u, CDS->getNumElements()), 357 [&](unsigned Elem) { return Offset + Elem * ElemSize; })); 358 return true; 359 } 360 361 if (isa<llvm::ConstantAggregateZero>(C)) { 362 CharUnits ElemSize = getSize(C); 363 assert(Hint > Offset && Hint < Offset + ElemSize && "nothing to split"); 364 replace(Elems, Index, Index + 1, 365 {getZeroes(Hint - Offset), getZeroes(Offset + ElemSize - Hint)}); 366 replace(Offsets, Index, Index + 1, {Offset, Hint}); 367 return true; 368 } 369 370 if (isa<llvm::UndefValue>(C)) { 371 replace(Elems, Index, Index + 1, {}); 372 replace(Offsets, Index, Index + 1, {}); 373 return true; 374 } 375 376 // FIXME: We could split a ConstantInt if the need ever arose. 377 // We don't need to do this to handle bit-fields because we always eagerly 378 // split them into 1-byte chunks. 379 380 return false; 381 } 382 383 static llvm::Constant * 384 EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType, 385 llvm::Type *CommonElementType, unsigned ArrayBound, 386 SmallVectorImpl<llvm::Constant *> &Elements, 387 llvm::Constant *Filler); 388 389 llvm::Constant *ConstantAggregateBuilder::buildFrom( 390 CodeGenModule &CGM, ArrayRef<llvm::Constant *> Elems, 391 ArrayRef<CharUnits> Offsets, CharUnits StartOffset, CharUnits Size, 392 bool NaturalLayout, llvm::Type *DesiredTy, bool AllowOversized) { 393 ConstantAggregateBuilderUtils Utils(CGM); 394 395 if (Elems.empty()) 396 return llvm::UndefValue::get(DesiredTy); 397 398 auto Offset = [&](size_t I) { return Offsets[I] - StartOffset; }; 399 400 // If we want an array type, see if all the elements are the same type and 401 // appropriately spaced. 402 if (llvm::ArrayType *ATy = dyn_cast<llvm::ArrayType>(DesiredTy)) { 403 assert(!AllowOversized && "oversized array emission not supported"); 404 405 bool CanEmitArray = true; 406 llvm::Type *CommonType = Elems[0]->getType(); 407 llvm::Constant *Filler = llvm::Constant::getNullValue(CommonType); 408 CharUnits ElemSize = Utils.getSize(ATy->getElementType()); 409 SmallVector<llvm::Constant*, 32> ArrayElements; 410 for (size_t I = 0; I != Elems.size(); ++I) { 411 // Skip zeroes; we'll use a zero value as our array filler. 412 if (Elems[I]->isNullValue()) 413 continue; 414 415 // All remaining elements must be the same type. 416 if (Elems[I]->getType() != CommonType || 417 Offset(I) % ElemSize != 0) { 418 CanEmitArray = false; 419 break; 420 } 421 ArrayElements.resize(Offset(I) / ElemSize + 1, Filler); 422 ArrayElements.back() = Elems[I]; 423 } 424 425 if (CanEmitArray) { 426 return EmitArrayConstant(CGM, ATy, CommonType, ATy->getNumElements(), 427 ArrayElements, Filler); 428 } 429 430 // Can't emit as an array, carry on to emit as a struct. 431 } 432 433 CharUnits DesiredSize = Utils.getSize(DesiredTy); 434 CharUnits Align = CharUnits::One(); 435 for (llvm::Constant *C : Elems) 436 Align = std::max(Align, Utils.getAlignment(C)); 437 CharUnits AlignedSize = Size.alignTo(Align); 438 439 bool Packed = false; 440 ArrayRef<llvm::Constant*> UnpackedElems = Elems; 441 llvm::SmallVector<llvm::Constant*, 32> UnpackedElemStorage; 442 if ((DesiredSize < AlignedSize && !AllowOversized) || 443 DesiredSize.alignTo(Align) != DesiredSize) { 444 // The natural layout would be the wrong size; force use of a packed layout. 445 NaturalLayout = false; 446 Packed = true; 447 } else if (DesiredSize > AlignedSize) { 448 // The constant would be too small. Add padding to fix it. 449 UnpackedElemStorage.assign(Elems.begin(), Elems.end()); 450 UnpackedElemStorage.push_back(Utils.getPadding(DesiredSize - Size)); 451 UnpackedElems = UnpackedElemStorage; 452 } 453 454 // If we don't have a natural layout, insert padding as necessary. 455 // As we go, double-check to see if we can actually just emit Elems 456 // as a non-packed struct and do so opportunistically if possible. 457 llvm::SmallVector<llvm::Constant*, 32> PackedElems; 458 if (!NaturalLayout) { 459 CharUnits SizeSoFar = CharUnits::Zero(); 460 for (size_t I = 0; I != Elems.size(); ++I) { 461 CharUnits Align = Utils.getAlignment(Elems[I]); 462 CharUnits NaturalOffset = SizeSoFar.alignTo(Align); 463 CharUnits DesiredOffset = Offset(I); 464 assert(DesiredOffset >= SizeSoFar && "elements out of order"); 465 466 if (DesiredOffset != NaturalOffset) 467 Packed = true; 468 if (DesiredOffset != SizeSoFar) 469 PackedElems.push_back(Utils.getPadding(DesiredOffset - SizeSoFar)); 470 PackedElems.push_back(Elems[I]); 471 SizeSoFar = DesiredOffset + Utils.getSize(Elems[I]); 472 } 473 // If we're using the packed layout, pad it out to the desired size if 474 // necessary. 475 if (Packed) { 476 assert((SizeSoFar <= DesiredSize || AllowOversized) && 477 "requested size is too small for contents"); 478 if (SizeSoFar < DesiredSize) 479 PackedElems.push_back(Utils.getPadding(DesiredSize - SizeSoFar)); 480 } 481 } 482 483 llvm::StructType *STy = llvm::ConstantStruct::getTypeForElements( 484 CGM.getLLVMContext(), Packed ? PackedElems : UnpackedElems, Packed); 485 486 // Pick the type to use. If the type is layout identical to the desired 487 // type then use it, otherwise use whatever the builder produced for us. 488 if (llvm::StructType *DesiredSTy = dyn_cast<llvm::StructType>(DesiredTy)) { 489 if (DesiredSTy->isLayoutIdentical(STy)) 490 STy = DesiredSTy; 491 } 492 493 return llvm::ConstantStruct::get(STy, Packed ? PackedElems : UnpackedElems); 494 } 495 496 void ConstantAggregateBuilder::condense(CharUnits Offset, 497 llvm::Type *DesiredTy) { 498 CharUnits Size = getSize(DesiredTy); 499 500 llvm::Optional<size_t> FirstElemToReplace = splitAt(Offset); 501 if (!FirstElemToReplace) 502 return; 503 size_t First = *FirstElemToReplace; 504 505 llvm::Optional<size_t> LastElemToReplace = splitAt(Offset + Size); 506 if (!LastElemToReplace) 507 return; 508 size_t Last = *LastElemToReplace; 509 510 size_t Length = Last - First; 511 if (Length == 0) 512 return; 513 514 if (Length == 1 && Offsets[First] == Offset && 515 getSize(Elems[First]) == Size) { 516 // Re-wrap single element structs if necessary. Otherwise, leave any single 517 // element constant of the right size alone even if it has the wrong type. 518 auto *STy = dyn_cast<llvm::StructType>(DesiredTy); 519 if (STy && STy->getNumElements() == 1 && 520 STy->getElementType(0) == Elems[First]->getType()) 521 Elems[First] = llvm::ConstantStruct::get(STy, Elems[First]); 522 return; 523 } 524 525 llvm::Constant *Replacement = buildFrom( 526 CGM, makeArrayRef(Elems).slice(First, Length), 527 makeArrayRef(Offsets).slice(First, Length), Offset, getSize(DesiredTy), 528 /*known to have natural layout=*/false, DesiredTy, false); 529 replace(Elems, First, Last, {Replacement}); 530 replace(Offsets, First, Last, {Offset}); 531 } 532 533 //===----------------------------------------------------------------------===// 534 // ConstStructBuilder 535 //===----------------------------------------------------------------------===// 536 537 class ConstStructBuilder { 538 CodeGenModule &CGM; 539 ConstantEmitter &Emitter; 540 ConstantAggregateBuilder &Builder; 541 CharUnits StartOffset; 542 543 public: 544 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter, 545 InitListExpr *ILE, QualType StructTy); 546 static llvm::Constant *BuildStruct(ConstantEmitter &Emitter, 547 const APValue &Value, QualType ValTy); 548 static bool UpdateStruct(ConstantEmitter &Emitter, 549 ConstantAggregateBuilder &Const, CharUnits Offset, 550 InitListExpr *Updater); 551 552 private: 553 ConstStructBuilder(ConstantEmitter &Emitter, 554 ConstantAggregateBuilder &Builder, CharUnits StartOffset) 555 : CGM(Emitter.CGM), Emitter(Emitter), Builder(Builder), 556 StartOffset(StartOffset) {} 557 558 bool AppendField(const FieldDecl *Field, uint64_t FieldOffset, 559 llvm::Constant *InitExpr, bool AllowOverwrite = false); 560 561 bool AppendBytes(CharUnits FieldOffsetInChars, llvm::Constant *InitCst, 562 bool AllowOverwrite = false); 563 564 bool AppendBitField(const FieldDecl *Field, uint64_t FieldOffset, 565 llvm::ConstantInt *InitExpr, bool AllowOverwrite = false); 566 567 bool Build(InitListExpr *ILE, bool AllowOverwrite); 568 bool Build(const APValue &Val, const RecordDecl *RD, bool IsPrimaryBase, 569 const CXXRecordDecl *VTableClass, CharUnits BaseOffset); 570 llvm::Constant *Finalize(QualType Ty); 571 }; 572 573 bool ConstStructBuilder::AppendField( 574 const FieldDecl *Field, uint64_t FieldOffset, llvm::Constant *InitCst, 575 bool AllowOverwrite) { 576 const ASTContext &Context = CGM.getContext(); 577 578 CharUnits FieldOffsetInChars = Context.toCharUnitsFromBits(FieldOffset); 579 580 return AppendBytes(FieldOffsetInChars, InitCst, AllowOverwrite); 581 } 582 583 bool ConstStructBuilder::AppendBytes(CharUnits FieldOffsetInChars, 584 llvm::Constant *InitCst, 585 bool AllowOverwrite) { 586 return Builder.add(InitCst, StartOffset + FieldOffsetInChars, AllowOverwrite); 587 } 588 589 bool ConstStructBuilder::AppendBitField( 590 const FieldDecl *Field, uint64_t FieldOffset, llvm::ConstantInt *CI, 591 bool AllowOverwrite) { 592 const CGRecordLayout &RL = 593 CGM.getTypes().getCGRecordLayout(Field->getParent()); 594 const CGBitFieldInfo &Info = RL.getBitFieldInfo(Field); 595 llvm::APInt FieldValue = CI->getValue(); 596 597 // Promote the size of FieldValue if necessary 598 // FIXME: This should never occur, but currently it can because initializer 599 // constants are cast to bool, and because clang is not enforcing bitfield 600 // width limits. 601 if (Info.Size > FieldValue.getBitWidth()) 602 FieldValue = FieldValue.zext(Info.Size); 603 604 // Truncate the size of FieldValue to the bit field size. 605 if (Info.Size < FieldValue.getBitWidth()) 606 FieldValue = FieldValue.trunc(Info.Size); 607 608 return Builder.addBits(FieldValue, 609 CGM.getContext().toBits(StartOffset) + FieldOffset, 610 AllowOverwrite); 611 } 612 613 static bool EmitDesignatedInitUpdater(ConstantEmitter &Emitter, 614 ConstantAggregateBuilder &Const, 615 CharUnits Offset, QualType Type, 616 InitListExpr *Updater) { 617 if (Type->isRecordType()) 618 return ConstStructBuilder::UpdateStruct(Emitter, Const, Offset, Updater); 619 620 auto CAT = Emitter.CGM.getContext().getAsConstantArrayType(Type); 621 if (!CAT) 622 return false; 623 QualType ElemType = CAT->getElementType(); 624 CharUnits ElemSize = Emitter.CGM.getContext().getTypeSizeInChars(ElemType); 625 llvm::Type *ElemTy = Emitter.CGM.getTypes().ConvertTypeForMem(ElemType); 626 627 llvm::Constant *FillC = nullptr; 628 if (Expr *Filler = Updater->getArrayFiller()) { 629 if (!isa<NoInitExpr>(Filler)) { 630 FillC = Emitter.tryEmitAbstractForMemory(Filler, ElemType); 631 if (!FillC) 632 return false; 633 } 634 } 635 636 unsigned NumElementsToUpdate = 637 FillC ? CAT->getSize().getZExtValue() : Updater->getNumInits(); 638 for (unsigned I = 0; I != NumElementsToUpdate; ++I, Offset += ElemSize) { 639 Expr *Init = nullptr; 640 if (I < Updater->getNumInits()) 641 Init = Updater->getInit(I); 642 643 if (!Init && FillC) { 644 if (!Const.add(FillC, Offset, true)) 645 return false; 646 } else if (!Init || isa<NoInitExpr>(Init)) { 647 continue; 648 } else if (InitListExpr *ChildILE = dyn_cast<InitListExpr>(Init)) { 649 if (!EmitDesignatedInitUpdater(Emitter, Const, Offset, ElemType, 650 ChildILE)) 651 return false; 652 // Attempt to reduce the array element to a single constant if necessary. 653 Const.condense(Offset, ElemTy); 654 } else { 655 llvm::Constant *Val = Emitter.tryEmitPrivateForMemory(Init, ElemType); 656 if (!Const.add(Val, Offset, true)) 657 return false; 658 } 659 } 660 661 return true; 662 } 663 664 bool ConstStructBuilder::Build(InitListExpr *ILE, bool AllowOverwrite) { 665 RecordDecl *RD = ILE->getType()->castAs<RecordType>()->getDecl(); 666 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); 667 668 unsigned FieldNo = -1; 669 unsigned ElementNo = 0; 670 671 // Bail out if we have base classes. We could support these, but they only 672 // arise in C++1z where we will have already constant folded most interesting 673 // cases. FIXME: There are still a few more cases we can handle this way. 674 if (auto *CXXRD = dyn_cast<CXXRecordDecl>(RD)) 675 if (CXXRD->getNumBases()) 676 return false; 677 678 for (FieldDecl *Field : RD->fields()) { 679 ++FieldNo; 680 681 // If this is a union, skip all the fields that aren't being initialized. 682 if (RD->isUnion() && 683 !declaresSameEntity(ILE->getInitializedFieldInUnion(), Field)) 684 continue; 685 686 // Don't emit anonymous bitfields or zero-sized fields. 687 if (Field->isUnnamedBitfield() || Field->isZeroSize(CGM.getContext())) 688 continue; 689 690 // Get the initializer. A struct can include fields without initializers, 691 // we just use explicit null values for them. 692 Expr *Init = nullptr; 693 if (ElementNo < ILE->getNumInits()) 694 Init = ILE->getInit(ElementNo++); 695 if (Init && isa<NoInitExpr>(Init)) 696 continue; 697 698 // When emitting a DesignatedInitUpdateExpr, a nested InitListExpr 699 // represents additional overwriting of our current constant value, and not 700 // a new constant to emit independently. 701 if (AllowOverwrite && 702 (Field->getType()->isArrayType() || Field->getType()->isRecordType())) { 703 if (auto *SubILE = dyn_cast<InitListExpr>(Init)) { 704 CharUnits Offset = CGM.getContext().toCharUnitsFromBits( 705 Layout.getFieldOffset(FieldNo)); 706 if (!EmitDesignatedInitUpdater(Emitter, Builder, StartOffset + Offset, 707 Field->getType(), SubILE)) 708 return false; 709 // If we split apart the field's value, try to collapse it down to a 710 // single value now. 711 Builder.condense(StartOffset + Offset, 712 CGM.getTypes().ConvertTypeForMem(Field->getType())); 713 continue; 714 } 715 } 716 717 llvm::Constant *EltInit = 718 Init ? Emitter.tryEmitPrivateForMemory(Init, Field->getType()) 719 : Emitter.emitNullForMemory(Field->getType()); 720 if (!EltInit) 721 return false; 722 723 if (!Field->isBitField()) { 724 // Handle non-bitfield members. 725 if (!AppendField(Field, Layout.getFieldOffset(FieldNo), EltInit, 726 AllowOverwrite)) 727 return false; 728 // After emitting a non-empty field with [[no_unique_address]], we may 729 // need to overwrite its tail padding. 730 if (Field->hasAttr<NoUniqueAddressAttr>()) 731 AllowOverwrite = true; 732 } else { 733 // Otherwise we have a bitfield. 734 if (auto *CI = dyn_cast<llvm::ConstantInt>(EltInit)) { 735 if (!AppendBitField(Field, Layout.getFieldOffset(FieldNo), CI, 736 AllowOverwrite)) 737 return false; 738 } else { 739 // We are trying to initialize a bitfield with a non-trivial constant, 740 // this must require run-time code. 741 return false; 742 } 743 } 744 } 745 746 return true; 747 } 748 749 namespace { 750 struct BaseInfo { 751 BaseInfo(const CXXRecordDecl *Decl, CharUnits Offset, unsigned Index) 752 : Decl(Decl), Offset(Offset), Index(Index) { 753 } 754 755 const CXXRecordDecl *Decl; 756 CharUnits Offset; 757 unsigned Index; 758 759 bool operator<(const BaseInfo &O) const { return Offset < O.Offset; } 760 }; 761 } 762 763 bool ConstStructBuilder::Build(const APValue &Val, const RecordDecl *RD, 764 bool IsPrimaryBase, 765 const CXXRecordDecl *VTableClass, 766 CharUnits Offset) { 767 const ASTRecordLayout &Layout = CGM.getContext().getASTRecordLayout(RD); 768 769 if (const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD)) { 770 // Add a vtable pointer, if we need one and it hasn't already been added. 771 if (CD->isDynamicClass() && !IsPrimaryBase) { 772 llvm::Constant *VTableAddressPoint = 773 CGM.getCXXABI().getVTableAddressPointForConstExpr( 774 BaseSubobject(CD, Offset), VTableClass); 775 if (!AppendBytes(Offset, VTableAddressPoint)) 776 return false; 777 } 778 779 // Accumulate and sort bases, in order to visit them in address order, which 780 // may not be the same as declaration order. 781 SmallVector<BaseInfo, 8> Bases; 782 Bases.reserve(CD->getNumBases()); 783 unsigned BaseNo = 0; 784 for (CXXRecordDecl::base_class_const_iterator Base = CD->bases_begin(), 785 BaseEnd = CD->bases_end(); Base != BaseEnd; ++Base, ++BaseNo) { 786 assert(!Base->isVirtual() && "should not have virtual bases here"); 787 const CXXRecordDecl *BD = Base->getType()->getAsCXXRecordDecl(); 788 CharUnits BaseOffset = Layout.getBaseClassOffset(BD); 789 Bases.push_back(BaseInfo(BD, BaseOffset, BaseNo)); 790 } 791 llvm::stable_sort(Bases); 792 793 for (unsigned I = 0, N = Bases.size(); I != N; ++I) { 794 BaseInfo &Base = Bases[I]; 795 796 bool IsPrimaryBase = Layout.getPrimaryBase() == Base.Decl; 797 Build(Val.getStructBase(Base.Index), Base.Decl, IsPrimaryBase, 798 VTableClass, Offset + Base.Offset); 799 } 800 } 801 802 unsigned FieldNo = 0; 803 uint64_t OffsetBits = CGM.getContext().toBits(Offset); 804 805 bool AllowOverwrite = false; 806 for (RecordDecl::field_iterator Field = RD->field_begin(), 807 FieldEnd = RD->field_end(); Field != FieldEnd; ++Field, ++FieldNo) { 808 // If this is a union, skip all the fields that aren't being initialized. 809 if (RD->isUnion() && !declaresSameEntity(Val.getUnionField(), *Field)) 810 continue; 811 812 // Don't emit anonymous bitfields or zero-sized fields. 813 if (Field->isUnnamedBitfield() || Field->isZeroSize(CGM.getContext())) 814 continue; 815 816 // Emit the value of the initializer. 817 const APValue &FieldValue = 818 RD->isUnion() ? Val.getUnionValue() : Val.getStructField(FieldNo); 819 llvm::Constant *EltInit = 820 Emitter.tryEmitPrivateForMemory(FieldValue, Field->getType()); 821 if (!EltInit) 822 return false; 823 824 if (!Field->isBitField()) { 825 // Handle non-bitfield members. 826 if (!AppendField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits, 827 EltInit, AllowOverwrite)) 828 return false; 829 // After emitting a non-empty field with [[no_unique_address]], we may 830 // need to overwrite its tail padding. 831 if (Field->hasAttr<NoUniqueAddressAttr>()) 832 AllowOverwrite = true; 833 } else { 834 // Otherwise we have a bitfield. 835 if (!AppendBitField(*Field, Layout.getFieldOffset(FieldNo) + OffsetBits, 836 cast<llvm::ConstantInt>(EltInit), AllowOverwrite)) 837 return false; 838 } 839 } 840 841 return true; 842 } 843 844 llvm::Constant *ConstStructBuilder::Finalize(QualType Type) { 845 RecordDecl *RD = Type->castAs<RecordType>()->getDecl(); 846 llvm::Type *ValTy = CGM.getTypes().ConvertType(Type); 847 return Builder.build(ValTy, RD->hasFlexibleArrayMember()); 848 } 849 850 llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter, 851 InitListExpr *ILE, 852 QualType ValTy) { 853 ConstantAggregateBuilder Const(Emitter.CGM); 854 ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero()); 855 856 if (!Builder.Build(ILE, /*AllowOverwrite*/false)) 857 return nullptr; 858 859 return Builder.Finalize(ValTy); 860 } 861 862 llvm::Constant *ConstStructBuilder::BuildStruct(ConstantEmitter &Emitter, 863 const APValue &Val, 864 QualType ValTy) { 865 ConstantAggregateBuilder Const(Emitter.CGM); 866 ConstStructBuilder Builder(Emitter, Const, CharUnits::Zero()); 867 868 const RecordDecl *RD = ValTy->castAs<RecordType>()->getDecl(); 869 const CXXRecordDecl *CD = dyn_cast<CXXRecordDecl>(RD); 870 if (!Builder.Build(Val, RD, false, CD, CharUnits::Zero())) 871 return nullptr; 872 873 return Builder.Finalize(ValTy); 874 } 875 876 bool ConstStructBuilder::UpdateStruct(ConstantEmitter &Emitter, 877 ConstantAggregateBuilder &Const, 878 CharUnits Offset, InitListExpr *Updater) { 879 return ConstStructBuilder(Emitter, Const, Offset) 880 .Build(Updater, /*AllowOverwrite*/ true); 881 } 882 883 //===----------------------------------------------------------------------===// 884 // ConstExprEmitter 885 //===----------------------------------------------------------------------===// 886 887 static ConstantAddress tryEmitGlobalCompoundLiteral(CodeGenModule &CGM, 888 CodeGenFunction *CGF, 889 const CompoundLiteralExpr *E) { 890 CharUnits Align = CGM.getContext().getTypeAlignInChars(E->getType()); 891 if (llvm::GlobalVariable *Addr = 892 CGM.getAddrOfConstantCompoundLiteralIfEmitted(E)) 893 return ConstantAddress(Addr, Align); 894 895 LangAS addressSpace = E->getType().getAddressSpace(); 896 897 ConstantEmitter emitter(CGM, CGF); 898 llvm::Constant *C = emitter.tryEmitForInitializer(E->getInitializer(), 899 addressSpace, E->getType()); 900 if (!C) { 901 assert(!E->isFileScope() && 902 "file-scope compound literal did not have constant initializer!"); 903 return ConstantAddress::invalid(); 904 } 905 906 auto GV = new llvm::GlobalVariable(CGM.getModule(), C->getType(), 907 CGM.isTypeConstant(E->getType(), true), 908 llvm::GlobalValue::InternalLinkage, 909 C, ".compoundliteral", nullptr, 910 llvm::GlobalVariable::NotThreadLocal, 911 CGM.getContext().getTargetAddressSpace(addressSpace)); 912 emitter.finalize(GV); 913 GV->setAlignment(Align.getAsAlign()); 914 CGM.setAddrOfConstantCompoundLiteral(E, GV); 915 return ConstantAddress(GV, Align); 916 } 917 918 static llvm::Constant * 919 EmitArrayConstant(CodeGenModule &CGM, llvm::ArrayType *DesiredType, 920 llvm::Type *CommonElementType, unsigned ArrayBound, 921 SmallVectorImpl<llvm::Constant *> &Elements, 922 llvm::Constant *Filler) { 923 // Figure out how long the initial prefix of non-zero elements is. 924 unsigned NonzeroLength = ArrayBound; 925 if (Elements.size() < NonzeroLength && Filler->isNullValue()) 926 NonzeroLength = Elements.size(); 927 if (NonzeroLength == Elements.size()) { 928 while (NonzeroLength > 0 && Elements[NonzeroLength - 1]->isNullValue()) 929 --NonzeroLength; 930 } 931 932 if (NonzeroLength == 0) 933 return llvm::ConstantAggregateZero::get(DesiredType); 934 935 // Add a zeroinitializer array filler if we have lots of trailing zeroes. 936 unsigned TrailingZeroes = ArrayBound - NonzeroLength; 937 if (TrailingZeroes >= 8) { 938 assert(Elements.size() >= NonzeroLength && 939 "missing initializer for non-zero element"); 940 941 // If all the elements had the same type up to the trailing zeroes, emit a 942 // struct of two arrays (the nonzero data and the zeroinitializer). 943 if (CommonElementType && NonzeroLength >= 8) { 944 llvm::Constant *Initial = llvm::ConstantArray::get( 945 llvm::ArrayType::get(CommonElementType, NonzeroLength), 946 makeArrayRef(Elements).take_front(NonzeroLength)); 947 Elements.resize(2); 948 Elements[0] = Initial; 949 } else { 950 Elements.resize(NonzeroLength + 1); 951 } 952 953 auto *FillerType = 954 CommonElementType ? CommonElementType : DesiredType->getElementType(); 955 FillerType = llvm::ArrayType::get(FillerType, TrailingZeroes); 956 Elements.back() = llvm::ConstantAggregateZero::get(FillerType); 957 CommonElementType = nullptr; 958 } else if (Elements.size() != ArrayBound) { 959 // Otherwise pad to the right size with the filler if necessary. 960 Elements.resize(ArrayBound, Filler); 961 if (Filler->getType() != CommonElementType) 962 CommonElementType = nullptr; 963 } 964 965 // If all elements have the same type, just emit an array constant. 966 if (CommonElementType) 967 return llvm::ConstantArray::get( 968 llvm::ArrayType::get(CommonElementType, ArrayBound), Elements); 969 970 // We have mixed types. Use a packed struct. 971 llvm::SmallVector<llvm::Type *, 16> Types; 972 Types.reserve(Elements.size()); 973 for (llvm::Constant *Elt : Elements) 974 Types.push_back(Elt->getType()); 975 llvm::StructType *SType = 976 llvm::StructType::get(CGM.getLLVMContext(), Types, true); 977 return llvm::ConstantStruct::get(SType, Elements); 978 } 979 980 // This class only needs to handle arrays, structs and unions. Outside C++11 981 // mode, we don't currently constant fold those types. All other types are 982 // handled by constant folding. 983 // 984 // Constant folding is currently missing support for a few features supported 985 // here: CK_ToUnion, CK_ReinterpretMemberPointer, and DesignatedInitUpdateExpr. 986 class ConstExprEmitter : 987 public StmtVisitor<ConstExprEmitter, llvm::Constant*, QualType> { 988 CodeGenModule &CGM; 989 ConstantEmitter &Emitter; 990 llvm::LLVMContext &VMContext; 991 public: 992 ConstExprEmitter(ConstantEmitter &emitter) 993 : CGM(emitter.CGM), Emitter(emitter), VMContext(CGM.getLLVMContext()) { 994 } 995 996 //===--------------------------------------------------------------------===// 997 // Visitor Methods 998 //===--------------------------------------------------------------------===// 999 1000 llvm::Constant *VisitStmt(Stmt *S, QualType T) { 1001 return nullptr; 1002 } 1003 1004 llvm::Constant *VisitConstantExpr(ConstantExpr *CE, QualType T) { 1005 return Visit(CE->getSubExpr(), T); 1006 } 1007 1008 llvm::Constant *VisitParenExpr(ParenExpr *PE, QualType T) { 1009 return Visit(PE->getSubExpr(), T); 1010 } 1011 1012 llvm::Constant * 1013 VisitSubstNonTypeTemplateParmExpr(SubstNonTypeTemplateParmExpr *PE, 1014 QualType T) { 1015 return Visit(PE->getReplacement(), T); 1016 } 1017 1018 llvm::Constant *VisitGenericSelectionExpr(GenericSelectionExpr *GE, 1019 QualType T) { 1020 return Visit(GE->getResultExpr(), T); 1021 } 1022 1023 llvm::Constant *VisitChooseExpr(ChooseExpr *CE, QualType T) { 1024 return Visit(CE->getChosenSubExpr(), T); 1025 } 1026 1027 llvm::Constant *VisitCompoundLiteralExpr(CompoundLiteralExpr *E, QualType T) { 1028 return Visit(E->getInitializer(), T); 1029 } 1030 1031 llvm::Constant *VisitCastExpr(CastExpr *E, QualType destType) { 1032 if (const auto *ECE = dyn_cast<ExplicitCastExpr>(E)) 1033 CGM.EmitExplicitCastExprType(ECE, Emitter.CGF); 1034 Expr *subExpr = E->getSubExpr(); 1035 1036 switch (E->getCastKind()) { 1037 case CK_ToUnion: { 1038 // GCC cast to union extension 1039 assert(E->getType()->isUnionType() && 1040 "Destination type is not union type!"); 1041 1042 auto field = E->getTargetUnionField(); 1043 1044 auto C = Emitter.tryEmitPrivateForMemory(subExpr, field->getType()); 1045 if (!C) return nullptr; 1046 1047 auto destTy = ConvertType(destType); 1048 if (C->getType() == destTy) return C; 1049 1050 // Build a struct with the union sub-element as the first member, 1051 // and padded to the appropriate size. 1052 SmallVector<llvm::Constant*, 2> Elts; 1053 SmallVector<llvm::Type*, 2> Types; 1054 Elts.push_back(C); 1055 Types.push_back(C->getType()); 1056 unsigned CurSize = CGM.getDataLayout().getTypeAllocSize(C->getType()); 1057 unsigned TotalSize = CGM.getDataLayout().getTypeAllocSize(destTy); 1058 1059 assert(CurSize <= TotalSize && "Union size mismatch!"); 1060 if (unsigned NumPadBytes = TotalSize - CurSize) { 1061 llvm::Type *Ty = CGM.Int8Ty; 1062 if (NumPadBytes > 1) 1063 Ty = llvm::ArrayType::get(Ty, NumPadBytes); 1064 1065 Elts.push_back(llvm::UndefValue::get(Ty)); 1066 Types.push_back(Ty); 1067 } 1068 1069 llvm::StructType *STy = llvm::StructType::get(VMContext, Types, false); 1070 return llvm::ConstantStruct::get(STy, Elts); 1071 } 1072 1073 case CK_AddressSpaceConversion: { 1074 auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType()); 1075 if (!C) return nullptr; 1076 LangAS destAS = E->getType()->getPointeeType().getAddressSpace(); 1077 LangAS srcAS = subExpr->getType()->getPointeeType().getAddressSpace(); 1078 llvm::Type *destTy = ConvertType(E->getType()); 1079 return CGM.getTargetCodeGenInfo().performAddrSpaceCast(CGM, C, srcAS, 1080 destAS, destTy); 1081 } 1082 1083 case CK_LValueToRValue: 1084 case CK_AtomicToNonAtomic: 1085 case CK_NonAtomicToAtomic: 1086 case CK_NoOp: 1087 case CK_ConstructorConversion: 1088 return Visit(subExpr, destType); 1089 1090 case CK_IntToOCLSampler: 1091 llvm_unreachable("global sampler variables are not generated"); 1092 1093 case CK_Dependent: llvm_unreachable("saw dependent cast!"); 1094 1095 case CK_BuiltinFnToFnPtr: 1096 llvm_unreachable("builtin functions are handled elsewhere"); 1097 1098 case CK_ReinterpretMemberPointer: 1099 case CK_DerivedToBaseMemberPointer: 1100 case CK_BaseToDerivedMemberPointer: { 1101 auto C = Emitter.tryEmitPrivate(subExpr, subExpr->getType()); 1102 if (!C) return nullptr; 1103 return CGM.getCXXABI().EmitMemberPointerConversion(E, C); 1104 } 1105 1106 // These will never be supported. 1107 case CK_ObjCObjectLValueCast: 1108 case CK_ARCProduceObject: 1109 case CK_ARCConsumeObject: 1110 case CK_ARCReclaimReturnedObject: 1111 case CK_ARCExtendBlockObject: 1112 case CK_CopyAndAutoreleaseBlockObject: 1113 return nullptr; 1114 1115 // These don't need to be handled here because Evaluate knows how to 1116 // evaluate them in the cases where they can be folded. 1117 case CK_BitCast: 1118 case CK_ToVoid: 1119 case CK_Dynamic: 1120 case CK_LValueBitCast: 1121 case CK_LValueToRValueBitCast: 1122 case CK_NullToMemberPointer: 1123 case CK_UserDefinedConversion: 1124 case CK_CPointerToObjCPointerCast: 1125 case CK_BlockPointerToObjCPointerCast: 1126 case CK_AnyPointerToBlockPointerCast: 1127 case CK_ArrayToPointerDecay: 1128 case CK_FunctionToPointerDecay: 1129 case CK_BaseToDerived: 1130 case CK_DerivedToBase: 1131 case CK_UncheckedDerivedToBase: 1132 case CK_MemberPointerToBoolean: 1133 case CK_VectorSplat: 1134 case CK_FloatingRealToComplex: 1135 case CK_FloatingComplexToReal: 1136 case CK_FloatingComplexToBoolean: 1137 case CK_FloatingComplexCast: 1138 case CK_FloatingComplexToIntegralComplex: 1139 case CK_IntegralRealToComplex: 1140 case CK_IntegralComplexToReal: 1141 case CK_IntegralComplexToBoolean: 1142 case CK_IntegralComplexCast: 1143 case CK_IntegralComplexToFloatingComplex: 1144 case CK_PointerToIntegral: 1145 case CK_PointerToBoolean: 1146 case CK_NullToPointer: 1147 case CK_IntegralCast: 1148 case CK_BooleanToSignedIntegral: 1149 case CK_IntegralToPointer: 1150 case CK_IntegralToBoolean: 1151 case CK_IntegralToFloating: 1152 case CK_FloatingToIntegral: 1153 case CK_FloatingToBoolean: 1154 case CK_FloatingCast: 1155 case CK_FixedPointCast: 1156 case CK_FixedPointToBoolean: 1157 case CK_FixedPointToIntegral: 1158 case CK_IntegralToFixedPoint: 1159 case CK_ZeroToOCLOpaqueType: 1160 return nullptr; 1161 } 1162 llvm_unreachable("Invalid CastKind"); 1163 } 1164 1165 llvm::Constant *VisitCXXDefaultInitExpr(CXXDefaultInitExpr *DIE, QualType T) { 1166 // No need for a DefaultInitExprScope: we don't handle 'this' in a 1167 // constant expression. 1168 return Visit(DIE->getExpr(), T); 1169 } 1170 1171 llvm::Constant *VisitExprWithCleanups(ExprWithCleanups *E, QualType T) { 1172 return Visit(E->getSubExpr(), T); 1173 } 1174 1175 llvm::Constant *VisitMaterializeTemporaryExpr(MaterializeTemporaryExpr *E, 1176 QualType T) { 1177 return Visit(E->getSubExpr(), T); 1178 } 1179 1180 llvm::Constant *EmitArrayInitialization(InitListExpr *ILE, QualType T) { 1181 auto *CAT = CGM.getContext().getAsConstantArrayType(ILE->getType()); 1182 assert(CAT && "can't emit array init for non-constant-bound array"); 1183 unsigned NumInitElements = ILE->getNumInits(); 1184 unsigned NumElements = CAT->getSize().getZExtValue(); 1185 1186 // Initialising an array requires us to automatically 1187 // initialise any elements that have not been initialised explicitly 1188 unsigned NumInitableElts = std::min(NumInitElements, NumElements); 1189 1190 QualType EltType = CAT->getElementType(); 1191 1192 // Initialize remaining array elements. 1193 llvm::Constant *fillC = nullptr; 1194 if (Expr *filler = ILE->getArrayFiller()) { 1195 fillC = Emitter.tryEmitAbstractForMemory(filler, EltType); 1196 if (!fillC) 1197 return nullptr; 1198 } 1199 1200 // Copy initializer elements. 1201 SmallVector<llvm::Constant*, 16> Elts; 1202 if (fillC && fillC->isNullValue()) 1203 Elts.reserve(NumInitableElts + 1); 1204 else 1205 Elts.reserve(NumElements); 1206 1207 llvm::Type *CommonElementType = nullptr; 1208 for (unsigned i = 0; i < NumInitableElts; ++i) { 1209 Expr *Init = ILE->getInit(i); 1210 llvm::Constant *C = Emitter.tryEmitPrivateForMemory(Init, EltType); 1211 if (!C) 1212 return nullptr; 1213 if (i == 0) 1214 CommonElementType = C->getType(); 1215 else if (C->getType() != CommonElementType) 1216 CommonElementType = nullptr; 1217 Elts.push_back(C); 1218 } 1219 1220 llvm::ArrayType *Desired = 1221 cast<llvm::ArrayType>(CGM.getTypes().ConvertType(ILE->getType())); 1222 return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts, 1223 fillC); 1224 } 1225 1226 llvm::Constant *EmitRecordInitialization(InitListExpr *ILE, QualType T) { 1227 return ConstStructBuilder::BuildStruct(Emitter, ILE, T); 1228 } 1229 1230 llvm::Constant *VisitImplicitValueInitExpr(ImplicitValueInitExpr* E, 1231 QualType T) { 1232 return CGM.EmitNullConstant(T); 1233 } 1234 1235 llvm::Constant *VisitInitListExpr(InitListExpr *ILE, QualType T) { 1236 if (ILE->isTransparent()) 1237 return Visit(ILE->getInit(0), T); 1238 1239 if (ILE->getType()->isArrayType()) 1240 return EmitArrayInitialization(ILE, T); 1241 1242 if (ILE->getType()->isRecordType()) 1243 return EmitRecordInitialization(ILE, T); 1244 1245 return nullptr; 1246 } 1247 1248 llvm::Constant *VisitDesignatedInitUpdateExpr(DesignatedInitUpdateExpr *E, 1249 QualType destType) { 1250 auto C = Visit(E->getBase(), destType); 1251 if (!C) 1252 return nullptr; 1253 1254 ConstantAggregateBuilder Const(CGM); 1255 Const.add(C, CharUnits::Zero(), false); 1256 1257 if (!EmitDesignatedInitUpdater(Emitter, Const, CharUnits::Zero(), destType, 1258 E->getUpdater())) 1259 return nullptr; 1260 1261 llvm::Type *ValTy = CGM.getTypes().ConvertType(destType); 1262 bool HasFlexibleArray = false; 1263 if (auto *RT = destType->getAs<RecordType>()) 1264 HasFlexibleArray = RT->getDecl()->hasFlexibleArrayMember(); 1265 return Const.build(ValTy, HasFlexibleArray); 1266 } 1267 1268 llvm::Constant *VisitCXXConstructExpr(CXXConstructExpr *E, QualType Ty) { 1269 if (!E->getConstructor()->isTrivial()) 1270 return nullptr; 1271 1272 // Only default and copy/move constructors can be trivial. 1273 if (E->getNumArgs()) { 1274 assert(E->getNumArgs() == 1 && "trivial ctor with > 1 argument"); 1275 assert(E->getConstructor()->isCopyOrMoveConstructor() && 1276 "trivial ctor has argument but isn't a copy/move ctor"); 1277 1278 Expr *Arg = E->getArg(0); 1279 assert(CGM.getContext().hasSameUnqualifiedType(Ty, Arg->getType()) && 1280 "argument to copy ctor is of wrong type"); 1281 1282 return Visit(Arg, Ty); 1283 } 1284 1285 return CGM.EmitNullConstant(Ty); 1286 } 1287 1288 llvm::Constant *VisitStringLiteral(StringLiteral *E, QualType T) { 1289 // This is a string literal initializing an array in an initializer. 1290 return CGM.GetConstantArrayFromStringLiteral(E); 1291 } 1292 1293 llvm::Constant *VisitObjCEncodeExpr(ObjCEncodeExpr *E, QualType T) { 1294 // This must be an @encode initializing an array in a static initializer. 1295 // Don't emit it as the address of the string, emit the string data itself 1296 // as an inline array. 1297 std::string Str; 1298 CGM.getContext().getObjCEncodingForType(E->getEncodedType(), Str); 1299 const ConstantArrayType *CAT = CGM.getContext().getAsConstantArrayType(T); 1300 1301 // Resize the string to the right size, adding zeros at the end, or 1302 // truncating as needed. 1303 Str.resize(CAT->getSize().getZExtValue(), '\0'); 1304 return llvm::ConstantDataArray::getString(VMContext, Str, false); 1305 } 1306 1307 llvm::Constant *VisitUnaryExtension(const UnaryOperator *E, QualType T) { 1308 return Visit(E->getSubExpr(), T); 1309 } 1310 1311 // Utility methods 1312 llvm::Type *ConvertType(QualType T) { 1313 return CGM.getTypes().ConvertType(T); 1314 } 1315 }; 1316 1317 } // end anonymous namespace. 1318 1319 llvm::Constant *ConstantEmitter::validateAndPopAbstract(llvm::Constant *C, 1320 AbstractState saved) { 1321 Abstract = saved.OldValue; 1322 1323 assert(saved.OldPlaceholdersSize == PlaceholderAddresses.size() && 1324 "created a placeholder while doing an abstract emission?"); 1325 1326 // No validation necessary for now. 1327 // No cleanup to do for now. 1328 return C; 1329 } 1330 1331 llvm::Constant * 1332 ConstantEmitter::tryEmitAbstractForInitializer(const VarDecl &D) { 1333 auto state = pushAbstract(); 1334 auto C = tryEmitPrivateForVarInit(D); 1335 return validateAndPopAbstract(C, state); 1336 } 1337 1338 llvm::Constant * 1339 ConstantEmitter::tryEmitAbstract(const Expr *E, QualType destType) { 1340 auto state = pushAbstract(); 1341 auto C = tryEmitPrivate(E, destType); 1342 return validateAndPopAbstract(C, state); 1343 } 1344 1345 llvm::Constant * 1346 ConstantEmitter::tryEmitAbstract(const APValue &value, QualType destType) { 1347 auto state = pushAbstract(); 1348 auto C = tryEmitPrivate(value, destType); 1349 return validateAndPopAbstract(C, state); 1350 } 1351 1352 llvm::Constant * 1353 ConstantEmitter::emitAbstract(const Expr *E, QualType destType) { 1354 auto state = pushAbstract(); 1355 auto C = tryEmitPrivate(E, destType); 1356 C = validateAndPopAbstract(C, state); 1357 if (!C) { 1358 CGM.Error(E->getExprLoc(), 1359 "internal error: could not emit constant value \"abstractly\""); 1360 C = CGM.EmitNullConstant(destType); 1361 } 1362 return C; 1363 } 1364 1365 llvm::Constant * 1366 ConstantEmitter::emitAbstract(SourceLocation loc, const APValue &value, 1367 QualType destType) { 1368 auto state = pushAbstract(); 1369 auto C = tryEmitPrivate(value, destType); 1370 C = validateAndPopAbstract(C, state); 1371 if (!C) { 1372 CGM.Error(loc, 1373 "internal error: could not emit constant value \"abstractly\""); 1374 C = CGM.EmitNullConstant(destType); 1375 } 1376 return C; 1377 } 1378 1379 llvm::Constant *ConstantEmitter::tryEmitForInitializer(const VarDecl &D) { 1380 initializeNonAbstract(D.getType().getAddressSpace()); 1381 return markIfFailed(tryEmitPrivateForVarInit(D)); 1382 } 1383 1384 llvm::Constant *ConstantEmitter::tryEmitForInitializer(const Expr *E, 1385 LangAS destAddrSpace, 1386 QualType destType) { 1387 initializeNonAbstract(destAddrSpace); 1388 return markIfFailed(tryEmitPrivateForMemory(E, destType)); 1389 } 1390 1391 llvm::Constant *ConstantEmitter::emitForInitializer(const APValue &value, 1392 LangAS destAddrSpace, 1393 QualType destType) { 1394 initializeNonAbstract(destAddrSpace); 1395 auto C = tryEmitPrivateForMemory(value, destType); 1396 assert(C && "couldn't emit constant value non-abstractly?"); 1397 return C; 1398 } 1399 1400 llvm::GlobalValue *ConstantEmitter::getCurrentAddrPrivate() { 1401 assert(!Abstract && "cannot get current address for abstract constant"); 1402 1403 1404 1405 // Make an obviously ill-formed global that should blow up compilation 1406 // if it survives. 1407 auto global = new llvm::GlobalVariable(CGM.getModule(), CGM.Int8Ty, true, 1408 llvm::GlobalValue::PrivateLinkage, 1409 /*init*/ nullptr, 1410 /*name*/ "", 1411 /*before*/ nullptr, 1412 llvm::GlobalVariable::NotThreadLocal, 1413 CGM.getContext().getTargetAddressSpace(DestAddressSpace)); 1414 1415 PlaceholderAddresses.push_back(std::make_pair(nullptr, global)); 1416 1417 return global; 1418 } 1419 1420 void ConstantEmitter::registerCurrentAddrPrivate(llvm::Constant *signal, 1421 llvm::GlobalValue *placeholder) { 1422 assert(!PlaceholderAddresses.empty()); 1423 assert(PlaceholderAddresses.back().first == nullptr); 1424 assert(PlaceholderAddresses.back().second == placeholder); 1425 PlaceholderAddresses.back().first = signal; 1426 } 1427 1428 namespace { 1429 struct ReplacePlaceholders { 1430 CodeGenModule &CGM; 1431 1432 /// The base address of the global. 1433 llvm::Constant *Base; 1434 llvm::Type *BaseValueTy = nullptr; 1435 1436 /// The placeholder addresses that were registered during emission. 1437 llvm::DenseMap<llvm::Constant*, llvm::GlobalVariable*> PlaceholderAddresses; 1438 1439 /// The locations of the placeholder signals. 1440 llvm::DenseMap<llvm::GlobalVariable*, llvm::Constant*> Locations; 1441 1442 /// The current index stack. We use a simple unsigned stack because 1443 /// we assume that placeholders will be relatively sparse in the 1444 /// initializer, but we cache the index values we find just in case. 1445 llvm::SmallVector<unsigned, 8> Indices; 1446 llvm::SmallVector<llvm::Constant*, 8> IndexValues; 1447 1448 ReplacePlaceholders(CodeGenModule &CGM, llvm::Constant *base, 1449 ArrayRef<std::pair<llvm::Constant*, 1450 llvm::GlobalVariable*>> addresses) 1451 : CGM(CGM), Base(base), 1452 PlaceholderAddresses(addresses.begin(), addresses.end()) { 1453 } 1454 1455 void replaceInInitializer(llvm::Constant *init) { 1456 // Remember the type of the top-most initializer. 1457 BaseValueTy = init->getType(); 1458 1459 // Initialize the stack. 1460 Indices.push_back(0); 1461 IndexValues.push_back(nullptr); 1462 1463 // Recurse into the initializer. 1464 findLocations(init); 1465 1466 // Check invariants. 1467 assert(IndexValues.size() == Indices.size() && "mismatch"); 1468 assert(Indices.size() == 1 && "didn't pop all indices"); 1469 1470 // Do the replacement; this basically invalidates 'init'. 1471 assert(Locations.size() == PlaceholderAddresses.size() && 1472 "missed a placeholder?"); 1473 1474 // We're iterating over a hashtable, so this would be a source of 1475 // non-determinism in compiler output *except* that we're just 1476 // messing around with llvm::Constant structures, which never itself 1477 // does anything that should be visible in compiler output. 1478 for (auto &entry : Locations) { 1479 assert(entry.first->getParent() == nullptr && "not a placeholder!"); 1480 entry.first->replaceAllUsesWith(entry.second); 1481 entry.first->eraseFromParent(); 1482 } 1483 } 1484 1485 private: 1486 void findLocations(llvm::Constant *init) { 1487 // Recurse into aggregates. 1488 if (auto agg = dyn_cast<llvm::ConstantAggregate>(init)) { 1489 for (unsigned i = 0, e = agg->getNumOperands(); i != e; ++i) { 1490 Indices.push_back(i); 1491 IndexValues.push_back(nullptr); 1492 1493 findLocations(agg->getOperand(i)); 1494 1495 IndexValues.pop_back(); 1496 Indices.pop_back(); 1497 } 1498 return; 1499 } 1500 1501 // Otherwise, check for registered constants. 1502 while (true) { 1503 auto it = PlaceholderAddresses.find(init); 1504 if (it != PlaceholderAddresses.end()) { 1505 setLocation(it->second); 1506 break; 1507 } 1508 1509 // Look through bitcasts or other expressions. 1510 if (auto expr = dyn_cast<llvm::ConstantExpr>(init)) { 1511 init = expr->getOperand(0); 1512 } else { 1513 break; 1514 } 1515 } 1516 } 1517 1518 void setLocation(llvm::GlobalVariable *placeholder) { 1519 assert(Locations.find(placeholder) == Locations.end() && 1520 "already found location for placeholder!"); 1521 1522 // Lazily fill in IndexValues with the values from Indices. 1523 // We do this in reverse because we should always have a strict 1524 // prefix of indices from the start. 1525 assert(Indices.size() == IndexValues.size()); 1526 for (size_t i = Indices.size() - 1; i != size_t(-1); --i) { 1527 if (IndexValues[i]) { 1528 #ifndef NDEBUG 1529 for (size_t j = 0; j != i + 1; ++j) { 1530 assert(IndexValues[j] && 1531 isa<llvm::ConstantInt>(IndexValues[j]) && 1532 cast<llvm::ConstantInt>(IndexValues[j])->getZExtValue() 1533 == Indices[j]); 1534 } 1535 #endif 1536 break; 1537 } 1538 1539 IndexValues[i] = llvm::ConstantInt::get(CGM.Int32Ty, Indices[i]); 1540 } 1541 1542 // Form a GEP and then bitcast to the placeholder type so that the 1543 // replacement will succeed. 1544 llvm::Constant *location = 1545 llvm::ConstantExpr::getInBoundsGetElementPtr(BaseValueTy, 1546 Base, IndexValues); 1547 location = llvm::ConstantExpr::getBitCast(location, 1548 placeholder->getType()); 1549 1550 Locations.insert({placeholder, location}); 1551 } 1552 }; 1553 } 1554 1555 void ConstantEmitter::finalize(llvm::GlobalVariable *global) { 1556 assert(InitializedNonAbstract && 1557 "finalizing emitter that was used for abstract emission?"); 1558 assert(!Finalized && "finalizing emitter multiple times"); 1559 assert(global->getInitializer()); 1560 1561 // Note that we might also be Failed. 1562 Finalized = true; 1563 1564 if (!PlaceholderAddresses.empty()) { 1565 ReplacePlaceholders(CGM, global, PlaceholderAddresses) 1566 .replaceInInitializer(global->getInitializer()); 1567 PlaceholderAddresses.clear(); // satisfy 1568 } 1569 } 1570 1571 ConstantEmitter::~ConstantEmitter() { 1572 assert((!InitializedNonAbstract || Finalized || Failed) && 1573 "not finalized after being initialized for non-abstract emission"); 1574 assert(PlaceholderAddresses.empty() && "unhandled placeholders"); 1575 } 1576 1577 static QualType getNonMemoryType(CodeGenModule &CGM, QualType type) { 1578 if (auto AT = type->getAs<AtomicType>()) { 1579 return CGM.getContext().getQualifiedType(AT->getValueType(), 1580 type.getQualifiers()); 1581 } 1582 return type; 1583 } 1584 1585 llvm::Constant *ConstantEmitter::tryEmitPrivateForVarInit(const VarDecl &D) { 1586 // Make a quick check if variable can be default NULL initialized 1587 // and avoid going through rest of code which may do, for c++11, 1588 // initialization of memory to all NULLs. 1589 if (!D.hasLocalStorage()) { 1590 QualType Ty = CGM.getContext().getBaseElementType(D.getType()); 1591 if (Ty->isRecordType()) 1592 if (const CXXConstructExpr *E = 1593 dyn_cast_or_null<CXXConstructExpr>(D.getInit())) { 1594 const CXXConstructorDecl *CD = E->getConstructor(); 1595 if (CD->isTrivial() && CD->isDefaultConstructor()) 1596 return CGM.EmitNullConstant(D.getType()); 1597 } 1598 InConstantContext = true; 1599 } 1600 1601 QualType destType = D.getType(); 1602 1603 // Try to emit the initializer. Note that this can allow some things that 1604 // are not allowed by tryEmitPrivateForMemory alone. 1605 if (auto value = D.evaluateValue()) { 1606 return tryEmitPrivateForMemory(*value, destType); 1607 } 1608 1609 // FIXME: Implement C++11 [basic.start.init]p2: if the initializer of a 1610 // reference is a constant expression, and the reference binds to a temporary, 1611 // then constant initialization is performed. ConstExprEmitter will 1612 // incorrectly emit a prvalue constant in this case, and the calling code 1613 // interprets that as the (pointer) value of the reference, rather than the 1614 // desired value of the referee. 1615 if (destType->isReferenceType()) 1616 return nullptr; 1617 1618 const Expr *E = D.getInit(); 1619 assert(E && "No initializer to emit"); 1620 1621 auto nonMemoryDestType = getNonMemoryType(CGM, destType); 1622 auto C = 1623 ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), nonMemoryDestType); 1624 return (C ? emitForMemory(C, destType) : nullptr); 1625 } 1626 1627 llvm::Constant * 1628 ConstantEmitter::tryEmitAbstractForMemory(const Expr *E, QualType destType) { 1629 auto nonMemoryDestType = getNonMemoryType(CGM, destType); 1630 auto C = tryEmitAbstract(E, nonMemoryDestType); 1631 return (C ? emitForMemory(C, destType) : nullptr); 1632 } 1633 1634 llvm::Constant * 1635 ConstantEmitter::tryEmitAbstractForMemory(const APValue &value, 1636 QualType destType) { 1637 auto nonMemoryDestType = getNonMemoryType(CGM, destType); 1638 auto C = tryEmitAbstract(value, nonMemoryDestType); 1639 return (C ? emitForMemory(C, destType) : nullptr); 1640 } 1641 1642 llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const Expr *E, 1643 QualType destType) { 1644 auto nonMemoryDestType = getNonMemoryType(CGM, destType); 1645 llvm::Constant *C = tryEmitPrivate(E, nonMemoryDestType); 1646 return (C ? emitForMemory(C, destType) : nullptr); 1647 } 1648 1649 llvm::Constant *ConstantEmitter::tryEmitPrivateForMemory(const APValue &value, 1650 QualType destType) { 1651 auto nonMemoryDestType = getNonMemoryType(CGM, destType); 1652 auto C = tryEmitPrivate(value, nonMemoryDestType); 1653 return (C ? emitForMemory(C, destType) : nullptr); 1654 } 1655 1656 llvm::Constant *ConstantEmitter::emitForMemory(CodeGenModule &CGM, 1657 llvm::Constant *C, 1658 QualType destType) { 1659 // For an _Atomic-qualified constant, we may need to add tail padding. 1660 if (auto AT = destType->getAs<AtomicType>()) { 1661 QualType destValueType = AT->getValueType(); 1662 C = emitForMemory(CGM, C, destValueType); 1663 1664 uint64_t innerSize = CGM.getContext().getTypeSize(destValueType); 1665 uint64_t outerSize = CGM.getContext().getTypeSize(destType); 1666 if (innerSize == outerSize) 1667 return C; 1668 1669 assert(innerSize < outerSize && "emitted over-large constant for atomic"); 1670 llvm::Constant *elts[] = { 1671 C, 1672 llvm::ConstantAggregateZero::get( 1673 llvm::ArrayType::get(CGM.Int8Ty, (outerSize - innerSize) / 8)) 1674 }; 1675 return llvm::ConstantStruct::getAnon(elts); 1676 } 1677 1678 // Zero-extend bool. 1679 if (C->getType()->isIntegerTy(1)) { 1680 llvm::Type *boolTy = CGM.getTypes().ConvertTypeForMem(destType); 1681 return llvm::ConstantExpr::getZExt(C, boolTy); 1682 } 1683 1684 return C; 1685 } 1686 1687 llvm::Constant *ConstantEmitter::tryEmitPrivate(const Expr *E, 1688 QualType destType) { 1689 Expr::EvalResult Result; 1690 1691 bool Success = false; 1692 1693 if (destType->isReferenceType()) 1694 Success = E->EvaluateAsLValue(Result, CGM.getContext()); 1695 else 1696 Success = E->EvaluateAsRValue(Result, CGM.getContext(), InConstantContext); 1697 1698 llvm::Constant *C; 1699 if (Success && !Result.HasSideEffects) 1700 C = tryEmitPrivate(Result.Val, destType); 1701 else 1702 C = ConstExprEmitter(*this).Visit(const_cast<Expr*>(E), destType); 1703 1704 return C; 1705 } 1706 1707 llvm::Constant *CodeGenModule::getNullPointer(llvm::PointerType *T, QualType QT) { 1708 return getTargetCodeGenInfo().getNullPointer(*this, T, QT); 1709 } 1710 1711 namespace { 1712 /// A struct which can be used to peephole certain kinds of finalization 1713 /// that normally happen during l-value emission. 1714 struct ConstantLValue { 1715 llvm::Constant *Value; 1716 bool HasOffsetApplied; 1717 1718 /*implicit*/ ConstantLValue(llvm::Constant *value, 1719 bool hasOffsetApplied = false) 1720 : Value(value), HasOffsetApplied(hasOffsetApplied) {} 1721 1722 /*implicit*/ ConstantLValue(ConstantAddress address) 1723 : ConstantLValue(address.getPointer()) {} 1724 }; 1725 1726 /// A helper class for emitting constant l-values. 1727 class ConstantLValueEmitter : public ConstStmtVisitor<ConstantLValueEmitter, 1728 ConstantLValue> { 1729 CodeGenModule &CGM; 1730 ConstantEmitter &Emitter; 1731 const APValue &Value; 1732 QualType DestType; 1733 1734 // Befriend StmtVisitorBase so that we don't have to expose Visit*. 1735 friend StmtVisitorBase; 1736 1737 public: 1738 ConstantLValueEmitter(ConstantEmitter &emitter, const APValue &value, 1739 QualType destType) 1740 : CGM(emitter.CGM), Emitter(emitter), Value(value), DestType(destType) {} 1741 1742 llvm::Constant *tryEmit(); 1743 1744 private: 1745 llvm::Constant *tryEmitAbsolute(llvm::Type *destTy); 1746 ConstantLValue tryEmitBase(const APValue::LValueBase &base); 1747 1748 ConstantLValue VisitStmt(const Stmt *S) { return nullptr; } 1749 ConstantLValue VisitConstantExpr(const ConstantExpr *E); 1750 ConstantLValue VisitCompoundLiteralExpr(const CompoundLiteralExpr *E); 1751 ConstantLValue VisitStringLiteral(const StringLiteral *E); 1752 ConstantLValue VisitObjCBoxedExpr(const ObjCBoxedExpr *E); 1753 ConstantLValue VisitObjCEncodeExpr(const ObjCEncodeExpr *E); 1754 ConstantLValue VisitObjCStringLiteral(const ObjCStringLiteral *E); 1755 ConstantLValue VisitPredefinedExpr(const PredefinedExpr *E); 1756 ConstantLValue VisitAddrLabelExpr(const AddrLabelExpr *E); 1757 ConstantLValue VisitCallExpr(const CallExpr *E); 1758 ConstantLValue VisitBlockExpr(const BlockExpr *E); 1759 ConstantLValue VisitCXXTypeidExpr(const CXXTypeidExpr *E); 1760 ConstantLValue VisitCXXUuidofExpr(const CXXUuidofExpr *E); 1761 ConstantLValue VisitMaterializeTemporaryExpr( 1762 const MaterializeTemporaryExpr *E); 1763 1764 bool hasNonZeroOffset() const { 1765 return !Value.getLValueOffset().isZero(); 1766 } 1767 1768 /// Return the value offset. 1769 llvm::Constant *getOffset() { 1770 return llvm::ConstantInt::get(CGM.Int64Ty, 1771 Value.getLValueOffset().getQuantity()); 1772 } 1773 1774 /// Apply the value offset to the given constant. 1775 llvm::Constant *applyOffset(llvm::Constant *C) { 1776 if (!hasNonZeroOffset()) 1777 return C; 1778 1779 llvm::Type *origPtrTy = C->getType(); 1780 unsigned AS = origPtrTy->getPointerAddressSpace(); 1781 llvm::Type *charPtrTy = CGM.Int8Ty->getPointerTo(AS); 1782 C = llvm::ConstantExpr::getBitCast(C, charPtrTy); 1783 C = llvm::ConstantExpr::getGetElementPtr(CGM.Int8Ty, C, getOffset()); 1784 C = llvm::ConstantExpr::getPointerCast(C, origPtrTy); 1785 return C; 1786 } 1787 }; 1788 1789 } 1790 1791 llvm::Constant *ConstantLValueEmitter::tryEmit() { 1792 const APValue::LValueBase &base = Value.getLValueBase(); 1793 1794 // The destination type should be a pointer or reference 1795 // type, but it might also be a cast thereof. 1796 // 1797 // FIXME: the chain of casts required should be reflected in the APValue. 1798 // We need this in order to correctly handle things like a ptrtoint of a 1799 // non-zero null pointer and addrspace casts that aren't trivially 1800 // represented in LLVM IR. 1801 auto destTy = CGM.getTypes().ConvertTypeForMem(DestType); 1802 assert(isa<llvm::IntegerType>(destTy) || isa<llvm::PointerType>(destTy)); 1803 1804 // If there's no base at all, this is a null or absolute pointer, 1805 // possibly cast back to an integer type. 1806 if (!base) { 1807 return tryEmitAbsolute(destTy); 1808 } 1809 1810 // Otherwise, try to emit the base. 1811 ConstantLValue result = tryEmitBase(base); 1812 1813 // If that failed, we're done. 1814 llvm::Constant *value = result.Value; 1815 if (!value) return nullptr; 1816 1817 // Apply the offset if necessary and not already done. 1818 if (!result.HasOffsetApplied) { 1819 value = applyOffset(value); 1820 } 1821 1822 // Convert to the appropriate type; this could be an lvalue for 1823 // an integer. FIXME: performAddrSpaceCast 1824 if (isa<llvm::PointerType>(destTy)) 1825 return llvm::ConstantExpr::getPointerCast(value, destTy); 1826 1827 return llvm::ConstantExpr::getPtrToInt(value, destTy); 1828 } 1829 1830 /// Try to emit an absolute l-value, such as a null pointer or an integer 1831 /// bitcast to pointer type. 1832 llvm::Constant * 1833 ConstantLValueEmitter::tryEmitAbsolute(llvm::Type *destTy) { 1834 // If we're producing a pointer, this is easy. 1835 auto destPtrTy = cast<llvm::PointerType>(destTy); 1836 if (Value.isNullPointer()) { 1837 // FIXME: integer offsets from non-zero null pointers. 1838 return CGM.getNullPointer(destPtrTy, DestType); 1839 } 1840 1841 // Convert the integer to a pointer-sized integer before converting it 1842 // to a pointer. 1843 // FIXME: signedness depends on the original integer type. 1844 auto intptrTy = CGM.getDataLayout().getIntPtrType(destPtrTy); 1845 llvm::Constant *C; 1846 C = llvm::ConstantExpr::getIntegerCast(getOffset(), intptrTy, 1847 /*isSigned*/ false); 1848 C = llvm::ConstantExpr::getIntToPtr(C, destPtrTy); 1849 return C; 1850 } 1851 1852 ConstantLValue 1853 ConstantLValueEmitter::tryEmitBase(const APValue::LValueBase &base) { 1854 // Handle values. 1855 if (const ValueDecl *D = base.dyn_cast<const ValueDecl*>()) { 1856 if (D->hasAttr<WeakRefAttr>()) 1857 return CGM.GetWeakRefReference(D).getPointer(); 1858 1859 if (auto FD = dyn_cast<FunctionDecl>(D)) 1860 return CGM.GetAddrOfFunction(FD); 1861 1862 if (auto VD = dyn_cast<VarDecl>(D)) { 1863 // We can never refer to a variable with local storage. 1864 if (!VD->hasLocalStorage()) { 1865 if (VD->isFileVarDecl() || VD->hasExternalStorage()) 1866 return CGM.GetAddrOfGlobalVar(VD); 1867 1868 if (VD->isLocalVarDecl()) { 1869 return CGM.getOrCreateStaticVarDecl( 1870 *VD, CGM.getLLVMLinkageVarDefinition(VD, /*IsConstant=*/false)); 1871 } 1872 } 1873 } 1874 1875 return nullptr; 1876 } 1877 1878 // Handle typeid(T). 1879 if (TypeInfoLValue TI = base.dyn_cast<TypeInfoLValue>()) { 1880 llvm::Type *StdTypeInfoPtrTy = 1881 CGM.getTypes().ConvertType(base.getTypeInfoType())->getPointerTo(); 1882 llvm::Constant *TypeInfo = 1883 CGM.GetAddrOfRTTIDescriptor(QualType(TI.getType(), 0)); 1884 if (TypeInfo->getType() != StdTypeInfoPtrTy) 1885 TypeInfo = llvm::ConstantExpr::getBitCast(TypeInfo, StdTypeInfoPtrTy); 1886 return TypeInfo; 1887 } 1888 1889 // Otherwise, it must be an expression. 1890 return Visit(base.get<const Expr*>()); 1891 } 1892 1893 ConstantLValue 1894 ConstantLValueEmitter::VisitConstantExpr(const ConstantExpr *E) { 1895 return Visit(E->getSubExpr()); 1896 } 1897 1898 ConstantLValue 1899 ConstantLValueEmitter::VisitCompoundLiteralExpr(const CompoundLiteralExpr *E) { 1900 return tryEmitGlobalCompoundLiteral(CGM, Emitter.CGF, E); 1901 } 1902 1903 ConstantLValue 1904 ConstantLValueEmitter::VisitStringLiteral(const StringLiteral *E) { 1905 return CGM.GetAddrOfConstantStringFromLiteral(E); 1906 } 1907 1908 ConstantLValue 1909 ConstantLValueEmitter::VisitObjCEncodeExpr(const ObjCEncodeExpr *E) { 1910 return CGM.GetAddrOfConstantStringFromObjCEncode(E); 1911 } 1912 1913 static ConstantLValue emitConstantObjCStringLiteral(const StringLiteral *S, 1914 QualType T, 1915 CodeGenModule &CGM) { 1916 auto C = CGM.getObjCRuntime().GenerateConstantString(S); 1917 return C.getElementBitCast(CGM.getTypes().ConvertTypeForMem(T)); 1918 } 1919 1920 ConstantLValue 1921 ConstantLValueEmitter::VisitObjCStringLiteral(const ObjCStringLiteral *E) { 1922 return emitConstantObjCStringLiteral(E->getString(), E->getType(), CGM); 1923 } 1924 1925 ConstantLValue 1926 ConstantLValueEmitter::VisitObjCBoxedExpr(const ObjCBoxedExpr *E) { 1927 assert(E->isExpressibleAsConstantInitializer() && 1928 "this boxed expression can't be emitted as a compile-time constant"); 1929 auto *SL = cast<StringLiteral>(E->getSubExpr()->IgnoreParenCasts()); 1930 return emitConstantObjCStringLiteral(SL, E->getType(), CGM); 1931 } 1932 1933 ConstantLValue 1934 ConstantLValueEmitter::VisitPredefinedExpr(const PredefinedExpr *E) { 1935 return CGM.GetAddrOfConstantStringFromLiteral(E->getFunctionName()); 1936 } 1937 1938 ConstantLValue 1939 ConstantLValueEmitter::VisitAddrLabelExpr(const AddrLabelExpr *E) { 1940 assert(Emitter.CGF && "Invalid address of label expression outside function"); 1941 llvm::Constant *Ptr = Emitter.CGF->GetAddrOfLabel(E->getLabel()); 1942 Ptr = llvm::ConstantExpr::getBitCast(Ptr, 1943 CGM.getTypes().ConvertType(E->getType())); 1944 return Ptr; 1945 } 1946 1947 ConstantLValue 1948 ConstantLValueEmitter::VisitCallExpr(const CallExpr *E) { 1949 unsigned builtin = E->getBuiltinCallee(); 1950 if (builtin != Builtin::BI__builtin___CFStringMakeConstantString && 1951 builtin != Builtin::BI__builtin___NSStringMakeConstantString) 1952 return nullptr; 1953 1954 auto literal = cast<StringLiteral>(E->getArg(0)->IgnoreParenCasts()); 1955 if (builtin == Builtin::BI__builtin___NSStringMakeConstantString) { 1956 return CGM.getObjCRuntime().GenerateConstantString(literal); 1957 } else { 1958 // FIXME: need to deal with UCN conversion issues. 1959 return CGM.GetAddrOfConstantCFString(literal); 1960 } 1961 } 1962 1963 ConstantLValue 1964 ConstantLValueEmitter::VisitBlockExpr(const BlockExpr *E) { 1965 StringRef functionName; 1966 if (auto CGF = Emitter.CGF) 1967 functionName = CGF->CurFn->getName(); 1968 else 1969 functionName = "global"; 1970 1971 return CGM.GetAddrOfGlobalBlock(E, functionName); 1972 } 1973 1974 ConstantLValue 1975 ConstantLValueEmitter::VisitCXXTypeidExpr(const CXXTypeidExpr *E) { 1976 QualType T; 1977 if (E->isTypeOperand()) 1978 T = E->getTypeOperand(CGM.getContext()); 1979 else 1980 T = E->getExprOperand()->getType(); 1981 return CGM.GetAddrOfRTTIDescriptor(T); 1982 } 1983 1984 ConstantLValue 1985 ConstantLValueEmitter::VisitCXXUuidofExpr(const CXXUuidofExpr *E) { 1986 return CGM.GetAddrOfUuidDescriptor(E); 1987 } 1988 1989 ConstantLValue 1990 ConstantLValueEmitter::VisitMaterializeTemporaryExpr( 1991 const MaterializeTemporaryExpr *E) { 1992 assert(E->getStorageDuration() == SD_Static); 1993 SmallVector<const Expr *, 2> CommaLHSs; 1994 SmallVector<SubobjectAdjustment, 2> Adjustments; 1995 const Expr *Inner = 1996 E->getSubExpr()->skipRValueSubobjectAdjustments(CommaLHSs, Adjustments); 1997 return CGM.GetAddrOfGlobalTemporary(E, Inner); 1998 } 1999 2000 llvm::Constant *ConstantEmitter::tryEmitPrivate(const APValue &Value, 2001 QualType DestType) { 2002 switch (Value.getKind()) { 2003 case APValue::None: 2004 case APValue::Indeterminate: 2005 // Out-of-lifetime and indeterminate values can be modeled as 'undef'. 2006 return llvm::UndefValue::get(CGM.getTypes().ConvertType(DestType)); 2007 case APValue::LValue: 2008 return ConstantLValueEmitter(*this, Value, DestType).tryEmit(); 2009 case APValue::Int: 2010 return llvm::ConstantInt::get(CGM.getLLVMContext(), Value.getInt()); 2011 case APValue::FixedPoint: 2012 return llvm::ConstantInt::get(CGM.getLLVMContext(), 2013 Value.getFixedPoint().getValue()); 2014 case APValue::ComplexInt: { 2015 llvm::Constant *Complex[2]; 2016 2017 Complex[0] = llvm::ConstantInt::get(CGM.getLLVMContext(), 2018 Value.getComplexIntReal()); 2019 Complex[1] = llvm::ConstantInt::get(CGM.getLLVMContext(), 2020 Value.getComplexIntImag()); 2021 2022 // FIXME: the target may want to specify that this is packed. 2023 llvm::StructType *STy = 2024 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType()); 2025 return llvm::ConstantStruct::get(STy, Complex); 2026 } 2027 case APValue::Float: { 2028 const llvm::APFloat &Init = Value.getFloat(); 2029 if (&Init.getSemantics() == &llvm::APFloat::IEEEhalf() && 2030 !CGM.getContext().getLangOpts().NativeHalfType && 2031 CGM.getContext().getTargetInfo().useFP16ConversionIntrinsics()) 2032 return llvm::ConstantInt::get(CGM.getLLVMContext(), 2033 Init.bitcastToAPInt()); 2034 else 2035 return llvm::ConstantFP::get(CGM.getLLVMContext(), Init); 2036 } 2037 case APValue::ComplexFloat: { 2038 llvm::Constant *Complex[2]; 2039 2040 Complex[0] = llvm::ConstantFP::get(CGM.getLLVMContext(), 2041 Value.getComplexFloatReal()); 2042 Complex[1] = llvm::ConstantFP::get(CGM.getLLVMContext(), 2043 Value.getComplexFloatImag()); 2044 2045 // FIXME: the target may want to specify that this is packed. 2046 llvm::StructType *STy = 2047 llvm::StructType::get(Complex[0]->getType(), Complex[1]->getType()); 2048 return llvm::ConstantStruct::get(STy, Complex); 2049 } 2050 case APValue::Vector: { 2051 unsigned NumElts = Value.getVectorLength(); 2052 SmallVector<llvm::Constant *, 4> Inits(NumElts); 2053 2054 for (unsigned I = 0; I != NumElts; ++I) { 2055 const APValue &Elt = Value.getVectorElt(I); 2056 if (Elt.isInt()) 2057 Inits[I] = llvm::ConstantInt::get(CGM.getLLVMContext(), Elt.getInt()); 2058 else if (Elt.isFloat()) 2059 Inits[I] = llvm::ConstantFP::get(CGM.getLLVMContext(), Elt.getFloat()); 2060 else 2061 llvm_unreachable("unsupported vector element type"); 2062 } 2063 return llvm::ConstantVector::get(Inits); 2064 } 2065 case APValue::AddrLabelDiff: { 2066 const AddrLabelExpr *LHSExpr = Value.getAddrLabelDiffLHS(); 2067 const AddrLabelExpr *RHSExpr = Value.getAddrLabelDiffRHS(); 2068 llvm::Constant *LHS = tryEmitPrivate(LHSExpr, LHSExpr->getType()); 2069 llvm::Constant *RHS = tryEmitPrivate(RHSExpr, RHSExpr->getType()); 2070 if (!LHS || !RHS) return nullptr; 2071 2072 // Compute difference 2073 llvm::Type *ResultType = CGM.getTypes().ConvertType(DestType); 2074 LHS = llvm::ConstantExpr::getPtrToInt(LHS, CGM.IntPtrTy); 2075 RHS = llvm::ConstantExpr::getPtrToInt(RHS, CGM.IntPtrTy); 2076 llvm::Constant *AddrLabelDiff = llvm::ConstantExpr::getSub(LHS, RHS); 2077 2078 // LLVM is a bit sensitive about the exact format of the 2079 // address-of-label difference; make sure to truncate after 2080 // the subtraction. 2081 return llvm::ConstantExpr::getTruncOrBitCast(AddrLabelDiff, ResultType); 2082 } 2083 case APValue::Struct: 2084 case APValue::Union: 2085 return ConstStructBuilder::BuildStruct(*this, Value, DestType); 2086 case APValue::Array: { 2087 const ConstantArrayType *CAT = 2088 CGM.getContext().getAsConstantArrayType(DestType); 2089 unsigned NumElements = Value.getArraySize(); 2090 unsigned NumInitElts = Value.getArrayInitializedElts(); 2091 2092 // Emit array filler, if there is one. 2093 llvm::Constant *Filler = nullptr; 2094 if (Value.hasArrayFiller()) { 2095 Filler = tryEmitAbstractForMemory(Value.getArrayFiller(), 2096 CAT->getElementType()); 2097 if (!Filler) 2098 return nullptr; 2099 } 2100 2101 // Emit initializer elements. 2102 SmallVector<llvm::Constant*, 16> Elts; 2103 if (Filler && Filler->isNullValue()) 2104 Elts.reserve(NumInitElts + 1); 2105 else 2106 Elts.reserve(NumElements); 2107 2108 llvm::Type *CommonElementType = nullptr; 2109 for (unsigned I = 0; I < NumInitElts; ++I) { 2110 llvm::Constant *C = tryEmitPrivateForMemory( 2111 Value.getArrayInitializedElt(I), CAT->getElementType()); 2112 if (!C) return nullptr; 2113 2114 if (I == 0) 2115 CommonElementType = C->getType(); 2116 else if (C->getType() != CommonElementType) 2117 CommonElementType = nullptr; 2118 Elts.push_back(C); 2119 } 2120 2121 // This means that the array type is probably "IncompleteType" or some 2122 // type that is not ConstantArray. 2123 if (CAT == nullptr && CommonElementType == nullptr && !NumInitElts) { 2124 const ArrayType *AT = CGM.getContext().getAsArrayType(DestType); 2125 CommonElementType = CGM.getTypes().ConvertType(AT->getElementType()); 2126 llvm::ArrayType *AType = llvm::ArrayType::get(CommonElementType, 2127 NumElements); 2128 return llvm::ConstantAggregateZero::get(AType); 2129 } 2130 2131 llvm::ArrayType *Desired = 2132 cast<llvm::ArrayType>(CGM.getTypes().ConvertType(DestType)); 2133 return EmitArrayConstant(CGM, Desired, CommonElementType, NumElements, Elts, 2134 Filler); 2135 } 2136 case APValue::MemberPointer: 2137 return CGM.getCXXABI().EmitMemberPointer(Value, DestType); 2138 } 2139 llvm_unreachable("Unknown APValue kind"); 2140 } 2141 2142 llvm::GlobalVariable *CodeGenModule::getAddrOfConstantCompoundLiteralIfEmitted( 2143 const CompoundLiteralExpr *E) { 2144 return EmittedCompoundLiterals.lookup(E); 2145 } 2146 2147 void CodeGenModule::setAddrOfConstantCompoundLiteral( 2148 const CompoundLiteralExpr *CLE, llvm::GlobalVariable *GV) { 2149 bool Ok = EmittedCompoundLiterals.insert(std::make_pair(CLE, GV)).second; 2150 (void)Ok; 2151 assert(Ok && "CLE has already been emitted!"); 2152 } 2153 2154 ConstantAddress 2155 CodeGenModule::GetAddrOfConstantCompoundLiteral(const CompoundLiteralExpr *E) { 2156 assert(E->isFileScope() && "not a file-scope compound literal expr"); 2157 return tryEmitGlobalCompoundLiteral(*this, nullptr, E); 2158 } 2159 2160 llvm::Constant * 2161 CodeGenModule::getMemberPointerConstant(const UnaryOperator *uo) { 2162 // Member pointer constants always have a very particular form. 2163 const MemberPointerType *type = cast<MemberPointerType>(uo->getType()); 2164 const ValueDecl *decl = cast<DeclRefExpr>(uo->getSubExpr())->getDecl(); 2165 2166 // A member function pointer. 2167 if (const CXXMethodDecl *method = dyn_cast<CXXMethodDecl>(decl)) 2168 return getCXXABI().EmitMemberFunctionPointer(method); 2169 2170 // Otherwise, a member data pointer. 2171 uint64_t fieldOffset = getContext().getFieldOffset(decl); 2172 CharUnits chars = getContext().toCharUnitsFromBits((int64_t) fieldOffset); 2173 return getCXXABI().EmitMemberDataPointer(type, chars); 2174 } 2175 2176 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM, 2177 llvm::Type *baseType, 2178 const CXXRecordDecl *base); 2179 2180 static llvm::Constant *EmitNullConstant(CodeGenModule &CGM, 2181 const RecordDecl *record, 2182 bool asCompleteObject) { 2183 const CGRecordLayout &layout = CGM.getTypes().getCGRecordLayout(record); 2184 llvm::StructType *structure = 2185 (asCompleteObject ? layout.getLLVMType() 2186 : layout.getBaseSubobjectLLVMType()); 2187 2188 unsigned numElements = structure->getNumElements(); 2189 std::vector<llvm::Constant *> elements(numElements); 2190 2191 auto CXXR = dyn_cast<CXXRecordDecl>(record); 2192 // Fill in all the bases. 2193 if (CXXR) { 2194 for (const auto &I : CXXR->bases()) { 2195 if (I.isVirtual()) { 2196 // Ignore virtual bases; if we're laying out for a complete 2197 // object, we'll lay these out later. 2198 continue; 2199 } 2200 2201 const CXXRecordDecl *base = 2202 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 2203 2204 // Ignore empty bases. 2205 if (base->isEmpty() || 2206 CGM.getContext().getASTRecordLayout(base).getNonVirtualSize() 2207 .isZero()) 2208 continue; 2209 2210 unsigned fieldIndex = layout.getNonVirtualBaseLLVMFieldNo(base); 2211 llvm::Type *baseType = structure->getElementType(fieldIndex); 2212 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base); 2213 } 2214 } 2215 2216 // Fill in all the fields. 2217 for (const auto *Field : record->fields()) { 2218 // Fill in non-bitfields. (Bitfields always use a zero pattern, which we 2219 // will fill in later.) 2220 if (!Field->isBitField() && !Field->isZeroSize(CGM.getContext())) { 2221 unsigned fieldIndex = layout.getLLVMFieldNo(Field); 2222 elements[fieldIndex] = CGM.EmitNullConstant(Field->getType()); 2223 } 2224 2225 // For unions, stop after the first named field. 2226 if (record->isUnion()) { 2227 if (Field->getIdentifier()) 2228 break; 2229 if (const auto *FieldRD = Field->getType()->getAsRecordDecl()) 2230 if (FieldRD->findFirstNamedDataMember()) 2231 break; 2232 } 2233 } 2234 2235 // Fill in the virtual bases, if we're working with the complete object. 2236 if (CXXR && asCompleteObject) { 2237 for (const auto &I : CXXR->vbases()) { 2238 const CXXRecordDecl *base = 2239 cast<CXXRecordDecl>(I.getType()->castAs<RecordType>()->getDecl()); 2240 2241 // Ignore empty bases. 2242 if (base->isEmpty()) 2243 continue; 2244 2245 unsigned fieldIndex = layout.getVirtualBaseIndex(base); 2246 2247 // We might have already laid this field out. 2248 if (elements[fieldIndex]) continue; 2249 2250 llvm::Type *baseType = structure->getElementType(fieldIndex); 2251 elements[fieldIndex] = EmitNullConstantForBase(CGM, baseType, base); 2252 } 2253 } 2254 2255 // Now go through all other fields and zero them out. 2256 for (unsigned i = 0; i != numElements; ++i) { 2257 if (!elements[i]) 2258 elements[i] = llvm::Constant::getNullValue(structure->getElementType(i)); 2259 } 2260 2261 return llvm::ConstantStruct::get(structure, elements); 2262 } 2263 2264 /// Emit the null constant for a base subobject. 2265 static llvm::Constant *EmitNullConstantForBase(CodeGenModule &CGM, 2266 llvm::Type *baseType, 2267 const CXXRecordDecl *base) { 2268 const CGRecordLayout &baseLayout = CGM.getTypes().getCGRecordLayout(base); 2269 2270 // Just zero out bases that don't have any pointer to data members. 2271 if (baseLayout.isZeroInitializableAsBase()) 2272 return llvm::Constant::getNullValue(baseType); 2273 2274 // Otherwise, we can just use its null constant. 2275 return EmitNullConstant(CGM, base, /*asCompleteObject=*/false); 2276 } 2277 2278 llvm::Constant *ConstantEmitter::emitNullForMemory(CodeGenModule &CGM, 2279 QualType T) { 2280 return emitForMemory(CGM, CGM.EmitNullConstant(T), T); 2281 } 2282 2283 llvm::Constant *CodeGenModule::EmitNullConstant(QualType T) { 2284 if (T->getAs<PointerType>()) 2285 return getNullPointer( 2286 cast<llvm::PointerType>(getTypes().ConvertTypeForMem(T)), T); 2287 2288 if (getTypes().isZeroInitializable(T)) 2289 return llvm::Constant::getNullValue(getTypes().ConvertTypeForMem(T)); 2290 2291 if (const ConstantArrayType *CAT = Context.getAsConstantArrayType(T)) { 2292 llvm::ArrayType *ATy = 2293 cast<llvm::ArrayType>(getTypes().ConvertTypeForMem(T)); 2294 2295 QualType ElementTy = CAT->getElementType(); 2296 2297 llvm::Constant *Element = 2298 ConstantEmitter::emitNullForMemory(*this, ElementTy); 2299 unsigned NumElements = CAT->getSize().getZExtValue(); 2300 SmallVector<llvm::Constant *, 8> Array(NumElements, Element); 2301 return llvm::ConstantArray::get(ATy, Array); 2302 } 2303 2304 if (const RecordType *RT = T->getAs<RecordType>()) 2305 return ::EmitNullConstant(*this, RT->getDecl(), /*complete object*/ true); 2306 2307 assert(T->isMemberDataPointerType() && 2308 "Should only see pointers to data members here!"); 2309 2310 return getCXXABI().EmitNullMemberPointer(T->castAs<MemberPointerType>()); 2311 } 2312 2313 llvm::Constant * 2314 CodeGenModule::EmitNullConstantForBase(const CXXRecordDecl *Record) { 2315 return ::EmitNullConstant(*this, Record, false); 2316 } 2317