CGExprConstant.cpp 77 KB

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