Clang Project

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