Bug Summary

File:tools/clang/lib/CodeGen/CGAtomic.cpp
Warning:line 972, column 17
Called C++ object pointer is null

Annotated Source Code

Press '?' to see keyboard shortcuts

clang -cc1 -triple x86_64-pc-linux-gnu -analyze -disable-free -disable-llvm-verifier -discard-value-names -main-file-name CGAtomic.cpp -analyzer-store=region -analyzer-opt-analyze-nested-blocks -analyzer-checker=core -analyzer-checker=apiModeling -analyzer-checker=unix -analyzer-checker=deadcode -analyzer-checker=cplusplus -analyzer-checker=security.insecureAPI.UncheckedReturn -analyzer-checker=security.insecureAPI.getpw -analyzer-checker=security.insecureAPI.gets -analyzer-checker=security.insecureAPI.mktemp -analyzer-checker=security.insecureAPI.mkstemp -analyzer-checker=security.insecureAPI.vfork -analyzer-checker=nullability.NullPassedToNonnull -analyzer-checker=nullability.NullReturnedFromNonnull -analyzer-output plist -w -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-10/lib/clang/10.0.0 -D CLANG_VENDOR="Debian " -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/include -I /build/llvm-toolchain-snapshot-10~svn373517/include -U NDEBUG -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/x86_64-linux-gnu/c++/6.3.0 -internal-isystem /usr/lib/gcc/x86_64-linux-gnu/6.3.0/../../../../include/c++/6.3.0/backward -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-10/lib/clang/10.0.0/include -internal-externc-isystem /usr/include/x86_64-linux-gnu -internal-externc-isystem /include -internal-externc-isystem /usr/include -O2 -Wno-unused-parameter -Wwrite-strings -Wno-missing-field-initializers -Wno-long-long -Wno-maybe-uninitialized -Wno-comment -std=c++14 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-10~svn373517/build-llvm/tools/clang/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~svn373517=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -faddrsig -o /tmp/scan-build-2019-10-02-234743-9763-1 -x c++ /build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp

/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp

1//===--- CGAtomic.cpp - Emit LLVM IR for atomic operations ----------------===//
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 file contains the code for emitting atomic operations.
10//
11//===----------------------------------------------------------------------===//
12
13#include "CGCall.h"
14#include "CGRecordLayout.h"
15#include "CodeGenFunction.h"
16#include "CodeGenModule.h"
17#include "TargetInfo.h"
18#include "clang/AST/ASTContext.h"
19#include "clang/CodeGen/CGFunctionInfo.h"
20#include "clang/Frontend/FrontendDiagnostic.h"
21#include "llvm/ADT/DenseMap.h"
22#include "llvm/IR/DataLayout.h"
23#include "llvm/IR/Intrinsics.h"
24#include "llvm/IR/Operator.h"
25
26using namespace clang;
27using namespace CodeGen;
28
29namespace {
30 class AtomicInfo {
31 CodeGenFunction &CGF;
32 QualType AtomicTy;
33 QualType ValueTy;
34 uint64_t AtomicSizeInBits;
35 uint64_t ValueSizeInBits;
36 CharUnits AtomicAlign;
37 CharUnits ValueAlign;
38 TypeEvaluationKind EvaluationKind;
39 bool UseLibcall;
40 LValue LVal;
41 CGBitFieldInfo BFI;
42 public:
43 AtomicInfo(CodeGenFunction &CGF, LValue &lvalue)
44 : CGF(CGF), AtomicSizeInBits(0), ValueSizeInBits(0),
45 EvaluationKind(TEK_Scalar), UseLibcall(true) {
46 assert(!lvalue.isGlobalReg())((!lvalue.isGlobalReg()) ? static_cast<void> (0) : __assert_fail
("!lvalue.isGlobalReg()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 46, __PRETTY_FUNCTION__))
;
47 ASTContext &C = CGF.getContext();
48 if (lvalue.isSimple()) {
49 AtomicTy = lvalue.getType();
50 if (auto *ATy = AtomicTy->getAs<AtomicType>())
51 ValueTy = ATy->getValueType();
52 else
53 ValueTy = AtomicTy;
54 EvaluationKind = CGF.getEvaluationKind(ValueTy);
55
56 uint64_t ValueAlignInBits;
57 uint64_t AtomicAlignInBits;
58 TypeInfo ValueTI = C.getTypeInfo(ValueTy);
59 ValueSizeInBits = ValueTI.Width;
60 ValueAlignInBits = ValueTI.Align;
61
62 TypeInfo AtomicTI = C.getTypeInfo(AtomicTy);
63 AtomicSizeInBits = AtomicTI.Width;
64 AtomicAlignInBits = AtomicTI.Align;
65
66 assert(ValueSizeInBits <= AtomicSizeInBits)((ValueSizeInBits <= AtomicSizeInBits) ? static_cast<void
> (0) : __assert_fail ("ValueSizeInBits <= AtomicSizeInBits"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 66, __PRETTY_FUNCTION__))
;
67 assert(ValueAlignInBits <= AtomicAlignInBits)((ValueAlignInBits <= AtomicAlignInBits) ? static_cast<
void> (0) : __assert_fail ("ValueAlignInBits <= AtomicAlignInBits"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 67, __PRETTY_FUNCTION__))
;
68
69 AtomicAlign = C.toCharUnitsFromBits(AtomicAlignInBits);
70 ValueAlign = C.toCharUnitsFromBits(ValueAlignInBits);
71 if (lvalue.getAlignment().isZero())
72 lvalue.setAlignment(AtomicAlign);
73
74 LVal = lvalue;
75 } else if (lvalue.isBitField()) {
76 ValueTy = lvalue.getType();
77 ValueSizeInBits = C.getTypeSize(ValueTy);
78 auto &OrigBFI = lvalue.getBitFieldInfo();
79 auto Offset = OrigBFI.Offset % C.toBits(lvalue.getAlignment());
80 AtomicSizeInBits = C.toBits(
81 C.toCharUnitsFromBits(Offset + OrigBFI.Size + C.getCharWidth() - 1)
82 .alignTo(lvalue.getAlignment()));
83 auto VoidPtrAddr = CGF.EmitCastToVoidPtr(lvalue.getBitFieldPointer());
84 auto OffsetInChars =
85 (C.toCharUnitsFromBits(OrigBFI.Offset) / lvalue.getAlignment()) *
86 lvalue.getAlignment();
87 VoidPtrAddr = CGF.Builder.CreateConstGEP1_64(
88 VoidPtrAddr, OffsetInChars.getQuantity());
89 auto Addr = CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
90 VoidPtrAddr,
91 CGF.Builder.getIntNTy(AtomicSizeInBits)->getPointerTo(),
92 "atomic_bitfield_base");
93 BFI = OrigBFI;
94 BFI.Offset = Offset;
95 BFI.StorageSize = AtomicSizeInBits;
96 BFI.StorageOffset += OffsetInChars;
97 LVal = LValue::MakeBitfield(Address(Addr, lvalue.getAlignment()),
98 BFI, lvalue.getType(), lvalue.getBaseInfo(),
99 lvalue.getTBAAInfo());
100 AtomicTy = C.getIntTypeForBitwidth(AtomicSizeInBits, OrigBFI.IsSigned);
101 if (AtomicTy.isNull()) {
102 llvm::APInt Size(
103 /*numBits=*/32,
104 C.toCharUnitsFromBits(AtomicSizeInBits).getQuantity());
105 AtomicTy = C.getConstantArrayType(C.CharTy, Size, ArrayType::Normal,
106 /*IndexTypeQuals=*/0);
107 }
108 AtomicAlign = ValueAlign = lvalue.getAlignment();
109 } else if (lvalue.isVectorElt()) {
110 ValueTy = lvalue.getType()->castAs<VectorType>()->getElementType();
111 ValueSizeInBits = C.getTypeSize(ValueTy);
112 AtomicTy = lvalue.getType();
113 AtomicSizeInBits = C.getTypeSize(AtomicTy);
114 AtomicAlign = ValueAlign = lvalue.getAlignment();
115 LVal = lvalue;
116 } else {
117 assert(lvalue.isExtVectorElt())((lvalue.isExtVectorElt()) ? static_cast<void> (0) : __assert_fail
("lvalue.isExtVectorElt()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 117, __PRETTY_FUNCTION__))
;
118 ValueTy = lvalue.getType();
119 ValueSizeInBits = C.getTypeSize(ValueTy);
120 AtomicTy = ValueTy = CGF.getContext().getExtVectorType(
121 lvalue.getType(), lvalue.getExtVectorAddress()
122 .getElementType()->getVectorNumElements());
123 AtomicSizeInBits = C.getTypeSize(AtomicTy);
124 AtomicAlign = ValueAlign = lvalue.getAlignment();
125 LVal = lvalue;
126 }
127 UseLibcall = !C.getTargetInfo().hasBuiltinAtomic(
128 AtomicSizeInBits, C.toBits(lvalue.getAlignment()));
129 }
130
131 QualType getAtomicType() const { return AtomicTy; }
132 QualType getValueType() const { return ValueTy; }
133 CharUnits getAtomicAlignment() const { return AtomicAlign; }
134 uint64_t getAtomicSizeInBits() const { return AtomicSizeInBits; }
135 uint64_t getValueSizeInBits() const { return ValueSizeInBits; }
136 TypeEvaluationKind getEvaluationKind() const { return EvaluationKind; }
137 bool shouldUseLibcall() const { return UseLibcall; }
138 const LValue &getAtomicLValue() const { return LVal; }
139 llvm::Value *getAtomicPointer() const {
140 if (LVal.isSimple())
141 return LVal.getPointer();
142 else if (LVal.isBitField())
143 return LVal.getBitFieldPointer();
144 else if (LVal.isVectorElt())
145 return LVal.getVectorPointer();
146 assert(LVal.isExtVectorElt())((LVal.isExtVectorElt()) ? static_cast<void> (0) : __assert_fail
("LVal.isExtVectorElt()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 146, __PRETTY_FUNCTION__))
;
147 return LVal.getExtVectorPointer();
148 }
149 Address getAtomicAddress() const {
150 return Address(getAtomicPointer(), getAtomicAlignment());
151 }
152
153 Address getAtomicAddressAsAtomicIntPointer() const {
154 return emitCastToAtomicIntPointer(getAtomicAddress());
155 }
156
157 /// Is the atomic size larger than the underlying value type?
158 ///
159 /// Note that the absence of padding does not mean that atomic
160 /// objects are completely interchangeable with non-atomic
161 /// objects: we might have promoted the alignment of a type
162 /// without making it bigger.
163 bool hasPadding() const {
164 return (ValueSizeInBits != AtomicSizeInBits);
165 }
166
167 bool emitMemSetZeroIfNecessary() const;
168
169 llvm::Value *getAtomicSizeValue() const {
170 CharUnits size = CGF.getContext().toCharUnitsFromBits(AtomicSizeInBits);
171 return CGF.CGM.getSize(size);
172 }
173
174 /// Cast the given pointer to an integer pointer suitable for atomic
175 /// operations if the source.
176 Address emitCastToAtomicIntPointer(Address Addr) const;
177
178 /// If Addr is compatible with the iN that will be used for an atomic
179 /// operation, bitcast it. Otherwise, create a temporary that is suitable
180 /// and copy the value across.
181 Address convertToAtomicIntPointer(Address Addr) const;
182
183 /// Turn an atomic-layout object into an r-value.
184 RValue convertAtomicTempToRValue(Address addr, AggValueSlot resultSlot,
185 SourceLocation loc, bool AsValue) const;
186
187 /// Converts a rvalue to integer value.
188 llvm::Value *convertRValueToInt(RValue RVal) const;
189
190 RValue ConvertIntToValueOrAtomic(llvm::Value *IntVal,
191 AggValueSlot ResultSlot,
192 SourceLocation Loc, bool AsValue) const;
193
194 /// Copy an atomic r-value into atomic-layout memory.
195 void emitCopyIntoMemory(RValue rvalue) const;
196
197 /// Project an l-value down to the value field.
198 LValue projectValue() const {
199 assert(LVal.isSimple())((LVal.isSimple()) ? static_cast<void> (0) : __assert_fail
("LVal.isSimple()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 199, __PRETTY_FUNCTION__))
;
200 Address addr = getAtomicAddress();
201 if (hasPadding())
202 addr = CGF.Builder.CreateStructGEP(addr, 0);
203
204 return LValue::MakeAddr(addr, getValueType(), CGF.getContext(),
205 LVal.getBaseInfo(), LVal.getTBAAInfo());
206 }
207
208 /// Emits atomic load.
209 /// \returns Loaded value.
210 RValue EmitAtomicLoad(AggValueSlot ResultSlot, SourceLocation Loc,
211 bool AsValue, llvm::AtomicOrdering AO,
212 bool IsVolatile);
213
214 /// Emits atomic compare-and-exchange sequence.
215 /// \param Expected Expected value.
216 /// \param Desired Desired value.
217 /// \param Success Atomic ordering for success operation.
218 /// \param Failure Atomic ordering for failed operation.
219 /// \param IsWeak true if atomic operation is weak, false otherwise.
220 /// \returns Pair of values: previous value from storage (value type) and
221 /// boolean flag (i1 type) with true if success and false otherwise.
222 std::pair<RValue, llvm::Value *>
223 EmitAtomicCompareExchange(RValue Expected, RValue Desired,
224 llvm::AtomicOrdering Success =
225 llvm::AtomicOrdering::SequentiallyConsistent,
226 llvm::AtomicOrdering Failure =
227 llvm::AtomicOrdering::SequentiallyConsistent,
228 bool IsWeak = false);
229
230 /// Emits atomic update.
231 /// \param AO Atomic ordering.
232 /// \param UpdateOp Update operation for the current lvalue.
233 void EmitAtomicUpdate(llvm::AtomicOrdering AO,
234 const llvm::function_ref<RValue(RValue)> &UpdateOp,
235 bool IsVolatile);
236 /// Emits atomic update.
237 /// \param AO Atomic ordering.
238 void EmitAtomicUpdate(llvm::AtomicOrdering AO, RValue UpdateRVal,
239 bool IsVolatile);
240
241 /// Materialize an atomic r-value in atomic-layout memory.
242 Address materializeRValue(RValue rvalue) const;
243
244 /// Creates temp alloca for intermediate operations on atomic value.
245 Address CreateTempAlloca() const;
246 private:
247 bool requiresMemSetZero(llvm::Type *type) const;
248
249
250 /// Emits atomic load as a libcall.
251 void EmitAtomicLoadLibcall(llvm::Value *AddForLoaded,
252 llvm::AtomicOrdering AO, bool IsVolatile);
253 /// Emits atomic load as LLVM instruction.
254 llvm::Value *EmitAtomicLoadOp(llvm::AtomicOrdering AO, bool IsVolatile);
255 /// Emits atomic compare-and-exchange op as a libcall.
256 llvm::Value *EmitAtomicCompareExchangeLibcall(
257 llvm::Value *ExpectedAddr, llvm::Value *DesiredAddr,
258 llvm::AtomicOrdering Success =
259 llvm::AtomicOrdering::SequentiallyConsistent,
260 llvm::AtomicOrdering Failure =
261 llvm::AtomicOrdering::SequentiallyConsistent);
262 /// Emits atomic compare-and-exchange op as LLVM instruction.
263 std::pair<llvm::Value *, llvm::Value *> EmitAtomicCompareExchangeOp(
264 llvm::Value *ExpectedVal, llvm::Value *DesiredVal,
265 llvm::AtomicOrdering Success =
266 llvm::AtomicOrdering::SequentiallyConsistent,
267 llvm::AtomicOrdering Failure =
268 llvm::AtomicOrdering::SequentiallyConsistent,
269 bool IsWeak = false);
270 /// Emit atomic update as libcalls.
271 void
272 EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO,
273 const llvm::function_ref<RValue(RValue)> &UpdateOp,
274 bool IsVolatile);
275 /// Emit atomic update as LLVM instructions.
276 void EmitAtomicUpdateOp(llvm::AtomicOrdering AO,
277 const llvm::function_ref<RValue(RValue)> &UpdateOp,
278 bool IsVolatile);
279 /// Emit atomic update as libcalls.
280 void EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO, RValue UpdateRVal,
281 bool IsVolatile);
282 /// Emit atomic update as LLVM instructions.
283 void EmitAtomicUpdateOp(llvm::AtomicOrdering AO, RValue UpdateRal,
284 bool IsVolatile);
285 };
286}
287
288Address AtomicInfo::CreateTempAlloca() const {
289 Address TempAlloca = CGF.CreateMemTemp(
290 (LVal.isBitField() && ValueSizeInBits > AtomicSizeInBits) ? ValueTy
291 : AtomicTy,
292 getAtomicAlignment(),
293 "atomic-temp");
294 // Cast to pointer to value type for bitfields.
295 if (LVal.isBitField())
296 return CGF.Builder.CreatePointerBitCastOrAddrSpaceCast(
297 TempAlloca, getAtomicAddress().getType());
298 return TempAlloca;
299}
300
301static RValue emitAtomicLibcall(CodeGenFunction &CGF,
302 StringRef fnName,
303 QualType resultType,
304 CallArgList &args) {
305 const CGFunctionInfo &fnInfo =
306 CGF.CGM.getTypes().arrangeBuiltinFunctionCall(resultType, args);
307 llvm::FunctionType *fnTy = CGF.CGM.getTypes().GetFunctionType(fnInfo);
308 llvm::FunctionCallee fn = CGF.CGM.CreateRuntimeFunction(fnTy, fnName);
309 auto callee = CGCallee::forDirect(fn);
310 return CGF.EmitCall(fnInfo, callee, ReturnValueSlot(), args);
311}
312
313/// Does a store of the given IR type modify the full expected width?
314static bool isFullSizeType(CodeGenModule &CGM, llvm::Type *type,
315 uint64_t expectedSize) {
316 return (CGM.getDataLayout().getTypeStoreSize(type) * 8 == expectedSize);
317}
318
319/// Does the atomic type require memsetting to zero before initialization?
320///
321/// The IR type is provided as a way of making certain queries faster.
322bool AtomicInfo::requiresMemSetZero(llvm::Type *type) const {
323 // If the atomic type has size padding, we definitely need a memset.
324 if (hasPadding()) return true;
325
326 // Otherwise, do some simple heuristics to try to avoid it:
327 switch (getEvaluationKind()) {
328 // For scalars and complexes, check whether the store size of the
329 // type uses the full size.
330 case TEK_Scalar:
331 return !isFullSizeType(CGF.CGM, type, AtomicSizeInBits);
332 case TEK_Complex:
333 return !isFullSizeType(CGF.CGM, type->getStructElementType(0),
334 AtomicSizeInBits / 2);
335
336 // Padding in structs has an undefined bit pattern. User beware.
337 case TEK_Aggregate:
338 return false;
339 }
340 llvm_unreachable("bad evaluation kind")::llvm::llvm_unreachable_internal("bad evaluation kind", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 340)
;
341}
342
343bool AtomicInfo::emitMemSetZeroIfNecessary() const {
344 assert(LVal.isSimple())((LVal.isSimple()) ? static_cast<void> (0) : __assert_fail
("LVal.isSimple()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 344, __PRETTY_FUNCTION__))
;
345 llvm::Value *addr = LVal.getPointer();
346 if (!requiresMemSetZero(addr->getType()->getPointerElementType()))
347 return false;
348
349 CGF.Builder.CreateMemSet(
350 addr, llvm::ConstantInt::get(CGF.Int8Ty, 0),
351 CGF.getContext().toCharUnitsFromBits(AtomicSizeInBits).getQuantity(),
352 LVal.getAlignment().getQuantity());
353 return true;
354}
355
356static void emitAtomicCmpXchg(CodeGenFunction &CGF, AtomicExpr *E, bool IsWeak,
357 Address Dest, Address Ptr,
358 Address Val1, Address Val2,
359 uint64_t Size,
360 llvm::AtomicOrdering SuccessOrder,
361 llvm::AtomicOrdering FailureOrder,
362 llvm::SyncScope::ID Scope) {
363 // Note that cmpxchg doesn't support weak cmpxchg, at least at the moment.
364 llvm::Value *Expected = CGF.Builder.CreateLoad(Val1);
365 llvm::Value *Desired = CGF.Builder.CreateLoad(Val2);
366
367 llvm::AtomicCmpXchgInst *Pair = CGF.Builder.CreateAtomicCmpXchg(
368 Ptr.getPointer(), Expected, Desired, SuccessOrder, FailureOrder,
369 Scope);
370 Pair->setVolatile(E->isVolatile());
371 Pair->setWeak(IsWeak);
372
373 // Cmp holds the result of the compare-exchange operation: true on success,
374 // false on failure.
375 llvm::Value *Old = CGF.Builder.CreateExtractValue(Pair, 0);
376 llvm::Value *Cmp = CGF.Builder.CreateExtractValue(Pair, 1);
377
378 // This basic block is used to hold the store instruction if the operation
379 // failed.
380 llvm::BasicBlock *StoreExpectedBB =
381 CGF.createBasicBlock("cmpxchg.store_expected", CGF.CurFn);
382
383 // This basic block is the exit point of the operation, we should end up
384 // here regardless of whether or not the operation succeeded.
385 llvm::BasicBlock *ContinueBB =
386 CGF.createBasicBlock("cmpxchg.continue", CGF.CurFn);
387
388 // Update Expected if Expected isn't equal to Old, otherwise branch to the
389 // exit point.
390 CGF.Builder.CreateCondBr(Cmp, ContinueBB, StoreExpectedBB);
391
392 CGF.Builder.SetInsertPoint(StoreExpectedBB);
393 // Update the memory at Expected with Old's value.
394 CGF.Builder.CreateStore(Old, Val1);
395 // Finally, branch to the exit point.
396 CGF.Builder.CreateBr(ContinueBB);
397
398 CGF.Builder.SetInsertPoint(ContinueBB);
399 // Update the memory at Dest with Cmp's value.
400 CGF.EmitStoreOfScalar(Cmp, CGF.MakeAddrLValue(Dest, E->getType()));
401}
402
403/// Given an ordering required on success, emit all possible cmpxchg
404/// instructions to cope with the provided (but possibly only dynamically known)
405/// FailureOrder.
406static void emitAtomicCmpXchgFailureSet(CodeGenFunction &CGF, AtomicExpr *E,
407 bool IsWeak, Address Dest, Address Ptr,
408 Address Val1, Address Val2,
409 llvm::Value *FailureOrderVal,
410 uint64_t Size,
411 llvm::AtomicOrdering SuccessOrder,
412 llvm::SyncScope::ID Scope) {
413 llvm::AtomicOrdering FailureOrder;
414 if (llvm::ConstantInt *FO = dyn_cast<llvm::ConstantInt>(FailureOrderVal)) {
415 auto FOS = FO->getSExtValue();
416 if (!llvm::isValidAtomicOrderingCABI(FOS))
417 FailureOrder = llvm::AtomicOrdering::Monotonic;
418 else
419 switch ((llvm::AtomicOrderingCABI)FOS) {
420 case llvm::AtomicOrderingCABI::relaxed:
421 case llvm::AtomicOrderingCABI::release:
422 case llvm::AtomicOrderingCABI::acq_rel:
423 FailureOrder = llvm::AtomicOrdering::Monotonic;
424 break;
425 case llvm::AtomicOrderingCABI::consume:
426 case llvm::AtomicOrderingCABI::acquire:
427 FailureOrder = llvm::AtomicOrdering::Acquire;
428 break;
429 case llvm::AtomicOrderingCABI::seq_cst:
430 FailureOrder = llvm::AtomicOrdering::SequentiallyConsistent;
431 break;
432 }
433 if (isStrongerThan(FailureOrder, SuccessOrder)) {
434 // Don't assert on undefined behavior "failure argument shall be no
435 // stronger than the success argument".
436 FailureOrder =
437 llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(SuccessOrder);
438 }
439 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size, SuccessOrder,
440 FailureOrder, Scope);
441 return;
442 }
443
444 // Create all the relevant BB's
445 llvm::BasicBlock *MonotonicBB = nullptr, *AcquireBB = nullptr,
446 *SeqCstBB = nullptr;
447 MonotonicBB = CGF.createBasicBlock("monotonic_fail", CGF.CurFn);
448 if (SuccessOrder != llvm::AtomicOrdering::Monotonic &&
449 SuccessOrder != llvm::AtomicOrdering::Release)
450 AcquireBB = CGF.createBasicBlock("acquire_fail", CGF.CurFn);
451 if (SuccessOrder == llvm::AtomicOrdering::SequentiallyConsistent)
452 SeqCstBB = CGF.createBasicBlock("seqcst_fail", CGF.CurFn);
453
454 llvm::BasicBlock *ContBB = CGF.createBasicBlock("atomic.continue", CGF.CurFn);
455
456 llvm::SwitchInst *SI = CGF.Builder.CreateSwitch(FailureOrderVal, MonotonicBB);
457
458 // Emit all the different atomics
459
460 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
461 // doesn't matter unless someone is crazy enough to use something that
462 // doesn't fold to a constant for the ordering.
463 CGF.Builder.SetInsertPoint(MonotonicBB);
464 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2,
465 Size, SuccessOrder, llvm::AtomicOrdering::Monotonic, Scope);
466 CGF.Builder.CreateBr(ContBB);
467
468 if (AcquireBB) {
469 CGF.Builder.SetInsertPoint(AcquireBB);
470 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2,
471 Size, SuccessOrder, llvm::AtomicOrdering::Acquire, Scope);
472 CGF.Builder.CreateBr(ContBB);
473 SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::consume),
474 AcquireBB);
475 SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::acquire),
476 AcquireBB);
477 }
478 if (SeqCstBB) {
479 CGF.Builder.SetInsertPoint(SeqCstBB);
480 emitAtomicCmpXchg(CGF, E, IsWeak, Dest, Ptr, Val1, Val2, Size, SuccessOrder,
481 llvm::AtomicOrdering::SequentiallyConsistent, Scope);
482 CGF.Builder.CreateBr(ContBB);
483 SI->addCase(CGF.Builder.getInt32((int)llvm::AtomicOrderingCABI::seq_cst),
484 SeqCstBB);
485 }
486
487 CGF.Builder.SetInsertPoint(ContBB);
488}
489
490static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *E, Address Dest,
491 Address Ptr, Address Val1, Address Val2,
492 llvm::Value *IsWeak, llvm::Value *FailureOrder,
493 uint64_t Size, llvm::AtomicOrdering Order,
494 llvm::SyncScope::ID Scope) {
495 llvm::AtomicRMWInst::BinOp Op = llvm::AtomicRMWInst::Add;
496 llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
497
498 switch (E->getOp()) {
499 case AtomicExpr::AO__c11_atomic_init:
500 case AtomicExpr::AO__opencl_atomic_init:
501 llvm_unreachable("Already handled!")::llvm::llvm_unreachable_internal("Already handled!", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 501)
;
502
503 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
504 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
505 emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
506 FailureOrder, Size, Order, Scope);
507 return;
508 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
509 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
510 emitAtomicCmpXchgFailureSet(CGF, E, true, Dest, Ptr, Val1, Val2,
511 FailureOrder, Size, Order, Scope);
512 return;
513 case AtomicExpr::AO__atomic_compare_exchange:
514 case AtomicExpr::AO__atomic_compare_exchange_n: {
515 if (llvm::ConstantInt *IsWeakC = dyn_cast<llvm::ConstantInt>(IsWeak)) {
516 emitAtomicCmpXchgFailureSet(CGF, E, IsWeakC->getZExtValue(), Dest, Ptr,
517 Val1, Val2, FailureOrder, Size, Order, Scope);
518 } else {
519 // Create all the relevant BB's
520 llvm::BasicBlock *StrongBB =
521 CGF.createBasicBlock("cmpxchg.strong", CGF.CurFn);
522 llvm::BasicBlock *WeakBB = CGF.createBasicBlock("cmxchg.weak", CGF.CurFn);
523 llvm::BasicBlock *ContBB =
524 CGF.createBasicBlock("cmpxchg.continue", CGF.CurFn);
525
526 llvm::SwitchInst *SI = CGF.Builder.CreateSwitch(IsWeak, WeakBB);
527 SI->addCase(CGF.Builder.getInt1(false), StrongBB);
528
529 CGF.Builder.SetInsertPoint(StrongBB);
530 emitAtomicCmpXchgFailureSet(CGF, E, false, Dest, Ptr, Val1, Val2,
531 FailureOrder, Size, Order, Scope);
532 CGF.Builder.CreateBr(ContBB);
533
534 CGF.Builder.SetInsertPoint(WeakBB);
535 emitAtomicCmpXchgFailureSet(CGF, E, true, Dest, Ptr, Val1, Val2,
536 FailureOrder, Size, Order, Scope);
537 CGF.Builder.CreateBr(ContBB);
538
539 CGF.Builder.SetInsertPoint(ContBB);
540 }
541 return;
542 }
543 case AtomicExpr::AO__c11_atomic_load:
544 case AtomicExpr::AO__opencl_atomic_load:
545 case AtomicExpr::AO__atomic_load_n:
546 case AtomicExpr::AO__atomic_load: {
547 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Ptr);
548 Load->setAtomic(Order, Scope);
549 Load->setVolatile(E->isVolatile());
550 CGF.Builder.CreateStore(Load, Dest);
551 return;
552 }
553
554 case AtomicExpr::AO__c11_atomic_store:
555 case AtomicExpr::AO__opencl_atomic_store:
556 case AtomicExpr::AO__atomic_store:
557 case AtomicExpr::AO__atomic_store_n: {
558 llvm::Value *LoadVal1 = CGF.Builder.CreateLoad(Val1);
559 llvm::StoreInst *Store = CGF.Builder.CreateStore(LoadVal1, Ptr);
560 Store->setAtomic(Order, Scope);
561 Store->setVolatile(E->isVolatile());
562 return;
563 }
564
565 case AtomicExpr::AO__c11_atomic_exchange:
566 case AtomicExpr::AO__opencl_atomic_exchange:
567 case AtomicExpr::AO__atomic_exchange_n:
568 case AtomicExpr::AO__atomic_exchange:
569 Op = llvm::AtomicRMWInst::Xchg;
570 break;
571
572 case AtomicExpr::AO__atomic_add_fetch:
573 PostOp = llvm::Instruction::Add;
574 LLVM_FALLTHROUGH[[gnu::fallthrough]];
575 case AtomicExpr::AO__c11_atomic_fetch_add:
576 case AtomicExpr::AO__opencl_atomic_fetch_add:
577 case AtomicExpr::AO__atomic_fetch_add:
578 Op = llvm::AtomicRMWInst::Add;
579 break;
580
581 case AtomicExpr::AO__atomic_sub_fetch:
582 PostOp = llvm::Instruction::Sub;
583 LLVM_FALLTHROUGH[[gnu::fallthrough]];
584 case AtomicExpr::AO__c11_atomic_fetch_sub:
585 case AtomicExpr::AO__opencl_atomic_fetch_sub:
586 case AtomicExpr::AO__atomic_fetch_sub:
587 Op = llvm::AtomicRMWInst::Sub;
588 break;
589
590 case AtomicExpr::AO__opencl_atomic_fetch_min:
591 case AtomicExpr::AO__atomic_fetch_min:
592 Op = E->getValueType()->isSignedIntegerType() ? llvm::AtomicRMWInst::Min
593 : llvm::AtomicRMWInst::UMin;
594 break;
595
596 case AtomicExpr::AO__opencl_atomic_fetch_max:
597 case AtomicExpr::AO__atomic_fetch_max:
598 Op = E->getValueType()->isSignedIntegerType() ? llvm::AtomicRMWInst::Max
599 : llvm::AtomicRMWInst::UMax;
600 break;
601
602 case AtomicExpr::AO__atomic_and_fetch:
603 PostOp = llvm::Instruction::And;
604 LLVM_FALLTHROUGH[[gnu::fallthrough]];
605 case AtomicExpr::AO__c11_atomic_fetch_and:
606 case AtomicExpr::AO__opencl_atomic_fetch_and:
607 case AtomicExpr::AO__atomic_fetch_and:
608 Op = llvm::AtomicRMWInst::And;
609 break;
610
611 case AtomicExpr::AO__atomic_or_fetch:
612 PostOp = llvm::Instruction::Or;
613 LLVM_FALLTHROUGH[[gnu::fallthrough]];
614 case AtomicExpr::AO__c11_atomic_fetch_or:
615 case AtomicExpr::AO__opencl_atomic_fetch_or:
616 case AtomicExpr::AO__atomic_fetch_or:
617 Op = llvm::AtomicRMWInst::Or;
618 break;
619
620 case AtomicExpr::AO__atomic_xor_fetch:
621 PostOp = llvm::Instruction::Xor;
622 LLVM_FALLTHROUGH[[gnu::fallthrough]];
623 case AtomicExpr::AO__c11_atomic_fetch_xor:
624 case AtomicExpr::AO__opencl_atomic_fetch_xor:
625 case AtomicExpr::AO__atomic_fetch_xor:
626 Op = llvm::AtomicRMWInst::Xor;
627 break;
628
629 case AtomicExpr::AO__atomic_nand_fetch:
630 PostOp = llvm::Instruction::And; // the NOT is special cased below
631 LLVM_FALLTHROUGH[[gnu::fallthrough]];
632 case AtomicExpr::AO__atomic_fetch_nand:
633 Op = llvm::AtomicRMWInst::Nand;
634 break;
635 }
636
637 llvm::Value *LoadVal1 = CGF.Builder.CreateLoad(Val1);
638 llvm::AtomicRMWInst *RMWI =
639 CGF.Builder.CreateAtomicRMW(Op, Ptr.getPointer(), LoadVal1, Order, Scope);
640 RMWI->setVolatile(E->isVolatile());
641
642 // For __atomic_*_fetch operations, perform the operation again to
643 // determine the value which was written.
644 llvm::Value *Result = RMWI;
645 if (PostOp)
646 Result = CGF.Builder.CreateBinOp(PostOp, RMWI, LoadVal1);
647 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
648 Result = CGF.Builder.CreateNot(Result);
649 CGF.Builder.CreateStore(Result, Dest);
650}
651
652// This function emits any expression (scalar, complex, or aggregate)
653// into a temporary alloca.
654static Address
655EmitValToTemp(CodeGenFunction &CGF, Expr *E) {
656 Address DeclPtr = CGF.CreateMemTemp(E->getType(), ".atomictmp");
657 CGF.EmitAnyExprToMem(E, DeclPtr, E->getType().getQualifiers(),
658 /*Init*/ true);
659 return DeclPtr;
660}
661
662static void EmitAtomicOp(CodeGenFunction &CGF, AtomicExpr *Expr, Address Dest,
663 Address Ptr, Address Val1, Address Val2,
664 llvm::Value *IsWeak, llvm::Value *FailureOrder,
665 uint64_t Size, llvm::AtomicOrdering Order,
666 llvm::Value *Scope) {
667 auto ScopeModel = Expr->getScopeModel();
668
669 // LLVM atomic instructions always have synch scope. If clang atomic
670 // expression has no scope operand, use default LLVM synch scope.
671 if (!ScopeModel) {
672 EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, IsWeak, FailureOrder, Size,
673 Order, CGF.CGM.getLLVMContext().getOrInsertSyncScopeID(""));
674 return;
675 }
676
677 // Handle constant scope.
678 if (auto SC = dyn_cast<llvm::ConstantInt>(Scope)) {
679 auto SCID = CGF.getTargetHooks().getLLVMSyncScopeID(
680 CGF.CGM.getLangOpts(), ScopeModel->map(SC->getZExtValue()),
681 Order, CGF.CGM.getLLVMContext());
682 EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, IsWeak, FailureOrder, Size,
683 Order, SCID);
684 return;
685 }
686
687 // Handle non-constant scope.
688 auto &Builder = CGF.Builder;
689 auto Scopes = ScopeModel->getRuntimeValues();
690 llvm::DenseMap<unsigned, llvm::BasicBlock *> BB;
691 for (auto S : Scopes)
692 BB[S] = CGF.createBasicBlock(getAsString(ScopeModel->map(S)), CGF.CurFn);
693
694 llvm::BasicBlock *ContBB =
695 CGF.createBasicBlock("atomic.scope.continue", CGF.CurFn);
696
697 auto *SC = Builder.CreateIntCast(Scope, Builder.getInt32Ty(), false);
698 // If unsupported synch scope is encountered at run time, assume a fallback
699 // synch scope value.
700 auto FallBack = ScopeModel->getFallBackValue();
701 llvm::SwitchInst *SI = Builder.CreateSwitch(SC, BB[FallBack]);
702 for (auto S : Scopes) {
703 auto *B = BB[S];
704 if (S != FallBack)
705 SI->addCase(Builder.getInt32(S), B);
706
707 Builder.SetInsertPoint(B);
708 EmitAtomicOp(CGF, Expr, Dest, Ptr, Val1, Val2, IsWeak, FailureOrder, Size,
709 Order,
710 CGF.getTargetHooks().getLLVMSyncScopeID(CGF.CGM.getLangOpts(),
711 ScopeModel->map(S),
712 Order,
713 CGF.getLLVMContext()));
714 Builder.CreateBr(ContBB);
715 }
716
717 Builder.SetInsertPoint(ContBB);
718}
719
720static void
721AddDirectArgument(CodeGenFunction &CGF, CallArgList &Args,
722 bool UseOptimizedLibcall, llvm::Value *Val, QualType ValTy,
723 SourceLocation Loc, CharUnits SizeInChars) {
724 if (UseOptimizedLibcall) {
725 // Load value and pass it to the function directly.
726 CharUnits Align = CGF.getContext().getTypeAlignInChars(ValTy);
727 int64_t SizeInBits = CGF.getContext().toBits(SizeInChars);
728 ValTy =
729 CGF.getContext().getIntTypeForBitwidth(SizeInBits, /*Signed=*/false);
730 llvm::Type *IPtrTy = llvm::IntegerType::get(CGF.getLLVMContext(),
731 SizeInBits)->getPointerTo();
732 Address Ptr = Address(CGF.Builder.CreateBitCast(Val, IPtrTy), Align);
733 Val = CGF.EmitLoadOfScalar(Ptr, false,
734 CGF.getContext().getPointerType(ValTy),
735 Loc);
736 // Coerce the value into an appropriately sized integer type.
737 Args.add(RValue::get(Val), ValTy);
738 } else {
739 // Non-optimized functions always take a reference.
740 Args.add(RValue::get(CGF.EmitCastToVoidPtr(Val)),
741 CGF.getContext().VoidPtrTy);
742 }
743}
744
745RValue CodeGenFunction::EmitAtomicExpr(AtomicExpr *E) {
746 QualType AtomicTy = E->getPtr()->getType()->getPointeeType();
747 QualType MemTy = AtomicTy;
748 if (const AtomicType *AT = AtomicTy->getAs<AtomicType>())
749 MemTy = AT->getValueType();
750 llvm::Value *IsWeak = nullptr, *OrderFail = nullptr;
751
752 Address Val1 = Address::invalid();
753 Address Val2 = Address::invalid();
754 Address Dest = Address::invalid();
755 Address Ptr = EmitPointerWithAlignment(E->getPtr());
756
757 if (E->getOp() == AtomicExpr::AO__c11_atomic_init ||
758 E->getOp() == AtomicExpr::AO__opencl_atomic_init) {
759 LValue lvalue = MakeAddrLValue(Ptr, AtomicTy);
760 EmitAtomicInit(E->getVal1(), lvalue);
761 return RValue::get(nullptr);
762 }
763
764 CharUnits sizeChars, alignChars;
765 std::tie(sizeChars, alignChars) = getContext().getTypeInfoInChars(AtomicTy);
766 uint64_t Size = sizeChars.getQuantity();
767 unsigned MaxInlineWidthInBits = getTarget().getMaxAtomicInlineWidth();
768
769 bool Oversized = getContext().toBits(sizeChars) > MaxInlineWidthInBits;
770 bool Misaligned = (Ptr.getAlignment() % sizeChars) != 0;
771 bool UseLibcall = Misaligned | Oversized;
772
773 if (UseLibcall) {
774 CGM.getDiags().Report(E->getBeginLoc(), diag::warn_atomic_op_misaligned)
775 << !Oversized;
776 }
777
778 llvm::Value *Order = EmitScalarExpr(E->getOrder());
779 llvm::Value *Scope =
780 E->getScopeModel() ? EmitScalarExpr(E->getScope()) : nullptr;
781
782 switch (E->getOp()) {
783 case AtomicExpr::AO__c11_atomic_init:
784 case AtomicExpr::AO__opencl_atomic_init:
785 llvm_unreachable("Already handled above with EmitAtomicInit!")::llvm::llvm_unreachable_internal("Already handled above with EmitAtomicInit!"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 785)
;
786
787 case AtomicExpr::AO__c11_atomic_load:
788 case AtomicExpr::AO__opencl_atomic_load:
789 case AtomicExpr::AO__atomic_load_n:
790 break;
791
792 case AtomicExpr::AO__atomic_load:
793 Dest = EmitPointerWithAlignment(E->getVal1());
794 break;
795
796 case AtomicExpr::AO__atomic_store:
797 Val1 = EmitPointerWithAlignment(E->getVal1());
798 break;
799
800 case AtomicExpr::AO__atomic_exchange:
801 Val1 = EmitPointerWithAlignment(E->getVal1());
802 Dest = EmitPointerWithAlignment(E->getVal2());
803 break;
804
805 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
806 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
807 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
808 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
809 case AtomicExpr::AO__atomic_compare_exchange_n:
810 case AtomicExpr::AO__atomic_compare_exchange:
811 Val1 = EmitPointerWithAlignment(E->getVal1());
812 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
813 Val2 = EmitPointerWithAlignment(E->getVal2());
814 else
815 Val2 = EmitValToTemp(*this, E->getVal2());
816 OrderFail = EmitScalarExpr(E->getOrderFail());
817 if (E->getOp() == AtomicExpr::AO__atomic_compare_exchange_n ||
818 E->getOp() == AtomicExpr::AO__atomic_compare_exchange)
819 IsWeak = EmitScalarExpr(E->getWeak());
820 break;
821
822 case AtomicExpr::AO__c11_atomic_fetch_add:
823 case AtomicExpr::AO__c11_atomic_fetch_sub:
824 case AtomicExpr::AO__opencl_atomic_fetch_add:
825 case AtomicExpr::AO__opencl_atomic_fetch_sub:
826 if (MemTy->isPointerType()) {
827 // For pointer arithmetic, we're required to do a bit of math:
828 // adding 1 to an int* is not the same as adding 1 to a uintptr_t.
829 // ... but only for the C11 builtins. The GNU builtins expect the
830 // user to multiply by sizeof(T).
831 QualType Val1Ty = E->getVal1()->getType();
832 llvm::Value *Val1Scalar = EmitScalarExpr(E->getVal1());
833 CharUnits PointeeIncAmt =
834 getContext().getTypeSizeInChars(MemTy->getPointeeType());
835 Val1Scalar = Builder.CreateMul(Val1Scalar, CGM.getSize(PointeeIncAmt));
836 auto Temp = CreateMemTemp(Val1Ty, ".atomictmp");
837 Val1 = Temp;
838 EmitStoreOfScalar(Val1Scalar, MakeAddrLValue(Temp, Val1Ty));
839 break;
840 }
841 LLVM_FALLTHROUGH[[gnu::fallthrough]];
842 case AtomicExpr::AO__atomic_fetch_add:
843 case AtomicExpr::AO__atomic_fetch_sub:
844 case AtomicExpr::AO__atomic_add_fetch:
845 case AtomicExpr::AO__atomic_sub_fetch:
846 case AtomicExpr::AO__c11_atomic_store:
847 case AtomicExpr::AO__c11_atomic_exchange:
848 case AtomicExpr::AO__opencl_atomic_store:
849 case AtomicExpr::AO__opencl_atomic_exchange:
850 case AtomicExpr::AO__atomic_store_n:
851 case AtomicExpr::AO__atomic_exchange_n:
852 case AtomicExpr::AO__c11_atomic_fetch_and:
853 case AtomicExpr::AO__c11_atomic_fetch_or:
854 case AtomicExpr::AO__c11_atomic_fetch_xor:
855 case AtomicExpr::AO__opencl_atomic_fetch_and:
856 case AtomicExpr::AO__opencl_atomic_fetch_or:
857 case AtomicExpr::AO__opencl_atomic_fetch_xor:
858 case AtomicExpr::AO__opencl_atomic_fetch_min:
859 case AtomicExpr::AO__opencl_atomic_fetch_max:
860 case AtomicExpr::AO__atomic_fetch_and:
861 case AtomicExpr::AO__atomic_fetch_or:
862 case AtomicExpr::AO__atomic_fetch_xor:
863 case AtomicExpr::AO__atomic_fetch_nand:
864 case AtomicExpr::AO__atomic_and_fetch:
865 case AtomicExpr::AO__atomic_or_fetch:
866 case AtomicExpr::AO__atomic_xor_fetch:
867 case AtomicExpr::AO__atomic_nand_fetch:
868 case AtomicExpr::AO__atomic_fetch_min:
869 case AtomicExpr::AO__atomic_fetch_max:
870 Val1 = EmitValToTemp(*this, E->getVal1());
871 break;
872 }
873
874 QualType RValTy = E->getType().getUnqualifiedType();
875
876 // The inlined atomics only function on iN types, where N is a power of 2. We
877 // need to make sure (via temporaries if necessary) that all incoming values
878 // are compatible.
879 LValue AtomicVal = MakeAddrLValue(Ptr, AtomicTy);
880 AtomicInfo Atomics(*this, AtomicVal);
881
882 Ptr = Atomics.emitCastToAtomicIntPointer(Ptr);
883 if (Val1.isValid()) Val1 = Atomics.convertToAtomicIntPointer(Val1);
884 if (Val2.isValid()) Val2 = Atomics.convertToAtomicIntPointer(Val2);
885 if (Dest.isValid())
886 Dest = Atomics.emitCastToAtomicIntPointer(Dest);
887 else if (E->isCmpXChg())
888 Dest = CreateMemTemp(RValTy, "cmpxchg.bool");
889 else if (!RValTy->isVoidType())
890 Dest = Atomics.emitCastToAtomicIntPointer(Atomics.CreateTempAlloca());
891
892 // Use a library call. See: http://gcc.gnu.org/wiki/Atomic/GCCMM/LIbrary .
893 if (UseLibcall) {
894 bool UseOptimizedLibcall = false;
895 switch (E->getOp()) {
896 case AtomicExpr::AO__c11_atomic_init:
897 case AtomicExpr::AO__opencl_atomic_init:
898 llvm_unreachable("Already handled above with EmitAtomicInit!")::llvm::llvm_unreachable_internal("Already handled above with EmitAtomicInit!"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 898)
;
899
900 case AtomicExpr::AO__c11_atomic_fetch_add:
901 case AtomicExpr::AO__opencl_atomic_fetch_add:
902 case AtomicExpr::AO__atomic_fetch_add:
903 case AtomicExpr::AO__c11_atomic_fetch_and:
904 case AtomicExpr::AO__opencl_atomic_fetch_and:
905 case AtomicExpr::AO__atomic_fetch_and:
906 case AtomicExpr::AO__c11_atomic_fetch_or:
907 case AtomicExpr::AO__opencl_atomic_fetch_or:
908 case AtomicExpr::AO__atomic_fetch_or:
909 case AtomicExpr::AO__atomic_fetch_nand:
910 case AtomicExpr::AO__c11_atomic_fetch_sub:
911 case AtomicExpr::AO__opencl_atomic_fetch_sub:
912 case AtomicExpr::AO__atomic_fetch_sub:
913 case AtomicExpr::AO__c11_atomic_fetch_xor:
914 case AtomicExpr::AO__opencl_atomic_fetch_xor:
915 case AtomicExpr::AO__opencl_atomic_fetch_min:
916 case AtomicExpr::AO__opencl_atomic_fetch_max:
917 case AtomicExpr::AO__atomic_fetch_xor:
918 case AtomicExpr::AO__atomic_add_fetch:
919 case AtomicExpr::AO__atomic_and_fetch:
920 case AtomicExpr::AO__atomic_nand_fetch:
921 case AtomicExpr::AO__atomic_or_fetch:
922 case AtomicExpr::AO__atomic_sub_fetch:
923 case AtomicExpr::AO__atomic_xor_fetch:
924 case AtomicExpr::AO__atomic_fetch_min:
925 case AtomicExpr::AO__atomic_fetch_max:
926 // For these, only library calls for certain sizes exist.
927 UseOptimizedLibcall = true;
928 break;
929
930 case AtomicExpr::AO__atomic_load:
931 case AtomicExpr::AO__atomic_store:
932 case AtomicExpr::AO__atomic_exchange:
933 case AtomicExpr::AO__atomic_compare_exchange:
934 // Use the generic version if we don't know that the operand will be
935 // suitably aligned for the optimized version.
936 if (Misaligned)
937 break;
938 LLVM_FALLTHROUGH[[gnu::fallthrough]];
939 case AtomicExpr::AO__c11_atomic_load:
940 case AtomicExpr::AO__c11_atomic_store:
941 case AtomicExpr::AO__c11_atomic_exchange:
942 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
943 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
944 case AtomicExpr::AO__opencl_atomic_load:
945 case AtomicExpr::AO__opencl_atomic_store:
946 case AtomicExpr::AO__opencl_atomic_exchange:
947 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
948 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
949 case AtomicExpr::AO__atomic_load_n:
950 case AtomicExpr::AO__atomic_store_n:
951 case AtomicExpr::AO__atomic_exchange_n:
952 case AtomicExpr::AO__atomic_compare_exchange_n:
953 // Only use optimized library calls for sizes for which they exist.
954 // FIXME: Size == 16 optimized library functions exist too.
955 if (Size == 1 || Size == 2 || Size == 4 || Size == 8)
956 UseOptimizedLibcall = true;
957 break;
958 }
959
960 CallArgList Args;
961 if (!UseOptimizedLibcall) {
962 // For non-optimized library calls, the size is the first parameter
963 Args.add(RValue::get(llvm::ConstantInt::get(SizeTy, Size)),
964 getContext().getSizeType());
965 }
966 // Atomic address is the first or second parameter
967 // The OpenCL atomic library functions only accept pointer arguments to
968 // generic address space.
969 auto CastToGenericAddrSpace = [&](llvm::Value *V, QualType PT) {
970 if (!E->isOpenCL())
1
Calling 'AtomicExpr::isOpenCL'
5
Returning from 'AtomicExpr::isOpenCL'
6
Taking false branch
971 return V;
972 auto AS = PT->getAs<PointerType>()->getPointeeType().getAddressSpace();
7
Assuming the object is not a 'PointerType'
8
Called C++ object pointer is null
973 if (AS == LangAS::opencl_generic)
974 return V;
975 auto DestAS = getContext().getTargetAddressSpace(LangAS::opencl_generic);
976 auto T = V->getType();
977 auto *DestType = T->getPointerElementType()->getPointerTo(DestAS);
978
979 return getTargetHooks().performAddrSpaceCast(
980 *this, V, AS, LangAS::opencl_generic, DestType, false);
981 };
982
983 Args.add(RValue::get(CastToGenericAddrSpace(
984 EmitCastToVoidPtr(Ptr.getPointer()), E->getPtr()->getType())),
985 getContext().VoidPtrTy);
986
987 std::string LibCallName;
988 QualType LoweredMemTy =
989 MemTy->isPointerType() ? getContext().getIntPtrType() : MemTy;
990 QualType RetTy;
991 bool HaveRetTy = false;
992 llvm::Instruction::BinaryOps PostOp = (llvm::Instruction::BinaryOps)0;
993 switch (E->getOp()) {
994 case AtomicExpr::AO__c11_atomic_init:
995 case AtomicExpr::AO__opencl_atomic_init:
996 llvm_unreachable("Already handled!")::llvm::llvm_unreachable_internal("Already handled!", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 996)
;
997
998 // There is only one libcall for compare an exchange, because there is no
999 // optimisation benefit possible from a libcall version of a weak compare
1000 // and exchange.
1001 // bool __atomic_compare_exchange(size_t size, void *mem, void *expected,
1002 // void *desired, int success, int failure)
1003 // bool __atomic_compare_exchange_N(T *mem, T *expected, T desired,
1004 // int success, int failure)
1005 case AtomicExpr::AO__c11_atomic_compare_exchange_weak:
1006 case AtomicExpr::AO__c11_atomic_compare_exchange_strong:
1007 case AtomicExpr::AO__opencl_atomic_compare_exchange_weak:
1008 case AtomicExpr::AO__opencl_atomic_compare_exchange_strong:
1009 case AtomicExpr::AO__atomic_compare_exchange:
1010 case AtomicExpr::AO__atomic_compare_exchange_n:
1011 LibCallName = "__atomic_compare_exchange";
1012 RetTy = getContext().BoolTy;
1013 HaveRetTy = true;
1014 Args.add(
1015 RValue::get(CastToGenericAddrSpace(
1016 EmitCastToVoidPtr(Val1.getPointer()), E->getVal1()->getType())),
1017 getContext().VoidPtrTy);
1018 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val2.getPointer(),
1019 MemTy, E->getExprLoc(), sizeChars);
1020 Args.add(RValue::get(Order), getContext().IntTy);
1021 Order = OrderFail;
1022 break;
1023 // void __atomic_exchange(size_t size, void *mem, void *val, void *return,
1024 // int order)
1025 // T __atomic_exchange_N(T *mem, T val, int order)
1026 case AtomicExpr::AO__c11_atomic_exchange:
1027 case AtomicExpr::AO__opencl_atomic_exchange:
1028 case AtomicExpr::AO__atomic_exchange_n:
1029 case AtomicExpr::AO__atomic_exchange:
1030 LibCallName = "__atomic_exchange";
1031 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1032 MemTy, E->getExprLoc(), sizeChars);
1033 break;
1034 // void __atomic_store(size_t size, void *mem, void *val, int order)
1035 // void __atomic_store_N(T *mem, T val, int order)
1036 case AtomicExpr::AO__c11_atomic_store:
1037 case AtomicExpr::AO__opencl_atomic_store:
1038 case AtomicExpr::AO__atomic_store:
1039 case AtomicExpr::AO__atomic_store_n:
1040 LibCallName = "__atomic_store";
1041 RetTy = getContext().VoidTy;
1042 HaveRetTy = true;
1043 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1044 MemTy, E->getExprLoc(), sizeChars);
1045 break;
1046 // void __atomic_load(size_t size, void *mem, void *return, int order)
1047 // T __atomic_load_N(T *mem, int order)
1048 case AtomicExpr::AO__c11_atomic_load:
1049 case AtomicExpr::AO__opencl_atomic_load:
1050 case AtomicExpr::AO__atomic_load:
1051 case AtomicExpr::AO__atomic_load_n:
1052 LibCallName = "__atomic_load";
1053 break;
1054 // T __atomic_add_fetch_N(T *mem, T val, int order)
1055 // T __atomic_fetch_add_N(T *mem, T val, int order)
1056 case AtomicExpr::AO__atomic_add_fetch:
1057 PostOp = llvm::Instruction::Add;
1058 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1059 case AtomicExpr::AO__c11_atomic_fetch_add:
1060 case AtomicExpr::AO__opencl_atomic_fetch_add:
1061 case AtomicExpr::AO__atomic_fetch_add:
1062 LibCallName = "__atomic_fetch_add";
1063 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1064 LoweredMemTy, E->getExprLoc(), sizeChars);
1065 break;
1066 // T __atomic_and_fetch_N(T *mem, T val, int order)
1067 // T __atomic_fetch_and_N(T *mem, T val, int order)
1068 case AtomicExpr::AO__atomic_and_fetch:
1069 PostOp = llvm::Instruction::And;
1070 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1071 case AtomicExpr::AO__c11_atomic_fetch_and:
1072 case AtomicExpr::AO__opencl_atomic_fetch_and:
1073 case AtomicExpr::AO__atomic_fetch_and:
1074 LibCallName = "__atomic_fetch_and";
1075 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1076 MemTy, E->getExprLoc(), sizeChars);
1077 break;
1078 // T __atomic_or_fetch_N(T *mem, T val, int order)
1079 // T __atomic_fetch_or_N(T *mem, T val, int order)
1080 case AtomicExpr::AO__atomic_or_fetch:
1081 PostOp = llvm::Instruction::Or;
1082 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1083 case AtomicExpr::AO__c11_atomic_fetch_or:
1084 case AtomicExpr::AO__opencl_atomic_fetch_or:
1085 case AtomicExpr::AO__atomic_fetch_or:
1086 LibCallName = "__atomic_fetch_or";
1087 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1088 MemTy, E->getExprLoc(), sizeChars);
1089 break;
1090 // T __atomic_sub_fetch_N(T *mem, T val, int order)
1091 // T __atomic_fetch_sub_N(T *mem, T val, int order)
1092 case AtomicExpr::AO__atomic_sub_fetch:
1093 PostOp = llvm::Instruction::Sub;
1094 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1095 case AtomicExpr::AO__c11_atomic_fetch_sub:
1096 case AtomicExpr::AO__opencl_atomic_fetch_sub:
1097 case AtomicExpr::AO__atomic_fetch_sub:
1098 LibCallName = "__atomic_fetch_sub";
1099 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1100 LoweredMemTy, E->getExprLoc(), sizeChars);
1101 break;
1102 // T __atomic_xor_fetch_N(T *mem, T val, int order)
1103 // T __atomic_fetch_xor_N(T *mem, T val, int order)
1104 case AtomicExpr::AO__atomic_xor_fetch:
1105 PostOp = llvm::Instruction::Xor;
1106 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1107 case AtomicExpr::AO__c11_atomic_fetch_xor:
1108 case AtomicExpr::AO__opencl_atomic_fetch_xor:
1109 case AtomicExpr::AO__atomic_fetch_xor:
1110 LibCallName = "__atomic_fetch_xor";
1111 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1112 MemTy, E->getExprLoc(), sizeChars);
1113 break;
1114 case AtomicExpr::AO__atomic_fetch_min:
1115 case AtomicExpr::AO__opencl_atomic_fetch_min:
1116 LibCallName = E->getValueType()->isSignedIntegerType()
1117 ? "__atomic_fetch_min"
1118 : "__atomic_fetch_umin";
1119 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1120 LoweredMemTy, E->getExprLoc(), sizeChars);
1121 break;
1122 case AtomicExpr::AO__atomic_fetch_max:
1123 case AtomicExpr::AO__opencl_atomic_fetch_max:
1124 LibCallName = E->getValueType()->isSignedIntegerType()
1125 ? "__atomic_fetch_max"
1126 : "__atomic_fetch_umax";
1127 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1128 LoweredMemTy, E->getExprLoc(), sizeChars);
1129 break;
1130 // T __atomic_nand_fetch_N(T *mem, T val, int order)
1131 // T __atomic_fetch_nand_N(T *mem, T val, int order)
1132 case AtomicExpr::AO__atomic_nand_fetch:
1133 PostOp = llvm::Instruction::And; // the NOT is special cased below
1134 LLVM_FALLTHROUGH[[gnu::fallthrough]];
1135 case AtomicExpr::AO__atomic_fetch_nand:
1136 LibCallName = "__atomic_fetch_nand";
1137 AddDirectArgument(*this, Args, UseOptimizedLibcall, Val1.getPointer(),
1138 MemTy, E->getExprLoc(), sizeChars);
1139 break;
1140 }
1141
1142 if (E->isOpenCL()) {
1143 LibCallName = std::string("__opencl") +
1144 StringRef(LibCallName).drop_front(1).str();
1145
1146 }
1147 // Optimized functions have the size in their name.
1148 if (UseOptimizedLibcall)
1149 LibCallName += "_" + llvm::utostr(Size);
1150 // By default, assume we return a value of the atomic type.
1151 if (!HaveRetTy) {
1152 if (UseOptimizedLibcall) {
1153 // Value is returned directly.
1154 // The function returns an appropriately sized integer type.
1155 RetTy = getContext().getIntTypeForBitwidth(
1156 getContext().toBits(sizeChars), /*Signed=*/false);
1157 } else {
1158 // Value is returned through parameter before the order.
1159 RetTy = getContext().VoidTy;
1160 Args.add(RValue::get(EmitCastToVoidPtr(Dest.getPointer())),
1161 getContext().VoidPtrTy);
1162 }
1163 }
1164 // order is always the last parameter
1165 Args.add(RValue::get(Order),
1166 getContext().IntTy);
1167 if (E->isOpenCL())
1168 Args.add(RValue::get(Scope), getContext().IntTy);
1169
1170 // PostOp is only needed for the atomic_*_fetch operations, and
1171 // thus is only needed for and implemented in the
1172 // UseOptimizedLibcall codepath.
1173 assert(UseOptimizedLibcall || !PostOp)((UseOptimizedLibcall || !PostOp) ? static_cast<void> (
0) : __assert_fail ("UseOptimizedLibcall || !PostOp", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 1173, __PRETTY_FUNCTION__))
;
1174
1175 RValue Res = emitAtomicLibcall(*this, LibCallName, RetTy, Args);
1176 // The value is returned directly from the libcall.
1177 if (E->isCmpXChg())
1178 return Res;
1179
1180 // The value is returned directly for optimized libcalls but the expr
1181 // provided an out-param.
1182 if (UseOptimizedLibcall && Res.getScalarVal()) {
1183 llvm::Value *ResVal = Res.getScalarVal();
1184 if (PostOp) {
1185 llvm::Value *LoadVal1 = Args[1].getRValue(*this).getScalarVal();
1186 ResVal = Builder.CreateBinOp(PostOp, ResVal, LoadVal1);
1187 }
1188 if (E->getOp() == AtomicExpr::AO__atomic_nand_fetch)
1189 ResVal = Builder.CreateNot(ResVal);
1190
1191 Builder.CreateStore(
1192 ResVal,
1193 Builder.CreateBitCast(Dest, ResVal->getType()->getPointerTo()));
1194 }
1195
1196 if (RValTy->isVoidType())
1197 return RValue::get(nullptr);
1198
1199 return convertTempToRValue(
1200 Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo()),
1201 RValTy, E->getExprLoc());
1202 }
1203
1204 bool IsStore = E->getOp() == AtomicExpr::AO__c11_atomic_store ||
1205 E->getOp() == AtomicExpr::AO__opencl_atomic_store ||
1206 E->getOp() == AtomicExpr::AO__atomic_store ||
1207 E->getOp() == AtomicExpr::AO__atomic_store_n;
1208 bool IsLoad = E->getOp() == AtomicExpr::AO__c11_atomic_load ||
1209 E->getOp() == AtomicExpr::AO__opencl_atomic_load ||
1210 E->getOp() == AtomicExpr::AO__atomic_load ||
1211 E->getOp() == AtomicExpr::AO__atomic_load_n;
1212
1213 if (isa<llvm::ConstantInt>(Order)) {
1214 auto ord = cast<llvm::ConstantInt>(Order)->getZExtValue();
1215 // We should not ever get to a case where the ordering isn't a valid C ABI
1216 // value, but it's hard to enforce that in general.
1217 if (llvm::isValidAtomicOrderingCABI(ord))
1218 switch ((llvm::AtomicOrderingCABI)ord) {
1219 case llvm::AtomicOrderingCABI::relaxed:
1220 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1221 llvm::AtomicOrdering::Monotonic, Scope);
1222 break;
1223 case llvm::AtomicOrderingCABI::consume:
1224 case llvm::AtomicOrderingCABI::acquire:
1225 if (IsStore)
1226 break; // Avoid crashing on code with undefined behavior
1227 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1228 llvm::AtomicOrdering::Acquire, Scope);
1229 break;
1230 case llvm::AtomicOrderingCABI::release:
1231 if (IsLoad)
1232 break; // Avoid crashing on code with undefined behavior
1233 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1234 llvm::AtomicOrdering::Release, Scope);
1235 break;
1236 case llvm::AtomicOrderingCABI::acq_rel:
1237 if (IsLoad || IsStore)
1238 break; // Avoid crashing on code with undefined behavior
1239 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1240 llvm::AtomicOrdering::AcquireRelease, Scope);
1241 break;
1242 case llvm::AtomicOrderingCABI::seq_cst:
1243 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1244 llvm::AtomicOrdering::SequentiallyConsistent, Scope);
1245 break;
1246 }
1247 if (RValTy->isVoidType())
1248 return RValue::get(nullptr);
1249
1250 return convertTempToRValue(
1251 Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo(
1252 Dest.getAddressSpace())),
1253 RValTy, E->getExprLoc());
1254 }
1255
1256 // Long case, when Order isn't obviously constant.
1257
1258 // Create all the relevant BB's
1259 llvm::BasicBlock *MonotonicBB = nullptr, *AcquireBB = nullptr,
1260 *ReleaseBB = nullptr, *AcqRelBB = nullptr,
1261 *SeqCstBB = nullptr;
1262 MonotonicBB = createBasicBlock("monotonic", CurFn);
1263 if (!IsStore)
1264 AcquireBB = createBasicBlock("acquire", CurFn);
1265 if (!IsLoad)
1266 ReleaseBB = createBasicBlock("release", CurFn);
1267 if (!IsLoad && !IsStore)
1268 AcqRelBB = createBasicBlock("acqrel", CurFn);
1269 SeqCstBB = createBasicBlock("seqcst", CurFn);
1270 llvm::BasicBlock *ContBB = createBasicBlock("atomic.continue", CurFn);
1271
1272 // Create the switch for the split
1273 // MonotonicBB is arbitrarily chosen as the default case; in practice, this
1274 // doesn't matter unless someone is crazy enough to use something that
1275 // doesn't fold to a constant for the ordering.
1276 Order = Builder.CreateIntCast(Order, Builder.getInt32Ty(), false);
1277 llvm::SwitchInst *SI = Builder.CreateSwitch(Order, MonotonicBB);
1278
1279 // Emit all the different atomics
1280 Builder.SetInsertPoint(MonotonicBB);
1281 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1282 llvm::AtomicOrdering::Monotonic, Scope);
1283 Builder.CreateBr(ContBB);
1284 if (!IsStore) {
1285 Builder.SetInsertPoint(AcquireBB);
1286 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1287 llvm::AtomicOrdering::Acquire, Scope);
1288 Builder.CreateBr(ContBB);
1289 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::consume),
1290 AcquireBB);
1291 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::acquire),
1292 AcquireBB);
1293 }
1294 if (!IsLoad) {
1295 Builder.SetInsertPoint(ReleaseBB);
1296 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1297 llvm::AtomicOrdering::Release, Scope);
1298 Builder.CreateBr(ContBB);
1299 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::release),
1300 ReleaseBB);
1301 }
1302 if (!IsLoad && !IsStore) {
1303 Builder.SetInsertPoint(AcqRelBB);
1304 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1305 llvm::AtomicOrdering::AcquireRelease, Scope);
1306 Builder.CreateBr(ContBB);
1307 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::acq_rel),
1308 AcqRelBB);
1309 }
1310 Builder.SetInsertPoint(SeqCstBB);
1311 EmitAtomicOp(*this, E, Dest, Ptr, Val1, Val2, IsWeak, OrderFail, Size,
1312 llvm::AtomicOrdering::SequentiallyConsistent, Scope);
1313 Builder.CreateBr(ContBB);
1314 SI->addCase(Builder.getInt32((int)llvm::AtomicOrderingCABI::seq_cst),
1315 SeqCstBB);
1316
1317 // Cleanup and return
1318 Builder.SetInsertPoint(ContBB);
1319 if (RValTy->isVoidType())
1320 return RValue::get(nullptr);
1321
1322 assert(Atomics.getValueSizeInBits() <= Atomics.getAtomicSizeInBits())((Atomics.getValueSizeInBits() <= Atomics.getAtomicSizeInBits
()) ? static_cast<void> (0) : __assert_fail ("Atomics.getValueSizeInBits() <= Atomics.getAtomicSizeInBits()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 1322, __PRETTY_FUNCTION__))
;
1323 return convertTempToRValue(
1324 Builder.CreateBitCast(Dest, ConvertTypeForMem(RValTy)->getPointerTo(
1325 Dest.getAddressSpace())),
1326 RValTy, E->getExprLoc());
1327}
1328
1329Address AtomicInfo::emitCastToAtomicIntPointer(Address addr) const {
1330 unsigned addrspace =
1331 cast<llvm::PointerType>(addr.getPointer()->getType())->getAddressSpace();
1332 llvm::IntegerType *ty =
1333 llvm::IntegerType::get(CGF.getLLVMContext(), AtomicSizeInBits);
1334 return CGF.Builder.CreateBitCast(addr, ty->getPointerTo(addrspace));
1335}
1336
1337Address AtomicInfo::convertToAtomicIntPointer(Address Addr) const {
1338 llvm::Type *Ty = Addr.getElementType();
1339 uint64_t SourceSizeInBits = CGF.CGM.getDataLayout().getTypeSizeInBits(Ty);
1340 if (SourceSizeInBits != AtomicSizeInBits) {
1341 Address Tmp = CreateTempAlloca();
1342 CGF.Builder.CreateMemCpy(Tmp, Addr,
1343 std::min(AtomicSizeInBits, SourceSizeInBits) / 8);
1344 Addr = Tmp;
1345 }
1346
1347 return emitCastToAtomicIntPointer(Addr);
1348}
1349
1350RValue AtomicInfo::convertAtomicTempToRValue(Address addr,
1351 AggValueSlot resultSlot,
1352 SourceLocation loc,
1353 bool asValue) const {
1354 if (LVal.isSimple()) {
1355 if (EvaluationKind == TEK_Aggregate)
1356 return resultSlot.asRValue();
1357
1358 // Drill into the padding structure if we have one.
1359 if (hasPadding())
1360 addr = CGF.Builder.CreateStructGEP(addr, 0);
1361
1362 // Otherwise, just convert the temporary to an r-value using the
1363 // normal conversion routine.
1364 return CGF.convertTempToRValue(addr, getValueType(), loc);
1365 }
1366 if (!asValue)
1367 // Get RValue from temp memory as atomic for non-simple lvalues
1368 return RValue::get(CGF.Builder.CreateLoad(addr));
1369 if (LVal.isBitField())
1370 return CGF.EmitLoadOfBitfieldLValue(
1371 LValue::MakeBitfield(addr, LVal.getBitFieldInfo(), LVal.getType(),
1372 LVal.getBaseInfo(), TBAAAccessInfo()), loc);
1373 if (LVal.isVectorElt())
1374 return CGF.EmitLoadOfLValue(
1375 LValue::MakeVectorElt(addr, LVal.getVectorIdx(), LVal.getType(),
1376 LVal.getBaseInfo(), TBAAAccessInfo()), loc);
1377 assert(LVal.isExtVectorElt())((LVal.isExtVectorElt()) ? static_cast<void> (0) : __assert_fail
("LVal.isExtVectorElt()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 1377, __PRETTY_FUNCTION__))
;
1378 return CGF.EmitLoadOfExtVectorElementLValue(LValue::MakeExtVectorElt(
1379 addr, LVal.getExtVectorElts(), LVal.getType(),
1380 LVal.getBaseInfo(), TBAAAccessInfo()));
1381}
1382
1383RValue AtomicInfo::ConvertIntToValueOrAtomic(llvm::Value *IntVal,
1384 AggValueSlot ResultSlot,
1385 SourceLocation Loc,
1386 bool AsValue) const {
1387 // Try not to in some easy cases.
1388 assert(IntVal->getType()->isIntegerTy() && "Expected integer value")((IntVal->getType()->isIntegerTy() && "Expected integer value"
) ? static_cast<void> (0) : __assert_fail ("IntVal->getType()->isIntegerTy() && \"Expected integer value\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 1388, __PRETTY_FUNCTION__))
;
1389 if (getEvaluationKind() == TEK_Scalar &&
1390 (((!LVal.isBitField() ||
1391 LVal.getBitFieldInfo().Size == ValueSizeInBits) &&
1392 !hasPadding()) ||
1393 !AsValue)) {
1394 auto *ValTy = AsValue
1395 ? CGF.ConvertTypeForMem(ValueTy)
1396 : getAtomicAddress().getType()->getPointerElementType();
1397 if (ValTy->isIntegerTy()) {
1398 assert(IntVal->getType() == ValTy && "Different integer types.")((IntVal->getType() == ValTy && "Different integer types."
) ? static_cast<void> (0) : __assert_fail ("IntVal->getType() == ValTy && \"Different integer types.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 1398, __PRETTY_FUNCTION__))
;
1399 return RValue::get(CGF.EmitFromMemory(IntVal, ValueTy));
1400 } else if (ValTy->isPointerTy())
1401 return RValue::get(CGF.Builder.CreateIntToPtr(IntVal, ValTy));
1402 else if (llvm::CastInst::isBitCastable(IntVal->getType(), ValTy))
1403 return RValue::get(CGF.Builder.CreateBitCast(IntVal, ValTy));
1404 }
1405
1406 // Create a temporary. This needs to be big enough to hold the
1407 // atomic integer.
1408 Address Temp = Address::invalid();
1409 bool TempIsVolatile = false;
1410 if (AsValue && getEvaluationKind() == TEK_Aggregate) {
1411 assert(!ResultSlot.isIgnored())((!ResultSlot.isIgnored()) ? static_cast<void> (0) : __assert_fail
("!ResultSlot.isIgnored()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 1411, __PRETTY_FUNCTION__))
;
1412 Temp = ResultSlot.getAddress();
1413 TempIsVolatile = ResultSlot.isVolatile();
1414 } else {
1415 Temp = CreateTempAlloca();
1416 }
1417
1418 // Slam the integer into the temporary.
1419 Address CastTemp = emitCastToAtomicIntPointer(Temp);
1420 CGF.Builder.CreateStore(IntVal, CastTemp)
1421 ->setVolatile(TempIsVolatile);
1422
1423 return convertAtomicTempToRValue(Temp, ResultSlot, Loc, AsValue);
1424}
1425
1426void AtomicInfo::EmitAtomicLoadLibcall(llvm::Value *AddForLoaded,
1427 llvm::AtomicOrdering AO, bool) {
1428 // void __atomic_load(size_t size, void *mem, void *return, int order);
1429 CallArgList Args;
1430 Args.add(RValue::get(getAtomicSizeValue()), CGF.getContext().getSizeType());
1431 Args.add(RValue::get(CGF.EmitCastToVoidPtr(getAtomicPointer())),
1432 CGF.getContext().VoidPtrTy);
1433 Args.add(RValue::get(CGF.EmitCastToVoidPtr(AddForLoaded)),
1434 CGF.getContext().VoidPtrTy);
1435 Args.add(
1436 RValue::get(llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(AO))),
1437 CGF.getContext().IntTy);
1438 emitAtomicLibcall(CGF, "__atomic_load", CGF.getContext().VoidTy, Args);
1439}
1440
1441llvm::Value *AtomicInfo::EmitAtomicLoadOp(llvm::AtomicOrdering AO,
1442 bool IsVolatile) {
1443 // Okay, we're doing this natively.
1444 Address Addr = getAtomicAddressAsAtomicIntPointer();
1445 llvm::LoadInst *Load = CGF.Builder.CreateLoad(Addr, "atomic-load");
1446 Load->setAtomic(AO);
1447
1448 // Other decoration.
1449 if (IsVolatile)
1450 Load->setVolatile(true);
1451 CGF.CGM.DecorateInstructionWithTBAA(Load, LVal.getTBAAInfo());
1452 return Load;
1453}
1454
1455/// An LValue is a candidate for having its loads and stores be made atomic if
1456/// we are operating under /volatile:ms *and* the LValue itself is volatile and
1457/// performing such an operation can be performed without a libcall.
1458bool CodeGenFunction::LValueIsSuitableForInlineAtomic(LValue LV) {
1459 if (!CGM.getCodeGenOpts().MSVolatile) return false;
1460 AtomicInfo AI(*this, LV);
1461 bool IsVolatile = LV.isVolatile() || hasVolatileMember(LV.getType());
1462 // An atomic is inline if we don't need to use a libcall.
1463 bool AtomicIsInline = !AI.shouldUseLibcall();
1464 // MSVC doesn't seem to do this for types wider than a pointer.
1465 if (getContext().getTypeSize(LV.getType()) >
1466 getContext().getTypeSize(getContext().getIntPtrType()))
1467 return false;
1468 return IsVolatile && AtomicIsInline;
1469}
1470
1471RValue CodeGenFunction::EmitAtomicLoad(LValue LV, SourceLocation SL,
1472 AggValueSlot Slot) {
1473 llvm::AtomicOrdering AO;
1474 bool IsVolatile = LV.isVolatileQualified();
1475 if (LV.getType()->isAtomicType()) {
1476 AO = llvm::AtomicOrdering::SequentiallyConsistent;
1477 } else {
1478 AO = llvm::AtomicOrdering::Acquire;
1479 IsVolatile = true;
1480 }
1481 return EmitAtomicLoad(LV, SL, AO, IsVolatile, Slot);
1482}
1483
1484RValue AtomicInfo::EmitAtomicLoad(AggValueSlot ResultSlot, SourceLocation Loc,
1485 bool AsValue, llvm::AtomicOrdering AO,
1486 bool IsVolatile) {
1487 // Check whether we should use a library call.
1488 if (shouldUseLibcall()) {
1489 Address TempAddr = Address::invalid();
1490 if (LVal.isSimple() && !ResultSlot.isIgnored()) {
1491 assert(getEvaluationKind() == TEK_Aggregate)((getEvaluationKind() == TEK_Aggregate) ? static_cast<void
> (0) : __assert_fail ("getEvaluationKind() == TEK_Aggregate"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 1491, __PRETTY_FUNCTION__))
;
1492 TempAddr = ResultSlot.getAddress();
1493 } else
1494 TempAddr = CreateTempAlloca();
1495
1496 EmitAtomicLoadLibcall(TempAddr.getPointer(), AO, IsVolatile);
1497
1498 // Okay, turn that back into the original value or whole atomic (for
1499 // non-simple lvalues) type.
1500 return convertAtomicTempToRValue(TempAddr, ResultSlot, Loc, AsValue);
1501 }
1502
1503 // Okay, we're doing this natively.
1504 auto *Load = EmitAtomicLoadOp(AO, IsVolatile);
1505
1506 // If we're ignoring an aggregate return, don't do anything.
1507 if (getEvaluationKind() == TEK_Aggregate && ResultSlot.isIgnored())
1508 return RValue::getAggregate(Address::invalid(), false);
1509
1510 // Okay, turn that back into the original value or atomic (for non-simple
1511 // lvalues) type.
1512 return ConvertIntToValueOrAtomic(Load, ResultSlot, Loc, AsValue);
1513}
1514
1515/// Emit a load from an l-value of atomic type. Note that the r-value
1516/// we produce is an r-value of the atomic *value* type.
1517RValue CodeGenFunction::EmitAtomicLoad(LValue src, SourceLocation loc,
1518 llvm::AtomicOrdering AO, bool IsVolatile,
1519 AggValueSlot resultSlot) {
1520 AtomicInfo Atomics(*this, src);
1521 return Atomics.EmitAtomicLoad(resultSlot, loc, /*AsValue=*/true, AO,
1522 IsVolatile);
1523}
1524
1525/// Copy an r-value into memory as part of storing to an atomic type.
1526/// This needs to create a bit-pattern suitable for atomic operations.
1527void AtomicInfo::emitCopyIntoMemory(RValue rvalue) const {
1528 assert(LVal.isSimple())((LVal.isSimple()) ? static_cast<void> (0) : __assert_fail
("LVal.isSimple()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 1528, __PRETTY_FUNCTION__))
;
1529 // If we have an r-value, the rvalue should be of the atomic type,
1530 // which means that the caller is responsible for having zeroed
1531 // any padding. Just do an aggregate copy of that type.
1532 if (rvalue.isAggregate()) {
1533 LValue Dest = CGF.MakeAddrLValue(getAtomicAddress(), getAtomicType());
1534 LValue Src = CGF.MakeAddrLValue(rvalue.getAggregateAddress(),
1535 getAtomicType());
1536 bool IsVolatile = rvalue.isVolatileQualified() ||
1537 LVal.isVolatileQualified();
1538 CGF.EmitAggregateCopy(Dest, Src, getAtomicType(),
1539 AggValueSlot::DoesNotOverlap, IsVolatile);
1540 return;
1541 }
1542
1543 // Okay, otherwise we're copying stuff.
1544
1545 // Zero out the buffer if necessary.
1546 emitMemSetZeroIfNecessary();
1547
1548 // Drill past the padding if present.
1549 LValue TempLVal = projectValue();
1550
1551 // Okay, store the rvalue in.
1552 if (rvalue.isScalar()) {
1553 CGF.EmitStoreOfScalar(rvalue.getScalarVal(), TempLVal, /*init*/ true);
1554 } else {
1555 CGF.EmitStoreOfComplex(rvalue.getComplexVal(), TempLVal, /*init*/ true);
1556 }
1557}
1558
1559
1560/// Materialize an r-value into memory for the purposes of storing it
1561/// to an atomic type.
1562Address AtomicInfo::materializeRValue(RValue rvalue) const {
1563 // Aggregate r-values are already in memory, and EmitAtomicStore
1564 // requires them to be values of the atomic type.
1565 if (rvalue.isAggregate())
1566 return rvalue.getAggregateAddress();
1567
1568 // Otherwise, make a temporary and materialize into it.
1569 LValue TempLV = CGF.MakeAddrLValue(CreateTempAlloca(), getAtomicType());
1570 AtomicInfo Atomics(CGF, TempLV);
1571 Atomics.emitCopyIntoMemory(rvalue);
1572 return TempLV.getAddress();
1573}
1574
1575llvm::Value *AtomicInfo::convertRValueToInt(RValue RVal) const {
1576 // If we've got a scalar value of the right size, try to avoid going
1577 // through memory.
1578 if (RVal.isScalar() && (!hasPadding() || !LVal.isSimple())) {
1579 llvm::Value *Value = RVal.getScalarVal();
1580 if (isa<llvm::IntegerType>(Value->getType()))
1581 return CGF.EmitToMemory(Value, ValueTy);
1582 else {
1583 llvm::IntegerType *InputIntTy = llvm::IntegerType::get(
1584 CGF.getLLVMContext(),
1585 LVal.isSimple() ? getValueSizeInBits() : getAtomicSizeInBits());
1586 if (isa<llvm::PointerType>(Value->getType()))
1587 return CGF.Builder.CreatePtrToInt(Value, InputIntTy);
1588 else if (llvm::BitCastInst::isBitCastable(Value->getType(), InputIntTy))
1589 return CGF.Builder.CreateBitCast(Value, InputIntTy);
1590 }
1591 }
1592 // Otherwise, we need to go through memory.
1593 // Put the r-value in memory.
1594 Address Addr = materializeRValue(RVal);
1595
1596 // Cast the temporary to the atomic int type and pull a value out.
1597 Addr = emitCastToAtomicIntPointer(Addr);
1598 return CGF.Builder.CreateLoad(Addr);
1599}
1600
1601std::pair<llvm::Value *, llvm::Value *> AtomicInfo::EmitAtomicCompareExchangeOp(
1602 llvm::Value *ExpectedVal, llvm::Value *DesiredVal,
1603 llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak) {
1604 // Do the atomic store.
1605 Address Addr = getAtomicAddressAsAtomicIntPointer();
1606 auto *Inst = CGF.Builder.CreateAtomicCmpXchg(Addr.getPointer(),
1607 ExpectedVal, DesiredVal,
1608 Success, Failure);
1609 // Other decoration.
1610 Inst->setVolatile(LVal.isVolatileQualified());
1611 Inst->setWeak(IsWeak);
1612
1613 // Okay, turn that back into the original value type.
1614 auto *PreviousVal = CGF.Builder.CreateExtractValue(Inst, /*Idxs=*/0);
1615 auto *SuccessFailureVal = CGF.Builder.CreateExtractValue(Inst, /*Idxs=*/1);
1616 return std::make_pair(PreviousVal, SuccessFailureVal);
1617}
1618
1619llvm::Value *
1620AtomicInfo::EmitAtomicCompareExchangeLibcall(llvm::Value *ExpectedAddr,
1621 llvm::Value *DesiredAddr,
1622 llvm::AtomicOrdering Success,
1623 llvm::AtomicOrdering Failure) {
1624 // bool __atomic_compare_exchange(size_t size, void *obj, void *expected,
1625 // void *desired, int success, int failure);
1626 CallArgList Args;
1627 Args.add(RValue::get(getAtomicSizeValue()), CGF.getContext().getSizeType());
1628 Args.add(RValue::get(CGF.EmitCastToVoidPtr(getAtomicPointer())),
1629 CGF.getContext().VoidPtrTy);
1630 Args.add(RValue::get(CGF.EmitCastToVoidPtr(ExpectedAddr)),
1631 CGF.getContext().VoidPtrTy);
1632 Args.add(RValue::get(CGF.EmitCastToVoidPtr(DesiredAddr)),
1633 CGF.getContext().VoidPtrTy);
1634 Args.add(RValue::get(
1635 llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(Success))),
1636 CGF.getContext().IntTy);
1637 Args.add(RValue::get(
1638 llvm::ConstantInt::get(CGF.IntTy, (int)llvm::toCABI(Failure))),
1639 CGF.getContext().IntTy);
1640 auto SuccessFailureRVal = emitAtomicLibcall(CGF, "__atomic_compare_exchange",
1641 CGF.getContext().BoolTy, Args);
1642
1643 return SuccessFailureRVal.getScalarVal();
1644}
1645
1646std::pair<RValue, llvm::Value *> AtomicInfo::EmitAtomicCompareExchange(
1647 RValue Expected, RValue Desired, llvm::AtomicOrdering Success,
1648 llvm::AtomicOrdering Failure, bool IsWeak) {
1649 if (isStrongerThan(Failure, Success))
1650 // Don't assert on undefined behavior "failure argument shall be no stronger
1651 // than the success argument".
1652 Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(Success);
1653
1654 // Check whether we should use a library call.
1655 if (shouldUseLibcall()) {
1656 // Produce a source address.
1657 Address ExpectedAddr = materializeRValue(Expected);
1658 Address DesiredAddr = materializeRValue(Desired);
1659 auto *Res = EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1660 DesiredAddr.getPointer(),
1661 Success, Failure);
1662 return std::make_pair(
1663 convertAtomicTempToRValue(ExpectedAddr, AggValueSlot::ignored(),
1664 SourceLocation(), /*AsValue=*/false),
1665 Res);
1666 }
1667
1668 // If we've got a scalar value of the right size, try to avoid going
1669 // through memory.
1670 auto *ExpectedVal = convertRValueToInt(Expected);
1671 auto *DesiredVal = convertRValueToInt(Desired);
1672 auto Res = EmitAtomicCompareExchangeOp(ExpectedVal, DesiredVal, Success,
1673 Failure, IsWeak);
1674 return std::make_pair(
1675 ConvertIntToValueOrAtomic(Res.first, AggValueSlot::ignored(),
1676 SourceLocation(), /*AsValue=*/false),
1677 Res.second);
1678}
1679
1680static void
1681EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics, RValue OldRVal,
1682 const llvm::function_ref<RValue(RValue)> &UpdateOp,
1683 Address DesiredAddr) {
1684 RValue UpRVal;
1685 LValue AtomicLVal = Atomics.getAtomicLValue();
1686 LValue DesiredLVal;
1687 if (AtomicLVal.isSimple()) {
1688 UpRVal = OldRVal;
1689 DesiredLVal = CGF.MakeAddrLValue(DesiredAddr, AtomicLVal.getType());
1690 } else {
1691 // Build new lvalue for temp address.
1692 Address Ptr = Atomics.materializeRValue(OldRVal);
1693 LValue UpdateLVal;
1694 if (AtomicLVal.isBitField()) {
1695 UpdateLVal =
1696 LValue::MakeBitfield(Ptr, AtomicLVal.getBitFieldInfo(),
1697 AtomicLVal.getType(),
1698 AtomicLVal.getBaseInfo(),
1699 AtomicLVal.getTBAAInfo());
1700 DesiredLVal =
1701 LValue::MakeBitfield(DesiredAddr, AtomicLVal.getBitFieldInfo(),
1702 AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1703 AtomicLVal.getTBAAInfo());
1704 } else if (AtomicLVal.isVectorElt()) {
1705 UpdateLVal = LValue::MakeVectorElt(Ptr, AtomicLVal.getVectorIdx(),
1706 AtomicLVal.getType(),
1707 AtomicLVal.getBaseInfo(),
1708 AtomicLVal.getTBAAInfo());
1709 DesiredLVal = LValue::MakeVectorElt(
1710 DesiredAddr, AtomicLVal.getVectorIdx(), AtomicLVal.getType(),
1711 AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
1712 } else {
1713 assert(AtomicLVal.isExtVectorElt())((AtomicLVal.isExtVectorElt()) ? static_cast<void> (0) :
__assert_fail ("AtomicLVal.isExtVectorElt()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 1713, __PRETTY_FUNCTION__))
;
1714 UpdateLVal = LValue::MakeExtVectorElt(Ptr, AtomicLVal.getExtVectorElts(),
1715 AtomicLVal.getType(),
1716 AtomicLVal.getBaseInfo(),
1717 AtomicLVal.getTBAAInfo());
1718 DesiredLVal = LValue::MakeExtVectorElt(
1719 DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
1720 AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
1721 }
1722 UpRVal = CGF.EmitLoadOfLValue(UpdateLVal, SourceLocation());
1723 }
1724 // Store new value in the corresponding memory area.
1725 RValue NewRVal = UpdateOp(UpRVal);
1726 if (NewRVal.isScalar()) {
1727 CGF.EmitStoreThroughLValue(NewRVal, DesiredLVal);
1728 } else {
1729 assert(NewRVal.isComplex())((NewRVal.isComplex()) ? static_cast<void> (0) : __assert_fail
("NewRVal.isComplex()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 1729, __PRETTY_FUNCTION__))
;
1730 CGF.EmitStoreOfComplex(NewRVal.getComplexVal(), DesiredLVal,
1731 /*isInit=*/false);
1732 }
1733}
1734
1735void AtomicInfo::EmitAtomicUpdateLibcall(
1736 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1737 bool IsVolatile) {
1738 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1739
1740 Address ExpectedAddr = CreateTempAlloca();
1741
1742 EmitAtomicLoadLibcall(ExpectedAddr.getPointer(), AO, IsVolatile);
1743 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1744 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1745 CGF.EmitBlock(ContBB);
1746 Address DesiredAddr = CreateTempAlloca();
1747 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
1748 requiresMemSetZero(getAtomicAddress().getElementType())) {
1749 auto *OldVal = CGF.Builder.CreateLoad(ExpectedAddr);
1750 CGF.Builder.CreateStore(OldVal, DesiredAddr);
1751 }
1752 auto OldRVal = convertAtomicTempToRValue(ExpectedAddr,
1753 AggValueSlot::ignored(),
1754 SourceLocation(), /*AsValue=*/false);
1755 EmitAtomicUpdateValue(CGF, *this, OldRVal, UpdateOp, DesiredAddr);
1756 auto *Res =
1757 EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1758 DesiredAddr.getPointer(),
1759 AO, Failure);
1760 CGF.Builder.CreateCondBr(Res, ExitBB, ContBB);
1761 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1762}
1763
1764void AtomicInfo::EmitAtomicUpdateOp(
1765 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1766 bool IsVolatile) {
1767 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1768
1769 // Do the atomic load.
1770 auto *OldVal = EmitAtomicLoadOp(AO, IsVolatile);
1771 // For non-simple lvalues perform compare-and-swap procedure.
1772 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1773 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1774 auto *CurBB = CGF.Builder.GetInsertBlock();
1775 CGF.EmitBlock(ContBB);
1776 llvm::PHINode *PHI = CGF.Builder.CreatePHI(OldVal->getType(),
1777 /*NumReservedValues=*/2);
1778 PHI->addIncoming(OldVal, CurBB);
1779 Address NewAtomicAddr = CreateTempAlloca();
1780 Address NewAtomicIntAddr = emitCastToAtomicIntPointer(NewAtomicAddr);
1781 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
1782 requiresMemSetZero(getAtomicAddress().getElementType())) {
1783 CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
1784 }
1785 auto OldRVal = ConvertIntToValueOrAtomic(PHI, AggValueSlot::ignored(),
1786 SourceLocation(), /*AsValue=*/false);
1787 EmitAtomicUpdateValue(CGF, *this, OldRVal, UpdateOp, NewAtomicAddr);
1788 auto *DesiredVal = CGF.Builder.CreateLoad(NewAtomicIntAddr);
1789 // Try to write new value using cmpxchg operation.
1790 auto Res = EmitAtomicCompareExchangeOp(PHI, DesiredVal, AO, Failure);
1791 PHI->addIncoming(Res.first, CGF.Builder.GetInsertBlock());
1792 CGF.Builder.CreateCondBr(Res.second, ExitBB, ContBB);
1793 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1794}
1795
1796static void EmitAtomicUpdateValue(CodeGenFunction &CGF, AtomicInfo &Atomics,
1797 RValue UpdateRVal, Address DesiredAddr) {
1798 LValue AtomicLVal = Atomics.getAtomicLValue();
1799 LValue DesiredLVal;
1800 // Build new lvalue for temp address.
1801 if (AtomicLVal.isBitField()) {
1802 DesiredLVal =
1803 LValue::MakeBitfield(DesiredAddr, AtomicLVal.getBitFieldInfo(),
1804 AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1805 AtomicLVal.getTBAAInfo());
1806 } else if (AtomicLVal.isVectorElt()) {
1807 DesiredLVal =
1808 LValue::MakeVectorElt(DesiredAddr, AtomicLVal.getVectorIdx(),
1809 AtomicLVal.getType(), AtomicLVal.getBaseInfo(),
1810 AtomicLVal.getTBAAInfo());
1811 } else {
1812 assert(AtomicLVal.isExtVectorElt())((AtomicLVal.isExtVectorElt()) ? static_cast<void> (0) :
__assert_fail ("AtomicLVal.isExtVectorElt()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 1812, __PRETTY_FUNCTION__))
;
1813 DesiredLVal = LValue::MakeExtVectorElt(
1814 DesiredAddr, AtomicLVal.getExtVectorElts(), AtomicLVal.getType(),
1815 AtomicLVal.getBaseInfo(), AtomicLVal.getTBAAInfo());
1816 }
1817 // Store new value in the corresponding memory area.
1818 assert(UpdateRVal.isScalar())((UpdateRVal.isScalar()) ? static_cast<void> (0) : __assert_fail
("UpdateRVal.isScalar()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 1818, __PRETTY_FUNCTION__))
;
1819 CGF.EmitStoreThroughLValue(UpdateRVal, DesiredLVal);
1820}
1821
1822void AtomicInfo::EmitAtomicUpdateLibcall(llvm::AtomicOrdering AO,
1823 RValue UpdateRVal, bool IsVolatile) {
1824 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1825
1826 Address ExpectedAddr = CreateTempAlloca();
1827
1828 EmitAtomicLoadLibcall(ExpectedAddr.getPointer(), AO, IsVolatile);
1829 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1830 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1831 CGF.EmitBlock(ContBB);
1832 Address DesiredAddr = CreateTempAlloca();
1833 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
1834 requiresMemSetZero(getAtomicAddress().getElementType())) {
1835 auto *OldVal = CGF.Builder.CreateLoad(ExpectedAddr);
1836 CGF.Builder.CreateStore(OldVal, DesiredAddr);
1837 }
1838 EmitAtomicUpdateValue(CGF, *this, UpdateRVal, DesiredAddr);
1839 auto *Res =
1840 EmitAtomicCompareExchangeLibcall(ExpectedAddr.getPointer(),
1841 DesiredAddr.getPointer(),
1842 AO, Failure);
1843 CGF.Builder.CreateCondBr(Res, ExitBB, ContBB);
1844 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1845}
1846
1847void AtomicInfo::EmitAtomicUpdateOp(llvm::AtomicOrdering AO, RValue UpdateRVal,
1848 bool IsVolatile) {
1849 auto Failure = llvm::AtomicCmpXchgInst::getStrongestFailureOrdering(AO);
1850
1851 // Do the atomic load.
1852 auto *OldVal = EmitAtomicLoadOp(AO, IsVolatile);
1853 // For non-simple lvalues perform compare-and-swap procedure.
1854 auto *ContBB = CGF.createBasicBlock("atomic_cont");
1855 auto *ExitBB = CGF.createBasicBlock("atomic_exit");
1856 auto *CurBB = CGF.Builder.GetInsertBlock();
1857 CGF.EmitBlock(ContBB);
1858 llvm::PHINode *PHI = CGF.Builder.CreatePHI(OldVal->getType(),
1859 /*NumReservedValues=*/2);
1860 PHI->addIncoming(OldVal, CurBB);
1861 Address NewAtomicAddr = CreateTempAlloca();
1862 Address NewAtomicIntAddr = emitCastToAtomicIntPointer(NewAtomicAddr);
1863 if ((LVal.isBitField() && BFI.Size != ValueSizeInBits) ||
1864 requiresMemSetZero(getAtomicAddress().getElementType())) {
1865 CGF.Builder.CreateStore(PHI, NewAtomicIntAddr);
1866 }
1867 EmitAtomicUpdateValue(CGF, *this, UpdateRVal, NewAtomicAddr);
1868 auto *DesiredVal = CGF.Builder.CreateLoad(NewAtomicIntAddr);
1869 // Try to write new value using cmpxchg operation.
1870 auto Res = EmitAtomicCompareExchangeOp(PHI, DesiredVal, AO, Failure);
1871 PHI->addIncoming(Res.first, CGF.Builder.GetInsertBlock());
1872 CGF.Builder.CreateCondBr(Res.second, ExitBB, ContBB);
1873 CGF.EmitBlock(ExitBB, /*IsFinished=*/true);
1874}
1875
1876void AtomicInfo::EmitAtomicUpdate(
1877 llvm::AtomicOrdering AO, const llvm::function_ref<RValue(RValue)> &UpdateOp,
1878 bool IsVolatile) {
1879 if (shouldUseLibcall()) {
1880 EmitAtomicUpdateLibcall(AO, UpdateOp, IsVolatile);
1881 } else {
1882 EmitAtomicUpdateOp(AO, UpdateOp, IsVolatile);
1883 }
1884}
1885
1886void AtomicInfo::EmitAtomicUpdate(llvm::AtomicOrdering AO, RValue UpdateRVal,
1887 bool IsVolatile) {
1888 if (shouldUseLibcall()) {
1889 EmitAtomicUpdateLibcall(AO, UpdateRVal, IsVolatile);
1890 } else {
1891 EmitAtomicUpdateOp(AO, UpdateRVal, IsVolatile);
1892 }
1893}
1894
1895void CodeGenFunction::EmitAtomicStore(RValue rvalue, LValue lvalue,
1896 bool isInit) {
1897 bool IsVolatile = lvalue.isVolatileQualified();
1898 llvm::AtomicOrdering AO;
1899 if (lvalue.getType()->isAtomicType()) {
1900 AO = llvm::AtomicOrdering::SequentiallyConsistent;
1901 } else {
1902 AO = llvm::AtomicOrdering::Release;
1903 IsVolatile = true;
1904 }
1905 return EmitAtomicStore(rvalue, lvalue, AO, IsVolatile, isInit);
1906}
1907
1908/// Emit a store to an l-value of atomic type.
1909///
1910/// Note that the r-value is expected to be an r-value *of the atomic
1911/// type*; this means that for aggregate r-values, it should include
1912/// storage for any padding that was necessary.
1913void CodeGenFunction::EmitAtomicStore(RValue rvalue, LValue dest,
1914 llvm::AtomicOrdering AO, bool IsVolatile,
1915 bool isInit) {
1916 // If this is an aggregate r-value, it should agree in type except
1917 // maybe for address-space qualification.
1918 assert(!rvalue.isAggregate() ||((!rvalue.isAggregate() || rvalue.getAggregateAddress().getElementType
() == dest.getAddress().getElementType()) ? static_cast<void
> (0) : __assert_fail ("!rvalue.isAggregate() || rvalue.getAggregateAddress().getElementType() == dest.getAddress().getElementType()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 1920, __PRETTY_FUNCTION__))
1919 rvalue.getAggregateAddress().getElementType()((!rvalue.isAggregate() || rvalue.getAggregateAddress().getElementType
() == dest.getAddress().getElementType()) ? static_cast<void
> (0) : __assert_fail ("!rvalue.isAggregate() || rvalue.getAggregateAddress().getElementType() == dest.getAddress().getElementType()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 1920, __PRETTY_FUNCTION__))
1920 == dest.getAddress().getElementType())((!rvalue.isAggregate() || rvalue.getAggregateAddress().getElementType
() == dest.getAddress().getElementType()) ? static_cast<void
> (0) : __assert_fail ("!rvalue.isAggregate() || rvalue.getAggregateAddress().getElementType() == dest.getAddress().getElementType()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 1920, __PRETTY_FUNCTION__))
;
1921
1922 AtomicInfo atomics(*this, dest);
1923 LValue LVal = atomics.getAtomicLValue();
1924
1925 // If this is an initialization, just put the value there normally.
1926 if (LVal.isSimple()) {
1927 if (isInit) {
1928 atomics.emitCopyIntoMemory(rvalue);
1929 return;
1930 }
1931
1932 // Check whether we should use a library call.
1933 if (atomics.shouldUseLibcall()) {
1934 // Produce a source address.
1935 Address srcAddr = atomics.materializeRValue(rvalue);
1936
1937 // void __atomic_store(size_t size, void *mem, void *val, int order)
1938 CallArgList args;
1939 args.add(RValue::get(atomics.getAtomicSizeValue()),
1940 getContext().getSizeType());
1941 args.add(RValue::get(EmitCastToVoidPtr(atomics.getAtomicPointer())),
1942 getContext().VoidPtrTy);
1943 args.add(RValue::get(EmitCastToVoidPtr(srcAddr.getPointer())),
1944 getContext().VoidPtrTy);
1945 args.add(
1946 RValue::get(llvm::ConstantInt::get(IntTy, (int)llvm::toCABI(AO))),
1947 getContext().IntTy);
1948 emitAtomicLibcall(*this, "__atomic_store", getContext().VoidTy, args);
1949 return;
1950 }
1951
1952 // Okay, we're doing this natively.
1953 llvm::Value *intValue = atomics.convertRValueToInt(rvalue);
1954
1955 // Do the atomic store.
1956 Address addr =
1957 atomics.emitCastToAtomicIntPointer(atomics.getAtomicAddress());
1958 intValue = Builder.CreateIntCast(
1959 intValue, addr.getElementType(), /*isSigned=*/false);
1960 llvm::StoreInst *store = Builder.CreateStore(intValue, addr);
1961
1962 // Initializations don't need to be atomic.
1963 if (!isInit)
1964 store->setAtomic(AO);
1965
1966 // Other decoration.
1967 if (IsVolatile)
1968 store->setVolatile(true);
1969 CGM.DecorateInstructionWithTBAA(store, dest.getTBAAInfo());
1970 return;
1971 }
1972
1973 // Emit simple atomic update operation.
1974 atomics.EmitAtomicUpdate(AO, rvalue, IsVolatile);
1975}
1976
1977/// Emit a compare-and-exchange op for atomic type.
1978///
1979std::pair<RValue, llvm::Value *> CodeGenFunction::EmitAtomicCompareExchange(
1980 LValue Obj, RValue Expected, RValue Desired, SourceLocation Loc,
1981 llvm::AtomicOrdering Success, llvm::AtomicOrdering Failure, bool IsWeak,
1982 AggValueSlot Slot) {
1983 // If this is an aggregate r-value, it should agree in type except
1984 // maybe for address-space qualification.
1985 assert(!Expected.isAggregate() ||((!Expected.isAggregate() || Expected.getAggregateAddress().getElementType
() == Obj.getAddress().getElementType()) ? static_cast<void
> (0) : __assert_fail ("!Expected.isAggregate() || Expected.getAggregateAddress().getElementType() == Obj.getAddress().getElementType()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 1987, __PRETTY_FUNCTION__))
1986 Expected.getAggregateAddress().getElementType() ==((!Expected.isAggregate() || Expected.getAggregateAddress().getElementType
() == Obj.getAddress().getElementType()) ? static_cast<void
> (0) : __assert_fail ("!Expected.isAggregate() || Expected.getAggregateAddress().getElementType() == Obj.getAddress().getElementType()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 1987, __PRETTY_FUNCTION__))
1987 Obj.getAddress().getElementType())((!Expected.isAggregate() || Expected.getAggregateAddress().getElementType
() == Obj.getAddress().getElementType()) ? static_cast<void
> (0) : __assert_fail ("!Expected.isAggregate() || Expected.getAggregateAddress().getElementType() == Obj.getAddress().getElementType()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 1987, __PRETTY_FUNCTION__))
;
1988 assert(!Desired.isAggregate() ||((!Desired.isAggregate() || Desired.getAggregateAddress().getElementType
() == Obj.getAddress().getElementType()) ? static_cast<void
> (0) : __assert_fail ("!Desired.isAggregate() || Desired.getAggregateAddress().getElementType() == Obj.getAddress().getElementType()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 1990, __PRETTY_FUNCTION__))
1989 Desired.getAggregateAddress().getElementType() ==((!Desired.isAggregate() || Desired.getAggregateAddress().getElementType
() == Obj.getAddress().getElementType()) ? static_cast<void
> (0) : __assert_fail ("!Desired.isAggregate() || Desired.getAggregateAddress().getElementType() == Obj.getAddress().getElementType()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 1990, __PRETTY_FUNCTION__))
1990 Obj.getAddress().getElementType())((!Desired.isAggregate() || Desired.getAggregateAddress().getElementType
() == Obj.getAddress().getElementType()) ? static_cast<void
> (0) : __assert_fail ("!Desired.isAggregate() || Desired.getAggregateAddress().getElementType() == Obj.getAddress().getElementType()"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 1990, __PRETTY_FUNCTION__))
;
1991 AtomicInfo Atomics(*this, Obj);
1992
1993 return Atomics.EmitAtomicCompareExchange(Expected, Desired, Success, Failure,
1994 IsWeak);
1995}
1996
1997void CodeGenFunction::EmitAtomicUpdate(
1998 LValue LVal, llvm::AtomicOrdering AO,
1999 const llvm::function_ref<RValue(RValue)> &UpdateOp, bool IsVolatile) {
2000 AtomicInfo Atomics(*this, LVal);
2001 Atomics.EmitAtomicUpdate(AO, UpdateOp, IsVolatile);
2002}
2003
2004void CodeGenFunction::EmitAtomicInit(Expr *init, LValue dest) {
2005 AtomicInfo atomics(*this, dest);
2006
2007 switch (atomics.getEvaluationKind()) {
2008 case TEK_Scalar: {
2009 llvm::Value *value = EmitScalarExpr(init);
2010 atomics.emitCopyIntoMemory(RValue::get(value));
2011 return;
2012 }
2013
2014 case TEK_Complex: {
2015 ComplexPairTy value = EmitComplexExpr(init);
2016 atomics.emitCopyIntoMemory(RValue::getComplex(value));
2017 return;
2018 }
2019
2020 case TEK_Aggregate: {
2021 // Fix up the destination if the initializer isn't an expression
2022 // of atomic type.
2023 bool Zeroed = false;
2024 if (!init->getType()->isAtomicType()) {
2025 Zeroed = atomics.emitMemSetZeroIfNecessary();
2026 dest = atomics.projectValue();
2027 }
2028
2029 // Evaluate the expression directly into the destination.
2030 AggValueSlot slot = AggValueSlot::forLValue(dest,
2031 AggValueSlot::IsNotDestructed,
2032 AggValueSlot::DoesNotNeedGCBarriers,
2033 AggValueSlot::IsNotAliased,
2034 AggValueSlot::DoesNotOverlap,
2035 Zeroed ? AggValueSlot::IsZeroed :
2036 AggValueSlot::IsNotZeroed);
2037
2038 EmitAggExpr(init, slot);
2039 return;
2040 }
2041 }
2042 llvm_unreachable("bad evaluation kind")::llvm::llvm_unreachable_internal("bad evaluation kind", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/lib/CodeGen/CGAtomic.cpp"
, 2042)
;
2043}

/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h

1//===--- Expr.h - Classes for representing expressions ----------*- C++ -*-===//
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 file defines the Expr interface and subclasses.
10//
11//===----------------------------------------------------------------------===//
12
13#ifndef LLVM_CLANG_AST_EXPR_H
14#define LLVM_CLANG_AST_EXPR_H
15
16#include "clang/AST/APValue.h"
17#include "clang/AST/ASTVector.h"
18#include "clang/AST/Decl.h"
19#include "clang/AST/DeclAccessPair.h"
20#include "clang/AST/OperationKinds.h"
21#include "clang/AST/Stmt.h"
22#include "clang/AST/TemplateBase.h"
23#include "clang/AST/Type.h"
24#include "clang/Basic/CharInfo.h"
25#include "clang/Basic/FixedPoint.h"
26#include "clang/Basic/LangOptions.h"
27#include "clang/Basic/SyncScope.h"
28#include "clang/Basic/TypeTraits.h"
29#include "llvm/ADT/APFloat.h"
30#include "llvm/ADT/APSInt.h"
31#include "llvm/ADT/iterator.h"
32#include "llvm/ADT/iterator_range.h"
33#include "llvm/ADT/SmallVector.h"
34#include "llvm/ADT/StringRef.h"
35#include "llvm/Support/AtomicOrdering.h"
36#include "llvm/Support/Compiler.h"
37#include "llvm/Support/TrailingObjects.h"
38
39namespace clang {
40 class APValue;
41 class ASTContext;
42 class BlockDecl;
43 class CXXBaseSpecifier;
44 class CXXMemberCallExpr;
45 class CXXOperatorCallExpr;
46 class CastExpr;
47 class Decl;
48 class IdentifierInfo;
49 class MaterializeTemporaryExpr;
50 class NamedDecl;
51 class ObjCPropertyRefExpr;
52 class OpaqueValueExpr;
53 class ParmVarDecl;
54 class StringLiteral;
55 class TargetInfo;
56 class ValueDecl;
57
58/// A simple array of base specifiers.
59typedef SmallVector<CXXBaseSpecifier*, 4> CXXCastPath;
60
61/// An adjustment to be made to the temporary created when emitting a
62/// reference binding, which accesses a particular subobject of that temporary.
63struct SubobjectAdjustment {
64 enum {
65 DerivedToBaseAdjustment,
66 FieldAdjustment,
67 MemberPointerAdjustment
68 } Kind;
69
70 struct DTB {
71 const CastExpr *BasePath;
72 const CXXRecordDecl *DerivedClass;
73 };
74
75 struct P {
76 const MemberPointerType *MPT;
77 Expr *RHS;
78 };
79
80 union {
81 struct DTB DerivedToBase;
82 FieldDecl *Field;
83 struct P Ptr;
84 };
85
86 SubobjectAdjustment(const CastExpr *BasePath,
87 const CXXRecordDecl *DerivedClass)
88 : Kind(DerivedToBaseAdjustment) {
89 DerivedToBase.BasePath = BasePath;
90 DerivedToBase.DerivedClass = DerivedClass;
91 }
92
93 SubobjectAdjustment(FieldDecl *Field)
94 : Kind(FieldAdjustment) {
95 this->Field = Field;
96 }
97
98 SubobjectAdjustment(const MemberPointerType *MPT, Expr *RHS)
99 : Kind(MemberPointerAdjustment) {
100 this->Ptr.MPT = MPT;
101 this->Ptr.RHS = RHS;
102 }
103};
104
105/// This represents one expression. Note that Expr's are subclasses of Stmt.
106/// This allows an expression to be transparently used any place a Stmt is
107/// required.
108class Expr : public ValueStmt {
109 QualType TR;
110
111public:
112 Expr() = delete;
113 Expr(const Expr&) = delete;
114 Expr(Expr &&) = delete;
115 Expr &operator=(const Expr&) = delete;
116 Expr &operator=(Expr&&) = delete;
117
118protected:
119 Expr(StmtClass SC, QualType T, ExprValueKind VK, ExprObjectKind OK,
120 bool TD, bool VD, bool ID, bool ContainsUnexpandedParameterPack)
121 : ValueStmt(SC)
122 {
123 ExprBits.TypeDependent = TD;
124 ExprBits.ValueDependent = VD;
125 ExprBits.InstantiationDependent = ID;
126 ExprBits.ValueKind = VK;
127 ExprBits.ObjectKind = OK;
128 assert(ExprBits.ObjectKind == OK && "truncated kind")((ExprBits.ObjectKind == OK && "truncated kind") ? static_cast
<void> (0) : __assert_fail ("ExprBits.ObjectKind == OK && \"truncated kind\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 128, __PRETTY_FUNCTION__))
;
129 ExprBits.ContainsUnexpandedParameterPack = ContainsUnexpandedParameterPack;
130 setType(T);
131 }
132
133 /// Construct an empty expression.
134 explicit Expr(StmtClass SC, EmptyShell) : ValueStmt(SC) { }
135
136public:
137 QualType getType() const { return TR; }
138 void setType(QualType t) {
139 // In C++, the type of an expression is always adjusted so that it
140 // will not have reference type (C++ [expr]p6). Use
141 // QualType::getNonReferenceType() to retrieve the non-reference
142 // type. Additionally, inspect Expr::isLvalue to determine whether
143 // an expression that is adjusted in this manner should be
144 // considered an lvalue.
145 assert((t.isNull() || !t->isReferenceType()) &&(((t.isNull() || !t->isReferenceType()) && "Expressions can't have reference type"
) ? static_cast<void> (0) : __assert_fail ("(t.isNull() || !t->isReferenceType()) && \"Expressions can't have reference type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 146, __PRETTY_FUNCTION__))
146 "Expressions can't have reference type")(((t.isNull() || !t->isReferenceType()) && "Expressions can't have reference type"
) ? static_cast<void> (0) : __assert_fail ("(t.isNull() || !t->isReferenceType()) && \"Expressions can't have reference type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 146, __PRETTY_FUNCTION__))
;
147
148 TR = t;
149 }
150
151 /// isValueDependent - Determines whether this expression is
152 /// value-dependent (C++ [temp.dep.constexpr]). For example, the
153 /// array bound of "Chars" in the following example is
154 /// value-dependent.
155 /// @code
156 /// template<int Size, char (&Chars)[Size]> struct meta_string;
157 /// @endcode
158 bool isValueDependent() const { return ExprBits.ValueDependent; }
159
160 /// Set whether this expression is value-dependent or not.
161 void setValueDependent(bool VD) {
162 ExprBits.ValueDependent = VD;
163 }
164
165 /// isTypeDependent - Determines whether this expression is
166 /// type-dependent (C++ [temp.dep.expr]), which means that its type
167 /// could change from one template instantiation to the next. For
168 /// example, the expressions "x" and "x + y" are type-dependent in
169 /// the following code, but "y" is not type-dependent:
170 /// @code
171 /// template<typename T>
172 /// void add(T x, int y) {
173 /// x + y;
174 /// }
175 /// @endcode
176 bool isTypeDependent() const { return ExprBits.TypeDependent; }
177
178 /// Set whether this expression is type-dependent or not.
179 void setTypeDependent(bool TD) {
180 ExprBits.TypeDependent = TD;
181 }
182
183 /// Whether this expression is instantiation-dependent, meaning that
184 /// it depends in some way on a template parameter, even if neither its type
185 /// nor (constant) value can change due to the template instantiation.
186 ///
187 /// In the following example, the expression \c sizeof(sizeof(T() + T())) is
188 /// instantiation-dependent (since it involves a template parameter \c T), but
189 /// is neither type- nor value-dependent, since the type of the inner
190 /// \c sizeof is known (\c std::size_t) and therefore the size of the outer
191 /// \c sizeof is known.
192 ///
193 /// \code
194 /// template<typename T>
195 /// void f(T x, T y) {
196 /// sizeof(sizeof(T() + T());
197 /// }
198 /// \endcode
199 ///
200 bool isInstantiationDependent() const {
201 return ExprBits.InstantiationDependent;
202 }
203
204 /// Set whether this expression is instantiation-dependent or not.
205 void setInstantiationDependent(bool ID) {
206 ExprBits.InstantiationDependent = ID;
207 }
208
209 /// Whether this expression contains an unexpanded parameter
210 /// pack (for C++11 variadic templates).
211 ///
212 /// Given the following function template:
213 ///
214 /// \code
215 /// template<typename F, typename ...Types>
216 /// void forward(const F &f, Types &&...args) {
217 /// f(static_cast<Types&&>(args)...);
218 /// }
219 /// \endcode
220 ///
221 /// The expressions \c args and \c static_cast<Types&&>(args) both
222 /// contain parameter packs.
223 bool containsUnexpandedParameterPack() const {
224 return ExprBits.ContainsUnexpandedParameterPack;
225 }
226
227 /// Set the bit that describes whether this expression
228 /// contains an unexpanded parameter pack.
229 void setContainsUnexpandedParameterPack(bool PP = true) {
230 ExprBits.ContainsUnexpandedParameterPack = PP;
231 }
232
233 /// getExprLoc - Return the preferred location for the arrow when diagnosing
234 /// a problem with a generic expression.
235 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__));
236
237 /// isUnusedResultAWarning - Return true if this immediate expression should
238 /// be warned about if the result is unused. If so, fill in expr, location,
239 /// and ranges with expr to warn on and source locations/ranges appropriate
240 /// for a warning.
241 bool isUnusedResultAWarning(const Expr *&WarnExpr, SourceLocation &Loc,
242 SourceRange &R1, SourceRange &R2,
243 ASTContext &Ctx) const;
244
245 /// isLValue - True if this expression is an "l-value" according to
246 /// the rules of the current language. C and C++ give somewhat
247 /// different rules for this concept, but in general, the result of
248 /// an l-value expression identifies a specific object whereas the
249 /// result of an r-value expression is a value detached from any
250 /// specific storage.
251 ///
252 /// C++11 divides the concept of "r-value" into pure r-values
253 /// ("pr-values") and so-called expiring values ("x-values"), which
254 /// identify specific objects that can be safely cannibalized for
255 /// their resources. This is an unfortunate abuse of terminology on
256 /// the part of the C++ committee. In Clang, when we say "r-value",
257 /// we generally mean a pr-value.
258 bool isLValue() const { return getValueKind() == VK_LValue; }
259 bool isRValue() const { return getValueKind() == VK_RValue; }
260 bool isXValue() const { return getValueKind() == VK_XValue; }
261 bool isGLValue() const { return getValueKind() != VK_RValue; }
262
263 enum LValueClassification {
264 LV_Valid,
265 LV_NotObjectType,
266 LV_IncompleteVoidType,
267 LV_DuplicateVectorComponents,
268 LV_InvalidExpression,
269 LV_InvalidMessageExpression,
270 LV_MemberFunction,
271 LV_SubObjCPropertySetting,
272 LV_ClassTemporary,
273 LV_ArrayTemporary
274 };
275 /// Reasons why an expression might not be an l-value.
276 LValueClassification ClassifyLValue(ASTContext &Ctx) const;
277
278 enum isModifiableLvalueResult {
279 MLV_Valid,
280 MLV_NotObjectType,
281 MLV_IncompleteVoidType,
282 MLV_DuplicateVectorComponents,
283 MLV_InvalidExpression,
284 MLV_LValueCast, // Specialized form of MLV_InvalidExpression.
285 MLV_IncompleteType,
286 MLV_ConstQualified,
287 MLV_ConstQualifiedField,
288 MLV_ConstAddrSpace,
289 MLV_ArrayType,
290 MLV_NoSetterProperty,
291 MLV_MemberFunction,
292 MLV_SubObjCPropertySetting,
293 MLV_InvalidMessageExpression,
294 MLV_ClassTemporary,
295 MLV_ArrayTemporary
296 };
297 /// isModifiableLvalue - C99 6.3.2.1: an lvalue that does not have array type,
298 /// does not have an incomplete type, does not have a const-qualified type,
299 /// and if it is a structure or union, does not have any member (including,
300 /// recursively, any member or element of all contained aggregates or unions)
301 /// with a const-qualified type.
302 ///
303 /// \param Loc [in,out] - A source location which *may* be filled
304 /// in with the location of the expression making this a
305 /// non-modifiable lvalue, if specified.
306 isModifiableLvalueResult
307 isModifiableLvalue(ASTContext &Ctx, SourceLocation *Loc = nullptr) const;
308
309 /// The return type of classify(). Represents the C++11 expression
310 /// taxonomy.
311 class Classification {
312 public:
313 /// The various classification results. Most of these mean prvalue.
314 enum Kinds {
315 CL_LValue,
316 CL_XValue,
317 CL_Function, // Functions cannot be lvalues in C.
318 CL_Void, // Void cannot be an lvalue in C.
319 CL_AddressableVoid, // Void expression whose address can be taken in C.
320 CL_DuplicateVectorComponents, // A vector shuffle with dupes.
321 CL_MemberFunction, // An expression referring to a member function
322 CL_SubObjCPropertySetting,
323 CL_ClassTemporary, // A temporary of class type, or subobject thereof.
324 CL_ArrayTemporary, // A temporary of array type.
325 CL_ObjCMessageRValue, // ObjC message is an rvalue
326 CL_PRValue // A prvalue for any other reason, of any other type
327 };
328 /// The results of modification testing.
329 enum ModifiableType {
330 CM_Untested, // testModifiable was false.
331 CM_Modifiable,
332 CM_RValue, // Not modifiable because it's an rvalue
333 CM_Function, // Not modifiable because it's a function; C++ only
334 CM_LValueCast, // Same as CM_RValue, but indicates GCC cast-as-lvalue ext
335 CM_NoSetterProperty,// Implicit assignment to ObjC property without setter
336 CM_ConstQualified,
337 CM_ConstQualifiedField,
338 CM_ConstAddrSpace,
339 CM_ArrayType,
340 CM_IncompleteType
341 };
342
343 private:
344 friend class Expr;
345
346 unsigned short Kind;
347 unsigned short Modifiable;
348
349 explicit Classification(Kinds k, ModifiableType m)
350 : Kind(k), Modifiable(m)
351 {}
352
353 public:
354 Classification() {}
355
356 Kinds getKind() const { return static_cast<Kinds>(Kind); }
357 ModifiableType getModifiable() const {
358 assert(Modifiable != CM_Untested && "Did not test for modifiability.")((Modifiable != CM_Untested && "Did not test for modifiability."
) ? static_cast<void> (0) : __assert_fail ("Modifiable != CM_Untested && \"Did not test for modifiability.\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 358, __PRETTY_FUNCTION__))
;
359 return static_cast<ModifiableType>(Modifiable);
360 }
361 bool isLValue() const { return Kind == CL_LValue; }
362 bool isXValue() const { return Kind == CL_XValue; }
363 bool isGLValue() const { return Kind <= CL_XValue; }
364 bool isPRValue() const { return Kind >= CL_Function; }
365 bool isRValue() const { return Kind >= CL_XValue; }
366 bool isModifiable() const { return getModifiable() == CM_Modifiable; }
367
368 /// Create a simple, modifiably lvalue
369 static Classification makeSimpleLValue() {
370 return Classification(CL_LValue, CM_Modifiable);
371 }
372
373 };
374 /// Classify - Classify this expression according to the C++11
375 /// expression taxonomy.
376 ///
377 /// C++11 defines ([basic.lval]) a new taxonomy of expressions to replace the
378 /// old lvalue vs rvalue. This function determines the type of expression this
379 /// is. There are three expression types:
380 /// - lvalues are classical lvalues as in C++03.
381 /// - prvalues are equivalent to rvalues in C++03.
382 /// - xvalues are expressions yielding unnamed rvalue references, e.g. a
383 /// function returning an rvalue reference.
384 /// lvalues and xvalues are collectively referred to as glvalues, while
385 /// prvalues and xvalues together form rvalues.
386 Classification Classify(ASTContext &Ctx) const {
387 return ClassifyImpl(Ctx, nullptr);
388 }
389
390 /// ClassifyModifiable - Classify this expression according to the
391 /// C++11 expression taxonomy, and see if it is valid on the left side
392 /// of an assignment.
393 ///
394 /// This function extends classify in that it also tests whether the
395 /// expression is modifiable (C99 6.3.2.1p1).
396 /// \param Loc A source location that might be filled with a relevant location
397 /// if the expression is not modifiable.
398 Classification ClassifyModifiable(ASTContext &Ctx, SourceLocation &Loc) const{
399 return ClassifyImpl(Ctx, &Loc);
400 }
401
402 /// getValueKindForType - Given a formal return or parameter type,
403 /// give its value kind.
404 static ExprValueKind getValueKindForType(QualType T) {
405 if (const ReferenceType *RT = T->getAs<ReferenceType>())
406 return (isa<LValueReferenceType>(RT)
407 ? VK_LValue
408 : (RT->getPointeeType()->isFunctionType()
409 ? VK_LValue : VK_XValue));
410 return VK_RValue;
411 }
412
413 /// getValueKind - The value kind that this expression produces.
414 ExprValueKind getValueKind() const {
415 return static_cast<ExprValueKind>(ExprBits.ValueKind);
416 }
417
418 /// getObjectKind - The object kind that this expression produces.
419 /// Object kinds are meaningful only for expressions that yield an
420 /// l-value or x-value.
421 ExprObjectKind getObjectKind() const {
422 return static_cast<ExprObjectKind>(ExprBits.ObjectKind);
423 }
424
425 bool isOrdinaryOrBitFieldObject() const {
426 ExprObjectKind OK = getObjectKind();
427 return (OK == OK_Ordinary || OK == OK_BitField);
428 }
429
430 /// setValueKind - Set the value kind produced by this expression.
431 void setValueKind(ExprValueKind Cat) { ExprBits.ValueKind = Cat; }
432
433 /// setObjectKind - Set the object kind produced by this expression.
434 void setObjectKind(ExprObjectKind Cat) { ExprBits.ObjectKind = Cat; }
435
436private:
437 Classification ClassifyImpl(ASTContext &Ctx, SourceLocation *Loc) const;
438
439public:
440
441 /// Returns true if this expression is a gl-value that
442 /// potentially refers to a bit-field.
443 ///
444 /// In C++, whether a gl-value refers to a bitfield is essentially
445 /// an aspect of the value-kind type system.
446 bool refersToBitField() const { return getObjectKind() == OK_BitField; }
447
448 /// If this expression refers to a bit-field, retrieve the
449 /// declaration of that bit-field.
450 ///
451 /// Note that this returns a non-null pointer in subtly different
452 /// places than refersToBitField returns true. In particular, this can
453 /// return a non-null pointer even for r-values loaded from
454 /// bit-fields, but it will return null for a conditional bit-field.
455 FieldDecl *getSourceBitField();
456
457 const FieldDecl *getSourceBitField() const {
458 return const_cast<Expr*>(this)->getSourceBitField();
459 }
460
461 Decl *getReferencedDeclOfCallee();
462 const Decl *getReferencedDeclOfCallee() const {
463 return const_cast<Expr*>(this)->getReferencedDeclOfCallee();
464 }
465
466 /// If this expression is an l-value for an Objective C
467 /// property, find the underlying property reference expression.
468 const ObjCPropertyRefExpr *getObjCProperty() const;
469
470 /// Check if this expression is the ObjC 'self' implicit parameter.
471 bool isObjCSelfExpr() const;
472
473 /// Returns whether this expression refers to a vector element.
474 bool refersToVectorElement() const;
475
476 /// Returns whether this expression refers to a global register
477 /// variable.
478 bool refersToGlobalRegisterVar() const;
479
480 /// Returns whether this expression has a placeholder type.
481 bool hasPlaceholderType() const {
482 return getType()->isPlaceholderType();
483 }
484
485 /// Returns whether this expression has a specific placeholder type.
486 bool hasPlaceholderType(BuiltinType::Kind K) const {
487 assert(BuiltinType::isPlaceholderTypeKind(K))((BuiltinType::isPlaceholderTypeKind(K)) ? static_cast<void
> (0) : __assert_fail ("BuiltinType::isPlaceholderTypeKind(K)"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 487, __PRETTY_FUNCTION__))
;
488 if (const BuiltinType *BT = dyn_cast<BuiltinType>(getType()))
489 return BT->getKind() == K;
490 return false;
491 }
492
493 /// isKnownToHaveBooleanValue - Return true if this is an integer expression
494 /// that is known to return 0 or 1. This happens for _Bool/bool expressions
495 /// but also int expressions which are produced by things like comparisons in
496 /// C.
497 bool isKnownToHaveBooleanValue() const;
498
499 /// isIntegerConstantExpr - Return true if this expression is a valid integer
500 /// constant expression, and, if so, return its value in Result. If not a
501 /// valid i-c-e, return false and fill in Loc (if specified) with the location
502 /// of the invalid expression.
503 ///
504 /// Note: This does not perform the implicit conversions required by C++11
505 /// [expr.const]p5.
506 bool isIntegerConstantExpr(llvm::APSInt &Result, const ASTContext &Ctx,
507 SourceLocation *Loc = nullptr,
508 bool isEvaluated = true) const;
509 bool isIntegerConstantExpr(const ASTContext &Ctx,
510 SourceLocation *Loc = nullptr) const;
511
512 /// isCXX98IntegralConstantExpr - Return true if this expression is an
513 /// integral constant expression in C++98. Can only be used in C++.
514 bool isCXX98IntegralConstantExpr(const ASTContext &Ctx) const;
515
516 /// isCXX11ConstantExpr - Return true if this expression is a constant
517 /// expression in C++11. Can only be used in C++.
518 ///
519 /// Note: This does not perform the implicit conversions required by C++11
520 /// [expr.const]p5.
521 bool isCXX11ConstantExpr(const ASTContext &Ctx, APValue *Result = nullptr,
522 SourceLocation *Loc = nullptr) const;
523
524 /// isPotentialConstantExpr - Return true if this function's definition
525 /// might be usable in a constant expression in C++11, if it were marked
526 /// constexpr. Return false if the function can never produce a constant
527 /// expression, along with diagnostics describing why not.
528 static bool isPotentialConstantExpr(const FunctionDecl *FD,
529 SmallVectorImpl<
530 PartialDiagnosticAt> &Diags);
531
532 /// isPotentialConstantExprUnevaluted - Return true if this expression might
533 /// be usable in a constant expression in C++11 in an unevaluated context, if
534 /// it were in function FD marked constexpr. Return false if the function can
535 /// never produce a constant expression, along with diagnostics describing
536 /// why not.
537 static bool isPotentialConstantExprUnevaluated(Expr *E,
538 const FunctionDecl *FD,
539 SmallVectorImpl<
540 PartialDiagnosticAt> &Diags);
541
542 /// isConstantInitializer - Returns true if this expression can be emitted to
543 /// IR as a constant, and thus can be used as a constant initializer in C.
544 /// If this expression is not constant and Culprit is non-null,
545 /// it is used to store the address of first non constant expr.
546 bool isConstantInitializer(ASTContext &Ctx, bool ForRef,
547 const Expr **Culprit = nullptr) const;
548
549 /// EvalStatus is a struct with detailed info about an evaluation in progress.
550 struct EvalStatus {
551 /// Whether the evaluated expression has side effects.
552 /// For example, (f() && 0) can be folded, but it still has side effects.
553 bool HasSideEffects;
554
555 /// Whether the evaluation hit undefined behavior.
556 /// For example, 1.0 / 0.0 can be folded to Inf, but has undefined behavior.
557 /// Likewise, INT_MAX + 1 can be folded to INT_MIN, but has UB.
558 bool HasUndefinedBehavior;
559
560 /// Diag - If this is non-null, it will be filled in with a stack of notes
561 /// indicating why evaluation failed (or why it failed to produce a constant
562 /// expression).
563 /// If the expression is unfoldable, the notes will indicate why it's not
564 /// foldable. If the expression is foldable, but not a constant expression,
565 /// the notes will describes why it isn't a constant expression. If the
566 /// expression *is* a constant expression, no notes will be produced.
567 SmallVectorImpl<PartialDiagnosticAt> *Diag;
568
569 EvalStatus()
570 : HasSideEffects(false), HasUndefinedBehavior(false), Diag(nullptr) {}
571
572 // hasSideEffects - Return true if the evaluated expression has
573 // side effects.
574 bool hasSideEffects() const {
575 return HasSideEffects;
576 }
577 };
578
579 /// EvalResult is a struct with detailed info about an evaluated expression.
580 struct EvalResult : EvalStatus {
581 /// Val - This is the value the expression can be folded to.
582 APValue Val;
583
584 // isGlobalLValue - Return true if the evaluated lvalue expression
585 // is global.
586 bool isGlobalLValue() const;
587 };
588
589 /// EvaluateAsRValue - Return true if this is a constant which we can fold to
590 /// an rvalue using any crazy technique (that has nothing to do with language
591 /// standards) that we want to, even if the expression has side-effects. If
592 /// this function returns true, it returns the folded constant in Result. If
593 /// the expression is a glvalue, an lvalue-to-rvalue conversion will be
594 /// applied.
595 bool EvaluateAsRValue(EvalResult &Result, const ASTContext &Ctx,
596 bool InConstantContext = false) const;
597
598 /// EvaluateAsBooleanCondition - Return true if this is a constant
599 /// which we can fold and convert to a boolean condition using
600 /// any crazy technique that we want to, even if the expression has
601 /// side-effects.
602 bool EvaluateAsBooleanCondition(bool &Result, const ASTContext &Ctx,
603 bool InConstantContext = false) const;
604
605 enum SideEffectsKind {
606 SE_NoSideEffects, ///< Strictly evaluate the expression.
607 SE_AllowUndefinedBehavior, ///< Allow UB that we can give a value, but not
608 ///< arbitrary unmodeled side effects.
609 SE_AllowSideEffects ///< Allow any unmodeled side effect.
610 };
611
612 /// EvaluateAsInt - Return true if this is a constant which we can fold and
613 /// convert to an integer, using any crazy technique that we want to.
614 bool EvaluateAsInt(EvalResult &Result, const ASTContext &Ctx,
615 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
616 bool InConstantContext = false) const;
617
618 /// EvaluateAsFloat - Return true if this is a constant which we can fold and
619 /// convert to a floating point value, using any crazy technique that we
620 /// want to.
621 bool EvaluateAsFloat(llvm::APFloat &Result, const ASTContext &Ctx,
622 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
623 bool InConstantContext = false) const;
624
625 /// EvaluateAsFloat - Return true if this is a constant which we can fold and
626 /// convert to a fixed point value.
627 bool EvaluateAsFixedPoint(EvalResult &Result, const ASTContext &Ctx,
628 SideEffectsKind AllowSideEffects = SE_NoSideEffects,
629 bool InConstantContext = false) const;
630
631 /// isEvaluatable - Call EvaluateAsRValue to see if this expression can be
632 /// constant folded without side-effects, but discard the result.
633 bool isEvaluatable(const ASTContext &Ctx,
634 SideEffectsKind AllowSideEffects = SE_NoSideEffects) const;
635
636 /// HasSideEffects - This routine returns true for all those expressions
637 /// which have any effect other than producing a value. Example is a function
638 /// call, volatile variable read, or throwing an exception. If
639 /// IncludePossibleEffects is false, this call treats certain expressions with
640 /// potential side effects (such as function call-like expressions,
641 /// instantiation-dependent expressions, or invocations from a macro) as not
642 /// having side effects.
643 bool HasSideEffects(const ASTContext &Ctx,
644 bool IncludePossibleEffects = true) const;
645
646 /// Determine whether this expression involves a call to any function
647 /// that is not trivial.
648 bool hasNonTrivialCall(const ASTContext &Ctx) const;
649
650 /// EvaluateKnownConstInt - Call EvaluateAsRValue and return the folded
651 /// integer. This must be called on an expression that constant folds to an
652 /// integer.
653 llvm::APSInt EvaluateKnownConstInt(
654 const ASTContext &Ctx,
655 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
656
657 llvm::APSInt EvaluateKnownConstIntCheckOverflow(
658 const ASTContext &Ctx,
659 SmallVectorImpl<PartialDiagnosticAt> *Diag = nullptr) const;
660
661 void EvaluateForOverflow(const ASTContext &Ctx) const;
662
663 /// EvaluateAsLValue - Evaluate an expression to see if we can fold it to an
664 /// lvalue with link time known address, with no side-effects.
665 bool EvaluateAsLValue(EvalResult &Result, const ASTContext &Ctx,
666 bool InConstantContext = false) const;
667
668 /// EvaluateAsInitializer - Evaluate an expression as if it were the
669 /// initializer of the given declaration. Returns true if the initializer
670 /// can be folded to a constant, and produces any relevant notes. In C++11,
671 /// notes will be produced if the expression is not a constant expression.
672 bool EvaluateAsInitializer(APValue &Result, const ASTContext &Ctx,
673 const VarDecl *VD,
674 SmallVectorImpl<PartialDiagnosticAt> &Notes) const;
675
676 /// EvaluateWithSubstitution - Evaluate an expression as if from the context
677 /// of a call to the given function with the given arguments, inside an
678 /// unevaluated context. Returns true if the expression could be folded to a
679 /// constant.
680 bool EvaluateWithSubstitution(APValue &Value, ASTContext &Ctx,
681 const FunctionDecl *Callee,
682 ArrayRef<const Expr*> Args,
683 const Expr *This = nullptr) const;
684
685 /// Indicates how the constant expression will be used.
686 enum ConstExprUsage { EvaluateForCodeGen, EvaluateForMangling };
687
688 /// Evaluate an expression that is required to be a constant expression.
689 bool EvaluateAsConstantExpr(EvalResult &Result, ConstExprUsage Usage,
690 const ASTContext &Ctx) const;
691
692 /// If the current Expr is a pointer, this will try to statically
693 /// determine the number of bytes available where the pointer is pointing.
694 /// Returns true if all of the above holds and we were able to figure out the
695 /// size, false otherwise.
696 ///
697 /// \param Type - How to evaluate the size of the Expr, as defined by the
698 /// "type" parameter of __builtin_object_size
699 bool tryEvaluateObjectSize(uint64_t &Result, ASTContext &Ctx,
700 unsigned Type) const;
701
702 /// Enumeration used to describe the kind of Null pointer constant
703 /// returned from \c isNullPointerConstant().
704 enum NullPointerConstantKind {
705 /// Expression is not a Null pointer constant.
706 NPCK_NotNull = 0,
707
708 /// Expression is a Null pointer constant built from a zero integer
709 /// expression that is not a simple, possibly parenthesized, zero literal.
710 /// C++ Core Issue 903 will classify these expressions as "not pointers"
711 /// once it is adopted.
712 /// http://www.open-std.org/jtc1/sc22/wg21/docs/cwg_active.html#903
713 NPCK_ZeroExpression,
714
715 /// Expression is a Null pointer constant built from a literal zero.
716 NPCK_ZeroLiteral,
717
718 /// Expression is a C++11 nullptr.
719 NPCK_CXX11_nullptr,
720
721 /// Expression is a GNU-style __null constant.
722 NPCK_GNUNull
723 };
724
725 /// Enumeration used to describe how \c isNullPointerConstant()
726 /// should cope with value-dependent expressions.
727 enum NullPointerConstantValueDependence {
728 /// Specifies that the expression should never be value-dependent.
729 NPC_NeverValueDependent = 0,
730
731 /// Specifies that a value-dependent expression of integral or
732 /// dependent type should be considered a null pointer constant.
733 NPC_ValueDependentIsNull,
734
735 /// Specifies that a value-dependent expression should be considered
736 /// to never be a null pointer constant.
737 NPC_ValueDependentIsNotNull
738 };
739
740 /// isNullPointerConstant - C99 6.3.2.3p3 - Test if this reduces down to
741 /// a Null pointer constant. The return value can further distinguish the
742 /// kind of NULL pointer constant that was detected.
743 NullPointerConstantKind isNullPointerConstant(
744 ASTContext &Ctx,
745 NullPointerConstantValueDependence NPC) const;
746
747 /// isOBJCGCCandidate - Return true if this expression may be used in a read/
748 /// write barrier.
749 bool isOBJCGCCandidate(ASTContext &Ctx) const;
750
751 /// Returns true if this expression is a bound member function.
752 bool isBoundMemberFunction(ASTContext &Ctx) const;
753
754 /// Given an expression of bound-member type, find the type
755 /// of the member. Returns null if this is an *overloaded* bound
756 /// member expression.
757 static QualType findBoundMemberType(const Expr *expr);
758
759 /// Skip past any implicit casts which might surround this expression until
760 /// reaching a fixed point. Skips:
761 /// * ImplicitCastExpr
762 /// * FullExpr
763 Expr *IgnoreImpCasts() LLVM_READONLY__attribute__((__pure__));
764 const Expr *IgnoreImpCasts() const {
765 return const_cast<Expr *>(this)->IgnoreImpCasts();
766 }
767
768 /// Skip past any casts which might surround this expression until reaching
769 /// a fixed point. Skips:
770 /// * CastExpr
771 /// * FullExpr
772 /// * MaterializeTemporaryExpr
773 /// * SubstNonTypeTemplateParmExpr
774 Expr *IgnoreCasts() LLVM_READONLY__attribute__((__pure__));
775 const Expr *IgnoreCasts() const {
776 return const_cast<Expr *>(this)->IgnoreCasts();
777 }
778
779 /// Skip past any implicit AST nodes which might surround this expression
780 /// until reaching a fixed point. Skips:
781 /// * What IgnoreImpCasts() skips
782 /// * MaterializeTemporaryExpr
783 /// * CXXBindTemporaryExpr
784 Expr *IgnoreImplicit() LLVM_READONLY__attribute__((__pure__));
785 const Expr *IgnoreImplicit() const {
786 return const_cast<Expr *>(this)->IgnoreImplicit();
787 }
788
789 /// Skip past any parentheses which might surround this expression until
790 /// reaching a fixed point. Skips:
791 /// * ParenExpr
792 /// * UnaryOperator if `UO_Extension`
793 /// * GenericSelectionExpr if `!isResultDependent()`
794 /// * ChooseExpr if `!isConditionDependent()`
795 /// * ConstantExpr
796 Expr *IgnoreParens() LLVM_READONLY__attribute__((__pure__));
797 const Expr *IgnoreParens() const {
798 return const_cast<Expr *>(this)->IgnoreParens();
799 }
800
801 /// Skip past any parentheses and implicit casts which might surround this
802 /// expression until reaching a fixed point.
803 /// FIXME: IgnoreParenImpCasts really ought to be equivalent to
804 /// IgnoreParens() + IgnoreImpCasts() until reaching a fixed point. However
805 /// this is currently not the case. Instead IgnoreParenImpCasts() skips:
806 /// * What IgnoreParens() skips
807 /// * What IgnoreImpCasts() skips
808 /// * MaterializeTemporaryExpr
809 /// * SubstNonTypeTemplateParmExpr
810 Expr *IgnoreParenImpCasts() LLVM_READONLY__attribute__((__pure__));
811 const Expr *IgnoreParenImpCasts() const {
812 return const_cast<Expr *>(this)->IgnoreParenImpCasts();
813 }
814
815 /// Skip past any parentheses and casts which might surround this expression
816 /// until reaching a fixed point. Skips:
817 /// * What IgnoreParens() skips
818 /// * What IgnoreCasts() skips
819 Expr *IgnoreParenCasts() LLVM_READONLY__attribute__((__pure__));
820 const Expr *IgnoreParenCasts() const {
821 return const_cast<Expr *>(this)->IgnoreParenCasts();
822 }
823
824 /// Skip conversion operators. If this Expr is a call to a conversion
825 /// operator, return the argument.
826 Expr *IgnoreConversionOperator() LLVM_READONLY__attribute__((__pure__));
827 const Expr *IgnoreConversionOperator() const {
828 return const_cast<Expr *>(this)->IgnoreConversionOperator();
829 }
830
831 /// Skip past any parentheses and lvalue casts which might surround this
832 /// expression until reaching a fixed point. Skips:
833 /// * What IgnoreParens() skips
834 /// * What IgnoreCasts() skips, except that only lvalue-to-rvalue
835 /// casts are skipped
836 /// FIXME: This is intended purely as a temporary workaround for code
837 /// that hasn't yet been rewritten to do the right thing about those
838 /// casts, and may disappear along with the last internal use.
839 Expr *IgnoreParenLValueCasts() LLVM_READONLY__attribute__((__pure__));
840 const Expr *IgnoreParenLValueCasts() const {
841 return const_cast<Expr *>(this)->IgnoreParenLValueCasts();
842 }
843
844 /// Skip past any parenthese and casts which do not change the value
845 /// (including ptr->int casts of the same size) until reaching a fixed point.
846 /// Skips:
847 /// * What IgnoreParens() skips
848 /// * CastExpr which do not change the value
849 /// * SubstNonTypeTemplateParmExpr
850 Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) LLVM_READONLY__attribute__((__pure__));
851 const Expr *IgnoreParenNoopCasts(const ASTContext &Ctx) const {
852 return const_cast<Expr *>(this)->IgnoreParenNoopCasts(Ctx);
853 }
854
855 /// Skip past any parentheses and derived-to-base casts until reaching a
856 /// fixed point. Skips:
857 /// * What IgnoreParens() skips
858 /// * CastExpr which represent a derived-to-base cast (CK_DerivedToBase,
859 /// CK_UncheckedDerivedToBase and CK_NoOp)
860 Expr *ignoreParenBaseCasts() LLVM_READONLY__attribute__((__pure__));
861 const Expr *ignoreParenBaseCasts() const {
862 return const_cast<Expr *>(this)->ignoreParenBaseCasts();
863 }
864
865 /// Determine whether this expression is a default function argument.
866 ///
867 /// Default arguments are implicitly generated in the abstract syntax tree
868 /// by semantic analysis for function calls, object constructions, etc. in
869 /// C++. Default arguments are represented by \c CXXDefaultArgExpr nodes;
870 /// this routine also looks through any implicit casts to determine whether
871 /// the expression is a default argument.
872 bool isDefaultArgument() const;
873
874 /// Determine whether the result of this expression is a
875 /// temporary object of the given class type.
876 bool isTemporaryObject(ASTContext &Ctx, const CXXRecordDecl *TempTy) const;
877
878 /// Whether this expression is an implicit reference to 'this' in C++.
879 bool isImplicitCXXThis() const;
880
881 static bool hasAnyTypeDependentArguments(ArrayRef<Expr *> Exprs);
882
883 /// For an expression of class type or pointer to class type,
884 /// return the most derived class decl the expression is known to refer to.
885 ///
886 /// If this expression is a cast, this method looks through it to find the
887 /// most derived decl that can be inferred from the expression.
888 /// This is valid because derived-to-base conversions have undefined
889 /// behavior if the object isn't dynamically of the derived type.
890 const CXXRecordDecl *getBestDynamicClassType() const;
891
892 /// Get the inner expression that determines the best dynamic class.
893 /// If this is a prvalue, we guarantee that it is of the most-derived type
894 /// for the object itself.
895 const Expr *getBestDynamicClassTypeExpr() const;
896
897 /// Walk outwards from an expression we want to bind a reference to and
898 /// find the expression whose lifetime needs to be extended. Record
899 /// the LHSs of comma expressions and adjustments needed along the path.
900 const Expr *skipRValueSubobjectAdjustments(
901 SmallVectorImpl<const Expr *> &CommaLHS,
902 SmallVectorImpl<SubobjectAdjustment> &Adjustments) const;
903 const Expr *skipRValueSubobjectAdjustments() const {
904 SmallVector<const Expr *, 8> CommaLHSs;
905 SmallVector<SubobjectAdjustment, 8> Adjustments;
906 return skipRValueSubobjectAdjustments(CommaLHSs, Adjustments);
907 }
908
909 /// Checks that the two Expr's will refer to the same value as a comparison
910 /// operand. The caller must ensure that the values referenced by the Expr's
911 /// are not modified between E1 and E2 or the result my be invalid.
912 static bool isSameComparisonOperand(const Expr* E1, const Expr* E2);
913
914 static bool classof(const Stmt *T) {
915 return T->getStmtClass() >= firstExprConstant &&
916 T->getStmtClass() <= lastExprConstant;
917 }
918};
919
920//===----------------------------------------------------------------------===//
921// Wrapper Expressions.
922//===----------------------------------------------------------------------===//
923
924/// FullExpr - Represents a "full-expression" node.
925class FullExpr : public Expr {
926protected:
927 Stmt *SubExpr;
928
929 FullExpr(StmtClass SC, Expr *subexpr)
930 : Expr(SC, subexpr->getType(),
931 subexpr->getValueKind(), subexpr->getObjectKind(),
932 subexpr->isTypeDependent(), subexpr->isValueDependent(),
933 subexpr->isInstantiationDependent(),
934 subexpr->containsUnexpandedParameterPack()), SubExpr(subexpr) {}
935 FullExpr(StmtClass SC, EmptyShell Empty)
936 : Expr(SC, Empty) {}
937public:
938 const Expr *getSubExpr() const { return cast<Expr>(SubExpr); }
939 Expr *getSubExpr() { return cast<Expr>(SubExpr); }
940
941 /// As with any mutator of the AST, be very careful when modifying an
942 /// existing AST to preserve its invariants.
943 void setSubExpr(Expr *E) { SubExpr = E; }
944
945 static bool classof(const Stmt *T) {
946 return T->getStmtClass() >= firstFullExprConstant &&
947 T->getStmtClass() <= lastFullExprConstant;
948 }
949};
950
951/// ConstantExpr - An expression that occurs in a constant context and
952/// optionally the result of evaluating the expression.
953class ConstantExpr final
954 : public FullExpr,
955 private llvm::TrailingObjects<ConstantExpr, APValue, uint64_t> {
956 static_assert(std::is_same<uint64_t, llvm::APInt::WordType>::value,
957 "this class assumes llvm::APInt::WordType is uint64_t for "
958 "trail-allocated storage");
959
960public:
961 /// Describes the kind of result that can be trail-allocated.
962 enum ResultStorageKind { RSK_None, RSK_Int64, RSK_APValue };
963
964private:
965 size_t numTrailingObjects(OverloadToken<APValue>) const {
966 return ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue;
967 }
968 size_t numTrailingObjects(OverloadToken<uint64_t>) const {
969 return ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64;
970 }
971
972 void DefaultInit(ResultStorageKind StorageKind);
973 uint64_t &Int64Result() {
974 assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 &&((ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 &&
"invalid accessor") ? static_cast<void> (0) : __assert_fail
("ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 && \"invalid accessor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 975, __PRETTY_FUNCTION__))
975 "invalid accessor")((ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 &&
"invalid accessor") ? static_cast<void> (0) : __assert_fail
("ConstantExprBits.ResultKind == ConstantExpr::RSK_Int64 && \"invalid accessor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 975, __PRETTY_FUNCTION__))
;
976 return *getTrailingObjects<uint64_t>();
977 }
978 const uint64_t &Int64Result() const {
979 return const_cast<ConstantExpr *>(this)->Int64Result();
980 }
981 APValue &APValueResult() {
982 assert(ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue &&((ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue &&
"invalid accessor") ? static_cast<void> (0) : __assert_fail
("ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue && \"invalid accessor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 983, __PRETTY_FUNCTION__))
983 "invalid accessor")((ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue &&
"invalid accessor") ? static_cast<void> (0) : __assert_fail
("ConstantExprBits.ResultKind == ConstantExpr::RSK_APValue && \"invalid accessor\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 983, __PRETTY_FUNCTION__))
;
984 return *getTrailingObjects<APValue>();
985 }
986 const APValue &APValueResult() const {
987 return const_cast<ConstantExpr *>(this)->APValueResult();
988 }
989
990 ConstantExpr(Expr *subexpr, ResultStorageKind StorageKind);
991 ConstantExpr(ResultStorageKind StorageKind, EmptyShell Empty);
992
993public:
994 friend TrailingObjects;
995 friend class ASTStmtReader;
996 friend class ASTStmtWriter;
997 static ConstantExpr *Create(const ASTContext &Context, Expr *E,
998 const APValue &Result);
999 static ConstantExpr *Create(const ASTContext &Context, Expr *E,
1000 ResultStorageKind Storage = RSK_None);
1001 static ConstantExpr *CreateEmpty(const ASTContext &Context,
1002 ResultStorageKind StorageKind,
1003 EmptyShell Empty);
1004
1005 static ResultStorageKind getStorageKind(const APValue &Value);
1006 static ResultStorageKind getStorageKind(const Type *T,
1007 const ASTContext &Context);
1008
1009 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
1010 return SubExpr->getBeginLoc();
1011 }
1012 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
1013 return SubExpr->getEndLoc();
1014 }
1015
1016 static bool classof(const Stmt *T) {
1017 return T->getStmtClass() == ConstantExprClass;
1018 }
1019
1020 void SetResult(APValue Value, const ASTContext &Context) {
1021 MoveIntoResult(Value, Context);
1022 }
1023 void MoveIntoResult(APValue &Value, const ASTContext &Context);
1024
1025 APValue::ValueKind getResultAPValueKind() const {
1026 return static_cast<APValue::ValueKind>(ConstantExprBits.APValueKind);
1027 }
1028 ResultStorageKind getResultStorageKind() const {
1029 return static_cast<ResultStorageKind>(ConstantExprBits.ResultKind);
1030 }
1031 APValue getAPValueResult() const;
1032 const APValue &getResultAsAPValue() const { return APValueResult(); }
1033 llvm::APSInt getResultAsAPSInt() const;
1034 // Iterators
1035 child_range children() { return child_range(&SubExpr, &SubExpr+1); }
1036 const_child_range children() const {
1037 return const_child_range(&SubExpr, &SubExpr + 1);
1038 }
1039};
1040
1041//===----------------------------------------------------------------------===//
1042// Primary Expressions.
1043//===----------------------------------------------------------------------===//
1044
1045/// OpaqueValueExpr - An expression referring to an opaque object of a
1046/// fixed type and value class. These don't correspond to concrete
1047/// syntax; instead they're used to express operations (usually copy
1048/// operations) on values whose source is generally obvious from
1049/// context.
1050class OpaqueValueExpr : public Expr {
1051 friend class ASTStmtReader;
1052 Expr *SourceExpr;
1053
1054public:
1055 OpaqueValueExpr(SourceLocation Loc, QualType T, ExprValueKind VK,
1056 ExprObjectKind OK = OK_Ordinary,
1057 Expr *SourceExpr = nullptr)
1058 : Expr(OpaqueValueExprClass, T, VK, OK,
1059 T->isDependentType() ||
1060 (SourceExpr && SourceExpr->isTypeDependent()),
1061 T->isDependentType() ||
1062 (SourceExpr && SourceExpr->isValueDependent()),
1063 T->isInstantiationDependentType() ||
1064 (SourceExpr && SourceExpr->isInstantiationDependent()),
1065 false),
1066 SourceExpr(SourceExpr) {
1067 setIsUnique(false);
1068 OpaqueValueExprBits.Loc = Loc;
1069 }
1070
1071 /// Given an expression which invokes a copy constructor --- i.e. a
1072 /// CXXConstructExpr, possibly wrapped in an ExprWithCleanups ---
1073 /// find the OpaqueValueExpr that's the source of the construction.
1074 static const OpaqueValueExpr *findInCopyConstruct(const Expr *expr);
1075
1076 explicit OpaqueValueExpr(EmptyShell Empty)
1077 : Expr(OpaqueValueExprClass, Empty) {}
1078
1079 /// Retrieve the location of this expression.
1080 SourceLocation getLocation() const { return OpaqueValueExprBits.Loc; }
1081
1082 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
1083 return SourceExpr ? SourceExpr->getBeginLoc() : getLocation();
1084 }
1085 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
1086 return SourceExpr ? SourceExpr->getEndLoc() : getLocation();
1087 }
1088 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) {
1089 return SourceExpr ? SourceExpr->getExprLoc() : getLocation();
1090 }
1091
1092 child_range children() {
1093 return child_range(child_iterator(), child_iterator());
1094 }
1095
1096 const_child_range children() const {
1097 return const_child_range(const_child_iterator(), const_child_iterator());
1098 }
1099
1100 /// The source expression of an opaque value expression is the
1101 /// expression which originally generated the value. This is
1102 /// provided as a convenience for analyses that don't wish to
1103 /// precisely model the execution behavior of the program.
1104 ///
1105 /// The source expression is typically set when building the
1106 /// expression which binds the opaque value expression in the first
1107 /// place.
1108 Expr *getSourceExpr() const { return SourceExpr; }
1109
1110 void setIsUnique(bool V) {
1111 assert((!V || SourceExpr) &&(((!V || SourceExpr) && "unique OVEs are expected to have source expressions"
) ? static_cast<void> (0) : __assert_fail ("(!V || SourceExpr) && \"unique OVEs are expected to have source expressions\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 1112, __PRETTY_FUNCTION__))
1112 "unique OVEs are expected to have source expressions")(((!V || SourceExpr) && "unique OVEs are expected to have source expressions"
) ? static_cast<void> (0) : __assert_fail ("(!V || SourceExpr) && \"unique OVEs are expected to have source expressions\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 1112, __PRETTY_FUNCTION__))
;
1113 OpaqueValueExprBits.IsUnique = V;
1114 }
1115
1116 bool isUnique() const { return OpaqueValueExprBits.IsUnique; }
1117
1118 static bool classof(const Stmt *T) {
1119 return T->getStmtClass() == OpaqueValueExprClass;
1120 }
1121};
1122
1123/// A reference to a declared variable, function, enum, etc.
1124/// [C99 6.5.1p2]
1125///
1126/// This encodes all the information about how a declaration is referenced
1127/// within an expression.
1128///
1129/// There are several optional constructs attached to DeclRefExprs only when
1130/// they apply in order to conserve memory. These are laid out past the end of
1131/// the object, and flags in the DeclRefExprBitfield track whether they exist:
1132///
1133/// DeclRefExprBits.HasQualifier:
1134/// Specifies when this declaration reference expression has a C++
1135/// nested-name-specifier.
1136/// DeclRefExprBits.HasFoundDecl:
1137/// Specifies when this declaration reference expression has a record of
1138/// a NamedDecl (different from the referenced ValueDecl) which was found
1139/// during name lookup and/or overload resolution.
1140/// DeclRefExprBits.HasTemplateKWAndArgsInfo:
1141/// Specifies when this declaration reference expression has an explicit
1142/// C++ template keyword and/or template argument list.
1143/// DeclRefExprBits.RefersToEnclosingVariableOrCapture
1144/// Specifies when this declaration reference expression (validly)
1145/// refers to an enclosed local or a captured variable.
1146class DeclRefExpr final
1147 : public Expr,
1148 private llvm::TrailingObjects<DeclRefExpr, NestedNameSpecifierLoc,
1149 NamedDecl *, ASTTemplateKWAndArgsInfo,
1150 TemplateArgumentLoc> {
1151 friend class ASTStmtReader;
1152 friend class ASTStmtWriter;
1153 friend TrailingObjects;
1154
1155 /// The declaration that we are referencing.
1156 ValueDecl *D;
1157
1158 /// Provides source/type location info for the declaration name
1159 /// embedded in D.
1160 DeclarationNameLoc DNLoc;
1161
1162 size_t numTrailingObjects(OverloadToken<NestedNameSpecifierLoc>) const {
1163 return hasQualifier();
1164 }
1165
1166 size_t numTrailingObjects(OverloadToken<NamedDecl *>) const {
1167 return hasFoundDecl();
1168 }
1169
1170 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
1171 return hasTemplateKWAndArgsInfo();
1172 }
1173
1174 /// Test whether there is a distinct FoundDecl attached to the end of
1175 /// this DRE.
1176 bool hasFoundDecl() const { return DeclRefExprBits.HasFoundDecl; }
1177
1178 DeclRefExpr(const ASTContext &Ctx, NestedNameSpecifierLoc QualifierLoc,
1179 SourceLocation TemplateKWLoc, ValueDecl *D,
1180 bool RefersToEnlosingVariableOrCapture,
1181 const DeclarationNameInfo &NameInfo, NamedDecl *FoundD,
1182 const TemplateArgumentListInfo *TemplateArgs, QualType T,
1183 ExprValueKind VK, NonOdrUseReason NOUR);
1184
1185 /// Construct an empty declaration reference expression.
1186 explicit DeclRefExpr(EmptyShell Empty) : Expr(DeclRefExprClass, Empty) {}
1187
1188 /// Computes the type- and value-dependence flags for this
1189 /// declaration reference expression.
1190 void computeDependence(const ASTContext &Ctx);
1191
1192public:
1193 DeclRefExpr(const ASTContext &Ctx, ValueDecl *D,
1194 bool RefersToEnclosingVariableOrCapture, QualType T,
1195 ExprValueKind VK, SourceLocation L,
1196 const DeclarationNameLoc &LocInfo = DeclarationNameLoc(),
1197 NonOdrUseReason NOUR = NOUR_None);
1198
1199 static DeclRefExpr *
1200 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1201 SourceLocation TemplateKWLoc, ValueDecl *D,
1202 bool RefersToEnclosingVariableOrCapture, SourceLocation NameLoc,
1203 QualType T, ExprValueKind VK, NamedDecl *FoundD = nullptr,
1204 const TemplateArgumentListInfo *TemplateArgs = nullptr,
1205 NonOdrUseReason NOUR = NOUR_None);
1206
1207 static DeclRefExpr *
1208 Create(const ASTContext &Context, NestedNameSpecifierLoc QualifierLoc,
1209 SourceLocation TemplateKWLoc, ValueDecl *D,
1210 bool RefersToEnclosingVariableOrCapture,
1211 const DeclarationNameInfo &NameInfo, QualType T, ExprValueKind VK,
1212 NamedDecl *FoundD = nullptr,
1213 const TemplateArgumentListInfo *TemplateArgs = nullptr,
1214 NonOdrUseReason NOUR = NOUR_None);
1215
1216 /// Construct an empty declaration reference expression.
1217 static DeclRefExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
1218 bool HasFoundDecl,
1219 bool HasTemplateKWAndArgsInfo,
1220 unsigned NumTemplateArgs);
1221
1222 ValueDecl *getDecl() { return D; }
1223 const ValueDecl *getDecl() const { return D; }
1224 void setDecl(ValueDecl *NewD) { D = NewD; }
1225
1226 DeclarationNameInfo getNameInfo() const {
1227 return DeclarationNameInfo(getDecl()->getDeclName(), getLocation(), DNLoc);
1228 }
1229
1230 SourceLocation getLocation() const { return DeclRefExprBits.Loc; }
1231 void setLocation(SourceLocation L) { DeclRefExprBits.Loc = L; }
1232 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
1233 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
1234
1235 /// Determine whether this declaration reference was preceded by a
1236 /// C++ nested-name-specifier, e.g., \c N::foo.
1237 bool hasQualifier() const { return DeclRefExprBits.HasQualifier; }
1238
1239 /// If the name was qualified, retrieves the nested-name-specifier
1240 /// that precedes the name, with source-location information.
1241 NestedNameSpecifierLoc getQualifierLoc() const {
1242 if (!hasQualifier())
1243 return NestedNameSpecifierLoc();
1244 return *getTrailingObjects<NestedNameSpecifierLoc>();
1245 }
1246
1247 /// If the name was qualified, retrieves the nested-name-specifier
1248 /// that precedes the name. Otherwise, returns NULL.
1249 NestedNameSpecifier *getQualifier() const {
1250 return getQualifierLoc().getNestedNameSpecifier();
1251 }
1252
1253 /// Get the NamedDecl through which this reference occurred.
1254 ///
1255 /// This Decl may be different from the ValueDecl actually referred to in the
1256 /// presence of using declarations, etc. It always returns non-NULL, and may
1257 /// simple return the ValueDecl when appropriate.
1258
1259 NamedDecl *getFoundDecl() {
1260 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1261 }
1262
1263 /// Get the NamedDecl through which this reference occurred.
1264 /// See non-const variant.
1265 const NamedDecl *getFoundDecl() const {
1266 return hasFoundDecl() ? *getTrailingObjects<NamedDecl *>() : D;
1267 }
1268
1269 bool hasTemplateKWAndArgsInfo() const {
1270 return DeclRefExprBits.HasTemplateKWAndArgsInfo;
1271 }
1272
1273 /// Retrieve the location of the template keyword preceding
1274 /// this name, if any.
1275 SourceLocation getTemplateKeywordLoc() const {
1276 if (!hasTemplateKWAndArgsInfo())
1277 return SourceLocation();
1278 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
1279 }
1280
1281 /// Retrieve the location of the left angle bracket starting the
1282 /// explicit template argument list following the name, if any.
1283 SourceLocation getLAngleLoc() const {
1284 if (!hasTemplateKWAndArgsInfo())
1285 return SourceLocation();
1286 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
1287 }
1288
1289 /// Retrieve the location of the right angle bracket ending the
1290 /// explicit template argument list following the name, if any.
1291 SourceLocation getRAngleLoc() const {
1292 if (!hasTemplateKWAndArgsInfo())
1293 return SourceLocation();
1294 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
1295 }
1296
1297 /// Determines whether the name in this declaration reference
1298 /// was preceded by the template keyword.
1299 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
1300
1301 /// Determines whether this declaration reference was followed by an
1302 /// explicit template argument list.
1303 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
1304
1305 /// Copies the template arguments (if present) into the given
1306 /// structure.
1307 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
1308 if (hasExplicitTemplateArgs())
1309 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
1310 getTrailingObjects<TemplateArgumentLoc>(), List);
1311 }
1312
1313 /// Retrieve the template arguments provided as part of this
1314 /// template-id.
1315 const TemplateArgumentLoc *getTemplateArgs() const {
1316 if (!hasExplicitTemplateArgs())
1317 return nullptr;
1318 return getTrailingObjects<TemplateArgumentLoc>();
1319 }
1320
1321 /// Retrieve the number of template arguments provided as part of this
1322 /// template-id.
1323 unsigned getNumTemplateArgs() const {
1324 if (!hasExplicitTemplateArgs())
1325 return 0;
1326 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
1327 }
1328
1329 ArrayRef<TemplateArgumentLoc> template_arguments() const {
1330 return {getTemplateArgs(), getNumTemplateArgs()};
1331 }
1332
1333 /// Returns true if this expression refers to a function that
1334 /// was resolved from an overloaded set having size greater than 1.
1335 bool hadMultipleCandidates() const {
1336 return DeclRefExprBits.HadMultipleCandidates;
1337 }
1338 /// Sets the flag telling whether this expression refers to
1339 /// a function that was resolved from an overloaded set having size
1340 /// greater than 1.
1341 void setHadMultipleCandidates(bool V = true) {
1342 DeclRefExprBits.HadMultipleCandidates = V;
1343 }
1344
1345 /// Is this expression a non-odr-use reference, and if so, why?
1346 NonOdrUseReason isNonOdrUse() const {
1347 return static_cast<NonOdrUseReason>(DeclRefExprBits.NonOdrUseReason);
1348 }
1349
1350 /// Does this DeclRefExpr refer to an enclosing local or a captured
1351 /// variable?
1352 bool refersToEnclosingVariableOrCapture() const {
1353 return DeclRefExprBits.RefersToEnclosingVariableOrCapture;
1354 }
1355
1356 static bool classof(const Stmt *T) {
1357 return T->getStmtClass() == DeclRefExprClass;
1358 }
1359
1360 // Iterators
1361 child_range children() {
1362 return child_range(child_iterator(), child_iterator());
1363 }
1364
1365 const_child_range children() const {
1366 return const_child_range(const_child_iterator(), const_child_iterator());
1367 }
1368};
1369
1370/// Used by IntegerLiteral/FloatingLiteral to store the numeric without
1371/// leaking memory.
1372///
1373/// For large floats/integers, APFloat/APInt will allocate memory from the heap
1374/// to represent these numbers. Unfortunately, when we use a BumpPtrAllocator
1375/// to allocate IntegerLiteral/FloatingLiteral nodes the memory associated with
1376/// the APFloat/APInt values will never get freed. APNumericStorage uses
1377/// ASTContext's allocator for memory allocation.
1378class APNumericStorage {
1379 union {
1380 uint64_t VAL; ///< Used to store the <= 64 bits integer value.
1381 uint64_t *pVal; ///< Used to store the >64 bits integer value.
1382 };
1383 unsigned BitWidth;
1384
1385 bool hasAllocation() const { return llvm::APInt::getNumWords(BitWidth) > 1; }
1386
1387 APNumericStorage(const APNumericStorage &) = delete;
1388 void operator=(const APNumericStorage &) = delete;
1389
1390protected:
1391 APNumericStorage() : VAL(0), BitWidth(0) { }
1392
1393 llvm::APInt getIntValue() const {
1394 unsigned NumWords = llvm::APInt::getNumWords(BitWidth);
1395 if (NumWords > 1)
1396 return llvm::APInt(BitWidth, NumWords, pVal);
1397 else
1398 return llvm::APInt(BitWidth, VAL);
1399 }
1400 void setIntValue(const ASTContext &C, const llvm::APInt &Val);
1401};
1402
1403class APIntStorage : private APNumericStorage {
1404public:
1405 llvm::APInt getValue() const { return getIntValue(); }
1406 void setValue(const ASTContext &C, const llvm::APInt &Val) {
1407 setIntValue(C, Val);
1408 }
1409};
1410
1411class APFloatStorage : private APNumericStorage {
1412public:
1413 llvm::APFloat getValue(const llvm::fltSemantics &Semantics) const {
1414 return llvm::APFloat(Semantics, getIntValue());
1415 }
1416 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1417 setIntValue(C, Val.bitcastToAPInt());
1418 }
1419};
1420
1421class IntegerLiteral : public Expr, public APIntStorage {
1422 SourceLocation Loc;
1423
1424 /// Construct an empty integer literal.
1425 explicit IntegerLiteral(EmptyShell Empty)
1426 : Expr(IntegerLiteralClass, Empty) { }
1427
1428public:
1429 // type should be IntTy, LongTy, LongLongTy, UnsignedIntTy, UnsignedLongTy,
1430 // or UnsignedLongLongTy
1431 IntegerLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1432 SourceLocation l);
1433
1434 /// Returns a new integer literal with value 'V' and type 'type'.
1435 /// \param type - either IntTy, LongTy, LongLongTy, UnsignedIntTy,
1436 /// UnsignedLongTy, or UnsignedLongLongTy which should match the size of V
1437 /// \param V - the value that the returned integer literal contains.
1438 static IntegerLiteral *Create(const ASTContext &C, const llvm::APInt &V,
1439 QualType type, SourceLocation l);
1440 /// Returns a new empty integer literal.
1441 static IntegerLiteral *Create(const ASTContext &C, EmptyShell Empty);
1442
1443 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1444 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1445
1446 /// Retrieve the location of the literal.
1447 SourceLocation getLocation() const { return Loc; }
1448
1449 void setLocation(SourceLocation Location) { Loc = Location; }
1450
1451 static bool classof(const Stmt *T) {
1452 return T->getStmtClass() == IntegerLiteralClass;
1453 }
1454
1455 // Iterators
1456 child_range children() {
1457 return child_range(child_iterator(), child_iterator());
1458 }
1459 const_child_range children() const {
1460 return const_child_range(const_child_iterator(), const_child_iterator());
1461 }
1462};
1463
1464class FixedPointLiteral : public Expr, public APIntStorage {
1465 SourceLocation Loc;
1466 unsigned Scale;
1467
1468 /// \brief Construct an empty integer literal.
1469 explicit FixedPointLiteral(EmptyShell Empty)
1470 : Expr(FixedPointLiteralClass, Empty) {}
1471
1472 public:
1473 FixedPointLiteral(const ASTContext &C, const llvm::APInt &V, QualType type,
1474 SourceLocation l, unsigned Scale);
1475
1476 // Store the int as is without any bit shifting.
1477 static FixedPointLiteral *CreateFromRawInt(const ASTContext &C,
1478 const llvm::APInt &V,
1479 QualType type, SourceLocation l,
1480 unsigned Scale);
1481
1482 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1483 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1484
1485 /// \brief Retrieve the location of the literal.
1486 SourceLocation getLocation() const { return Loc; }
1487
1488 void setLocation(SourceLocation Location) { Loc = Location; }
1489
1490 static bool classof(const Stmt *T) {
1491 return T->getStmtClass() == FixedPointLiteralClass;
1492 }
1493
1494 std::string getValueAsString(unsigned Radix) const;
1495
1496 // Iterators
1497 child_range children() {
1498 return child_range(child_iterator(), child_iterator());
1499 }
1500 const_child_range children() const {
1501 return const_child_range(const_child_iterator(), const_child_iterator());
1502 }
1503};
1504
1505class CharacterLiteral : public Expr {
1506public:
1507 enum CharacterKind {
1508 Ascii,
1509 Wide,
1510 UTF8,
1511 UTF16,
1512 UTF32
1513 };
1514
1515private:
1516 unsigned Value;
1517 SourceLocation Loc;
1518public:
1519 // type should be IntTy
1520 CharacterLiteral(unsigned value, CharacterKind kind, QualType type,
1521 SourceLocation l)
1522 : Expr(CharacterLiteralClass, type, VK_RValue, OK_Ordinary, false, false,
1523 false, false),
1524 Value(value), Loc(l) {
1525 CharacterLiteralBits.Kind = kind;
1526 }
1527
1528 /// Construct an empty character literal.
1529 CharacterLiteral(EmptyShell Empty) : Expr(CharacterLiteralClass, Empty) { }
1530
1531 SourceLocation getLocation() const { return Loc; }
1532 CharacterKind getKind() const {
1533 return static_cast<CharacterKind>(CharacterLiteralBits.Kind);
1534 }
1535
1536 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1537 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1538
1539 unsigned getValue() const { return Value; }
1540
1541 void setLocation(SourceLocation Location) { Loc = Location; }
1542 void setKind(CharacterKind kind) { CharacterLiteralBits.Kind = kind; }
1543 void setValue(unsigned Val) { Value = Val; }
1544
1545 static bool classof(const Stmt *T) {
1546 return T->getStmtClass() == CharacterLiteralClass;
1547 }
1548
1549 // Iterators
1550 child_range children() {
1551 return child_range(child_iterator(), child_iterator());
1552 }
1553 const_child_range children() const {
1554 return const_child_range(const_child_iterator(), const_child_iterator());
1555 }
1556};
1557
1558class FloatingLiteral : public Expr, private APFloatStorage {
1559 SourceLocation Loc;
1560
1561 FloatingLiteral(const ASTContext &C, const llvm::APFloat &V, bool isexact,
1562 QualType Type, SourceLocation L);
1563
1564 /// Construct an empty floating-point literal.
1565 explicit FloatingLiteral(const ASTContext &C, EmptyShell Empty);
1566
1567public:
1568 static FloatingLiteral *Create(const ASTContext &C, const llvm::APFloat &V,
1569 bool isexact, QualType Type, SourceLocation L);
1570 static FloatingLiteral *Create(const ASTContext &C, EmptyShell Empty);
1571
1572 llvm::APFloat getValue() const {
1573 return APFloatStorage::getValue(getSemantics());
1574 }
1575 void setValue(const ASTContext &C, const llvm::APFloat &Val) {
1576 assert(&getSemantics() == &Val.getSemantics() && "Inconsistent semantics")((&getSemantics() == &Val.getSemantics() && "Inconsistent semantics"
) ? static_cast<void> (0) : __assert_fail ("&getSemantics() == &Val.getSemantics() && \"Inconsistent semantics\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 1576, __PRETTY_FUNCTION__))
;
1577 APFloatStorage::setValue(C, Val);
1578 }
1579
1580 /// Get a raw enumeration value representing the floating-point semantics of
1581 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1582 llvm::APFloatBase::Semantics getRawSemantics() const {
1583 return static_cast<llvm::APFloatBase::Semantics>(
1584 FloatingLiteralBits.Semantics);
1585 }
1586
1587 /// Set the raw enumeration value representing the floating-point semantics of
1588 /// this literal (32-bit IEEE, x87, ...), suitable for serialisation.
1589 void setRawSemantics(llvm::APFloatBase::Semantics Sem) {
1590 FloatingLiteralBits.Semantics = Sem;
1591 }
1592
1593 /// Return the APFloat semantics this literal uses.
1594 const llvm::fltSemantics &getSemantics() const {
1595 return llvm::APFloatBase::EnumToSemantics(
1596 static_cast<llvm::APFloatBase::Semantics>(
1597 FloatingLiteralBits.Semantics));
1598 }
1599
1600 /// Set the APFloat semantics this literal uses.
1601 void setSemantics(const llvm::fltSemantics &Sem) {
1602 FloatingLiteralBits.Semantics = llvm::APFloatBase::SemanticsToEnum(Sem);
1603 }
1604
1605 bool isExact() const { return FloatingLiteralBits.IsExact; }
1606 void setExact(bool E) { FloatingLiteralBits.IsExact = E; }
1607
1608 /// getValueAsApproximateDouble - This returns the value as an inaccurate
1609 /// double. Note that this may cause loss of precision, but is useful for
1610 /// debugging dumps, etc.
1611 double getValueAsApproximateDouble() const;
1612
1613 SourceLocation getLocation() const { return Loc; }
1614 void setLocation(SourceLocation L) { Loc = L; }
1615
1616 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1617 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Loc; }
1618
1619 static bool classof(const Stmt *T) {
1620 return T->getStmtClass() == FloatingLiteralClass;
1621 }
1622
1623 // Iterators
1624 child_range children() {
1625 return child_range(child_iterator(), child_iterator());
1626 }
1627 const_child_range children() const {
1628 return const_child_range(const_child_iterator(), const_child_iterator());
1629 }
1630};
1631
1632/// ImaginaryLiteral - We support imaginary integer and floating point literals,
1633/// like "1.0i". We represent these as a wrapper around FloatingLiteral and
1634/// IntegerLiteral classes. Instances of this class always have a Complex type
1635/// whose element type matches the subexpression.
1636///
1637class ImaginaryLiteral : public Expr {
1638 Stmt *Val;
1639public:
1640 ImaginaryLiteral(Expr *val, QualType Ty)
1641 : Expr(ImaginaryLiteralClass, Ty, VK_RValue, OK_Ordinary, false, false,
1642 false, false),
1643 Val(val) {}
1644
1645 /// Build an empty imaginary literal.
1646 explicit ImaginaryLiteral(EmptyShell Empty)
1647 : Expr(ImaginaryLiteralClass, Empty) { }
1648
1649 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1650 Expr *getSubExpr() { return cast<Expr>(Val); }
1651 void setSubExpr(Expr *E) { Val = E; }
1652
1653 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
1654 return Val->getBeginLoc();
1655 }
1656 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Val->getEndLoc(); }
1657
1658 static bool classof(const Stmt *T) {
1659 return T->getStmtClass() == ImaginaryLiteralClass;
1660 }
1661
1662 // Iterators
1663 child_range children() { return child_range(&Val, &Val+1); }
1664 const_child_range children() const {
1665 return const_child_range(&Val, &Val + 1);
1666 }
1667};
1668
1669/// StringLiteral - This represents a string literal expression, e.g. "foo"
1670/// or L"bar" (wide strings). The actual string data can be obtained with
1671/// getBytes() and is NOT null-terminated. The length of the string data is
1672/// determined by calling getByteLength().
1673///
1674/// The C type for a string is always a ConstantArrayType. In C++, the char
1675/// type is const qualified, in C it is not.
1676///
1677/// Note that strings in C can be formed by concatenation of multiple string
1678/// literal pptokens in translation phase #6. This keeps track of the locations
1679/// of each of these pieces.
1680///
1681/// Strings in C can also be truncated and extended by assigning into arrays,
1682/// e.g. with constructs like:
1683/// char X[2] = "foobar";
1684/// In this case, getByteLength() will return 6, but the string literal will
1685/// have type "char[2]".
1686class StringLiteral final
1687 : public Expr,
1688 private llvm::TrailingObjects<StringLiteral, unsigned, SourceLocation,
1689 char> {
1690 friend class ASTStmtReader;
1691 friend TrailingObjects;
1692
1693 /// StringLiteral is followed by several trailing objects. They are in order:
1694 ///
1695 /// * A single unsigned storing the length in characters of this string. The
1696 /// length in bytes is this length times the width of a single character.
1697 /// Always present and stored as a trailing objects because storing it in
1698 /// StringLiteral would increase the size of StringLiteral by sizeof(void *)
1699 /// due to alignment requirements. If you add some data to StringLiteral,
1700 /// consider moving it inside StringLiteral.
1701 ///
1702 /// * An array of getNumConcatenated() SourceLocation, one for each of the
1703 /// token this string is made of.
1704 ///
1705 /// * An array of getByteLength() char used to store the string data.
1706
1707public:
1708 enum StringKind { Ascii, Wide, UTF8, UTF16, UTF32 };
1709
1710private:
1711 unsigned numTrailingObjects(OverloadToken<unsigned>) const { return 1; }
1712 unsigned numTrailingObjects(OverloadToken<SourceLocation>) const {
1713 return getNumConcatenated();
1714 }
1715
1716 unsigned numTrailingObjects(OverloadToken<char>) const {
1717 return getByteLength();
1718 }
1719
1720 char *getStrDataAsChar() { return getTrailingObjects<char>(); }
1721 const char *getStrDataAsChar() const { return getTrailingObjects<char>(); }
1722
1723 const uint16_t *getStrDataAsUInt16() const {
1724 return reinterpret_cast<const uint16_t *>(getTrailingObjects<char>());
1725 }
1726
1727 const uint32_t *getStrDataAsUInt32() const {
1728 return reinterpret_cast<const uint32_t *>(getTrailingObjects<char>());
1729 }
1730
1731 /// Build a string literal.
1732 StringLiteral(const ASTContext &Ctx, StringRef Str, StringKind Kind,
1733 bool Pascal, QualType Ty, const SourceLocation *Loc,
1734 unsigned NumConcatenated);
1735
1736 /// Build an empty string literal.
1737 StringLiteral(EmptyShell Empty, unsigned NumConcatenated, unsigned Length,
1738 unsigned CharByteWidth);
1739
1740 /// Map a target and string kind to the appropriate character width.
1741 static unsigned mapCharByteWidth(TargetInfo const &Target, StringKind SK);
1742
1743 /// Set one of the string literal token.
1744 void setStrTokenLoc(unsigned TokNum, SourceLocation L) {
1745 assert(TokNum < getNumConcatenated() && "Invalid tok number")((TokNum < getNumConcatenated() && "Invalid tok number"
) ? static_cast<void> (0) : __assert_fail ("TokNum < getNumConcatenated() && \"Invalid tok number\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 1745, __PRETTY_FUNCTION__))
;
1746 getTrailingObjects<SourceLocation>()[TokNum] = L;
1747 }
1748
1749public:
1750 /// This is the "fully general" constructor that allows representation of
1751 /// strings formed from multiple concatenated tokens.
1752 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1753 StringKind Kind, bool Pascal, QualType Ty,
1754 const SourceLocation *Loc,
1755 unsigned NumConcatenated);
1756
1757 /// Simple constructor for string literals made from one token.
1758 static StringLiteral *Create(const ASTContext &Ctx, StringRef Str,
1759 StringKind Kind, bool Pascal, QualType Ty,
1760 SourceLocation Loc) {
1761 return Create(Ctx, Str, Kind, Pascal, Ty, &Loc, 1);
1762 }
1763
1764 /// Construct an empty string literal.
1765 static StringLiteral *CreateEmpty(const ASTContext &Ctx,
1766 unsigned NumConcatenated, unsigned Length,
1767 unsigned CharByteWidth);
1768
1769 StringRef getString() const {
1770 assert(getCharByteWidth() == 1 &&((getCharByteWidth() == 1 && "This function is used in places that assume strings use char"
) ? static_cast<void> (0) : __assert_fail ("getCharByteWidth() == 1 && \"This function is used in places that assume strings use char\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 1771, __PRETTY_FUNCTION__))
1771 "This function is used in places that assume strings use char")((getCharByteWidth() == 1 && "This function is used in places that assume strings use char"
) ? static_cast<void> (0) : __assert_fail ("getCharByteWidth() == 1 && \"This function is used in places that assume strings use char\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 1771, __PRETTY_FUNCTION__))
;
1772 return StringRef(getStrDataAsChar(), getByteLength());
1773 }
1774
1775 /// Allow access to clients that need the byte representation, such as
1776 /// ASTWriterStmt::VisitStringLiteral().
1777 StringRef getBytes() const {
1778 // FIXME: StringRef may not be the right type to use as a result for this.
1779 return StringRef(getStrDataAsChar(), getByteLength());
1780 }
1781
1782 void outputString(raw_ostream &OS) const;
1783
1784 uint32_t getCodeUnit(size_t i) const {
1785 assert(i < getLength() && "out of bounds access")((i < getLength() && "out of bounds access") ? static_cast
<void> (0) : __assert_fail ("i < getLength() && \"out of bounds access\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 1785, __PRETTY_FUNCTION__))
;
1786 switch (getCharByteWidth()) {
1787 case 1:
1788 return static_cast<unsigned char>(getStrDataAsChar()[i]);
1789 case 2:
1790 return getStrDataAsUInt16()[i];
1791 case 4:
1792 return getStrDataAsUInt32()[i];
1793 }
1794 llvm_unreachable("Unsupported character width!")::llvm::llvm_unreachable_internal("Unsupported character width!"
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 1794)
;
1795 }
1796
1797 unsigned getByteLength() const { return getCharByteWidth() * getLength(); }
1798 unsigned getLength() const { return *getTrailingObjects<unsigned>(); }
1799 unsigned getCharByteWidth() const { return StringLiteralBits.CharByteWidth; }
1800
1801 StringKind getKind() const {
1802 return static_cast<StringKind>(StringLiteralBits.Kind);
1803 }
1804
1805 bool isAscii() const { return getKind() == Ascii; }
1806 bool isWide() const { return getKind() == Wide; }
1807 bool isUTF8() const { return getKind() == UTF8; }
1808 bool isUTF16() const { return getKind() == UTF16; }
1809 bool isUTF32() const { return getKind() == UTF32; }
1810 bool isPascal() const { return StringLiteralBits.IsPascal; }
1811
1812 bool containsNonAscii() const {
1813 for (auto c : getString())
1814 if (!isASCII(c))
1815 return true;
1816 return false;
1817 }
1818
1819 bool containsNonAsciiOrNull() const {
1820 for (auto c : getString())
1821 if (!isASCII(c) || !c)
1822 return true;
1823 return false;
1824 }
1825
1826 /// getNumConcatenated - Get the number of string literal tokens that were
1827 /// concatenated in translation phase #6 to form this string literal.
1828 unsigned getNumConcatenated() const {
1829 return StringLiteralBits.NumConcatenated;
1830 }
1831
1832 /// Get one of the string literal token.
1833 SourceLocation getStrTokenLoc(unsigned TokNum) const {
1834 assert(TokNum < getNumConcatenated() && "Invalid tok number")((TokNum < getNumConcatenated() && "Invalid tok number"
) ? static_cast<void> (0) : __assert_fail ("TokNum < getNumConcatenated() && \"Invalid tok number\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 1834, __PRETTY_FUNCTION__))
;
1835 return getTrailingObjects<SourceLocation>()[TokNum];
1836 }
1837
1838 /// getLocationOfByte - Return a source location that points to the specified
1839 /// byte of this string literal.
1840 ///
1841 /// Strings are amazingly complex. They can be formed from multiple tokens
1842 /// and can have escape sequences in them in addition to the usual trigraph
1843 /// and escaped newline business. This routine handles this complexity.
1844 ///
1845 SourceLocation
1846 getLocationOfByte(unsigned ByteNo, const SourceManager &SM,
1847 const LangOptions &Features, const TargetInfo &Target,
1848 unsigned *StartToken = nullptr,
1849 unsigned *StartTokenByteOffset = nullptr) const;
1850
1851 typedef const SourceLocation *tokloc_iterator;
1852
1853 tokloc_iterator tokloc_begin() const {
1854 return getTrailingObjects<SourceLocation>();
1855 }
1856
1857 tokloc_iterator tokloc_end() const {
1858 return getTrailingObjects<SourceLocation>() + getNumConcatenated();
1859 }
1860
1861 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return *tokloc_begin(); }
1862 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return *(tokloc_end() - 1); }
1863
1864 static bool classof(const Stmt *T) {
1865 return T->getStmtClass() == StringLiteralClass;
1866 }
1867
1868 // Iterators
1869 child_range children() {
1870 return child_range(child_iterator(), child_iterator());
1871 }
1872 const_child_range children() const {
1873 return const_child_range(const_child_iterator(), const_child_iterator());
1874 }
1875};
1876
1877/// [C99 6.4.2.2] - A predefined identifier such as __func__.
1878class PredefinedExpr final
1879 : public Expr,
1880 private llvm::TrailingObjects<PredefinedExpr, Stmt *> {
1881 friend class ASTStmtReader;
1882 friend TrailingObjects;
1883
1884 // PredefinedExpr is optionally followed by a single trailing
1885 // "Stmt *" for the predefined identifier. It is present if and only if
1886 // hasFunctionName() is true and is always a "StringLiteral *".
1887
1888public:
1889 enum IdentKind {
1890 Func,
1891 Function,
1892 LFunction, // Same as Function, but as wide string.
1893 FuncDName,
1894 FuncSig,
1895 LFuncSig, // Same as FuncSig, but as as wide string
1896 PrettyFunction,
1897 /// The same as PrettyFunction, except that the
1898 /// 'virtual' keyword is omitted for virtual member functions.
1899 PrettyFunctionNoVirtual
1900 };
1901
1902private:
1903 PredefinedExpr(SourceLocation L, QualType FNTy, IdentKind IK,
1904 StringLiteral *SL);
1905
1906 explicit PredefinedExpr(EmptyShell Empty, bool HasFunctionName);
1907
1908 /// True if this PredefinedExpr has storage for a function name.
1909 bool hasFunctionName() const { return PredefinedExprBits.HasFunctionName; }
1910
1911 void setFunctionName(StringLiteral *SL) {
1912 assert(hasFunctionName() &&((hasFunctionName() && "This PredefinedExpr has no storage for a function name!"
) ? static_cast<void> (0) : __assert_fail ("hasFunctionName() && \"This PredefinedExpr has no storage for a function name!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 1913, __PRETTY_FUNCTION__))
1913 "This PredefinedExpr has no storage for a function name!")((hasFunctionName() && "This PredefinedExpr has no storage for a function name!"
) ? static_cast<void> (0) : __assert_fail ("hasFunctionName() && \"This PredefinedExpr has no storage for a function name!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 1913, __PRETTY_FUNCTION__))
;
1914 *getTrailingObjects<Stmt *>() = SL;
1915 }
1916
1917public:
1918 /// Create a PredefinedExpr.
1919 static PredefinedExpr *Create(const ASTContext &Ctx, SourceLocation L,
1920 QualType FNTy, IdentKind IK, StringLiteral *SL);
1921
1922 /// Create an empty PredefinedExpr.
1923 static PredefinedExpr *CreateEmpty(const ASTContext &Ctx,
1924 bool HasFunctionName);
1925
1926 IdentKind getIdentKind() const {
1927 return static_cast<IdentKind>(PredefinedExprBits.Kind);
1928 }
1929
1930 SourceLocation getLocation() const { return PredefinedExprBits.Loc; }
1931 void setLocation(SourceLocation L) { PredefinedExprBits.Loc = L; }
1932
1933 StringLiteral *getFunctionName() {
1934 return hasFunctionName()
1935 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
1936 : nullptr;
1937 }
1938
1939 const StringLiteral *getFunctionName() const {
1940 return hasFunctionName()
1941 ? static_cast<StringLiteral *>(*getTrailingObjects<Stmt *>())
1942 : nullptr;
1943 }
1944
1945 static StringRef getIdentKindName(IdentKind IK);
1946 static std::string ComputeName(IdentKind IK, const Decl *CurrentDecl);
1947
1948 SourceLocation getBeginLoc() const { return getLocation(); }
1949 SourceLocation getEndLoc() const { return getLocation(); }
1950
1951 static bool classof(const Stmt *T) {
1952 return T->getStmtClass() == PredefinedExprClass;
1953 }
1954
1955 // Iterators
1956 child_range children() {
1957 return child_range(getTrailingObjects<Stmt *>(),
1958 getTrailingObjects<Stmt *>() + hasFunctionName());
1959 }
1960
1961 const_child_range children() const {
1962 return const_child_range(getTrailingObjects<Stmt *>(),
1963 getTrailingObjects<Stmt *>() + hasFunctionName());
1964 }
1965};
1966
1967/// ParenExpr - This represents a parethesized expression, e.g. "(1)". This
1968/// AST node is only formed if full location information is requested.
1969class ParenExpr : public Expr {
1970 SourceLocation L, R;
1971 Stmt *Val;
1972public:
1973 ParenExpr(SourceLocation l, SourceLocation r, Expr *val)
1974 : Expr(ParenExprClass, val->getType(),
1975 val->getValueKind(), val->getObjectKind(),
1976 val->isTypeDependent(), val->isValueDependent(),
1977 val->isInstantiationDependent(),
1978 val->containsUnexpandedParameterPack()),
1979 L(l), R(r), Val(val) {}
1980
1981 /// Construct an empty parenthesized expression.
1982 explicit ParenExpr(EmptyShell Empty)
1983 : Expr(ParenExprClass, Empty) { }
1984
1985 const Expr *getSubExpr() const { return cast<Expr>(Val); }
1986 Expr *getSubExpr() { return cast<Expr>(Val); }
1987 void setSubExpr(Expr *E) { Val = E; }
1988
1989 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return L; }
1990 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return R; }
1991
1992 /// Get the location of the left parentheses '('.
1993 SourceLocation getLParen() const { return L; }
1994 void setLParen(SourceLocation Loc) { L = Loc; }
1995
1996 /// Get the location of the right parentheses ')'.
1997 SourceLocation getRParen() const { return R; }
1998 void setRParen(SourceLocation Loc) { R = Loc; }
1999
2000 static bool classof(const Stmt *T) {
2001 return T->getStmtClass() == ParenExprClass;
2002 }
2003
2004 // Iterators
2005 child_range children() { return child_range(&Val, &Val+1); }
2006 const_child_range children() const {
2007 return const_child_range(&Val, &Val + 1);
2008 }
2009};
2010
2011/// UnaryOperator - This represents the unary-expression's (except sizeof and
2012/// alignof), the postinc/postdec operators from postfix-expression, and various
2013/// extensions.
2014///
2015/// Notes on various nodes:
2016///
2017/// Real/Imag - These return the real/imag part of a complex operand. If
2018/// applied to a non-complex value, the former returns its operand and the
2019/// later returns zero in the type of the operand.
2020///
2021class UnaryOperator : public Expr {
2022 Stmt *Val;
2023
2024public:
2025 typedef UnaryOperatorKind Opcode;
2026
2027 UnaryOperator(Expr *input, Opcode opc, QualType type, ExprValueKind VK,
2028 ExprObjectKind OK, SourceLocation l, bool CanOverflow)
2029 : Expr(UnaryOperatorClass, type, VK, OK,
2030 input->isTypeDependent() || type->isDependentType(),
2031 input->isValueDependent(),
2032 (input->isInstantiationDependent() ||
2033 type->isInstantiationDependentType()),
2034 input->containsUnexpandedParameterPack()),
2035 Val(input) {
2036 UnaryOperatorBits.Opc = opc;
2037 UnaryOperatorBits.CanOverflow = CanOverflow;
2038 UnaryOperatorBits.Loc = l;
2039 }
2040
2041 /// Build an empty unary operator.
2042 explicit UnaryOperator(EmptyShell Empty) : Expr(UnaryOperatorClass, Empty) {
2043 UnaryOperatorBits.Opc = UO_AddrOf;
2044 }
2045
2046 Opcode getOpcode() const {
2047 return static_cast<Opcode>(UnaryOperatorBits.Opc);
2048 }
2049 void setOpcode(Opcode Opc) { UnaryOperatorBits.Opc = Opc; }
2050
2051 Expr *getSubExpr() const { return cast<Expr>(Val); }
2052 void setSubExpr(Expr *E) { Val = E; }
2053
2054 /// getOperatorLoc - Return the location of the operator.
2055 SourceLocation getOperatorLoc() const { return UnaryOperatorBits.Loc; }
2056 void setOperatorLoc(SourceLocation L) { UnaryOperatorBits.Loc = L; }
2057
2058 /// Returns true if the unary operator can cause an overflow. For instance,
2059 /// signed int i = INT_MAX; i++;
2060 /// signed char c = CHAR_MAX; c++;
2061 /// Due to integer promotions, c++ is promoted to an int before the postfix
2062 /// increment, and the result is an int that cannot overflow. However, i++
2063 /// can overflow.
2064 bool canOverflow() const { return UnaryOperatorBits.CanOverflow; }
2065 void setCanOverflow(bool C) { UnaryOperatorBits.CanOverflow = C; }
2066
2067 /// isPostfix - Return true if this is a postfix operation, like x++.
2068 static bool isPostfix(Opcode Op) {
2069 return Op == UO_PostInc || Op == UO_PostDec;
2070 }
2071
2072 /// isPrefix - Return true if this is a prefix operation, like --x.
2073 static bool isPrefix(Opcode Op) {
2074 return Op == UO_PreInc || Op == UO_PreDec;
2075 }
2076
2077 bool isPrefix() const { return isPrefix(getOpcode()); }
2078 bool isPostfix() const { return isPostfix(getOpcode()); }
2079
2080 static bool isIncrementOp(Opcode Op) {
2081 return Op == UO_PreInc || Op == UO_PostInc;
2082 }
2083 bool isIncrementOp() const {
2084 return isIncrementOp(getOpcode());
2085 }
2086
2087 static bool isDecrementOp(Opcode Op) {
2088 return Op == UO_PreDec || Op == UO_PostDec;
2089 }
2090 bool isDecrementOp() const {
2091 return isDecrementOp(getOpcode());
2092 }
2093
2094 static bool isIncrementDecrementOp(Opcode Op) { return Op <= UO_PreDec; }
2095 bool isIncrementDecrementOp() const {
2096 return isIncrementDecrementOp(getOpcode());
2097 }
2098
2099 static bool isArithmeticOp(Opcode Op) {
2100 return Op >= UO_Plus && Op <= UO_LNot;
2101 }
2102 bool isArithmeticOp() const { return isArithmeticOp(getOpcode()); }
2103
2104 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
2105 /// corresponds to, e.g. "sizeof" or "[pre]++"
2106 static StringRef getOpcodeStr(Opcode Op);
2107
2108 /// Retrieve the unary opcode that corresponds to the given
2109 /// overloaded operator.
2110 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO, bool Postfix);
2111
2112 /// Retrieve the overloaded operator kind that corresponds to
2113 /// the given unary opcode.
2114 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
2115
2116 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
2117 return isPostfix() ? Val->getBeginLoc() : getOperatorLoc();
2118 }
2119 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
2120 return isPostfix() ? getOperatorLoc() : Val->getEndLoc();
2121 }
2122 SourceLocation getExprLoc() const { return getOperatorLoc(); }
2123
2124 static bool classof(const Stmt *T) {
2125 return T->getStmtClass() == UnaryOperatorClass;
2126 }
2127
2128 // Iterators
2129 child_range children() { return child_range(&Val, &Val+1); }
2130 const_child_range children() const {
2131 return const_child_range(&Val, &Val + 1);
2132 }
2133};
2134
2135/// Helper class for OffsetOfExpr.
2136
2137// __builtin_offsetof(type, identifier(.identifier|[expr])*)
2138class OffsetOfNode {
2139public:
2140 /// The kind of offsetof node we have.
2141 enum Kind {
2142 /// An index into an array.
2143 Array = 0x00,
2144 /// A field.
2145 Field = 0x01,
2146 /// A field in a dependent type, known only by its name.
2147 Identifier = 0x02,
2148 /// An implicit indirection through a C++ base class, when the
2149 /// field found is in a base class.
2150 Base = 0x03
2151 };
2152
2153private:
2154 enum { MaskBits = 2, Mask = 0x03 };
2155
2156 /// The source range that covers this part of the designator.
2157 SourceRange Range;
2158
2159 /// The data describing the designator, which comes in three
2160 /// different forms, depending on the lower two bits.
2161 /// - An unsigned index into the array of Expr*'s stored after this node
2162 /// in memory, for [constant-expression] designators.
2163 /// - A FieldDecl*, for references to a known field.
2164 /// - An IdentifierInfo*, for references to a field with a given name
2165 /// when the class type is dependent.
2166 /// - A CXXBaseSpecifier*, for references that look at a field in a
2167 /// base class.
2168 uintptr_t Data;
2169
2170public:
2171 /// Create an offsetof node that refers to an array element.
2172 OffsetOfNode(SourceLocation LBracketLoc, unsigned Index,
2173 SourceLocation RBracketLoc)
2174 : Range(LBracketLoc, RBracketLoc), Data((Index << 2) | Array) {}
2175
2176 /// Create an offsetof node that refers to a field.
2177 OffsetOfNode(SourceLocation DotLoc, FieldDecl *Field, SourceLocation NameLoc)
2178 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2179 Data(reinterpret_cast<uintptr_t>(Field) | OffsetOfNode::Field) {}
2180
2181 /// Create an offsetof node that refers to an identifier.
2182 OffsetOfNode(SourceLocation DotLoc, IdentifierInfo *Name,
2183 SourceLocation NameLoc)
2184 : Range(DotLoc.isValid() ? DotLoc : NameLoc, NameLoc),
2185 Data(reinterpret_cast<uintptr_t>(Name) | Identifier) {}
2186
2187 /// Create an offsetof node that refers into a C++ base class.
2188 explicit OffsetOfNode(const CXXBaseSpecifier *Base)
2189 : Range(), Data(reinterpret_cast<uintptr_t>(Base) | OffsetOfNode::Base) {}
2190
2191 /// Determine what kind of offsetof node this is.
2192 Kind getKind() const { return static_cast<Kind>(Data & Mask); }
2193
2194 /// For an array element node, returns the index into the array
2195 /// of expressions.
2196 unsigned getArrayExprIndex() const {
2197 assert(getKind() == Array)((getKind() == Array) ? static_cast<void> (0) : __assert_fail
("getKind() == Array", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2197, __PRETTY_FUNCTION__))
;
2198 return Data >> 2;
2199 }
2200
2201 /// For a field offsetof node, returns the field.
2202 FieldDecl *getField() const {
2203 assert(getKind() == Field)((getKind() == Field) ? static_cast<void> (0) : __assert_fail
("getKind() == Field", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2203, __PRETTY_FUNCTION__))
;
2204 return reinterpret_cast<FieldDecl *>(Data & ~(uintptr_t)Mask);
2205 }
2206
2207 /// For a field or identifier offsetof node, returns the name of
2208 /// the field.
2209 IdentifierInfo *getFieldName() const;
2210
2211 /// For a base class node, returns the base specifier.
2212 CXXBaseSpecifier *getBase() const {
2213 assert(getKind() == Base)((getKind() == Base) ? static_cast<void> (0) : __assert_fail
("getKind() == Base", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2213, __PRETTY_FUNCTION__))
;
2214 return reinterpret_cast<CXXBaseSpecifier *>(Data & ~(uintptr_t)Mask);
2215 }
2216
2217 /// Retrieve the source range that covers this offsetof node.
2218 ///
2219 /// For an array element node, the source range contains the locations of
2220 /// the square brackets. For a field or identifier node, the source range
2221 /// contains the location of the period (if there is one) and the
2222 /// identifier.
2223 SourceRange getSourceRange() const LLVM_READONLY__attribute__((__pure__)) { return Range; }
2224 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getBegin(); }
2225 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return Range.getEnd(); }
2226};
2227
2228/// OffsetOfExpr - [C99 7.17] - This represents an expression of the form
2229/// offsetof(record-type, member-designator). For example, given:
2230/// @code
2231/// struct S {
2232/// float f;
2233/// double d;
2234/// };
2235/// struct T {
2236/// int i;
2237/// struct S s[10];
2238/// };
2239/// @endcode
2240/// we can represent and evaluate the expression @c offsetof(struct T, s[2].d).
2241
2242class OffsetOfExpr final
2243 : public Expr,
2244 private llvm::TrailingObjects<OffsetOfExpr, OffsetOfNode, Expr *> {
2245 SourceLocation OperatorLoc, RParenLoc;
2246 // Base type;
2247 TypeSourceInfo *TSInfo;
2248 // Number of sub-components (i.e. instances of OffsetOfNode).
2249 unsigned NumComps;
2250 // Number of sub-expressions (i.e. array subscript expressions).
2251 unsigned NumExprs;
2252
2253 size_t numTrailingObjects(OverloadToken<OffsetOfNode>) const {
2254 return NumComps;
2255 }
2256
2257 OffsetOfExpr(const ASTContext &C, QualType type,
2258 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2259 ArrayRef<OffsetOfNode> comps, ArrayRef<Expr*> exprs,
2260 SourceLocation RParenLoc);
2261
2262 explicit OffsetOfExpr(unsigned numComps, unsigned numExprs)
2263 : Expr(OffsetOfExprClass, EmptyShell()),
2264 TSInfo(nullptr), NumComps(numComps), NumExprs(numExprs) {}
2265
2266public:
2267
2268 static OffsetOfExpr *Create(const ASTContext &C, QualType type,
2269 SourceLocation OperatorLoc, TypeSourceInfo *tsi,
2270 ArrayRef<OffsetOfNode> comps,
2271 ArrayRef<Expr*> exprs, SourceLocation RParenLoc);
2272
2273 static OffsetOfExpr *CreateEmpty(const ASTContext &C,
2274 unsigned NumComps, unsigned NumExprs);
2275
2276 /// getOperatorLoc - Return the location of the operator.
2277 SourceLocation getOperatorLoc() const { return OperatorLoc; }
2278 void setOperatorLoc(SourceLocation L) { OperatorLoc = L; }
2279
2280 /// Return the location of the right parentheses.
2281 SourceLocation getRParenLoc() const { return RParenLoc; }
2282 void setRParenLoc(SourceLocation R) { RParenLoc = R; }
2283
2284 TypeSourceInfo *getTypeSourceInfo() const {
2285 return TSInfo;
2286 }
2287 void setTypeSourceInfo(TypeSourceInfo *tsi) {
2288 TSInfo = tsi;
2289 }
2290
2291 const OffsetOfNode &getComponent(unsigned Idx) const {
2292 assert(Idx < NumComps && "Subscript out of range")((Idx < NumComps && "Subscript out of range") ? static_cast
<void> (0) : __assert_fail ("Idx < NumComps && \"Subscript out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2292, __PRETTY_FUNCTION__))
;
2293 return getTrailingObjects<OffsetOfNode>()[Idx];
2294 }
2295
2296 void setComponent(unsigned Idx, OffsetOfNode ON) {
2297 assert(Idx < NumComps && "Subscript out of range")((Idx < NumComps && "Subscript out of range") ? static_cast
<void> (0) : __assert_fail ("Idx < NumComps && \"Subscript out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2297, __PRETTY_FUNCTION__))
;
2298 getTrailingObjects<OffsetOfNode>()[Idx] = ON;
2299 }
2300
2301 unsigned getNumComponents() const {
2302 return NumComps;
2303 }
2304
2305 Expr* getIndexExpr(unsigned Idx) {
2306 assert(Idx < NumExprs && "Subscript out of range")((Idx < NumExprs && "Subscript out of range") ? static_cast
<void> (0) : __assert_fail ("Idx < NumExprs && \"Subscript out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2306, __PRETTY_FUNCTION__))
;
2307 return getTrailingObjects<Expr *>()[Idx];
2308 }
2309
2310 const Expr *getIndexExpr(unsigned Idx) const {
2311 assert(Idx < NumExprs && "Subscript out of range")((Idx < NumExprs && "Subscript out of range") ? static_cast
<void> (0) : __assert_fail ("Idx < NumExprs && \"Subscript out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2311, __PRETTY_FUNCTION__))
;
2312 return getTrailingObjects<Expr *>()[Idx];
2313 }
2314
2315 void setIndexExpr(unsigned Idx, Expr* E) {
2316 assert(Idx < NumComps && "Subscript out of range")((Idx < NumComps && "Subscript out of range") ? static_cast
<void> (0) : __assert_fail ("Idx < NumComps && \"Subscript out of range\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2316, __PRETTY_FUNCTION__))
;
2317 getTrailingObjects<Expr *>()[Idx] = E;
2318 }
2319
2320 unsigned getNumExpressions() const {
2321 return NumExprs;
2322 }
2323
2324 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return OperatorLoc; }
2325 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
2326
2327 static bool classof(const Stmt *T) {
2328 return T->getStmtClass() == OffsetOfExprClass;
2329 }
2330
2331 // Iterators
2332 child_range children() {
2333 Stmt **begin = reinterpret_cast<Stmt **>(getTrailingObjects<Expr *>());
2334 return child_range(begin, begin + NumExprs);
2335 }
2336 const_child_range children() const {
2337 Stmt *const *begin =
2338 reinterpret_cast<Stmt *const *>(getTrailingObjects<Expr *>());
2339 return const_child_range(begin, begin + NumExprs);
2340 }
2341 friend TrailingObjects;
2342};
2343
2344/// UnaryExprOrTypeTraitExpr - expression with either a type or (unevaluated)
2345/// expression operand. Used for sizeof/alignof (C99 6.5.3.4) and
2346/// vec_step (OpenCL 1.1 6.11.12).
2347class UnaryExprOrTypeTraitExpr : public Expr {
2348 union {
2349 TypeSourceInfo *Ty;
2350 Stmt *Ex;
2351 } Argument;
2352 SourceLocation OpLoc, RParenLoc;
2353
2354public:
2355 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, TypeSourceInfo *TInfo,
2356 QualType resultType, SourceLocation op,
2357 SourceLocation rp) :
2358 Expr(UnaryExprOrTypeTraitExprClass, resultType, VK_RValue, OK_Ordinary,
2359 false, // Never type-dependent (C++ [temp.dep.expr]p3).
2360 // Value-dependent if the argument is type-dependent.
2361 TInfo->getType()->isDependentType(),
2362 TInfo->getType()->isInstantiationDependentType(),
2363 TInfo->getType()->containsUnexpandedParameterPack()),
2364 OpLoc(op), RParenLoc(rp) {
2365 UnaryExprOrTypeTraitExprBits.Kind = ExprKind;
2366 UnaryExprOrTypeTraitExprBits.IsType = true;
2367 Argument.Ty = TInfo;
2368 }
2369
2370 UnaryExprOrTypeTraitExpr(UnaryExprOrTypeTrait ExprKind, Expr *E,
2371 QualType resultType, SourceLocation op,
2372 SourceLocation rp);
2373
2374 /// Construct an empty sizeof/alignof expression.
2375 explicit UnaryExprOrTypeTraitExpr(EmptyShell Empty)
2376 : Expr(UnaryExprOrTypeTraitExprClass, Empty) { }
2377
2378 UnaryExprOrTypeTrait getKind() const {
2379 return static_cast<UnaryExprOrTypeTrait>(UnaryExprOrTypeTraitExprBits.Kind);
2380 }
2381 void setKind(UnaryExprOrTypeTrait K) { UnaryExprOrTypeTraitExprBits.Kind = K;}
2382
2383 bool isArgumentType() const { return UnaryExprOrTypeTraitExprBits.IsType; }
2384 QualType getArgumentType() const {
2385 return getArgumentTypeInfo()->getType();
2386 }
2387 TypeSourceInfo *getArgumentTypeInfo() const {
2388 assert(isArgumentType() && "calling getArgumentType() when arg is expr")((isArgumentType() && "calling getArgumentType() when arg is expr"
) ? static_cast<void> (0) : __assert_fail ("isArgumentType() && \"calling getArgumentType() when arg is expr\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2388, __PRETTY_FUNCTION__))
;
2389 return Argument.Ty;
2390 }
2391 Expr *getArgumentExpr() {
2392 assert(!isArgumentType() && "calling getArgumentExpr() when arg is type")((!isArgumentType() && "calling getArgumentExpr() when arg is type"
) ? static_cast<void> (0) : __assert_fail ("!isArgumentType() && \"calling getArgumentExpr() when arg is type\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2392, __PRETTY_FUNCTION__))
;
2393 return static_cast<Expr*>(Argument.Ex);
2394 }
2395 const Expr *getArgumentExpr() const {
2396 return const_cast<UnaryExprOrTypeTraitExpr*>(this)->getArgumentExpr();
2397 }
2398
2399 void setArgument(Expr *E) {
2400 Argument.Ex = E;
2401 UnaryExprOrTypeTraitExprBits.IsType = false;
2402 }
2403 void setArgument(TypeSourceInfo *TInfo) {
2404 Argument.Ty = TInfo;
2405 UnaryExprOrTypeTraitExprBits.IsType = true;
2406 }
2407
2408 /// Gets the argument type, or the type of the argument expression, whichever
2409 /// is appropriate.
2410 QualType getTypeOfArgument() const {
2411 return isArgumentType() ? getArgumentType() : getArgumentExpr()->getType();
2412 }
2413
2414 SourceLocation getOperatorLoc() const { return OpLoc; }
2415 void setOperatorLoc(SourceLocation L) { OpLoc = L; }
2416
2417 SourceLocation getRParenLoc() const { return RParenLoc; }
2418 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2419
2420 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return OpLoc; }
2421 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) { return RParenLoc; }
2422
2423 static bool classof(const Stmt *T) {
2424 return T->getStmtClass() == UnaryExprOrTypeTraitExprClass;
2425 }
2426
2427 // Iterators
2428 child_range children();
2429 const_child_range children() const;
2430};
2431
2432//===----------------------------------------------------------------------===//
2433// Postfix Operators.
2434//===----------------------------------------------------------------------===//
2435
2436/// ArraySubscriptExpr - [C99 6.5.2.1] Array Subscripting.
2437class ArraySubscriptExpr : public Expr {
2438 enum { LHS, RHS, END_EXPR };
2439 Stmt *SubExprs[END_EXPR];
2440
2441 bool lhsIsBase() const { return getRHS()->getType()->isIntegerType(); }
2442
2443public:
2444 ArraySubscriptExpr(Expr *lhs, Expr *rhs, QualType t,
2445 ExprValueKind VK, ExprObjectKind OK,
2446 SourceLocation rbracketloc)
2447 : Expr(ArraySubscriptExprClass, t, VK, OK,
2448 lhs->isTypeDependent() || rhs->isTypeDependent(),
2449 lhs->isValueDependent() || rhs->isValueDependent(),
2450 (lhs->isInstantiationDependent() ||
2451 rhs->isInstantiationDependent()),
2452 (lhs->containsUnexpandedParameterPack() ||
2453 rhs->containsUnexpandedParameterPack())) {
2454 SubExprs[LHS] = lhs;
2455 SubExprs[RHS] = rhs;
2456 ArraySubscriptExprBits.RBracketLoc = rbracketloc;
2457 }
2458
2459 /// Create an empty array subscript expression.
2460 explicit ArraySubscriptExpr(EmptyShell Shell)
2461 : Expr(ArraySubscriptExprClass, Shell) { }
2462
2463 /// An array access can be written A[4] or 4[A] (both are equivalent).
2464 /// - getBase() and getIdx() always present the normalized view: A[4].
2465 /// In this case getBase() returns "A" and getIdx() returns "4".
2466 /// - getLHS() and getRHS() present the syntactic view. e.g. for
2467 /// 4[A] getLHS() returns "4".
2468 /// Note: Because vector element access is also written A[4] we must
2469 /// predicate the format conversion in getBase and getIdx only on the
2470 /// the type of the RHS, as it is possible for the LHS to be a vector of
2471 /// integer type
2472 Expr *getLHS() { return cast<Expr>(SubExprs[LHS]); }
2473 const Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
2474 void setLHS(Expr *E) { SubExprs[LHS] = E; }
2475
2476 Expr *getRHS() { return cast<Expr>(SubExprs[RHS]); }
2477 const Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
2478 void setRHS(Expr *E) { SubExprs[RHS] = E; }
2479
2480 Expr *getBase() { return lhsIsBase() ? getLHS() : getRHS(); }
2481 const Expr *getBase() const { return lhsIsBase() ? getLHS() : getRHS(); }
2482
2483 Expr *getIdx() { return lhsIsBase() ? getRHS() : getLHS(); }
2484 const Expr *getIdx() const { return lhsIsBase() ? getRHS() : getLHS(); }
2485
2486 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
2487 return getLHS()->getBeginLoc();
2488 }
2489 SourceLocation getEndLoc() const { return getRBracketLoc(); }
2490
2491 SourceLocation getRBracketLoc() const {
2492 return ArraySubscriptExprBits.RBracketLoc;
2493 }
2494 void setRBracketLoc(SourceLocation L) {
2495 ArraySubscriptExprBits.RBracketLoc = L;
2496 }
2497
2498 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) {
2499 return getBase()->getExprLoc();
2500 }
2501
2502 static bool classof(const Stmt *T) {
2503 return T->getStmtClass() == ArraySubscriptExprClass;
2504 }
2505
2506 // Iterators
2507 child_range children() {
2508 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
2509 }
2510 const_child_range children() const {
2511 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
2512 }
2513};
2514
2515/// CallExpr - Represents a function call (C99 6.5.2.2, C++ [expr.call]).
2516/// CallExpr itself represents a normal function call, e.g., "f(x, 2)",
2517/// while its subclasses may represent alternative syntax that (semantically)
2518/// results in a function call. For example, CXXOperatorCallExpr is
2519/// a subclass for overloaded operator calls that use operator syntax, e.g.,
2520/// "str1 + str2" to resolve to a function call.
2521class CallExpr : public Expr {
2522 enum { FN = 0, PREARGS_START = 1 };
2523
2524 /// The number of arguments in the call expression.
2525 unsigned NumArgs;
2526
2527 /// The location of the right parenthese. This has a different meaning for
2528 /// the derived classes of CallExpr.
2529 SourceLocation RParenLoc;
2530
2531 void updateDependenciesFromArg(Expr *Arg);
2532
2533 // CallExpr store some data in trailing objects. However since CallExpr
2534 // is used a base of other expression classes we cannot use
2535 // llvm::TrailingObjects. Instead we manually perform the pointer arithmetic
2536 // and casts.
2537 //
2538 // The trailing objects are in order:
2539 //
2540 // * A single "Stmt *" for the callee expression.
2541 //
2542 // * An array of getNumPreArgs() "Stmt *" for the pre-argument expressions.
2543 //
2544 // * An array of getNumArgs() "Stmt *" for the argument expressions.
2545 //
2546 // Note that we store the offset in bytes from the this pointer to the start
2547 // of the trailing objects. It would be perfectly possible to compute it
2548 // based on the dynamic kind of the CallExpr. However 1.) we have plenty of
2549 // space in the bit-fields of Stmt. 2.) It was benchmarked to be faster to
2550 // compute this once and then load the offset from the bit-fields of Stmt,
2551 // instead of re-computing the offset each time the trailing objects are
2552 // accessed.
2553
2554 /// Return a pointer to the start of the trailing array of "Stmt *".
2555 Stmt **getTrailingStmts() {
2556 return reinterpret_cast<Stmt **>(reinterpret_cast<char *>(this) +
2557 CallExprBits.OffsetToTrailingObjects);
2558 }
2559 Stmt *const *getTrailingStmts() const {
2560 return const_cast<CallExpr *>(this)->getTrailingStmts();
2561 }
2562
2563 /// Map a statement class to the appropriate offset in bytes from the
2564 /// this pointer to the trailing objects.
2565 static unsigned offsetToTrailingObjects(StmtClass SC);
2566
2567public:
2568 enum class ADLCallKind : bool { NotADL, UsesADL };
2569 static constexpr ADLCallKind NotADL = ADLCallKind::NotADL;
2570 static constexpr ADLCallKind UsesADL = ADLCallKind::UsesADL;
2571
2572protected:
2573 /// Build a call expression, assuming that appropriate storage has been
2574 /// allocated for the trailing objects.
2575 CallExpr(StmtClass SC, Expr *Fn, ArrayRef<Expr *> PreArgs,
2576 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
2577 SourceLocation RParenLoc, unsigned MinNumArgs, ADLCallKind UsesADL);
2578
2579 /// Build an empty call expression, for deserialization.
2580 CallExpr(StmtClass SC, unsigned NumPreArgs, unsigned NumArgs,
2581 EmptyShell Empty);
2582
2583 /// Return the size in bytes needed for the trailing objects.
2584 /// Used by the derived classes to allocate the right amount of storage.
2585 static unsigned sizeOfTrailingObjects(unsigned NumPreArgs, unsigned NumArgs) {
2586 return (1 + NumPreArgs + NumArgs) * sizeof(Stmt *);
2587 }
2588
2589 Stmt *getPreArg(unsigned I) {
2590 assert(I < getNumPreArgs() && "Prearg access out of range!")((I < getNumPreArgs() && "Prearg access out of range!"
) ? static_cast<void> (0) : __assert_fail ("I < getNumPreArgs() && \"Prearg access out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2590, __PRETTY_FUNCTION__))
;
2591 return getTrailingStmts()[PREARGS_START + I];
2592 }
2593 const Stmt *getPreArg(unsigned I) const {
2594 assert(I < getNumPreArgs() && "Prearg access out of range!")((I < getNumPreArgs() && "Prearg access out of range!"
) ? static_cast<void> (0) : __assert_fail ("I < getNumPreArgs() && \"Prearg access out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2594, __PRETTY_FUNCTION__))
;
2595 return getTrailingStmts()[PREARGS_START + I];
2596 }
2597 void setPreArg(unsigned I, Stmt *PreArg) {
2598 assert(I < getNumPreArgs() && "Prearg access out of range!")((I < getNumPreArgs() && "Prearg access out of range!"
) ? static_cast<void> (0) : __assert_fail ("I < getNumPreArgs() && \"Prearg access out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2598, __PRETTY_FUNCTION__))
;
2599 getTrailingStmts()[PREARGS_START + I] = PreArg;
2600 }
2601
2602 unsigned getNumPreArgs() const { return CallExprBits.NumPreArgs; }
2603
2604public:
2605 /// Create a call expression. Fn is the callee expression, Args is the
2606 /// argument array, Ty is the type of the call expression (which is *not*
2607 /// the return type in general), VK is the value kind of the call expression
2608 /// (lvalue, rvalue, ...), and RParenLoc is the location of the right
2609 /// parenthese in the call expression. MinNumArgs specifies the minimum
2610 /// number of arguments. The actual number of arguments will be the greater
2611 /// of Args.size() and MinNumArgs. This is used in a few places to allocate
2612 /// enough storage for the default arguments. UsesADL specifies whether the
2613 /// callee was found through argument-dependent lookup.
2614 ///
2615 /// Note that you can use CreateTemporary if you need a temporary call
2616 /// expression on the stack.
2617 static CallExpr *Create(const ASTContext &Ctx, Expr *Fn,
2618 ArrayRef<Expr *> Args, QualType Ty, ExprValueKind VK,
2619 SourceLocation RParenLoc, unsigned MinNumArgs = 0,
2620 ADLCallKind UsesADL = NotADL);
2621
2622 /// Create a temporary call expression with no arguments in the memory
2623 /// pointed to by Mem. Mem must points to at least sizeof(CallExpr)
2624 /// + sizeof(Stmt *) bytes of storage, aligned to alignof(CallExpr):
2625 ///
2626 /// \code{.cpp}
2627 /// alignas(CallExpr) char Buffer[sizeof(CallExpr) + sizeof(Stmt *)];
2628 /// CallExpr *TheCall = CallExpr::CreateTemporary(Buffer, etc);
2629 /// \endcode
2630 static CallExpr *CreateTemporary(void *Mem, Expr *Fn, QualType Ty,
2631 ExprValueKind VK, SourceLocation RParenLoc,
2632 ADLCallKind UsesADL = NotADL);
2633
2634 /// Create an empty call expression, for deserialization.
2635 static CallExpr *CreateEmpty(const ASTContext &Ctx, unsigned NumArgs,
2636 EmptyShell Empty);
2637
2638 Expr *getCallee() { return cast<Expr>(getTrailingStmts()[FN]); }
2639 const Expr *getCallee() const { return cast<Expr>(getTrailingStmts()[FN]); }
2640 void setCallee(Expr *F) { getTrailingStmts()[FN] = F; }
2641
2642 ADLCallKind getADLCallKind() const {
2643 return static_cast<ADLCallKind>(CallExprBits.UsesADL);
2644 }
2645 void setADLCallKind(ADLCallKind V = UsesADL) {
2646 CallExprBits.UsesADL = static_cast<bool>(V);
2647 }
2648 bool usesADL() const { return getADLCallKind() == UsesADL; }
2649
2650 Decl *getCalleeDecl() { return getCallee()->getReferencedDeclOfCallee(); }
2651 const Decl *getCalleeDecl() const {
2652 return getCallee()->getReferencedDeclOfCallee();
2653 }
2654
2655 /// If the callee is a FunctionDecl, return it. Otherwise return null.
2656 FunctionDecl *getDirectCallee() {
2657 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
2658 }
2659 const FunctionDecl *getDirectCallee() const {
2660 return dyn_cast_or_null<FunctionDecl>(getCalleeDecl());
2661 }
2662
2663 /// getNumArgs - Return the number of actual arguments to this call.
2664 unsigned getNumArgs() const { return NumArgs; }
2665
2666 /// Retrieve the call arguments.
2667 Expr **getArgs() {
2668 return reinterpret_cast<Expr **>(getTrailingStmts() + PREARGS_START +
2669 getNumPreArgs());
2670 }
2671 const Expr *const *getArgs() const {
2672 return reinterpret_cast<const Expr *const *>(
2673 getTrailingStmts() + PREARGS_START + getNumPreArgs());
2674 }
2675
2676 /// getArg - Return the specified argument.
2677 Expr *getArg(unsigned Arg) {
2678 assert(Arg < getNumArgs() && "Arg access out of range!")((Arg < getNumArgs() && "Arg access out of range!"
) ? static_cast<void> (0) : __assert_fail ("Arg < getNumArgs() && \"Arg access out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2678, __PRETTY_FUNCTION__))
;
2679 return getArgs()[Arg];
2680 }
2681 const Expr *getArg(unsigned Arg) const {
2682 assert(Arg < getNumArgs() && "Arg access out of range!")((Arg < getNumArgs() && "Arg access out of range!"
) ? static_cast<void> (0) : __assert_fail ("Arg < getNumArgs() && \"Arg access out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2682, __PRETTY_FUNCTION__))
;
2683 return getArgs()[Arg];
2684 }
2685
2686 /// setArg - Set the specified argument.
2687 void setArg(unsigned Arg, Expr *ArgExpr) {
2688 assert(Arg < getNumArgs() && "Arg access out of range!")((Arg < getNumArgs() && "Arg access out of range!"
) ? static_cast<void> (0) : __assert_fail ("Arg < getNumArgs() && \"Arg access out of range!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2688, __PRETTY_FUNCTION__))
;
2689 getArgs()[Arg] = ArgExpr;
2690 }
2691
2692 /// Reduce the number of arguments in this call expression. This is used for
2693 /// example during error recovery to drop extra arguments. There is no way
2694 /// to perform the opposite because: 1.) We don't track how much storage
2695 /// we have for the argument array 2.) This would potentially require growing
2696 /// the argument array, something we cannot support since the arguments are
2697 /// stored in a trailing array.
2698 void shrinkNumArgs(unsigned NewNumArgs) {
2699 assert((NewNumArgs <= getNumArgs()) &&(((NewNumArgs <= getNumArgs()) && "shrinkNumArgs cannot increase the number of arguments!"
) ? static_cast<void> (0) : __assert_fail ("(NewNumArgs <= getNumArgs()) && \"shrinkNumArgs cannot increase the number of arguments!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2700, __PRETTY_FUNCTION__))
2700 "shrinkNumArgs cannot increase the number of arguments!")(((NewNumArgs <= getNumArgs()) && "shrinkNumArgs cannot increase the number of arguments!"
) ? static_cast<void> (0) : __assert_fail ("(NewNumArgs <= getNumArgs()) && \"shrinkNumArgs cannot increase the number of arguments!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 2700, __PRETTY_FUNCTION__))
;
2701 NumArgs = NewNumArgs;
2702 }
2703
2704 /// Bluntly set a new number of arguments without doing any checks whatsoever.
2705 /// Only used during construction of a CallExpr in a few places in Sema.
2706 /// FIXME: Find a way to remove it.
2707 void setNumArgsUnsafe(unsigned NewNumArgs) { NumArgs = NewNumArgs; }
2708
2709 typedef ExprIterator arg_iterator;
2710 typedef ConstExprIterator const_arg_iterator;
2711 typedef llvm::iterator_range<arg_iterator> arg_range;
2712 typedef llvm::iterator_range<const_arg_iterator> const_arg_range;
2713
2714 arg_range arguments() { return arg_range(arg_begin(), arg_end()); }
2715 const_arg_range arguments() const {
2716 return const_arg_range(arg_begin(), arg_end());
2717 }
2718
2719 arg_iterator arg_begin() {
2720 return getTrailingStmts() + PREARGS_START + getNumPreArgs();
2721 }
2722 arg_iterator arg_end() { return arg_begin() + getNumArgs(); }
2723
2724 const_arg_iterator arg_begin() const {
2725 return getTrailingStmts() + PREARGS_START + getNumPreArgs();
2726 }
2727 const_arg_iterator arg_end() const { return arg_begin() + getNumArgs(); }
2728
2729 /// This method provides fast access to all the subexpressions of
2730 /// a CallExpr without going through the slower virtual child_iterator
2731 /// interface. This provides efficient reverse iteration of the
2732 /// subexpressions. This is currently used for CFG construction.
2733 ArrayRef<Stmt *> getRawSubExprs() {
2734 return llvm::makeArrayRef(getTrailingStmts(),
2735 PREARGS_START + getNumPreArgs() + getNumArgs());
2736 }
2737
2738 /// getNumCommas - Return the number of commas that must have been present in
2739 /// this function call.
2740 unsigned getNumCommas() const { return getNumArgs() ? getNumArgs() - 1 : 0; }
2741
2742 /// getBuiltinCallee - If this is a call to a builtin, return the builtin ID
2743 /// of the callee. If not, return 0.
2744 unsigned getBuiltinCallee() const;
2745
2746 /// Returns \c true if this is a call to a builtin which does not
2747 /// evaluate side-effects within its arguments.
2748 bool isUnevaluatedBuiltinCall(const ASTContext &Ctx) const;
2749
2750 /// getCallReturnType - Get the return type of the call expr. This is not
2751 /// always the type of the expr itself, if the return type is a reference
2752 /// type.
2753 QualType getCallReturnType(const ASTContext &Ctx) const;
2754
2755 /// Returns the WarnUnusedResultAttr that is either declared on the called
2756 /// function, or its return type declaration.
2757 const Attr *getUnusedResultAttr(const ASTContext &Ctx) const;
2758
2759 /// Returns true if this call expression should warn on unused results.
2760 bool hasUnusedResultAttr(const ASTContext &Ctx) const {
2761 return getUnusedResultAttr(Ctx) != nullptr;
2762 }
2763
2764 SourceLocation getRParenLoc() const { return RParenLoc; }
2765 void setRParenLoc(SourceLocation L) { RParenLoc = L; }
2766
2767 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
2768 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
2769
2770 /// Return true if this is a call to __assume() or __builtin_assume() with
2771 /// a non-value-dependent constant parameter evaluating as false.
2772 bool isBuiltinAssumeFalse(const ASTContext &Ctx) const;
2773
2774 bool isCallToStdMove() const {
2775 const FunctionDecl *FD = getDirectCallee();
2776 return getNumArgs() == 1 && FD && FD->isInStdNamespace() &&
2777 FD->getIdentifier() && FD->getIdentifier()->isStr("move");
2778 }
2779
2780 static bool classof(const Stmt *T) {
2781 return T->getStmtClass() >= firstCallExprConstant &&
2782 T->getStmtClass() <= lastCallExprConstant;
2783 }
2784
2785 // Iterators
2786 child_range children() {
2787 return child_range(getTrailingStmts(), getTrailingStmts() + PREARGS_START +
2788 getNumPreArgs() + getNumArgs());
2789 }
2790
2791 const_child_range children() const {
2792 return const_child_range(getTrailingStmts(),
2793 getTrailingStmts() + PREARGS_START +
2794 getNumPreArgs() + getNumArgs());
2795 }
2796};
2797
2798/// Extra data stored in some MemberExpr objects.
2799struct MemberExprNameQualifier {
2800 /// The nested-name-specifier that qualifies the name, including
2801 /// source-location information.
2802 NestedNameSpecifierLoc QualifierLoc;
2803
2804 /// The DeclAccessPair through which the MemberDecl was found due to
2805 /// name qualifiers.
2806 DeclAccessPair FoundDecl;
2807};
2808
2809/// MemberExpr - [C99 6.5.2.3] Structure and Union Members. X->F and X.F.
2810///
2811class MemberExpr final
2812 : public Expr,
2813 private llvm::TrailingObjects<MemberExpr, MemberExprNameQualifier,
2814 ASTTemplateKWAndArgsInfo,
2815 TemplateArgumentLoc> {
2816 friend class ASTReader;
2817 friend class ASTStmtReader;
2818 friend class ASTStmtWriter;
2819 friend TrailingObjects;
2820
2821 /// Base - the expression for the base pointer or structure references. In
2822 /// X.F, this is "X".
2823 Stmt *Base;
2824
2825 /// MemberDecl - This is the decl being referenced by the field/member name.
2826 /// In X.F, this is the decl referenced by F.
2827 ValueDecl *MemberDecl;
2828
2829 /// MemberDNLoc - Provides source/type location info for the
2830 /// declaration name embedded in MemberDecl.
2831 DeclarationNameLoc MemberDNLoc;
2832
2833 /// MemberLoc - This is the location of the member name.
2834 SourceLocation MemberLoc;
2835
2836 size_t numTrailingObjects(OverloadToken<MemberExprNameQualifier>) const {
2837 return hasQualifierOrFoundDecl();
2838 }
2839
2840 size_t numTrailingObjects(OverloadToken<ASTTemplateKWAndArgsInfo>) const {
2841 return hasTemplateKWAndArgsInfo();
2842 }
2843
2844 bool hasQualifierOrFoundDecl() const {
2845 return MemberExprBits.HasQualifierOrFoundDecl;
2846 }
2847
2848 bool hasTemplateKWAndArgsInfo() const {
2849 return MemberExprBits.HasTemplateKWAndArgsInfo;
2850 }
2851
2852 MemberExpr(Expr *Base, bool IsArrow, SourceLocation OperatorLoc,
2853 ValueDecl *MemberDecl, const DeclarationNameInfo &NameInfo,
2854 QualType T, ExprValueKind VK, ExprObjectKind OK,
2855 NonOdrUseReason NOUR);
2856 MemberExpr(EmptyShell Empty)
2857 : Expr(MemberExprClass, Empty), Base(), MemberDecl() {}
2858
2859public:
2860 static MemberExpr *Create(const ASTContext &C, Expr *Base, bool IsArrow,
2861 SourceLocation OperatorLoc,
2862 NestedNameSpecifierLoc QualifierLoc,
2863 SourceLocation TemplateKWLoc, ValueDecl *MemberDecl,
2864 DeclAccessPair FoundDecl,
2865 DeclarationNameInfo MemberNameInfo,
2866 const TemplateArgumentListInfo *TemplateArgs,
2867 QualType T, ExprValueKind VK, ExprObjectKind OK,
2868 NonOdrUseReason NOUR);
2869
2870 /// Create an implicit MemberExpr, with no location, qualifier, template
2871 /// arguments, and so on. Suitable only for non-static member access.
2872 static MemberExpr *CreateImplicit(const ASTContext &C, Expr *Base,
2873 bool IsArrow, ValueDecl *MemberDecl,
2874 QualType T, ExprValueKind VK,
2875 ExprObjectKind OK) {
2876 return Create(C, Base, IsArrow, SourceLocation(), NestedNameSpecifierLoc(),
2877 SourceLocation(), MemberDecl,
2878 DeclAccessPair::make(MemberDecl, MemberDecl->getAccess()),
2879 DeclarationNameInfo(), nullptr, T, VK, OK, NOUR_None);
2880 }
2881
2882 static MemberExpr *CreateEmpty(const ASTContext &Context, bool HasQualifier,
2883 bool HasFoundDecl,
2884 bool HasTemplateKWAndArgsInfo,
2885 unsigned NumTemplateArgs);
2886
2887 void setBase(Expr *E) { Base = E; }
2888 Expr *getBase() const { return cast<Expr>(Base); }
2889
2890 /// Retrieve the member declaration to which this expression refers.
2891 ///
2892 /// The returned declaration will be a FieldDecl or (in C++) a VarDecl (for
2893 /// static data members), a CXXMethodDecl, or an EnumConstantDecl.
2894 ValueDecl *getMemberDecl() const { return MemberDecl; }
2895 void setMemberDecl(ValueDecl *D) { MemberDecl = D; }
2896
2897 /// Retrieves the declaration found by lookup.
2898 DeclAccessPair getFoundDecl() const {
2899 if (!hasQualifierOrFoundDecl())
2900 return DeclAccessPair::make(getMemberDecl(),
2901 getMemberDecl()->getAccess());
2902 return getTrailingObjects<MemberExprNameQualifier>()->FoundDecl;
2903 }
2904
2905 /// Determines whether this member expression actually had
2906 /// a C++ nested-name-specifier prior to the name of the member, e.g.,
2907 /// x->Base::foo.
2908 bool hasQualifier() const { return getQualifier() != nullptr; }
2909
2910 /// If the member name was qualified, retrieves the
2911 /// nested-name-specifier that precedes the member name, with source-location
2912 /// information.
2913 NestedNameSpecifierLoc getQualifierLoc() const {
2914 if (!hasQualifierOrFoundDecl())
2915 return NestedNameSpecifierLoc();
2916 return getTrailingObjects<MemberExprNameQualifier>()->QualifierLoc;
2917 }
2918
2919 /// If the member name was qualified, retrieves the
2920 /// nested-name-specifier that precedes the member name. Otherwise, returns
2921 /// NULL.
2922 NestedNameSpecifier *getQualifier() const {
2923 return getQualifierLoc().getNestedNameSpecifier();
2924 }
2925
2926 /// Retrieve the location of the template keyword preceding
2927 /// the member name, if any.
2928 SourceLocation getTemplateKeywordLoc() const {
2929 if (!hasTemplateKWAndArgsInfo())
2930 return SourceLocation();
2931 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->TemplateKWLoc;
2932 }
2933
2934 /// Retrieve the location of the left angle bracket starting the
2935 /// explicit template argument list following the member name, if any.
2936 SourceLocation getLAngleLoc() const {
2937 if (!hasTemplateKWAndArgsInfo())
2938 return SourceLocation();
2939 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->LAngleLoc;
2940 }
2941
2942 /// Retrieve the location of the right angle bracket ending the
2943 /// explicit template argument list following the member name, if any.
2944 SourceLocation getRAngleLoc() const {
2945 if (!hasTemplateKWAndArgsInfo())
2946 return SourceLocation();
2947 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->RAngleLoc;
2948 }
2949
2950 /// Determines whether the member name was preceded by the template keyword.
2951 bool hasTemplateKeyword() const { return getTemplateKeywordLoc().isValid(); }
2952
2953 /// Determines whether the member name was followed by an
2954 /// explicit template argument list.
2955 bool hasExplicitTemplateArgs() const { return getLAngleLoc().isValid(); }
2956
2957 /// Copies the template arguments (if present) into the given
2958 /// structure.
2959 void copyTemplateArgumentsInto(TemplateArgumentListInfo &List) const {
2960 if (hasExplicitTemplateArgs())
2961 getTrailingObjects<ASTTemplateKWAndArgsInfo>()->copyInto(
2962 getTrailingObjects<TemplateArgumentLoc>(), List);
2963 }
2964
2965 /// Retrieve the template arguments provided as part of this
2966 /// template-id.
2967 const TemplateArgumentLoc *getTemplateArgs() const {
2968 if (!hasExplicitTemplateArgs())
2969 return nullptr;
2970
2971 return getTrailingObjects<TemplateArgumentLoc>();
2972 }
2973
2974 /// Retrieve the number of template arguments provided as part of this
2975 /// template-id.
2976 unsigned getNumTemplateArgs() const {
2977 if (!hasExplicitTemplateArgs())
2978 return 0;
2979
2980 return getTrailingObjects<ASTTemplateKWAndArgsInfo>()->NumTemplateArgs;
2981 }
2982
2983 ArrayRef<TemplateArgumentLoc> template_arguments() const {
2984 return {getTemplateArgs(), getNumTemplateArgs()};
2985 }
2986
2987 /// Retrieve the member declaration name info.
2988 DeclarationNameInfo getMemberNameInfo() const {
2989 return DeclarationNameInfo(MemberDecl->getDeclName(),
2990 MemberLoc, MemberDNLoc);
2991 }
2992
2993 SourceLocation getOperatorLoc() const { return MemberExprBits.OperatorLoc; }
2994
2995 bool isArrow() const { return MemberExprBits.IsArrow; }
2996 void setArrow(bool A) { MemberExprBits.IsArrow = A; }
2997
2998 /// getMemberLoc - Return the location of the "member", in X->F, it is the
2999 /// location of 'F'.
3000 SourceLocation getMemberLoc() const { return MemberLoc; }
3001 void setMemberLoc(SourceLocation L) { MemberLoc = L; }
3002
3003 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__));
3004 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__));
3005
3006 SourceLocation getExprLoc() const LLVM_READONLY__attribute__((__pure__)) { return MemberLoc; }
3007
3008 /// Determine whether the base of this explicit is implicit.
3009 bool isImplicitAccess() const {
3010 return getBase() && getBase()->isImplicitCXXThis();
3011 }
3012
3013 /// Returns true if this member expression refers to a method that
3014 /// was resolved from an overloaded set having size greater than 1.
3015 bool hadMultipleCandidates() const {
3016 return MemberExprBits.HadMultipleCandidates;
3017 }
3018 /// Sets the flag telling whether this expression refers to
3019 /// a method that was resolved from an overloaded set having size
3020 /// greater than 1.
3021 void setHadMultipleCandidates(bool V = true) {
3022 MemberExprBits.HadMultipleCandidates = V;
3023 }
3024
3025 /// Returns true if virtual dispatch is performed.
3026 /// If the member access is fully qualified, (i.e. X::f()), virtual
3027 /// dispatching is not performed. In -fapple-kext mode qualified
3028 /// calls to virtual method will still go through the vtable.
3029 bool performsVirtualDispatch(const LangOptions &LO) const {
3030 return LO.AppleKext || !hasQualifier();
3031 }
3032
3033 /// Is this expression a non-odr-use reference, and if so, why?
3034 /// This is only meaningful if the named member is a static member.
3035 NonOdrUseReason isNonOdrUse() const {
3036 return static_cast<NonOdrUseReason>(MemberExprBits.NonOdrUseReason);
3037 }
3038
3039 static bool classof(const Stmt *T) {
3040 return T->getStmtClass() == MemberExprClass;
3041 }
3042
3043 // Iterators
3044 child_range children() { return child_range(&Base, &Base+1); }
3045 const_child_range children() const {
3046 return const_child_range(&Base, &Base + 1);
3047 }
3048};
3049
3050/// CompoundLiteralExpr - [C99 6.5.2.5]
3051///
3052class CompoundLiteralExpr : public Expr {
3053 /// LParenLoc - If non-null, this is the location of the left paren in a
3054 /// compound literal like "(int){4}". This can be null if this is a
3055 /// synthesized compound expression.
3056 SourceLocation LParenLoc;
3057
3058 /// The type as written. This can be an incomplete array type, in
3059 /// which case the actual expression type will be different.
3060 /// The int part of the pair stores whether this expr is file scope.
3061 llvm::PointerIntPair<TypeSourceInfo *, 1, bool> TInfoAndScope;
3062 Stmt *Init;
3063public:
3064 CompoundLiteralExpr(SourceLocation lparenloc, TypeSourceInfo *tinfo,
3065 QualType T, ExprValueKind VK, Expr *init, bool fileScope)
3066 : Expr(CompoundLiteralExprClass, T, VK, OK_Ordinary,
3067 tinfo->getType()->isDependentType(),
3068 init->isValueDependent(),
3069 (init->isInstantiationDependent() ||
3070 tinfo->getType()->isInstantiationDependentType()),
3071 init->containsUnexpandedParameterPack()),
3072 LParenLoc(lparenloc), TInfoAndScope(tinfo, fileScope), Init(init) {}
3073
3074 /// Construct an empty compound literal.
3075 explicit CompoundLiteralExpr(EmptyShell Empty)
3076 : Expr(CompoundLiteralExprClass, Empty) { }
3077
3078 const Expr *getInitializer() const { return cast<Expr>(Init); }
3079 Expr *getInitializer() { return cast<Expr>(Init); }
3080 void setInitializer(Expr *E) { Init = E; }
3081
3082 bool isFileScope() const { return TInfoAndScope.getInt(); }
3083 void setFileScope(bool FS) { TInfoAndScope.setInt(FS); }
3084
3085 SourceLocation getLParenLoc() const { return LParenLoc; }
3086 void setLParenLoc(SourceLocation L) { LParenLoc = L; }
3087
3088 TypeSourceInfo *getTypeSourceInfo() const {
3089 return TInfoAndScope.getPointer();
3090 }
3091 void setTypeSourceInfo(TypeSourceInfo *tinfo) {
3092 TInfoAndScope.setPointer(tinfo);
3093 }
3094
3095 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3096 // FIXME: Init should never be null.
3097 if (!Init)
3098 return SourceLocation();
3099 if (LParenLoc.isInvalid())
3100 return Init->getBeginLoc();
3101 return LParenLoc;
3102 }
3103 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3104 // FIXME: Init should never be null.
3105 if (!Init)
3106 return SourceLocation();
3107 return Init->getEndLoc();
3108 }
3109
3110 static bool classof(const Stmt *T) {
3111 return T->getStmtClass() == CompoundLiteralExprClass;
3112 }
3113
3114 // Iterators
3115 child_range children() { return child_range(&Init, &Init+1); }
3116 const_child_range children() const {
3117 return const_child_range(&Init, &Init + 1);
3118 }
3119};
3120
3121/// CastExpr - Base class for type casts, including both implicit
3122/// casts (ImplicitCastExpr) and explicit casts that have some
3123/// representation in the source code (ExplicitCastExpr's derived
3124/// classes).
3125class CastExpr : public Expr {
3126 Stmt *Op;
3127
3128 bool CastConsistency() const;
3129
3130 const CXXBaseSpecifier * const *path_buffer() const {
3131 return const_cast<CastExpr*>(this)->path_buffer();
3132 }
3133 CXXBaseSpecifier **path_buffer();
3134
3135protected:
3136 CastExpr(StmtClass SC, QualType ty, ExprValueKind VK, const CastKind kind,
3137 Expr *op, unsigned BasePathSize)
3138 : Expr(SC, ty, VK, OK_Ordinary,
3139 // Cast expressions are type-dependent if the type is
3140 // dependent (C++ [temp.dep.expr]p3).
3141 ty->isDependentType(),
3142 // Cast expressions are value-dependent if the type is
3143 // dependent or if the subexpression is value-dependent.
3144 ty->isDependentType() || (op && op->isValueDependent()),
3145 (ty->isInstantiationDependentType() ||
3146 (op && op->isInstantiationDependent())),
3147 // An implicit cast expression doesn't (lexically) contain an
3148 // unexpanded pack, even if its target type does.
3149 ((SC != ImplicitCastExprClass &&
3150 ty->containsUnexpandedParameterPack()) ||
3151 (op && op->containsUnexpandedParameterPack()))),
3152 Op(op) {
3153 CastExprBits.Kind = kind;
3154 CastExprBits.PartOfExplicitCast = false;
3155 CastExprBits.BasePathSize = BasePathSize;
3156 assert((CastExprBits.BasePathSize == BasePathSize) &&(((CastExprBits.BasePathSize == BasePathSize) && "BasePathSize overflow!"
) ? static_cast<void> (0) : __assert_fail ("(CastExprBits.BasePathSize == BasePathSize) && \"BasePathSize overflow!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3157, __PRETTY_FUNCTION__))
3157 "BasePathSize overflow!")(((CastExprBits.BasePathSize == BasePathSize) && "BasePathSize overflow!"
) ? static_cast<void> (0) : __assert_fail ("(CastExprBits.BasePathSize == BasePathSize) && \"BasePathSize overflow!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3157, __PRETTY_FUNCTION__))
;
3158 assert(CastConsistency())((CastConsistency()) ? static_cast<void> (0) : __assert_fail
("CastConsistency()", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3158, __PRETTY_FUNCTION__))
;
3159 }
3160
3161 /// Construct an empty cast.
3162 CastExpr(StmtClass SC, EmptyShell Empty, unsigned BasePathSize)
3163 : Expr(SC, Empty) {
3164 CastExprBits.PartOfExplicitCast = false;
3165 CastExprBits.BasePathSize = BasePathSize;
3166 assert((CastExprBits.BasePathSize == BasePathSize) &&(((CastExprBits.BasePathSize == BasePathSize) && "BasePathSize overflow!"
) ? static_cast<void> (0) : __assert_fail ("(CastExprBits.BasePathSize == BasePathSize) && \"BasePathSize overflow!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3167, __PRETTY_FUNCTION__))
3167 "BasePathSize overflow!")(((CastExprBits.BasePathSize == BasePathSize) && "BasePathSize overflow!"
) ? static_cast<void> (0) : __assert_fail ("(CastExprBits.BasePathSize == BasePathSize) && \"BasePathSize overflow!\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3167, __PRETTY_FUNCTION__))
;
3168 }
3169
3170public:
3171 CastKind getCastKind() const { return (CastKind) CastExprBits.Kind; }
3172 void setCastKind(CastKind K) { CastExprBits.Kind = K; }
3173
3174 static const char *getCastKindName(CastKind CK);
3175 const char *getCastKindName() const { return getCastKindName(getCastKind()); }
3176
3177 Expr *getSubExpr() { return cast<Expr>(Op); }
3178 const Expr *getSubExpr() const { return cast<Expr>(Op); }
3179 void setSubExpr(Expr *E) { Op = E; }
3180
3181 /// Retrieve the cast subexpression as it was written in the source
3182 /// code, looking through any implicit casts or other intermediate nodes
3183 /// introduced by semantic analysis.
3184 Expr *getSubExprAsWritten();
3185 const Expr *getSubExprAsWritten() const {
3186 return const_cast<CastExpr *>(this)->getSubExprAsWritten();
3187 }
3188
3189 /// If this cast applies a user-defined conversion, retrieve the conversion
3190 /// function that it invokes.
3191 NamedDecl *getConversionFunction() const;
3192
3193 typedef CXXBaseSpecifier **path_iterator;
3194 typedef const CXXBaseSpecifier *const *path_const_iterator;
3195 bool path_empty() const { return path_size() == 0; }
3196 unsigned path_size() const { return CastExprBits.BasePathSize; }
3197 path_iterator path_begin() { return path_buffer(); }
3198 path_iterator path_end() { return path_buffer() + path_size(); }
3199 path_const_iterator path_begin() const { return path_buffer(); }
3200 path_const_iterator path_end() const { return path_buffer() + path_size(); }
3201
3202 llvm::iterator_range<path_iterator> path() {
3203 return llvm::make_range(path_begin(), path_end());
3204 }
3205 llvm::iterator_range<path_const_iterator> path() const {
3206 return llvm::make_range(path_begin(), path_end());
3207 }
3208
3209 const FieldDecl *getTargetUnionField() const {
3210 assert(getCastKind() == CK_ToUnion)((getCastKind() == CK_ToUnion) ? static_cast<void> (0) :
__assert_fail ("getCastKind() == CK_ToUnion", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3210, __PRETTY_FUNCTION__))
;
3211 return getTargetFieldForToUnionCast(getType(), getSubExpr()->getType());
3212 }
3213
3214 static const FieldDecl *getTargetFieldForToUnionCast(QualType unionType,
3215 QualType opType);
3216 static const FieldDecl *getTargetFieldForToUnionCast(const RecordDecl *RD,
3217 QualType opType);
3218
3219 static bool classof(const Stmt *T) {
3220 return T->getStmtClass() >= firstCastExprConstant &&
3221 T->getStmtClass() <= lastCastExprConstant;
3222 }
3223
3224 // Iterators
3225 child_range children() { return child_range(&Op, &Op+1); }
3226 const_child_range children() const { return const_child_range(&Op, &Op + 1); }
3227};
3228
3229/// ImplicitCastExpr - Allows us to explicitly represent implicit type
3230/// conversions, which have no direct representation in the original
3231/// source code. For example: converting T[]->T*, void f()->void
3232/// (*f)(), float->double, short->int, etc.
3233///
3234/// In C, implicit casts always produce rvalues. However, in C++, an
3235/// implicit cast whose result is being bound to a reference will be
3236/// an lvalue or xvalue. For example:
3237///
3238/// @code
3239/// class Base { };
3240/// class Derived : public Base { };
3241/// Derived &&ref();
3242/// void f(Derived d) {
3243/// Base& b = d; // initializer is an ImplicitCastExpr
3244/// // to an lvalue of type Base
3245/// Base&& r = ref(); // initializer is an ImplicitCastExpr
3246/// // to an xvalue of type Base
3247/// }
3248/// @endcode
3249class ImplicitCastExpr final
3250 : public CastExpr,
3251 private llvm::TrailingObjects<ImplicitCastExpr, CXXBaseSpecifier *> {
3252
3253 ImplicitCastExpr(QualType ty, CastKind kind, Expr *op,
3254 unsigned BasePathLength, ExprValueKind VK)
3255 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, BasePathLength) { }
3256
3257 /// Construct an empty implicit cast.
3258 explicit ImplicitCastExpr(EmptyShell Shell, unsigned PathSize)
3259 : CastExpr(ImplicitCastExprClass, Shell, PathSize) { }
3260
3261public:
3262 enum OnStack_t { OnStack };
3263 ImplicitCastExpr(OnStack_t _, QualType ty, CastKind kind, Expr *op,
3264 ExprValueKind VK)
3265 : CastExpr(ImplicitCastExprClass, ty, VK, kind, op, 0) {
3266 }
3267
3268 bool isPartOfExplicitCast() const { return CastExprBits.PartOfExplicitCast; }
3269 void setIsPartOfExplicitCast(bool PartOfExplicitCast) {
3270 CastExprBits.PartOfExplicitCast = PartOfExplicitCast;
3271 }
3272
3273 static ImplicitCastExpr *Create(const ASTContext &Context, QualType T,
3274 CastKind Kind, Expr *Operand,
3275 const CXXCastPath *BasePath,
3276 ExprValueKind Cat);
3277
3278 static ImplicitCastExpr *CreateEmpty(const ASTContext &Context,
3279 unsigned PathSize);
3280
3281 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3282 return getSubExpr()->getBeginLoc();
3283 }
3284 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3285 return getSubExpr()->getEndLoc();
3286 }
3287
3288 static bool classof(const Stmt *T) {
3289 return T->getStmtClass() == ImplicitCastExprClass;
3290 }
3291
3292 friend TrailingObjects;
3293 friend class CastExpr;
3294};
3295
3296/// ExplicitCastExpr - An explicit cast written in the source
3297/// code.
3298///
3299/// This class is effectively an abstract class, because it provides
3300/// the basic representation of an explicitly-written cast without
3301/// specifying which kind of cast (C cast, functional cast, static
3302/// cast, etc.) was written; specific derived classes represent the
3303/// particular style of cast and its location information.
3304///
3305/// Unlike implicit casts, explicit cast nodes have two different
3306/// types: the type that was written into the source code, and the
3307/// actual type of the expression as determined by semantic
3308/// analysis. These types may differ slightly. For example, in C++ one
3309/// can cast to a reference type, which indicates that the resulting
3310/// expression will be an lvalue or xvalue. The reference type, however,
3311/// will not be used as the type of the expression.
3312class ExplicitCastExpr : public CastExpr {
3313 /// TInfo - Source type info for the (written) type
3314 /// this expression is casting to.
3315 TypeSourceInfo *TInfo;
3316
3317protected:
3318 ExplicitCastExpr(StmtClass SC, QualType exprTy, ExprValueKind VK,
3319 CastKind kind, Expr *op, unsigned PathSize,
3320 TypeSourceInfo *writtenTy)
3321 : CastExpr(SC, exprTy, VK, kind, op, PathSize), TInfo(writtenTy) {}
3322
3323 /// Construct an empty explicit cast.
3324 ExplicitCastExpr(StmtClass SC, EmptyShell Shell, unsigned PathSize)
3325 : CastExpr(SC, Shell, PathSize) { }
3326
3327public:
3328 /// getTypeInfoAsWritten - Returns the type source info for the type
3329 /// that this expression is casting to.
3330 TypeSourceInfo *getTypeInfoAsWritten() const { return TInfo; }
3331 void setTypeInfoAsWritten(TypeSourceInfo *writtenTy) { TInfo = writtenTy; }
3332
3333 /// getTypeAsWritten - Returns the type that this expression is
3334 /// casting to, as written in the source code.
3335 QualType getTypeAsWritten() const { return TInfo->getType(); }
3336
3337 static bool classof(const Stmt *T) {
3338 return T->getStmtClass() >= firstExplicitCastExprConstant &&
3339 T->getStmtClass() <= lastExplicitCastExprConstant;
3340 }
3341};
3342
3343/// CStyleCastExpr - An explicit cast in C (C99 6.5.4) or a C-style
3344/// cast in C++ (C++ [expr.cast]), which uses the syntax
3345/// (Type)expr. For example: @c (int)f.
3346class CStyleCastExpr final
3347 : public ExplicitCastExpr,
3348 private llvm::TrailingObjects<CStyleCastExpr, CXXBaseSpecifier *> {
3349 SourceLocation LPLoc; // the location of the left paren
3350 SourceLocation RPLoc; // the location of the right paren
3351
3352 CStyleCastExpr(QualType exprTy, ExprValueKind vk, CastKind kind, Expr *op,
3353 unsigned PathSize, TypeSourceInfo *writtenTy,
3354 SourceLocation l, SourceLocation r)
3355 : ExplicitCastExpr(CStyleCastExprClass, exprTy, vk, kind, op, PathSize,
3356 writtenTy), LPLoc(l), RPLoc(r) {}
3357
3358 /// Construct an empty C-style explicit cast.
3359 explicit CStyleCastExpr(EmptyShell Shell, unsigned PathSize)
3360 : ExplicitCastExpr(CStyleCastExprClass, Shell, PathSize) { }
3361
3362public:
3363 static CStyleCastExpr *Create(const ASTContext &Context, QualType T,
3364 ExprValueKind VK, CastKind K,
3365 Expr *Op, const CXXCastPath *BasePath,
3366 TypeSourceInfo *WrittenTy, SourceLocation L,
3367 SourceLocation R);
3368
3369 static CStyleCastExpr *CreateEmpty(const ASTContext &Context,
3370 unsigned PathSize);
3371
3372 SourceLocation getLParenLoc() const { return LPLoc; }
3373 void setLParenLoc(SourceLocation L) { LPLoc = L; }
3374
3375 SourceLocation getRParenLoc() const { return RPLoc; }
3376 void setRParenLoc(SourceLocation L) { RPLoc = L; }
3377
3378 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) { return LPLoc; }
3379 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3380 return getSubExpr()->getEndLoc();
3381 }
3382
3383 static bool classof(const Stmt *T) {
3384 return T->getStmtClass() == CStyleCastExprClass;
3385 }
3386
3387 friend TrailingObjects;
3388 friend class CastExpr;
3389};
3390
3391/// A builtin binary operation expression such as "x + y" or "x <= y".
3392///
3393/// This expression node kind describes a builtin binary operation,
3394/// such as "x + y" for integer values "x" and "y". The operands will
3395/// already have been converted to appropriate types (e.g., by
3396/// performing promotions or conversions).
3397///
3398/// In C++, where operators may be overloaded, a different kind of
3399/// expression node (CXXOperatorCallExpr) is used to express the
3400/// invocation of an overloaded operator with operator syntax. Within
3401/// a C++ template, whether BinaryOperator or CXXOperatorCallExpr is
3402/// used to store an expression "x + y" depends on the subexpressions
3403/// for x and y. If neither x or y is type-dependent, and the "+"
3404/// operator resolves to a built-in operation, BinaryOperator will be
3405/// used to express the computation (x and y may still be
3406/// value-dependent). If either x or y is type-dependent, or if the
3407/// "+" resolves to an overloaded operator, CXXOperatorCallExpr will
3408/// be used to express the computation.
3409class BinaryOperator : public Expr {
3410 enum { LHS, RHS, END_EXPR };
3411 Stmt *SubExprs[END_EXPR];
3412
3413public:
3414 typedef BinaryOperatorKind Opcode;
3415
3416 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3417 ExprValueKind VK, ExprObjectKind OK,
3418 SourceLocation opLoc, FPOptions FPFeatures)
3419 : Expr(BinaryOperatorClass, ResTy, VK, OK,
3420 lhs->isTypeDependent() || rhs->isTypeDependent(),
3421 lhs->isValueDependent() || rhs->isValueDependent(),
3422 (lhs->isInstantiationDependent() ||
3423 rhs->isInstantiationDependent()),
3424 (lhs->containsUnexpandedParameterPack() ||
3425 rhs->containsUnexpandedParameterPack())) {
3426 BinaryOperatorBits.Opc = opc;
3427 BinaryOperatorBits.FPFeatures = FPFeatures.getInt();
3428 BinaryOperatorBits.OpLoc = opLoc;
3429 SubExprs[LHS] = lhs;
3430 SubExprs[RHS] = rhs;
3431 assert(!isCompoundAssignmentOp() &&((!isCompoundAssignmentOp() && "Use CompoundAssignOperator for compound assignments"
) ? static_cast<void> (0) : __assert_fail ("!isCompoundAssignmentOp() && \"Use CompoundAssignOperator for compound assignments\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3432, __PRETTY_FUNCTION__))
3432 "Use CompoundAssignOperator for compound assignments")((!isCompoundAssignmentOp() && "Use CompoundAssignOperator for compound assignments"
) ? static_cast<void> (0) : __assert_fail ("!isCompoundAssignmentOp() && \"Use CompoundAssignOperator for compound assignments\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3432, __PRETTY_FUNCTION__))
;
3433 }
3434
3435 /// Construct an empty binary operator.
3436 explicit BinaryOperator(EmptyShell Empty) : Expr(BinaryOperatorClass, Empty) {
3437 BinaryOperatorBits.Opc = BO_Comma;
3438 }
3439
3440 SourceLocation getExprLoc() const { return getOperatorLoc(); }
3441 SourceLocation getOperatorLoc() const { return BinaryOperatorBits.OpLoc; }
3442 void setOperatorLoc(SourceLocation L) { BinaryOperatorBits.OpLoc = L; }
3443
3444 Opcode getOpcode() const {
3445 return static_cast<Opcode>(BinaryOperatorBits.Opc);
3446 }
3447 void setOpcode(Opcode Opc) { BinaryOperatorBits.Opc = Opc; }
3448
3449 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3450 void setLHS(Expr *E) { SubExprs[LHS] = E; }
3451 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3452 void setRHS(Expr *E) { SubExprs[RHS] = E; }
3453
3454 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3455 return getLHS()->getBeginLoc();
3456 }
3457 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3458 return getRHS()->getEndLoc();
3459 }
3460
3461 /// getOpcodeStr - Turn an Opcode enum value into the punctuation char it
3462 /// corresponds to, e.g. "<<=".
3463 static StringRef getOpcodeStr(Opcode Op);
3464
3465 StringRef getOpcodeStr() const { return getOpcodeStr(getOpcode()); }
3466
3467 /// Retrieve the binary opcode that corresponds to the given
3468 /// overloaded operator.
3469 static Opcode getOverloadedOpcode(OverloadedOperatorKind OO);
3470
3471 /// Retrieve the overloaded operator kind that corresponds to
3472 /// the given binary opcode.
3473 static OverloadedOperatorKind getOverloadedOperator(Opcode Opc);
3474
3475 /// predicates to categorize the respective opcodes.
3476 static bool isPtrMemOp(Opcode Opc) {
3477 return Opc == BO_PtrMemD || Opc == BO_PtrMemI;
3478 }
3479 bool isPtrMemOp() const { return isPtrMemOp(getOpcode()); }
3480
3481 static bool isMultiplicativeOp(Opcode Opc) {
3482 return Opc >= BO_Mul && Opc <= BO_Rem;
3483 }
3484 bool isMultiplicativeOp() const { return isMultiplicativeOp(getOpcode()); }
3485 static bool isAdditiveOp(Opcode Opc) { return Opc == BO_Add || Opc==BO_Sub; }
3486 bool isAdditiveOp() const { return isAdditiveOp(getOpcode()); }
3487 static bool isShiftOp(Opcode Opc) { return Opc == BO_Shl || Opc == BO_Shr; }
3488 bool isShiftOp() const { return isShiftOp(getOpcode()); }
3489
3490 static bool isBitwiseOp(Opcode Opc) { return Opc >= BO_And && Opc <= BO_Or; }
3491 bool isBitwiseOp() const { return isBitwiseOp(getOpcode()); }
3492
3493 static bool isRelationalOp(Opcode Opc) { return Opc >= BO_LT && Opc<=BO_GE; }
3494 bool isRelationalOp() const { return isRelationalOp(getOpcode()); }
3495
3496 static bool isEqualityOp(Opcode Opc) { return Opc == BO_EQ || Opc == BO_NE; }
3497 bool isEqualityOp() const { return isEqualityOp(getOpcode()); }
3498
3499 static bool isComparisonOp(Opcode Opc) { return Opc >= BO_Cmp && Opc<=BO_NE; }
3500 bool isComparisonOp() const { return isComparisonOp(getOpcode()); }
3501
3502 static bool isCommaOp(Opcode Opc) { return Opc == BO_Comma; }
3503 bool isCommaOp() const { return isCommaOp(getOpcode()); }
3504
3505 static Opcode negateComparisonOp(Opcode Opc) {
3506 switch (Opc) {
3507 default:
3508 llvm_unreachable("Not a comparison operator.")::llvm::llvm_unreachable_internal("Not a comparison operator."
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3508)
;
3509 case BO_LT: return BO_GE;
3510 case BO_GT: return BO_LE;
3511 case BO_LE: return BO_GT;
3512 case BO_GE: return BO_LT;
3513 case BO_EQ: return BO_NE;
3514 case BO_NE: return BO_EQ;
3515 }
3516 }
3517
3518 static Opcode reverseComparisonOp(Opcode Opc) {
3519 switch (Opc) {
3520 default:
3521 llvm_unreachable("Not a comparison operator.")::llvm::llvm_unreachable_internal("Not a comparison operator."
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3521)
;
3522 case BO_LT: return BO_GT;
3523 case BO_GT: return BO_LT;
3524 case BO_LE: return BO_GE;
3525 case BO_GE: return BO_LE;
3526 case BO_EQ:
3527 case BO_NE:
3528 return Opc;
3529 }
3530 }
3531
3532 static bool isLogicalOp(Opcode Opc) { return Opc == BO_LAnd || Opc==BO_LOr; }
3533 bool isLogicalOp() const { return isLogicalOp(getOpcode()); }
3534
3535 static bool isAssignmentOp(Opcode Opc) {
3536 return Opc >= BO_Assign && Opc <= BO_OrAssign;
3537 }
3538 bool isAssignmentOp() const { return isAssignmentOp(getOpcode()); }
3539
3540 static bool isCompoundAssignmentOp(Opcode Opc) {
3541 return Opc > BO_Assign && Opc <= BO_OrAssign;
3542 }
3543 bool isCompoundAssignmentOp() const {
3544 return isCompoundAssignmentOp(getOpcode());
3545 }
3546 static Opcode getOpForCompoundAssignment(Opcode Opc) {
3547 assert(isCompoundAssignmentOp(Opc))((isCompoundAssignmentOp(Opc)) ? static_cast<void> (0) :
__assert_fail ("isCompoundAssignmentOp(Opc)", "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3547, __PRETTY_FUNCTION__))
;
3548 if (Opc >= BO_AndAssign)
3549 return Opcode(unsigned(Opc) - BO_AndAssign + BO_And);
3550 else
3551 return Opcode(unsigned(Opc) - BO_MulAssign + BO_Mul);
3552 }
3553
3554 static bool isShiftAssignOp(Opcode Opc) {
3555 return Opc == BO_ShlAssign || Opc == BO_ShrAssign;
3556 }
3557 bool isShiftAssignOp() const {
3558 return isShiftAssignOp(getOpcode());
3559 }
3560
3561 // Return true if a binary operator using the specified opcode and operands
3562 // would match the 'p = (i8*)nullptr + n' idiom for casting a pointer-sized
3563 // integer to a pointer.
3564 static bool isNullPointerArithmeticExtension(ASTContext &Ctx, Opcode Opc,
3565 Expr *LHS, Expr *RHS);
3566
3567 static bool classof(const Stmt *S) {
3568 return S->getStmtClass() >= firstBinaryOperatorConstant &&
3569 S->getStmtClass() <= lastBinaryOperatorConstant;
3570 }
3571
3572 // Iterators
3573 child_range children() {
3574 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3575 }
3576 const_child_range children() const {
3577 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3578 }
3579
3580 // Set the FP contractability status of this operator. Only meaningful for
3581 // operations on floating point types.
3582 void setFPFeatures(FPOptions F) {
3583 BinaryOperatorBits.FPFeatures = F.getInt();
3584 }
3585
3586 FPOptions getFPFeatures() const {
3587 return FPOptions(BinaryOperatorBits.FPFeatures);
3588 }
3589
3590 // Get the FP contractability status of this operator. Only meaningful for
3591 // operations on floating point types.
3592 bool isFPContractableWithinStatement() const {
3593 return getFPFeatures().allowFPContractWithinStatement();
3594 }
3595
3596 // Get the FENV_ACCESS status of this operator. Only meaningful for
3597 // operations on floating point types.
3598 bool isFEnvAccessOn() const { return getFPFeatures().allowFEnvAccess(); }
3599
3600protected:
3601 BinaryOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResTy,
3602 ExprValueKind VK, ExprObjectKind OK,
3603 SourceLocation opLoc, FPOptions FPFeatures, bool dead2)
3604 : Expr(CompoundAssignOperatorClass, ResTy, VK, OK,
3605 lhs->isTypeDependent() || rhs->isTypeDependent(),
3606 lhs->isValueDependent() || rhs->isValueDependent(),
3607 (lhs->isInstantiationDependent() ||
3608 rhs->isInstantiationDependent()),
3609 (lhs->containsUnexpandedParameterPack() ||
3610 rhs->containsUnexpandedParameterPack())) {
3611 BinaryOperatorBits.Opc = opc;
3612 BinaryOperatorBits.FPFeatures = FPFeatures.getInt();
3613 BinaryOperatorBits.OpLoc = opLoc;
3614 SubExprs[LHS] = lhs;
3615 SubExprs[RHS] = rhs;
3616 }
3617
3618 BinaryOperator(StmtClass SC, EmptyShell Empty) : Expr(SC, Empty) {
3619 BinaryOperatorBits.Opc = BO_MulAssign;
3620 }
3621};
3622
3623/// CompoundAssignOperator - For compound assignments (e.g. +=), we keep
3624/// track of the type the operation is performed in. Due to the semantics of
3625/// these operators, the operands are promoted, the arithmetic performed, an
3626/// implicit conversion back to the result type done, then the assignment takes
3627/// place. This captures the intermediate type which the computation is done
3628/// in.
3629class CompoundAssignOperator : public BinaryOperator {
3630 QualType ComputationLHSType;
3631 QualType ComputationResultType;
3632public:
3633 CompoundAssignOperator(Expr *lhs, Expr *rhs, Opcode opc, QualType ResType,
3634 ExprValueKind VK, ExprObjectKind OK,
3635 QualType CompLHSType, QualType CompResultType,
3636 SourceLocation OpLoc, FPOptions FPFeatures)
3637 : BinaryOperator(lhs, rhs, opc, ResType, VK, OK, OpLoc, FPFeatures,
3638 true),
3639 ComputationLHSType(CompLHSType),
3640 ComputationResultType(CompResultType) {
3641 assert(isCompoundAssignmentOp() &&((isCompoundAssignmentOp() && "Only should be used for compound assignments"
) ? static_cast<void> (0) : __assert_fail ("isCompoundAssignmentOp() && \"Only should be used for compound assignments\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3642, __PRETTY_FUNCTION__))
3642 "Only should be used for compound assignments")((isCompoundAssignmentOp() && "Only should be used for compound assignments"
) ? static_cast<void> (0) : __assert_fail ("isCompoundAssignmentOp() && \"Only should be used for compound assignments\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3642, __PRETTY_FUNCTION__))
;
3643 }
3644
3645 /// Build an empty compound assignment operator expression.
3646 explicit CompoundAssignOperator(EmptyShell Empty)
3647 : BinaryOperator(CompoundAssignOperatorClass, Empty) { }
3648
3649 // The two computation types are the type the LHS is converted
3650 // to for the computation and the type of the result; the two are
3651 // distinct in a few cases (specifically, int+=ptr and ptr-=ptr).
3652 QualType getComputationLHSType() const { return ComputationLHSType; }
3653 void setComputationLHSType(QualType T) { ComputationLHSType = T; }
3654
3655 QualType getComputationResultType() const { return ComputationResultType; }
3656 void setComputationResultType(QualType T) { ComputationResultType = T; }
3657
3658 static bool classof(const Stmt *S) {
3659 return S->getStmtClass() == CompoundAssignOperatorClass;
3660 }
3661};
3662
3663/// AbstractConditionalOperator - An abstract base class for
3664/// ConditionalOperator and BinaryConditionalOperator.
3665class AbstractConditionalOperator : public Expr {
3666 SourceLocation QuestionLoc, ColonLoc;
3667 friend class ASTStmtReader;
3668
3669protected:
3670 AbstractConditionalOperator(StmtClass SC, QualType T,
3671 ExprValueKind VK, ExprObjectKind OK,
3672 bool TD, bool VD, bool ID,
3673 bool ContainsUnexpandedParameterPack,
3674 SourceLocation qloc,
3675 SourceLocation cloc)
3676 : Expr(SC, T, VK, OK, TD, VD, ID, ContainsUnexpandedParameterPack),
3677 QuestionLoc(qloc), ColonLoc(cloc) {}
3678
3679 AbstractConditionalOperator(StmtClass SC, EmptyShell Empty)
3680 : Expr(SC, Empty) { }
3681
3682public:
3683 // getCond - Return the expression representing the condition for
3684 // the ?: operator.
3685 Expr *getCond() const;
3686
3687 // getTrueExpr - Return the subexpression representing the value of
3688 // the expression if the condition evaluates to true.
3689 Expr *getTrueExpr() const;
3690
3691 // getFalseExpr - Return the subexpression representing the value of
3692 // the expression if the condition evaluates to false. This is
3693 // the same as getRHS.
3694 Expr *getFalseExpr() const;
3695
3696 SourceLocation getQuestionLoc() const { return QuestionLoc; }
3697 SourceLocation getColonLoc() const { return ColonLoc; }
3698
3699 static bool classof(const Stmt *T) {
3700 return T->getStmtClass() == ConditionalOperatorClass ||
3701 T->getStmtClass() == BinaryConditionalOperatorClass;
3702 }
3703};
3704
3705/// ConditionalOperator - The ?: ternary operator. The GNU "missing
3706/// middle" extension is a BinaryConditionalOperator.
3707class ConditionalOperator : public AbstractConditionalOperator {
3708 enum { COND, LHS, RHS, END_EXPR };
3709 Stmt* SubExprs[END_EXPR]; // Left/Middle/Right hand sides.
3710
3711 friend class ASTStmtReader;
3712public:
3713 ConditionalOperator(Expr *cond, SourceLocation QLoc, Expr *lhs,
3714 SourceLocation CLoc, Expr *rhs,
3715 QualType t, ExprValueKind VK, ExprObjectKind OK)
3716 : AbstractConditionalOperator(ConditionalOperatorClass, t, VK, OK,
3717 // FIXME: the type of the conditional operator doesn't
3718 // depend on the type of the conditional, but the standard
3719 // seems to imply that it could. File a bug!
3720 (lhs->isTypeDependent() || rhs->isTypeDependent()),
3721 (cond->isValueDependent() || lhs->isValueDependent() ||
3722 rhs->isValueDependent()),
3723 (cond->isInstantiationDependent() ||
3724 lhs->isInstantiationDependent() ||
3725 rhs->isInstantiationDependent()),
3726 (cond->containsUnexpandedParameterPack() ||
3727 lhs->containsUnexpandedParameterPack() ||
3728 rhs->containsUnexpandedParameterPack()),
3729 QLoc, CLoc) {
3730 SubExprs[COND] = cond;
3731 SubExprs[LHS] = lhs;
3732 SubExprs[RHS] = rhs;
3733 }
3734
3735 /// Build an empty conditional operator.
3736 explicit ConditionalOperator(EmptyShell Empty)
3737 : AbstractConditionalOperator(ConditionalOperatorClass, Empty) { }
3738
3739 // getCond - Return the expression representing the condition for
3740 // the ?: operator.
3741 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3742
3743 // getTrueExpr - Return the subexpression representing the value of
3744 // the expression if the condition evaluates to true.
3745 Expr *getTrueExpr() const { return cast<Expr>(SubExprs[LHS]); }
3746
3747 // getFalseExpr - Return the subexpression representing the value of
3748 // the expression if the condition evaluates to false. This is
3749 // the same as getRHS.
3750 Expr *getFalseExpr() const { return cast<Expr>(SubExprs[RHS]); }
3751
3752 Expr *getLHS() const { return cast<Expr>(SubExprs[LHS]); }
3753 Expr *getRHS() const { return cast<Expr>(SubExprs[RHS]); }
3754
3755 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3756 return getCond()->getBeginLoc();
3757 }
3758 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3759 return getRHS()->getEndLoc();
3760 }
3761
3762 static bool classof(const Stmt *T) {
3763 return T->getStmtClass() == ConditionalOperatorClass;
3764 }
3765
3766 // Iterators
3767 child_range children() {
3768 return child_range(&SubExprs[0], &SubExprs[0]+END_EXPR);
3769 }
3770 const_child_range children() const {
3771 return const_child_range(&SubExprs[0], &SubExprs[0] + END_EXPR);
3772 }
3773};
3774
3775/// BinaryConditionalOperator - The GNU extension to the conditional
3776/// operator which allows the middle operand to be omitted.
3777///
3778/// This is a different expression kind on the assumption that almost
3779/// every client ends up needing to know that these are different.
3780class BinaryConditionalOperator : public AbstractConditionalOperator {
3781 enum { COMMON, COND, LHS, RHS, NUM_SUBEXPRS };
3782
3783 /// - the common condition/left-hand-side expression, which will be
3784 /// evaluated as the opaque value
3785 /// - the condition, expressed in terms of the opaque value
3786 /// - the left-hand-side, expressed in terms of the opaque value
3787 /// - the right-hand-side
3788 Stmt *SubExprs[NUM_SUBEXPRS];
3789 OpaqueValueExpr *OpaqueValue;
3790
3791 friend class ASTStmtReader;
3792public:
3793 BinaryConditionalOperator(Expr *common, OpaqueValueExpr *opaqueValue,
3794 Expr *cond, Expr *lhs, Expr *rhs,
3795 SourceLocation qloc, SourceLocation cloc,
3796 QualType t, ExprValueKind VK, ExprObjectKind OK)
3797 : AbstractConditionalOperator(BinaryConditionalOperatorClass, t, VK, OK,
3798 (common->isTypeDependent() || rhs->isTypeDependent()),
3799 (common->isValueDependent() || rhs->isValueDependent()),
3800 (common->isInstantiationDependent() ||
3801 rhs->isInstantiationDependent()),
3802 (common->containsUnexpandedParameterPack() ||
3803 rhs->containsUnexpandedParameterPack()),
3804 qloc, cloc),
3805 OpaqueValue(opaqueValue) {
3806 SubExprs[COMMON] = common;
3807 SubExprs[COND] = cond;
3808 SubExprs[LHS] = lhs;
3809 SubExprs[RHS] = rhs;
3810 assert(OpaqueValue->getSourceExpr() == common && "Wrong opaque value")((OpaqueValue->getSourceExpr() == common && "Wrong opaque value"
) ? static_cast<void> (0) : __assert_fail ("OpaqueValue->getSourceExpr() == common && \"Wrong opaque value\""
, "/build/llvm-toolchain-snapshot-10~svn373517/tools/clang/include/clang/AST/Expr.h"
, 3810, __PRETTY_FUNCTION__))
;
3811 }
3812
3813 /// Build an empty conditional operator.
3814 explicit BinaryConditionalOperator(EmptyShell Empty)
3815 : AbstractConditionalOperator(BinaryConditionalOperatorClass, Empty) { }
3816
3817 /// getCommon - Return the common expression, written to the
3818 /// left of the condition. The opaque value will be bound to the
3819 /// result of this expression.
3820 Expr *getCommon() const { return cast<Expr>(SubExprs[COMMON]); }
3821
3822 /// getOpaqueValue - Return the opaque value placeholder.
3823 OpaqueValueExpr *getOpaqueValue() const { return OpaqueValue; }
3824
3825 /// getCond - Return the condition expression; this is defined
3826 /// in terms of the opaque value.
3827 Expr *getCond() const { return cast<Expr>(SubExprs[COND]); }
3828
3829 /// getTrueExpr - Return the subexpression which will be
3830 /// evaluated if the condition evaluates to true; this is defined
3831 /// in terms of the opaque value.
3832 Expr *getTrueExpr() const {
3833 return cast<Expr>(SubExprs[LHS]);
3834 }
3835
3836 /// getFalseExpr - Return the subexpression which will be
3837 /// evaluated if the condnition evaluates to false; this is
3838 /// defined in terms of the opaque value.
3839 Expr *getFalseExpr() const {
3840 return cast<Expr>(SubExprs[RHS]);
3841 }
3842
3843 SourceLocation getBeginLoc() const LLVM_READONLY__attribute__((__pure__)) {
3844 return getCommon()->getBeginLoc();
3845 }
3846 SourceLocation getEndLoc() const LLVM_READONLY__attribute__((__pure__)) {
3847 return getFalseExpr()->getEndLoc();
3848 }
3849
3850 static bool classof(const Stmt *T) {
3851 return T->getStmtClass() == BinaryConditionalOperatorClass;
3852 }
3853
3854 // Iterators
3855 child_range children() {
3856 return child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3857 }
3858 const_child_range children() const {
3859 return const_child_range(SubExprs, SubExprs + NUM_SUBEXPRS);
3860 }
3861};
3862
3863inline Expr *AbstractConditionalOperator::getCond() const {
3864 if (const ConditionalOperator *co = dyn_cast<ConditionalOperator>(this))
3865 return co->getCond();
3866