CGExprConstant.cpp 86 KB

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