Bug Summary

File:clang/lib/CodeGen/CGObjCGNU.cpp
Warning:line 1235, column 43
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 CGObjCGNU.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 -setup-static-analyzer -analyzer-config-compatibility-mode=true -mrelocation-model pic -pic-level 2 -mthread-model posix -mframe-pointer=none -relaxed-aliasing -fmath-errno -fno-rounding-math -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~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/build-llvm/include -I /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/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~+201911111502510600c19528f1809/build-llvm/tools/clang/lib/CodeGen -fdebug-prefix-map=/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809=. -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -stack-protector 2 -fgnuc-version=4.2.1 -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-12-07-102640-14763-1 -x c++ /build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp

1//===------- CGObjCGNU.cpp - Emit LLVM Code from ASTs for a Module --------===//
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 provides Objective-C code generation targeting the GNU runtime. The
10// class in this file generates structures used by the GNU Objective-C runtime
11// library. These structures are defined in objc/objc.h and objc/objc-api.h in
12// the GNU runtime distribution.
13//
14//===----------------------------------------------------------------------===//
15
16#include "CGObjCRuntime.h"
17#include "CGCleanup.h"
18#include "CodeGenFunction.h"
19#include "CodeGenModule.h"
20#include "CGCXXABI.h"
21#include "clang/CodeGen/ConstantInitBuilder.h"
22#include "clang/AST/ASTContext.h"
23#include "clang/AST/Decl.h"
24#include "clang/AST/DeclObjC.h"
25#include "clang/AST/RecordLayout.h"
26#include "clang/AST/StmtObjC.h"
27#include "clang/Basic/FileManager.h"
28#include "clang/Basic/SourceManager.h"
29#include "llvm/ADT/SmallVector.h"
30#include "llvm/ADT/StringMap.h"
31#include "llvm/IR/DataLayout.h"
32#include "llvm/IR/Intrinsics.h"
33#include "llvm/IR/LLVMContext.h"
34#include "llvm/IR/Module.h"
35#include "llvm/Support/Compiler.h"
36#include "llvm/Support/ConvertUTF.h"
37#include <cctype>
38
39using namespace clang;
40using namespace CodeGen;
41
42namespace {
43
44std::string SymbolNameForMethod( StringRef ClassName,
45 StringRef CategoryName, const Selector MethodName,
46 bool isClassMethod) {
47 std::string MethodNameColonStripped = MethodName.getAsString();
48 std::replace(MethodNameColonStripped.begin(), MethodNameColonStripped.end(),
49 ':', '_');
50 return (Twine(isClassMethod ? "_c_" : "_i_") + ClassName + "_" +
51 CategoryName + "_" + MethodNameColonStripped).str();
52}
53
54/// Class that lazily initialises the runtime function. Avoids inserting the
55/// types and the function declaration into a module if they're not used, and
56/// avoids constructing the type more than once if it's used more than once.
57class LazyRuntimeFunction {
58 CodeGenModule *CGM;
59 llvm::FunctionType *FTy;
60 const char *FunctionName;
61 llvm::FunctionCallee Function;
62
63public:
64 /// Constructor leaves this class uninitialized, because it is intended to
65 /// be used as a field in another class and not all of the types that are
66 /// used as arguments will necessarily be available at construction time.
67 LazyRuntimeFunction()
68 : CGM(nullptr), FunctionName(nullptr), Function(nullptr) {}
69
70 /// Initialises the lazy function with the name, return type, and the types
71 /// of the arguments.
72 template <typename... Tys>
73 void init(CodeGenModule *Mod, const char *name, llvm::Type *RetTy,
74 Tys *... Types) {
75 CGM = Mod;
76 FunctionName = name;
77 Function = nullptr;
78 if(sizeof...(Tys)) {
79 SmallVector<llvm::Type *, 8> ArgTys({Types...});
80 FTy = llvm::FunctionType::get(RetTy, ArgTys, false);
81 }
82 else {
83 FTy = llvm::FunctionType::get(RetTy, None, false);
84 }
85 }
86
87 llvm::FunctionType *getType() { return FTy; }
88
89 /// Overloaded cast operator, allows the class to be implicitly cast to an
90 /// LLVM constant.
91 operator llvm::FunctionCallee() {
92 if (!Function) {
93 if (!FunctionName)
94 return nullptr;
95 Function = CGM->CreateRuntimeFunction(FTy, FunctionName);
96 }
97 return Function;
98 }
99};
100
101
102/// GNU Objective-C runtime code generation. This class implements the parts of
103/// Objective-C support that are specific to the GNU family of runtimes (GCC,
104/// GNUstep and ObjFW).
105class CGObjCGNU : public CGObjCRuntime {
106protected:
107 /// The LLVM module into which output is inserted
108 llvm::Module &TheModule;
109 /// strut objc_super. Used for sending messages to super. This structure
110 /// contains the receiver (object) and the expected class.
111 llvm::StructType *ObjCSuperTy;
112 /// struct objc_super*. The type of the argument to the superclass message
113 /// lookup functions.
114 llvm::PointerType *PtrToObjCSuperTy;
115 /// LLVM type for selectors. Opaque pointer (i8*) unless a header declaring
116 /// SEL is included in a header somewhere, in which case it will be whatever
117 /// type is declared in that header, most likely {i8*, i8*}.
118 llvm::PointerType *SelectorTy;
119 /// LLVM i8 type. Cached here to avoid repeatedly getting it in all of the
120 /// places where it's used
121 llvm::IntegerType *Int8Ty;
122 /// Pointer to i8 - LLVM type of char*, for all of the places where the
123 /// runtime needs to deal with C strings.
124 llvm::PointerType *PtrToInt8Ty;
125 /// struct objc_protocol type
126 llvm::StructType *ProtocolTy;
127 /// Protocol * type.
128 llvm::PointerType *ProtocolPtrTy;
129 /// Instance Method Pointer type. This is a pointer to a function that takes,
130 /// at a minimum, an object and a selector, and is the generic type for
131 /// Objective-C methods. Due to differences between variadic / non-variadic
132 /// calling conventions, it must always be cast to the correct type before
133 /// actually being used.
134 llvm::PointerType *IMPTy;
135 /// Type of an untyped Objective-C object. Clang treats id as a built-in type
136 /// when compiling Objective-C code, so this may be an opaque pointer (i8*),
137 /// but if the runtime header declaring it is included then it may be a
138 /// pointer to a structure.
139 llvm::PointerType *IdTy;
140 /// Pointer to a pointer to an Objective-C object. Used in the new ABI
141 /// message lookup function and some GC-related functions.
142 llvm::PointerType *PtrToIdTy;
143 /// The clang type of id. Used when using the clang CGCall infrastructure to
144 /// call Objective-C methods.
145 CanQualType ASTIdTy;
146 /// LLVM type for C int type.
147 llvm::IntegerType *IntTy;
148 /// LLVM type for an opaque pointer. This is identical to PtrToInt8Ty, but is
149 /// used in the code to document the difference between i8* meaning a pointer
150 /// to a C string and i8* meaning a pointer to some opaque type.
151 llvm::PointerType *PtrTy;
152 /// LLVM type for C long type. The runtime uses this in a lot of places where
153 /// it should be using intptr_t, but we can't fix this without breaking
154 /// compatibility with GCC...
155 llvm::IntegerType *LongTy;
156 /// LLVM type for C size_t. Used in various runtime data structures.
157 llvm::IntegerType *SizeTy;
158 /// LLVM type for C intptr_t.
159 llvm::IntegerType *IntPtrTy;
160 /// LLVM type for C ptrdiff_t. Mainly used in property accessor functions.
161 llvm::IntegerType *PtrDiffTy;
162 /// LLVM type for C int*. Used for GCC-ABI-compatible non-fragile instance
163 /// variables.
164 llvm::PointerType *PtrToIntTy;
165 /// LLVM type for Objective-C BOOL type.
166 llvm::Type *BoolTy;
167 /// 32-bit integer type, to save us needing to look it up every time it's used.
168 llvm::IntegerType *Int32Ty;
169 /// 64-bit integer type, to save us needing to look it up every time it's used.
170 llvm::IntegerType *Int64Ty;
171 /// The type of struct objc_property.
172 llvm::StructType *PropertyMetadataTy;
173 /// Metadata kind used to tie method lookups to message sends. The GNUstep
174 /// runtime provides some LLVM passes that can use this to do things like
175 /// automatic IMP caching and speculative inlining.
176 unsigned msgSendMDKind;
177 /// Does the current target use SEH-based exceptions? False implies
178 /// Itanium-style DWARF unwinding.
179 bool usesSEHExceptions;
180
181 /// Helper to check if we are targeting a specific runtime version or later.
182 bool isRuntime(ObjCRuntime::Kind kind, unsigned major, unsigned minor=0) {
183 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
184 return (R.getKind() == kind) &&
185 (R.getVersion() >= VersionTuple(major, minor));
186 }
187
188 std::string ManglePublicSymbol(StringRef Name) {
189 return (StringRef(CGM.getTriple().isOSBinFormatCOFF() ? "$_" : "._") + Name).str();
190 }
191
192 std::string SymbolForProtocol(Twine Name) {
193 return (ManglePublicSymbol("OBJC_PROTOCOL_") + Name).str();
194 }
195
196 std::string SymbolForProtocolRef(StringRef Name) {
197 return (ManglePublicSymbol("OBJC_REF_PROTOCOL_") + Name).str();
198 }
199
200
201 /// Helper function that generates a constant string and returns a pointer to
202 /// the start of the string. The result of this function can be used anywhere
203 /// where the C code specifies const char*.
204 llvm::Constant *MakeConstantString(StringRef Str, const char *Name = "") {
205 ConstantAddress Array = CGM.GetAddrOfConstantCString(Str, Name);
206 return llvm::ConstantExpr::getGetElementPtr(Array.getElementType(),
207 Array.getPointer(), Zeros);
208 }
209
210 /// Emits a linkonce_odr string, whose name is the prefix followed by the
211 /// string value. This allows the linker to combine the strings between
212 /// different modules. Used for EH typeinfo names, selector strings, and a
213 /// few other things.
214 llvm::Constant *ExportUniqueString(const std::string &Str,
215 const std::string &prefix,
216 bool Private=false) {
217 std::string name = prefix + Str;
218 auto *ConstStr = TheModule.getGlobalVariable(name);
219 if (!ConstStr) {
220 llvm::Constant *value = llvm::ConstantDataArray::getString(VMContext,Str);
221 auto *GV = new llvm::GlobalVariable(TheModule, value->getType(), true,
222 llvm::GlobalValue::LinkOnceODRLinkage, value, name);
223 GV->setComdat(TheModule.getOrInsertComdat(name));
224 if (Private)
225 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
226 ConstStr = GV;
227 }
228 return llvm::ConstantExpr::getGetElementPtr(ConstStr->getValueType(),
229 ConstStr, Zeros);
230 }
231
232 /// Returns a property name and encoding string.
233 llvm::Constant *MakePropertyEncodingString(const ObjCPropertyDecl *PD,
234 const Decl *Container) {
235 assert(!isRuntime(ObjCRuntime::GNUstep, 2))((!isRuntime(ObjCRuntime::GNUstep, 2)) ? static_cast<void>
(0) : __assert_fail ("!isRuntime(ObjCRuntime::GNUstep, 2)", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 235, __PRETTY_FUNCTION__))
;
236 if (isRuntime(ObjCRuntime::GNUstep, 1, 6)) {
237 std::string NameAndAttributes;
238 std::string TypeStr =
239 CGM.getContext().getObjCEncodingForPropertyDecl(PD, Container);
240 NameAndAttributes += '\0';
241 NameAndAttributes += TypeStr.length() + 3;
242 NameAndAttributes += TypeStr;
243 NameAndAttributes += '\0';
244 NameAndAttributes += PD->getNameAsString();
245 return MakeConstantString(NameAndAttributes);
246 }
247 return MakeConstantString(PD->getNameAsString());
248 }
249
250 /// Push the property attributes into two structure fields.
251 void PushPropertyAttributes(ConstantStructBuilder &Fields,
252 const ObjCPropertyDecl *property, bool isSynthesized=true, bool
253 isDynamic=true) {
254 int attrs = property->getPropertyAttributes();
255 // For read-only properties, clear the copy and retain flags
256 if (attrs & ObjCPropertyDecl::OBJC_PR_readonly) {
257 attrs &= ~ObjCPropertyDecl::OBJC_PR_copy;
258 attrs &= ~ObjCPropertyDecl::OBJC_PR_retain;
259 attrs &= ~ObjCPropertyDecl::OBJC_PR_weak;
260 attrs &= ~ObjCPropertyDecl::OBJC_PR_strong;
261 }
262 // The first flags field has the same attribute values as clang uses internally
263 Fields.addInt(Int8Ty, attrs & 0xff);
264 attrs >>= 8;
265 attrs <<= 2;
266 // For protocol properties, synthesized and dynamic have no meaning, so we
267 // reuse these flags to indicate that this is a protocol property (both set
268 // has no meaning, as a property can't be both synthesized and dynamic)
269 attrs |= isSynthesized ? (1<<0) : 0;
270 attrs |= isDynamic ? (1<<1) : 0;
271 // The second field is the next four fields left shifted by two, with the
272 // low bit set to indicate whether the field is synthesized or dynamic.
273 Fields.addInt(Int8Ty, attrs & 0xff);
274 // Two padding fields
275 Fields.addInt(Int8Ty, 0);
276 Fields.addInt(Int8Ty, 0);
277 }
278
279 virtual llvm::Constant *GenerateCategoryProtocolList(const
280 ObjCCategoryDecl *OCD);
281 virtual ConstantArrayBuilder PushPropertyListHeader(ConstantStructBuilder &Fields,
282 int count) {
283 // int count;
284 Fields.addInt(IntTy, count);
285 // int size; (only in GNUstep v2 ABI.
286 if (isRuntime(ObjCRuntime::GNUstep, 2)) {
287 llvm::DataLayout td(&TheModule);
288 Fields.addInt(IntTy, td.getTypeSizeInBits(PropertyMetadataTy) /
289 CGM.getContext().getCharWidth());
290 }
291 // struct objc_property_list *next;
292 Fields.add(NULLPtr);
293 // struct objc_property properties[]
294 return Fields.beginArray(PropertyMetadataTy);
295 }
296 virtual void PushProperty(ConstantArrayBuilder &PropertiesArray,
297 const ObjCPropertyDecl *property,
298 const Decl *OCD,
299 bool isSynthesized=true, bool
300 isDynamic=true) {
301 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
302 ASTContext &Context = CGM.getContext();
303 Fields.add(MakePropertyEncodingString(property, OCD));
304 PushPropertyAttributes(Fields, property, isSynthesized, isDynamic);
305 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
306 if (accessor) {
307 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
308 llvm::Constant *TypeEncoding = MakeConstantString(TypeStr);
309 Fields.add(MakeConstantString(accessor->getSelector().getAsString()));
310 Fields.add(TypeEncoding);
311 } else {
312 Fields.add(NULLPtr);
313 Fields.add(NULLPtr);
314 }
315 };
316 addPropertyMethod(property->getGetterMethodDecl());
317 addPropertyMethod(property->getSetterMethodDecl());
318 Fields.finishAndAddTo(PropertiesArray);
319 }
320
321 /// Ensures that the value has the required type, by inserting a bitcast if
322 /// required. This function lets us avoid inserting bitcasts that are
323 /// redundant.
324 llvm::Value* EnforceType(CGBuilderTy &B, llvm::Value *V, llvm::Type *Ty) {
325 if (V->getType() == Ty) return V;
326 return B.CreateBitCast(V, Ty);
327 }
328 Address EnforceType(CGBuilderTy &B, Address V, llvm::Type *Ty) {
329 if (V.getType() == Ty) return V;
330 return B.CreateBitCast(V, Ty);
331 }
332
333 // Some zeros used for GEPs in lots of places.
334 llvm::Constant *Zeros[2];
335 /// Null pointer value. Mainly used as a terminator in various arrays.
336 llvm::Constant *NULLPtr;
337 /// LLVM context.
338 llvm::LLVMContext &VMContext;
339
340protected:
341
342 /// Placeholder for the class. Lots of things refer to the class before we've
343 /// actually emitted it. We use this alias as a placeholder, and then replace
344 /// it with a pointer to the class structure before finally emitting the
345 /// module.
346 llvm::GlobalAlias *ClassPtrAlias;
347 /// Placeholder for the metaclass. Lots of things refer to the class before
348 /// we've / actually emitted it. We use this alias as a placeholder, and then
349 /// replace / it with a pointer to the metaclass structure before finally
350 /// emitting the / module.
351 llvm::GlobalAlias *MetaClassPtrAlias;
352 /// All of the classes that have been generated for this compilation units.
353 std::vector<llvm::Constant*> Classes;
354 /// All of the categories that have been generated for this compilation units.
355 std::vector<llvm::Constant*> Categories;
356 /// All of the Objective-C constant strings that have been generated for this
357 /// compilation units.
358 std::vector<llvm::Constant*> ConstantStrings;
359 /// Map from string values to Objective-C constant strings in the output.
360 /// Used to prevent emitting Objective-C strings more than once. This should
361 /// not be required at all - CodeGenModule should manage this list.
362 llvm::StringMap<llvm::Constant*> ObjCStrings;
363 /// All of the protocols that have been declared.
364 llvm::StringMap<llvm::Constant*> ExistingProtocols;
365 /// For each variant of a selector, we store the type encoding and a
366 /// placeholder value. For an untyped selector, the type will be the empty
367 /// string. Selector references are all done via the module's selector table,
368 /// so we create an alias as a placeholder and then replace it with the real
369 /// value later.
370 typedef std::pair<std::string, llvm::GlobalAlias*> TypedSelector;
371 /// Type of the selector map. This is roughly equivalent to the structure
372 /// used in the GNUstep runtime, which maintains a list of all of the valid
373 /// types for a selector in a table.
374 typedef llvm::DenseMap<Selector, SmallVector<TypedSelector, 2> >
375 SelectorMap;
376 /// A map from selectors to selector types. This allows us to emit all
377 /// selectors of the same name and type together.
378 SelectorMap SelectorTable;
379
380 /// Selectors related to memory management. When compiling in GC mode, we
381 /// omit these.
382 Selector RetainSel, ReleaseSel, AutoreleaseSel;
383 /// Runtime functions used for memory management in GC mode. Note that clang
384 /// supports code generation for calling these functions, but neither GNU
385 /// runtime actually supports this API properly yet.
386 LazyRuntimeFunction IvarAssignFn, StrongCastAssignFn, MemMoveFn, WeakReadFn,
387 WeakAssignFn, GlobalAssignFn;
388
389 typedef std::pair<std::string, std::string> ClassAliasPair;
390 /// All classes that have aliases set for them.
391 std::vector<ClassAliasPair> ClassAliases;
392
393protected:
394 /// Function used for throwing Objective-C exceptions.
395 LazyRuntimeFunction ExceptionThrowFn;
396 /// Function used for rethrowing exceptions, used at the end of \@finally or
397 /// \@synchronize blocks.
398 LazyRuntimeFunction ExceptionReThrowFn;
399 /// Function called when entering a catch function. This is required for
400 /// differentiating Objective-C exceptions and foreign exceptions.
401 LazyRuntimeFunction EnterCatchFn;
402 /// Function called when exiting from a catch block. Used to do exception
403 /// cleanup.
404 LazyRuntimeFunction ExitCatchFn;
405 /// Function called when entering an \@synchronize block. Acquires the lock.
406 LazyRuntimeFunction SyncEnterFn;
407 /// Function called when exiting an \@synchronize block. Releases the lock.
408 LazyRuntimeFunction SyncExitFn;
409
410private:
411 /// Function called if fast enumeration detects that the collection is
412 /// modified during the update.
413 LazyRuntimeFunction EnumerationMutationFn;
414 /// Function for implementing synthesized property getters that return an
415 /// object.
416 LazyRuntimeFunction GetPropertyFn;
417 /// Function for implementing synthesized property setters that return an
418 /// object.
419 LazyRuntimeFunction SetPropertyFn;
420 /// Function used for non-object declared property getters.
421 LazyRuntimeFunction GetStructPropertyFn;
422 /// Function used for non-object declared property setters.
423 LazyRuntimeFunction SetStructPropertyFn;
424
425protected:
426 /// The version of the runtime that this class targets. Must match the
427 /// version in the runtime.
428 int RuntimeVersion;
429 /// The version of the protocol class. Used to differentiate between ObjC1
430 /// and ObjC2 protocols. Objective-C 1 protocols can not contain optional
431 /// components and can not contain declared properties. We always emit
432 /// Objective-C 2 property structures, but we have to pretend that they're
433 /// Objective-C 1 property structures when targeting the GCC runtime or it
434 /// will abort.
435 const int ProtocolVersion;
436 /// The version of the class ABI. This value is used in the class structure
437 /// and indicates how various fields should be interpreted.
438 const int ClassABIVersion;
439 /// Generates an instance variable list structure. This is a structure
440 /// containing a size and an array of structures containing instance variable
441 /// metadata. This is used purely for introspection in the fragile ABI. In
442 /// the non-fragile ABI, it's used for instance variable fixup.
443 virtual llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
444 ArrayRef<llvm::Constant *> IvarTypes,
445 ArrayRef<llvm::Constant *> IvarOffsets,
446 ArrayRef<llvm::Constant *> IvarAlign,
447 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership);
448
449 /// Generates a method list structure. This is a structure containing a size
450 /// and an array of structures containing method metadata.
451 ///
452 /// This structure is used by both classes and categories, and contains a next
453 /// pointer allowing them to be chained together in a linked list.
454 llvm::Constant *GenerateMethodList(StringRef ClassName,
455 StringRef CategoryName,
456 ArrayRef<const ObjCMethodDecl*> Methods,
457 bool isClassMethodList);
458
459 /// Emits an empty protocol. This is used for \@protocol() where no protocol
460 /// is found. The runtime will (hopefully) fix up the pointer to refer to the
461 /// real protocol.
462 virtual llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName);
463
464 /// Generates a list of property metadata structures. This follows the same
465 /// pattern as method and instance variable metadata lists.
466 llvm::Constant *GeneratePropertyList(const Decl *Container,
467 const ObjCContainerDecl *OCD,
468 bool isClassProperty=false,
469 bool protocolOptionalProperties=false);
470
471 /// Generates a list of referenced protocols. Classes, categories, and
472 /// protocols all use this structure.
473 llvm::Constant *GenerateProtocolList(ArrayRef<std::string> Protocols);
474
475 /// To ensure that all protocols are seen by the runtime, we add a category on
476 /// a class defined in the runtime, declaring no methods, but adopting the
477 /// protocols. This is a horribly ugly hack, but it allows us to collect all
478 /// of the protocols without changing the ABI.
479 void GenerateProtocolHolderCategory();
480
481 /// Generates a class structure.
482 llvm::Constant *GenerateClassStructure(
483 llvm::Constant *MetaClass,
484 llvm::Constant *SuperClass,
485 unsigned info,
486 const char *Name,
487 llvm::Constant *Version,
488 llvm::Constant *InstanceSize,
489 llvm::Constant *IVars,
490 llvm::Constant *Methods,
491 llvm::Constant *Protocols,
492 llvm::Constant *IvarOffsets,
493 llvm::Constant *Properties,
494 llvm::Constant *StrongIvarBitmap,
495 llvm::Constant *WeakIvarBitmap,
496 bool isMeta=false);
497
498 /// Generates a method list. This is used by protocols to define the required
499 /// and optional methods.
500 virtual llvm::Constant *GenerateProtocolMethodList(
501 ArrayRef<const ObjCMethodDecl*> Methods);
502 /// Emits optional and required method lists.
503 template<class T>
504 void EmitProtocolMethodList(T &&Methods, llvm::Constant *&Required,
505 llvm::Constant *&Optional) {
506 SmallVector<const ObjCMethodDecl*, 16> RequiredMethods;
507 SmallVector<const ObjCMethodDecl*, 16> OptionalMethods;
508 for (const auto *I : Methods)
509 if (I->isOptional())
510 OptionalMethods.push_back(I);
511 else
512 RequiredMethods.push_back(I);
513 Required = GenerateProtocolMethodList(RequiredMethods);
514 Optional = GenerateProtocolMethodList(OptionalMethods);
515 }
516
517 /// Returns a selector with the specified type encoding. An empty string is
518 /// used to return an untyped selector (with the types field set to NULL).
519 virtual llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
520 const std::string &TypeEncoding);
521
522 /// Returns the name of ivar offset variables. In the GNUstep v1 ABI, this
523 /// contains the class and ivar names, in the v2 ABI this contains the type
524 /// encoding as well.
525 virtual std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
526 const ObjCIvarDecl *Ivar) {
527 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
528 + '.' + Ivar->getNameAsString();
529 return Name;
530 }
531 /// Returns the variable used to store the offset of an instance variable.
532 llvm::GlobalVariable *ObjCIvarOffsetVariable(const ObjCInterfaceDecl *ID,
533 const ObjCIvarDecl *Ivar);
534 /// Emits a reference to a class. This allows the linker to object if there
535 /// is no class of the matching name.
536 void EmitClassRef(const std::string &className);
537
538 /// Emits a pointer to the named class
539 virtual llvm::Value *GetClassNamed(CodeGenFunction &CGF,
540 const std::string &Name, bool isWeak);
541
542 /// Looks up the method for sending a message to the specified object. This
543 /// mechanism differs between the GCC and GNU runtimes, so this method must be
544 /// overridden in subclasses.
545 virtual llvm::Value *LookupIMP(CodeGenFunction &CGF,
546 llvm::Value *&Receiver,
547 llvm::Value *cmd,
548 llvm::MDNode *node,
549 MessageSendInfo &MSI) = 0;
550
551 /// Looks up the method for sending a message to a superclass. This
552 /// mechanism differs between the GCC and GNU runtimes, so this method must
553 /// be overridden in subclasses.
554 virtual llvm::Value *LookupIMPSuper(CodeGenFunction &CGF,
555 Address ObjCSuper,
556 llvm::Value *cmd,
557 MessageSendInfo &MSI) = 0;
558
559 /// Libobjc2 uses a bitfield representation where small(ish) bitfields are
560 /// stored in a 64-bit value with the low bit set to 1 and the remaining 63
561 /// bits set to their values, LSB first, while larger ones are stored in a
562 /// structure of this / form:
563 ///
564 /// struct { int32_t length; int32_t values[length]; };
565 ///
566 /// The values in the array are stored in host-endian format, with the least
567 /// significant bit being assumed to come first in the bitfield. Therefore,
568 /// a bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] },
569 /// while a bitfield / with the 63rd bit set will be 1<<64.
570 llvm::Constant *MakeBitField(ArrayRef<bool> bits);
571
572public:
573 CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
574 unsigned protocolClassVersion, unsigned classABI=1);
575
576 ConstantAddress GenerateConstantString(const StringLiteral *) override;
577
578 RValue
579 GenerateMessageSend(CodeGenFunction &CGF, ReturnValueSlot Return,
580 QualType ResultType, Selector Sel,
581 llvm::Value *Receiver, const CallArgList &CallArgs,
582 const ObjCInterfaceDecl *Class,
583 const ObjCMethodDecl *Method) override;
584 RValue
585 GenerateMessageSendSuper(CodeGenFunction &CGF, ReturnValueSlot Return,
586 QualType ResultType, Selector Sel,
587 const ObjCInterfaceDecl *Class,
588 bool isCategoryImpl, llvm::Value *Receiver,
589 bool IsClassMessage, const CallArgList &CallArgs,
590 const ObjCMethodDecl *Method) override;
591 llvm::Value *GetClass(CodeGenFunction &CGF,
592 const ObjCInterfaceDecl *OID) override;
593 llvm::Value *GetSelector(CodeGenFunction &CGF, Selector Sel) override;
594 Address GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) override;
595 llvm::Value *GetSelector(CodeGenFunction &CGF,
596 const ObjCMethodDecl *Method) override;
597 virtual llvm::Constant *GetConstantSelector(Selector Sel,
598 const std::string &TypeEncoding) {
599 llvm_unreachable("Runtime unable to generate constant selector")::llvm::llvm_unreachable_internal("Runtime unable to generate constant selector"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 599)
;
600 }
601 llvm::Constant *GetConstantSelector(const ObjCMethodDecl *M) {
602 return GetConstantSelector(M->getSelector(),
603 CGM.getContext().getObjCEncodingForMethodDecl(M));
604 }
605 llvm::Constant *GetEHType(QualType T) override;
606
607 llvm::Function *GenerateMethod(const ObjCMethodDecl *OMD,
608 const ObjCContainerDecl *CD) override;
609 void GenerateCategory(const ObjCCategoryImplDecl *CMD) override;
610 void GenerateClass(const ObjCImplementationDecl *ClassDecl) override;
611 void RegisterAlias(const ObjCCompatibleAliasDecl *OAD) override;
612 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
613 const ObjCProtocolDecl *PD) override;
614 void GenerateProtocol(const ObjCProtocolDecl *PD) override;
615 llvm::Function *ModuleInitFunction() override;
616 llvm::FunctionCallee GetPropertyGetFunction() override;
617 llvm::FunctionCallee GetPropertySetFunction() override;
618 llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
619 bool copy) override;
620 llvm::FunctionCallee GetSetStructFunction() override;
621 llvm::FunctionCallee GetGetStructFunction() override;
622 llvm::FunctionCallee GetCppAtomicObjectGetFunction() override;
623 llvm::FunctionCallee GetCppAtomicObjectSetFunction() override;
624 llvm::FunctionCallee EnumerationMutationFunction() override;
625
626 void EmitTryStmt(CodeGenFunction &CGF,
627 const ObjCAtTryStmt &S) override;
628 void EmitSynchronizedStmt(CodeGenFunction &CGF,
629 const ObjCAtSynchronizedStmt &S) override;
630 void EmitThrowStmt(CodeGenFunction &CGF,
631 const ObjCAtThrowStmt &S,
632 bool ClearInsertionPoint=true) override;
633 llvm::Value * EmitObjCWeakRead(CodeGenFunction &CGF,
634 Address AddrWeakObj) override;
635 void EmitObjCWeakAssign(CodeGenFunction &CGF,
636 llvm::Value *src, Address dst) override;
637 void EmitObjCGlobalAssign(CodeGenFunction &CGF,
638 llvm::Value *src, Address dest,
639 bool threadlocal=false) override;
640 void EmitObjCIvarAssign(CodeGenFunction &CGF, llvm::Value *src,
641 Address dest, llvm::Value *ivarOffset) override;
642 void EmitObjCStrongCastAssign(CodeGenFunction &CGF,
643 llvm::Value *src, Address dest) override;
644 void EmitGCMemmoveCollectable(CodeGenFunction &CGF, Address DestPtr,
645 Address SrcPtr,
646 llvm::Value *Size) override;
647 LValue EmitObjCValueForIvar(CodeGenFunction &CGF, QualType ObjectTy,
648 llvm::Value *BaseValue, const ObjCIvarDecl *Ivar,
649 unsigned CVRQualifiers) override;
650 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
651 const ObjCInterfaceDecl *Interface,
652 const ObjCIvarDecl *Ivar) override;
653 llvm::Value *EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) override;
654 llvm::Constant *BuildGCBlockLayout(CodeGenModule &CGM,
655 const CGBlockInfo &blockInfo) override {
656 return NULLPtr;
657 }
658 llvm::Constant *BuildRCBlockLayout(CodeGenModule &CGM,
659 const CGBlockInfo &blockInfo) override {
660 return NULLPtr;
661 }
662
663 llvm::Constant *BuildByrefLayout(CodeGenModule &CGM, QualType T) override {
664 return NULLPtr;
665 }
666};
667
668/// Class representing the legacy GCC Objective-C ABI. This is the default when
669/// -fobjc-nonfragile-abi is not specified.
670///
671/// The GCC ABI target actually generates code that is approximately compatible
672/// with the new GNUstep runtime ABI, but refrains from using any features that
673/// would not work with the GCC runtime. For example, clang always generates
674/// the extended form of the class structure, and the extra fields are simply
675/// ignored by GCC libobjc.
676class CGObjCGCC : public CGObjCGNU {
677 /// The GCC ABI message lookup function. Returns an IMP pointing to the
678 /// method implementation for this message.
679 LazyRuntimeFunction MsgLookupFn;
680 /// The GCC ABI superclass message lookup function. Takes a pointer to a
681 /// structure describing the receiver and the class, and a selector as
682 /// arguments. Returns the IMP for the corresponding method.
683 LazyRuntimeFunction MsgLookupSuperFn;
684
685protected:
686 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
687 llvm::Value *cmd, llvm::MDNode *node,
688 MessageSendInfo &MSI) override {
689 CGBuilderTy &Builder = CGF.Builder;
690 llvm::Value *args[] = {
691 EnforceType(Builder, Receiver, IdTy),
692 EnforceType(Builder, cmd, SelectorTy) };
693 llvm::CallBase *imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
694 imp->setMetadata(msgSendMDKind, node);
695 return imp;
696 }
697
698 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
699 llvm::Value *cmd, MessageSendInfo &MSI) override {
700 CGBuilderTy &Builder = CGF.Builder;
701 llvm::Value *lookupArgs[] = {EnforceType(Builder, ObjCSuper,
702 PtrToObjCSuperTy).getPointer(), cmd};
703 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
704 }
705
706public:
707 CGObjCGCC(CodeGenModule &Mod) : CGObjCGNU(Mod, 8, 2) {
708 // IMP objc_msg_lookup(id, SEL);
709 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
710 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
711 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
712 PtrToObjCSuperTy, SelectorTy);
713 }
714};
715
716/// Class used when targeting the new GNUstep runtime ABI.
717class CGObjCGNUstep : public CGObjCGNU {
718 /// The slot lookup function. Returns a pointer to a cacheable structure
719 /// that contains (among other things) the IMP.
720 LazyRuntimeFunction SlotLookupFn;
721 /// The GNUstep ABI superclass message lookup function. Takes a pointer to
722 /// a structure describing the receiver and the class, and a selector as
723 /// arguments. Returns the slot for the corresponding method. Superclass
724 /// message lookup rarely changes, so this is a good caching opportunity.
725 LazyRuntimeFunction SlotLookupSuperFn;
726 /// Specialised function for setting atomic retain properties
727 LazyRuntimeFunction SetPropertyAtomic;
728 /// Specialised function for setting atomic copy properties
729 LazyRuntimeFunction SetPropertyAtomicCopy;
730 /// Specialised function for setting nonatomic retain properties
731 LazyRuntimeFunction SetPropertyNonAtomic;
732 /// Specialised function for setting nonatomic copy properties
733 LazyRuntimeFunction SetPropertyNonAtomicCopy;
734 /// Function to perform atomic copies of C++ objects with nontrivial copy
735 /// constructors from Objective-C ivars.
736 LazyRuntimeFunction CxxAtomicObjectGetFn;
737 /// Function to perform atomic copies of C++ objects with nontrivial copy
738 /// constructors to Objective-C ivars.
739 LazyRuntimeFunction CxxAtomicObjectSetFn;
740 /// Type of an slot structure pointer. This is returned by the various
741 /// lookup functions.
742 llvm::Type *SlotTy;
743
744 public:
745 llvm::Constant *GetEHType(QualType T) override;
746
747 protected:
748 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
749 llvm::Value *cmd, llvm::MDNode *node,
750 MessageSendInfo &MSI) override {
751 CGBuilderTy &Builder = CGF.Builder;
752 llvm::FunctionCallee LookupFn = SlotLookupFn;
753
754 // Store the receiver on the stack so that we can reload it later
755 Address ReceiverPtr =
756 CGF.CreateTempAlloca(Receiver->getType(), CGF.getPointerAlign());
757 Builder.CreateStore(Receiver, ReceiverPtr);
758
759 llvm::Value *self;
760
761 if (isa<ObjCMethodDecl>(CGF.CurCodeDecl)) {
762 self = CGF.LoadObjCSelf();
763 } else {
764 self = llvm::ConstantPointerNull::get(IdTy);
765 }
766
767 // The lookup function is guaranteed not to capture the receiver pointer.
768 if (auto *LookupFn2 = dyn_cast<llvm::Function>(LookupFn.getCallee()))
769 LookupFn2->addParamAttr(0, llvm::Attribute::NoCapture);
770
771 llvm::Value *args[] = {
772 EnforceType(Builder, ReceiverPtr.getPointer(), PtrToIdTy),
773 EnforceType(Builder, cmd, SelectorTy),
774 EnforceType(Builder, self, IdTy) };
775 llvm::CallBase *slot = CGF.EmitRuntimeCallOrInvoke(LookupFn, args);
776 slot->setOnlyReadsMemory();
777 slot->setMetadata(msgSendMDKind, node);
778
779 // Load the imp from the slot
780 llvm::Value *imp = Builder.CreateAlignedLoad(
781 Builder.CreateStructGEP(nullptr, slot, 4), CGF.getPointerAlign());
782
783 // The lookup function may have changed the receiver, so make sure we use
784 // the new one.
785 Receiver = Builder.CreateLoad(ReceiverPtr, true);
786 return imp;
787 }
788
789 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
790 llvm::Value *cmd,
791 MessageSendInfo &MSI) override {
792 CGBuilderTy &Builder = CGF.Builder;
793 llvm::Value *lookupArgs[] = {ObjCSuper.getPointer(), cmd};
794
795 llvm::CallInst *slot =
796 CGF.EmitNounwindRuntimeCall(SlotLookupSuperFn, lookupArgs);
797 slot->setOnlyReadsMemory();
798
799 return Builder.CreateAlignedLoad(Builder.CreateStructGEP(nullptr, slot, 4),
800 CGF.getPointerAlign());
801 }
802
803 public:
804 CGObjCGNUstep(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 9, 3, 1) {}
805 CGObjCGNUstep(CodeGenModule &Mod, unsigned ABI, unsigned ProtocolABI,
806 unsigned ClassABI) :
807 CGObjCGNU(Mod, ABI, ProtocolABI, ClassABI) {
808 const ObjCRuntime &R = CGM.getLangOpts().ObjCRuntime;
809
810 llvm::StructType *SlotStructTy =
811 llvm::StructType::get(PtrTy, PtrTy, PtrTy, IntTy, IMPTy);
812 SlotTy = llvm::PointerType::getUnqual(SlotStructTy);
813 // Slot_t objc_msg_lookup_sender(id *receiver, SEL selector, id sender);
814 SlotLookupFn.init(&CGM, "objc_msg_lookup_sender", SlotTy, PtrToIdTy,
815 SelectorTy, IdTy);
816 // Slot_t objc_slot_lookup_super(struct objc_super*, SEL);
817 SlotLookupSuperFn.init(&CGM, "objc_slot_lookup_super", SlotTy,
818 PtrToObjCSuperTy, SelectorTy);
819 // If we're in ObjC++ mode, then we want to make
820 if (usesSEHExceptions) {
821 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
822 // void objc_exception_rethrow(void)
823 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy);
824 } else if (CGM.getLangOpts().CPlusPlus) {
825 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
826 // void *__cxa_begin_catch(void *e)
827 EnterCatchFn.init(&CGM, "__cxa_begin_catch", PtrTy, PtrTy);
828 // void __cxa_end_catch(void)
829 ExitCatchFn.init(&CGM, "__cxa_end_catch", VoidTy);
830 // void _Unwind_Resume_or_Rethrow(void*)
831 ExceptionReThrowFn.init(&CGM, "_Unwind_Resume_or_Rethrow", VoidTy,
832 PtrTy);
833 } else if (R.getVersion() >= VersionTuple(1, 7)) {
834 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
835 // id objc_begin_catch(void *e)
836 EnterCatchFn.init(&CGM, "objc_begin_catch", IdTy, PtrTy);
837 // void objc_end_catch(void)
838 ExitCatchFn.init(&CGM, "objc_end_catch", VoidTy);
839 // void _Unwind_Resume_or_Rethrow(void*)
840 ExceptionReThrowFn.init(&CGM, "objc_exception_rethrow", VoidTy, PtrTy);
841 }
842 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
843 SetPropertyAtomic.init(&CGM, "objc_setProperty_atomic", VoidTy, IdTy,
844 SelectorTy, IdTy, PtrDiffTy);
845 SetPropertyAtomicCopy.init(&CGM, "objc_setProperty_atomic_copy", VoidTy,
846 IdTy, SelectorTy, IdTy, PtrDiffTy);
847 SetPropertyNonAtomic.init(&CGM, "objc_setProperty_nonatomic", VoidTy,
848 IdTy, SelectorTy, IdTy, PtrDiffTy);
849 SetPropertyNonAtomicCopy.init(&CGM, "objc_setProperty_nonatomic_copy",
850 VoidTy, IdTy, SelectorTy, IdTy, PtrDiffTy);
851 // void objc_setCppObjectAtomic(void *dest, const void *src, void
852 // *helper);
853 CxxAtomicObjectSetFn.init(&CGM, "objc_setCppObjectAtomic", VoidTy, PtrTy,
854 PtrTy, PtrTy);
855 // void objc_getCppObjectAtomic(void *dest, const void *src, void
856 // *helper);
857 CxxAtomicObjectGetFn.init(&CGM, "objc_getCppObjectAtomic", VoidTy, PtrTy,
858 PtrTy, PtrTy);
859 }
860
861 llvm::FunctionCallee GetCppAtomicObjectGetFunction() override {
862 // The optimised functions were added in version 1.7 of the GNUstep
863 // runtime.
864 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=((CGM.getLangOpts().ObjCRuntime.getVersion() >= VersionTuple
(1, 7)) ? static_cast<void> (0) : __assert_fail ("CGM.getLangOpts().ObjCRuntime.getVersion() >= VersionTuple(1, 7)"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 865, __PRETTY_FUNCTION__))
865 VersionTuple(1, 7))((CGM.getLangOpts().ObjCRuntime.getVersion() >= VersionTuple
(1, 7)) ? static_cast<void> (0) : __assert_fail ("CGM.getLangOpts().ObjCRuntime.getVersion() >= VersionTuple(1, 7)"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 865, __PRETTY_FUNCTION__))
;
866 return CxxAtomicObjectGetFn;
867 }
868
869 llvm::FunctionCallee GetCppAtomicObjectSetFunction() override {
870 // The optimised functions were added in version 1.7 of the GNUstep
871 // runtime.
872 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=((CGM.getLangOpts().ObjCRuntime.getVersion() >= VersionTuple
(1, 7)) ? static_cast<void> (0) : __assert_fail ("CGM.getLangOpts().ObjCRuntime.getVersion() >= VersionTuple(1, 7)"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 873, __PRETTY_FUNCTION__))
873 VersionTuple(1, 7))((CGM.getLangOpts().ObjCRuntime.getVersion() >= VersionTuple
(1, 7)) ? static_cast<void> (0) : __assert_fail ("CGM.getLangOpts().ObjCRuntime.getVersion() >= VersionTuple(1, 7)"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 873, __PRETTY_FUNCTION__))
;
874 return CxxAtomicObjectSetFn;
875 }
876
877 llvm::FunctionCallee GetOptimizedPropertySetFunction(bool atomic,
878 bool copy) override {
879 // The optimised property functions omit the GC check, and so are not
880 // safe to use in GC mode. The standard functions are fast in GC mode,
881 // so there is less advantage in using them.
882 assert ((CGM.getLangOpts().getGC() == LangOptions::NonGC))(((CGM.getLangOpts().getGC() == LangOptions::NonGC)) ? static_cast
<void> (0) : __assert_fail ("(CGM.getLangOpts().getGC() == LangOptions::NonGC)"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 882, __PRETTY_FUNCTION__))
;
883 // The optimised functions were added in version 1.7 of the GNUstep
884 // runtime.
885 assert (CGM.getLangOpts().ObjCRuntime.getVersion() >=((CGM.getLangOpts().ObjCRuntime.getVersion() >= VersionTuple
(1, 7)) ? static_cast<void> (0) : __assert_fail ("CGM.getLangOpts().ObjCRuntime.getVersion() >= VersionTuple(1, 7)"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 886, __PRETTY_FUNCTION__))
886 VersionTuple(1, 7))((CGM.getLangOpts().ObjCRuntime.getVersion() >= VersionTuple
(1, 7)) ? static_cast<void> (0) : __assert_fail ("CGM.getLangOpts().ObjCRuntime.getVersion() >= VersionTuple(1, 7)"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 886, __PRETTY_FUNCTION__))
;
887
888 if (atomic) {
889 if (copy) return SetPropertyAtomicCopy;
890 return SetPropertyAtomic;
891 }
892
893 return copy ? SetPropertyNonAtomicCopy : SetPropertyNonAtomic;
894 }
895};
896
897/// GNUstep Objective-C ABI version 2 implementation.
898/// This is the ABI that provides a clean break with the legacy GCC ABI and
899/// cleans up a number of things that were added to work around 1980s linkers.
900class CGObjCGNUstep2 : public CGObjCGNUstep {
901 enum SectionKind
902 {
903 SelectorSection = 0,
904 ClassSection,
905 ClassReferenceSection,
906 CategorySection,
907 ProtocolSection,
908 ProtocolReferenceSection,
909 ClassAliasSection,
910 ConstantStringSection
911 };
912 static const char *const SectionsBaseNames[8];
913 static const char *const PECOFFSectionsBaseNames[8];
914 template<SectionKind K>
915 std::string sectionName() {
916 if (CGM.getTriple().isOSBinFormatCOFF()) {
917 std::string name(PECOFFSectionsBaseNames[K]);
918 name += "$m";
919 return name;
920 }
921 return SectionsBaseNames[K];
922 }
923 /// The GCC ABI superclass message lookup function. Takes a pointer to a
924 /// structure describing the receiver and the class, and a selector as
925 /// arguments. Returns the IMP for the corresponding method.
926 LazyRuntimeFunction MsgLookupSuperFn;
927 /// A flag indicating if we've emitted at least one protocol.
928 /// If we haven't, then we need to emit an empty protocol, to ensure that the
929 /// __start__objc_protocols and __stop__objc_protocols sections exist.
930 bool EmittedProtocol = false;
931 /// A flag indicating if we've emitted at least one protocol reference.
932 /// If we haven't, then we need to emit an empty protocol, to ensure that the
933 /// __start__objc_protocol_refs and __stop__objc_protocol_refs sections
934 /// exist.
935 bool EmittedProtocolRef = false;
936 /// A flag indicating if we've emitted at least one class.
937 /// If we haven't, then we need to emit an empty protocol, to ensure that the
938 /// __start__objc_classes and __stop__objc_classes sections / exist.
939 bool EmittedClass = false;
940 /// Generate the name of a symbol for a reference to a class. Accesses to
941 /// classes should be indirected via this.
942
943 typedef std::pair<std::string, std::pair<llvm::Constant*, int>> EarlyInitPair;
944 std::vector<EarlyInitPair> EarlyInitList;
945
946 std::string SymbolForClassRef(StringRef Name, bool isWeak) {
947 if (isWeak)
3
Assuming 'isWeak' is false, which participates in a condition later
4
Taking false branch
948 return (ManglePublicSymbol("OBJC_WEAK_REF_CLASS_") + Name).str();
949 else
950 return (ManglePublicSymbol("OBJC_REF_CLASS_") + Name).str();
951 }
952 /// Generate the name of a class symbol.
953 std::string SymbolForClass(StringRef Name) {
954 return (ManglePublicSymbol("OBJC_CLASS_") + Name).str();
955 }
956 void CallRuntimeFunction(CGBuilderTy &B, StringRef FunctionName,
957 ArrayRef<llvm::Value*> Args) {
958 SmallVector<llvm::Type *,8> Types;
959 for (auto *Arg : Args)
960 Types.push_back(Arg->getType());
961 llvm::FunctionType *FT = llvm::FunctionType::get(B.getVoidTy(), Types,
962 false);
963 llvm::FunctionCallee Fn = CGM.CreateRuntimeFunction(FT, FunctionName);
964 B.CreateCall(Fn, Args);
965 }
966
967 ConstantAddress GenerateConstantString(const StringLiteral *SL) override {
968
969 auto Str = SL->getString();
970 CharUnits Align = CGM.getPointerAlign();
971
972 // Look for an existing one
973 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
974 if (old != ObjCStrings.end())
975 return ConstantAddress(old->getValue(), Align);
976
977 bool isNonASCII = SL->containsNonAscii();
978
979 auto LiteralLength = SL->getLength();
980
981 if ((CGM.getTarget().getPointerWidth(0) == 64) &&
982 (LiteralLength < 9) && !isNonASCII) {
983 // Tiny strings are only used on 64-bit platforms. They store 8 7-bit
984 // ASCII characters in the high 56 bits, followed by a 4-bit length and a
985 // 3-bit tag (which is always 4).
986 uint64_t str = 0;
987 // Fill in the characters
988 for (unsigned i=0 ; i<LiteralLength ; i++)
989 str |= ((uint64_t)SL->getCodeUnit(i)) << ((64 - 4 - 3) - (i*7));
990 // Fill in the length
991 str |= LiteralLength << 3;
992 // Set the tag
993 str |= 4;
994 auto *ObjCStr = llvm::ConstantExpr::getIntToPtr(
995 llvm::ConstantInt::get(Int64Ty, str), IdTy);
996 ObjCStrings[Str] = ObjCStr;
997 return ConstantAddress(ObjCStr, Align);
998 }
999
1000 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
1001
1002 if (StringClass.empty()) StringClass = "NSConstantString";
1003
1004 std::string Sym = SymbolForClass(StringClass);
1005
1006 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
1007
1008 if (!isa) {
1009 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
1010 llvm::GlobalValue::ExternalLinkage, nullptr, Sym);
1011 if (CGM.getTriple().isOSBinFormatCOFF()) {
1012 cast<llvm::GlobalValue>(isa)->setDLLStorageClass(llvm::GlobalValue::DLLImportStorageClass);
1013 }
1014 } else if (isa->getType() != PtrToIdTy)
1015 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
1016
1017 // struct
1018 // {
1019 // Class isa;
1020 // uint32_t flags;
1021 // uint32_t length; // Number of codepoints
1022 // uint32_t size; // Number of bytes
1023 // uint32_t hash;
1024 // const char *data;
1025 // };
1026
1027 ConstantInitBuilder Builder(CGM);
1028 auto Fields = Builder.beginStruct();
1029 if (!CGM.getTriple().isOSBinFormatCOFF()) {
1030 Fields.add(isa);
1031 } else {
1032 Fields.addNullPointer(PtrTy);
1033 }
1034 // For now, all non-ASCII strings are represented as UTF-16. As such, the
1035 // number of bytes is simply double the number of UTF-16 codepoints. In
1036 // ASCII strings, the number of bytes is equal to the number of non-ASCII
1037 // codepoints.
1038 if (isNonASCII) {
1039 unsigned NumU8CodeUnits = Str.size();
1040 // A UTF-16 representation of a unicode string contains at most the same
1041 // number of code units as a UTF-8 representation. Allocate that much
1042 // space, plus one for the final null character.
1043 SmallVector<llvm::UTF16, 128> ToBuf(NumU8CodeUnits + 1);
1044 const llvm::UTF8 *FromPtr = (const llvm::UTF8 *)Str.data();
1045 llvm::UTF16 *ToPtr = &ToBuf[0];
1046 (void)llvm::ConvertUTF8toUTF16(&FromPtr, FromPtr + NumU8CodeUnits,
1047 &ToPtr, ToPtr + NumU8CodeUnits, llvm::strictConversion);
1048 uint32_t StringLength = ToPtr - &ToBuf[0];
1049 // Add null terminator
1050 *ToPtr = 0;
1051 // Flags: 2 indicates UTF-16 encoding
1052 Fields.addInt(Int32Ty, 2);
1053 // Number of UTF-16 codepoints
1054 Fields.addInt(Int32Ty, StringLength);
1055 // Number of bytes
1056 Fields.addInt(Int32Ty, StringLength * 2);
1057 // Hash. Not currently initialised by the compiler.
1058 Fields.addInt(Int32Ty, 0);
1059 // pointer to the data string.
1060 auto Arr = llvm::makeArrayRef(&ToBuf[0], ToPtr+1);
1061 auto *C = llvm::ConstantDataArray::get(VMContext, Arr);
1062 auto *Buffer = new llvm::GlobalVariable(TheModule, C->getType(),
1063 /*isConstant=*/true, llvm::GlobalValue::PrivateLinkage, C, ".str");
1064 Buffer->setUnnamedAddr(llvm::GlobalValue::UnnamedAddr::Global);
1065 Fields.add(Buffer);
1066 } else {
1067 // Flags: 0 indicates ASCII encoding
1068 Fields.addInt(Int32Ty, 0);
1069 // Number of UTF-16 codepoints, each ASCII byte is a UTF-16 codepoint
1070 Fields.addInt(Int32Ty, Str.size());
1071 // Number of bytes
1072 Fields.addInt(Int32Ty, Str.size());
1073 // Hash. Not currently initialised by the compiler.
1074 Fields.addInt(Int32Ty, 0);
1075 // Data pointer
1076 Fields.add(MakeConstantString(Str));
1077 }
1078 std::string StringName;
1079 bool isNamed = !isNonASCII;
1080 if (isNamed) {
1081 StringName = ".objc_str_";
1082 for (int i=0,e=Str.size() ; i<e ; ++i) {
1083 unsigned char c = Str[i];
1084 if (isalnum(c))
1085 StringName += c;
1086 else if (c == ' ')
1087 StringName += '_';
1088 else {
1089 isNamed = false;
1090 break;
1091 }
1092 }
1093 }
1094 auto *ObjCStrGV =
1095 Fields.finishAndCreateGlobal(
1096 isNamed ? StringRef(StringName) : ".objc_string",
1097 Align, false, isNamed ? llvm::GlobalValue::LinkOnceODRLinkage
1098 : llvm::GlobalValue::PrivateLinkage);
1099 ObjCStrGV->setSection(sectionName<ConstantStringSection>());
1100 if (isNamed) {
1101 ObjCStrGV->setComdat(TheModule.getOrInsertComdat(StringName));
1102 ObjCStrGV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1103 }
1104 if (CGM.getTriple().isOSBinFormatCOFF()) {
1105 std::pair<llvm::Constant*, int> v{ObjCStrGV, 0};
1106 EarlyInitList.emplace_back(Sym, v);
1107 }
1108 llvm::Constant *ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStrGV, IdTy);
1109 ObjCStrings[Str] = ObjCStr;
1110 ConstantStrings.push_back(ObjCStr);
1111 return ConstantAddress(ObjCStr, Align);
1112 }
1113
1114 void PushProperty(ConstantArrayBuilder &PropertiesArray,
1115 const ObjCPropertyDecl *property,
1116 const Decl *OCD,
1117 bool isSynthesized=true, bool
1118 isDynamic=true) override {
1119 // struct objc_property
1120 // {
1121 // const char *name;
1122 // const char *attributes;
1123 // const char *type;
1124 // SEL getter;
1125 // SEL setter;
1126 // };
1127 auto Fields = PropertiesArray.beginStruct(PropertyMetadataTy);
1128 ASTContext &Context = CGM.getContext();
1129 Fields.add(MakeConstantString(property->getNameAsString()));
1130 std::string TypeStr =
1131 CGM.getContext().getObjCEncodingForPropertyDecl(property, OCD);
1132 Fields.add(MakeConstantString(TypeStr));
1133 std::string typeStr;
1134 Context.getObjCEncodingForType(property->getType(), typeStr);
1135 Fields.add(MakeConstantString(typeStr));
1136 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
1137 if (accessor) {
1138 std::string TypeStr = Context.getObjCEncodingForMethodDecl(accessor);
1139 Fields.add(GetConstantSelector(accessor->getSelector(), TypeStr));
1140 } else {
1141 Fields.add(NULLPtr);
1142 }
1143 };
1144 addPropertyMethod(property->getGetterMethodDecl());
1145 addPropertyMethod(property->getSetterMethodDecl());
1146 Fields.finishAndAddTo(PropertiesArray);
1147 }
1148
1149 llvm::Constant *
1150 GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) override {
1151 // struct objc_protocol_method_description
1152 // {
1153 // SEL selector;
1154 // const char *types;
1155 // };
1156 llvm::StructType *ObjCMethodDescTy =
1157 llvm::StructType::get(CGM.getLLVMContext(),
1158 { PtrToInt8Ty, PtrToInt8Ty });
1159 ASTContext &Context = CGM.getContext();
1160 ConstantInitBuilder Builder(CGM);
1161 // struct objc_protocol_method_description_list
1162 // {
1163 // int count;
1164 // int size;
1165 // struct objc_protocol_method_description methods[];
1166 // };
1167 auto MethodList = Builder.beginStruct();
1168 // int count;
1169 MethodList.addInt(IntTy, Methods.size());
1170 // int size; // sizeof(struct objc_method_description)
1171 llvm::DataLayout td(&TheModule);
1172 MethodList.addInt(IntTy, td.getTypeSizeInBits(ObjCMethodDescTy) /
1173 CGM.getContext().getCharWidth());
1174 // struct objc_method_description[]
1175 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
1176 for (auto *M : Methods) {
1177 auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
1178 Method.add(CGObjCGNU::GetConstantSelector(M));
1179 Method.add(GetTypeString(Context.getObjCEncodingForMethodDecl(M, true)));
1180 Method.finishAndAddTo(MethodArray);
1181 }
1182 MethodArray.finishAndAddTo(MethodList);
1183 return MethodList.finishAndCreateGlobal(".objc_protocol_method_list",
1184 CGM.getPointerAlign());
1185 }
1186 llvm::Constant *GenerateCategoryProtocolList(const ObjCCategoryDecl *OCD)
1187 override {
1188 SmallVector<llvm::Constant*, 16> Protocols;
1189 for (const auto *PI : OCD->getReferencedProtocols())
1190 Protocols.push_back(
1191 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
1192 ProtocolPtrTy));
1193 return GenerateProtocolList(Protocols);
1194 }
1195
1196 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
1197 llvm::Value *cmd, MessageSendInfo &MSI) override {
1198 // Don't access the slot unless we're trying to cache the result.
1199 CGBuilderTy &Builder = CGF.Builder;
1200 llvm::Value *lookupArgs[] = {CGObjCGNU::EnforceType(Builder, ObjCSuper,
1201 PtrToObjCSuperTy).getPointer(), cmd};
1202 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
1203 }
1204
1205 llvm::GlobalVariable *GetClassVar(StringRef Name, bool isWeak=false) {
1206 std::string SymbolName = SymbolForClassRef(Name, isWeak);
2
Calling 'CGObjCGNUstep2::SymbolForClassRef'
5
Returning from 'CGObjCGNUstep2::SymbolForClassRef'
1207 auto *ClassSymbol = TheModule.getNamedGlobal(SymbolName);
1208 if (ClassSymbol)
6
Assuming 'ClassSymbol' is null
7
Taking false branch
1209 return ClassSymbol;
1210 ClassSymbol = new llvm::GlobalVariable(TheModule,
1211 IdTy, false, llvm::GlobalValue::ExternalLinkage,
1212 nullptr, SymbolName);
1213 // If this is a weak symbol, then we are creating a valid definition for
1214 // the symbol, pointing to a weak definition of the real class pointer. If
1215 // this is not a weak reference, then we are expecting another compilation
1216 // unit to provide the real indirection symbol.
1217 if (isWeak
7.1
'isWeak' is false
7.1
'isWeak' is false
)
8
Taking false branch
1218 ClassSymbol->setInitializer(new llvm::GlobalVariable(TheModule,
1219 Int8Ty, false, llvm::GlobalValue::ExternalWeakLinkage,
1220 nullptr, SymbolForClass(Name)));
1221 else {
1222 if (CGM.getTriple().isOSBinFormatCOFF()) {
9
Calling 'Triple::isOSBinFormatCOFF'
11
Returning from 'Triple::isOSBinFormatCOFF'
12
Taking true branch
1223 IdentifierInfo &II = CGM.getContext().Idents.get(Name);
1224 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
1225 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
1226
1227 const ObjCInterfaceDecl *OID = nullptr;
13
'OID' initialized to a null pointer value
1228 for (const auto &Result : DC->lookup(&II))
1229 if ((OID = dyn_cast<ObjCInterfaceDecl>(Result)))
1230 break;
1231
1232 // The first Interface we find may be a @class,
1233 // which should only be treated as the source of
1234 // truth in the absence of a true declaration.
1235 const ObjCInterfaceDecl *OIDDef = OID->getDefinition();
14
Called C++ object pointer is null
1236 if (OIDDef != nullptr)
1237 OID = OIDDef;
1238
1239 auto Storage = llvm::GlobalValue::DefaultStorageClass;
1240 if (OID->hasAttr<DLLImportAttr>())
1241 Storage = llvm::GlobalValue::DLLImportStorageClass;
1242 else if (OID->hasAttr<DLLExportAttr>())
1243 Storage = llvm::GlobalValue::DLLExportStorageClass;
1244
1245 cast<llvm::GlobalValue>(ClassSymbol)->setDLLStorageClass(Storage);
1246 }
1247 }
1248 assert(ClassSymbol->getName() == SymbolName)((ClassSymbol->getName() == SymbolName) ? static_cast<void
> (0) : __assert_fail ("ClassSymbol->getName() == SymbolName"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 1248, __PRETTY_FUNCTION__))
;
1249 return ClassSymbol;
1250 }
1251 llvm::Value *GetClassNamed(CodeGenFunction &CGF,
1252 const std::string &Name,
1253 bool isWeak) override {
1254 return CGF.Builder.CreateLoad(Address(GetClassVar(Name, isWeak),
1
Calling 'CGObjCGNUstep2::GetClassVar'
1255 CGM.getPointerAlign()));
1256 }
1257 int32_t FlagsForOwnership(Qualifiers::ObjCLifetime Ownership) {
1258 // typedef enum {
1259 // ownership_invalid = 0,
1260 // ownership_strong = 1,
1261 // ownership_weak = 2,
1262 // ownership_unsafe = 3
1263 // } ivar_ownership;
1264 int Flag;
1265 switch (Ownership) {
1266 case Qualifiers::OCL_Strong:
1267 Flag = 1;
1268 break;
1269 case Qualifiers::OCL_Weak:
1270 Flag = 2;
1271 break;
1272 case Qualifiers::OCL_ExplicitNone:
1273 Flag = 3;
1274 break;
1275 case Qualifiers::OCL_None:
1276 case Qualifiers::OCL_Autoreleasing:
1277 assert(Ownership != Qualifiers::OCL_Autoreleasing)((Ownership != Qualifiers::OCL_Autoreleasing) ? static_cast<
void> (0) : __assert_fail ("Ownership != Qualifiers::OCL_Autoreleasing"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 1277, __PRETTY_FUNCTION__))
;
1278 Flag = 0;
1279 }
1280 return Flag;
1281 }
1282 llvm::Constant *GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
1283 ArrayRef<llvm::Constant *> IvarTypes,
1284 ArrayRef<llvm::Constant *> IvarOffsets,
1285 ArrayRef<llvm::Constant *> IvarAlign,
1286 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) override {
1287 llvm_unreachable("Method should not be called!")::llvm::llvm_unreachable_internal("Method should not be called!"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 1287)
;
1288 }
1289
1290 llvm::Constant *GenerateEmptyProtocol(StringRef ProtocolName) override {
1291 std::string Name = SymbolForProtocol(ProtocolName);
1292 auto *GV = TheModule.getGlobalVariable(Name);
1293 if (!GV) {
1294 // Emit a placeholder symbol.
1295 GV = new llvm::GlobalVariable(TheModule, ProtocolTy, false,
1296 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1297 GV->setAlignment(CGM.getPointerAlign().getAsAlign());
1298 }
1299 return llvm::ConstantExpr::getBitCast(GV, ProtocolPtrTy);
1300 }
1301
1302 /// Existing protocol references.
1303 llvm::StringMap<llvm::Constant*> ExistingProtocolRefs;
1304
1305 llvm::Value *GenerateProtocolRef(CodeGenFunction &CGF,
1306 const ObjCProtocolDecl *PD) override {
1307 auto Name = PD->getNameAsString();
1308 auto *&Ref = ExistingProtocolRefs[Name];
1309 if (!Ref) {
1310 auto *&Protocol = ExistingProtocols[Name];
1311 if (!Protocol)
1312 Protocol = GenerateProtocolRef(PD);
1313 std::string RefName = SymbolForProtocolRef(Name);
1314 assert(!TheModule.getGlobalVariable(RefName))((!TheModule.getGlobalVariable(RefName)) ? static_cast<void
> (0) : __assert_fail ("!TheModule.getGlobalVariable(RefName)"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 1314, __PRETTY_FUNCTION__))
;
1315 // Emit a reference symbol.
1316 auto GV = new llvm::GlobalVariable(TheModule, ProtocolPtrTy,
1317 false, llvm::GlobalValue::LinkOnceODRLinkage,
1318 llvm::ConstantExpr::getBitCast(Protocol, ProtocolPtrTy), RefName);
1319 GV->setComdat(TheModule.getOrInsertComdat(RefName));
1320 GV->setSection(sectionName<ProtocolReferenceSection>());
1321 GV->setAlignment(CGM.getPointerAlign().getAsAlign());
1322 Ref = GV;
1323 }
1324 EmittedProtocolRef = true;
1325 return CGF.Builder.CreateAlignedLoad(Ref, CGM.getPointerAlign());
1326 }
1327
1328 llvm::Constant *GenerateProtocolList(ArrayRef<llvm::Constant*> Protocols) {
1329 llvm::ArrayType *ProtocolArrayTy = llvm::ArrayType::get(ProtocolPtrTy,
1330 Protocols.size());
1331 llvm::Constant * ProtocolArray = llvm::ConstantArray::get(ProtocolArrayTy,
1332 Protocols);
1333 ConstantInitBuilder builder(CGM);
1334 auto ProtocolBuilder = builder.beginStruct();
1335 ProtocolBuilder.addNullPointer(PtrTy);
1336 ProtocolBuilder.addInt(SizeTy, Protocols.size());
1337 ProtocolBuilder.add(ProtocolArray);
1338 return ProtocolBuilder.finishAndCreateGlobal(".objc_protocol_list",
1339 CGM.getPointerAlign(), false, llvm::GlobalValue::InternalLinkage);
1340 }
1341
1342 void GenerateProtocol(const ObjCProtocolDecl *PD) override {
1343 // Do nothing - we only emit referenced protocols.
1344 }
1345 llvm::Constant *GenerateProtocolRef(const ObjCProtocolDecl *PD) {
1346 std::string ProtocolName = PD->getNameAsString();
1347 auto *&Protocol = ExistingProtocols[ProtocolName];
1348 if (Protocol)
1349 return Protocol;
1350
1351 EmittedProtocol = true;
1352
1353 auto SymName = SymbolForProtocol(ProtocolName);
1354 auto *OldGV = TheModule.getGlobalVariable(SymName);
1355
1356 // Use the protocol definition, if there is one.
1357 if (const ObjCProtocolDecl *Def = PD->getDefinition())
1358 PD = Def;
1359 else {
1360 // If there is no definition, then create an external linkage symbol and
1361 // hope that someone else fills it in for us (and fail to link if they
1362 // don't).
1363 assert(!OldGV)((!OldGV) ? static_cast<void> (0) : __assert_fail ("!OldGV"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 1363, __PRETTY_FUNCTION__))
;
1364 Protocol = new llvm::GlobalVariable(TheModule, ProtocolTy,
1365 /*isConstant*/false,
1366 llvm::GlobalValue::ExternalLinkage, nullptr, SymName);
1367 return Protocol;
1368 }
1369
1370 SmallVector<llvm::Constant*, 16> Protocols;
1371 for (const auto *PI : PD->protocols())
1372 Protocols.push_back(
1373 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(PI),
1374 ProtocolPtrTy));
1375 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
1376
1377 // Collect information about methods
1378 llvm::Constant *InstanceMethodList, *OptionalInstanceMethodList;
1379 llvm::Constant *ClassMethodList, *OptionalClassMethodList;
1380 EmitProtocolMethodList(PD->instance_methods(), InstanceMethodList,
1381 OptionalInstanceMethodList);
1382 EmitProtocolMethodList(PD->class_methods(), ClassMethodList,
1383 OptionalClassMethodList);
1384
1385 // The isa pointer must be set to a magic number so the runtime knows it's
1386 // the correct layout.
1387 ConstantInitBuilder builder(CGM);
1388 auto ProtocolBuilder = builder.beginStruct();
1389 ProtocolBuilder.add(llvm::ConstantExpr::getIntToPtr(
1390 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
1391 ProtocolBuilder.add(MakeConstantString(ProtocolName));
1392 ProtocolBuilder.add(ProtocolList);
1393 ProtocolBuilder.add(InstanceMethodList);
1394 ProtocolBuilder.add(ClassMethodList);
1395 ProtocolBuilder.add(OptionalInstanceMethodList);
1396 ProtocolBuilder.add(OptionalClassMethodList);
1397 // Required instance properties
1398 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, false));
1399 // Optional instance properties
1400 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, false, true));
1401 // Required class properties
1402 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, false));
1403 // Optional class properties
1404 ProtocolBuilder.add(GeneratePropertyList(nullptr, PD, true, true));
1405
1406 auto *GV = ProtocolBuilder.finishAndCreateGlobal(SymName,
1407 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1408 GV->setSection(sectionName<ProtocolSection>());
1409 GV->setComdat(TheModule.getOrInsertComdat(SymName));
1410 if (OldGV) {
1411 OldGV->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(GV,
1412 OldGV->getType()));
1413 OldGV->removeFromParent();
1414 GV->setName(SymName);
1415 }
1416 Protocol = GV;
1417 return GV;
1418 }
1419 llvm::Constant *EnforceType(llvm::Constant *Val, llvm::Type *Ty) {
1420 if (Val->getType() == Ty)
1421 return Val;
1422 return llvm::ConstantExpr::getBitCast(Val, Ty);
1423 }
1424 llvm::Value *GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
1425 const std::string &TypeEncoding) override {
1426 return GetConstantSelector(Sel, TypeEncoding);
1427 }
1428 llvm::Constant *GetTypeString(llvm::StringRef TypeEncoding) {
1429 if (TypeEncoding.empty())
1430 return NULLPtr;
1431 std::string MangledTypes = TypeEncoding;
1432 std::replace(MangledTypes.begin(), MangledTypes.end(),
1433 '@', '\1');
1434 std::string TypesVarName = ".objc_sel_types_" + MangledTypes;
1435 auto *TypesGlobal = TheModule.getGlobalVariable(TypesVarName);
1436 if (!TypesGlobal) {
1437 llvm::Constant *Init = llvm::ConstantDataArray::getString(VMContext,
1438 TypeEncoding);
1439 auto *GV = new llvm::GlobalVariable(TheModule, Init->getType(),
1440 true, llvm::GlobalValue::LinkOnceODRLinkage, Init, TypesVarName);
1441 GV->setComdat(TheModule.getOrInsertComdat(TypesVarName));
1442 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1443 TypesGlobal = GV;
1444 }
1445 return llvm::ConstantExpr::getGetElementPtr(TypesGlobal->getValueType(),
1446 TypesGlobal, Zeros);
1447 }
1448 llvm::Constant *GetConstantSelector(Selector Sel,
1449 const std::string &TypeEncoding) override {
1450 // @ is used as a special character in symbol names (used for symbol
1451 // versioning), so mangle the name to not include it. Replace it with a
1452 // character that is not a valid type encoding character (and, being
1453 // non-printable, never will be!)
1454 std::string MangledTypes = TypeEncoding;
1455 std::replace(MangledTypes.begin(), MangledTypes.end(),
1456 '@', '\1');
1457 auto SelVarName = (StringRef(".objc_selector_") + Sel.getAsString() + "_" +
1458 MangledTypes).str();
1459 if (auto *GV = TheModule.getNamedGlobal(SelVarName))
1460 return EnforceType(GV, SelectorTy);
1461 ConstantInitBuilder builder(CGM);
1462 auto SelBuilder = builder.beginStruct();
1463 SelBuilder.add(ExportUniqueString(Sel.getAsString(), ".objc_sel_name_",
1464 true));
1465 SelBuilder.add(GetTypeString(TypeEncoding));
1466 auto *GV = SelBuilder.finishAndCreateGlobal(SelVarName,
1467 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1468 GV->setComdat(TheModule.getOrInsertComdat(SelVarName));
1469 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1470 GV->setSection(sectionName<SelectorSection>());
1471 auto *SelVal = EnforceType(GV, SelectorTy);
1472 return SelVal;
1473 }
1474 llvm::StructType *emptyStruct = nullptr;
1475
1476 /// Return pointers to the start and end of a section. On ELF platforms, we
1477 /// use the __start_ and __stop_ symbols that GNU-compatible linkers will set
1478 /// to the start and end of section names, as long as those section names are
1479 /// valid identifiers and the symbols are referenced but not defined. On
1480 /// Windows, we use the fact that MSVC-compatible linkers will lexically sort
1481 /// by subsections and place everything that we want to reference in a middle
1482 /// subsection and then insert zero-sized symbols in subsections a and z.
1483 std::pair<llvm::Constant*,llvm::Constant*>
1484 GetSectionBounds(StringRef Section) {
1485 if (CGM.getTriple().isOSBinFormatCOFF()) {
1486 if (emptyStruct == nullptr) {
1487 emptyStruct = llvm::StructType::create(VMContext, ".objc_section_sentinel");
1488 emptyStruct->setBody({}, /*isPacked*/true);
1489 }
1490 auto ZeroInit = llvm::Constant::getNullValue(emptyStruct);
1491 auto Sym = [&](StringRef Prefix, StringRef SecSuffix) {
1492 auto *Sym = new llvm::GlobalVariable(TheModule, emptyStruct,
1493 /*isConstant*/false,
1494 llvm::GlobalValue::LinkOnceODRLinkage, ZeroInit, Prefix +
1495 Section);
1496 Sym->setVisibility(llvm::GlobalValue::HiddenVisibility);
1497 Sym->setSection((Section + SecSuffix).str());
1498 Sym->setComdat(TheModule.getOrInsertComdat((Prefix +
1499 Section).str()));
1500 Sym->setAlignment(CGM.getPointerAlign().getAsAlign());
1501 return Sym;
1502 };
1503 return { Sym("__start_", "$a"), Sym("__stop", "$z") };
1504 }
1505 auto *Start = new llvm::GlobalVariable(TheModule, PtrTy,
1506 /*isConstant*/false,
1507 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__start_") +
1508 Section);
1509 Start->setVisibility(llvm::GlobalValue::HiddenVisibility);
1510 auto *Stop = new llvm::GlobalVariable(TheModule, PtrTy,
1511 /*isConstant*/false,
1512 llvm::GlobalValue::ExternalLinkage, nullptr, StringRef("__stop_") +
1513 Section);
1514 Stop->setVisibility(llvm::GlobalValue::HiddenVisibility);
1515 return { Start, Stop };
1516 }
1517 CatchTypeInfo getCatchAllTypeInfo() override {
1518 return CGM.getCXXABI().getCatchAllTypeInfo();
1519 }
1520 llvm::Function *ModuleInitFunction() override {
1521 llvm::Function *LoadFunction = llvm::Function::Create(
1522 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
1523 llvm::GlobalValue::LinkOnceODRLinkage, ".objcv2_load_function",
1524 &TheModule);
1525 LoadFunction->setVisibility(llvm::GlobalValue::HiddenVisibility);
1526 LoadFunction->setComdat(TheModule.getOrInsertComdat(".objcv2_load_function"));
1527
1528 llvm::BasicBlock *EntryBB =
1529 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
1530 CGBuilderTy B(CGM, VMContext);
1531 B.SetInsertPoint(EntryBB);
1532 ConstantInitBuilder builder(CGM);
1533 auto InitStructBuilder = builder.beginStruct();
1534 InitStructBuilder.addInt(Int64Ty, 0);
1535 auto &sectionVec = CGM.getTriple().isOSBinFormatCOFF() ? PECOFFSectionsBaseNames : SectionsBaseNames;
1536 for (auto *s : sectionVec) {
1537 auto bounds = GetSectionBounds(s);
1538 InitStructBuilder.add(bounds.first);
1539 InitStructBuilder.add(bounds.second);
1540 }
1541 auto *InitStruct = InitStructBuilder.finishAndCreateGlobal(".objc_init",
1542 CGM.getPointerAlign(), false, llvm::GlobalValue::LinkOnceODRLinkage);
1543 InitStruct->setVisibility(llvm::GlobalValue::HiddenVisibility);
1544 InitStruct->setComdat(TheModule.getOrInsertComdat(".objc_init"));
1545
1546 CallRuntimeFunction(B, "__objc_load", {InitStruct});;
1547 B.CreateRetVoid();
1548 // Make sure that the optimisers don't delete this function.
1549 CGM.addCompilerUsedGlobal(LoadFunction);
1550 // FIXME: Currently ELF only!
1551 // We have to do this by hand, rather than with @llvm.ctors, so that the
1552 // linker can remove the duplicate invocations.
1553 auto *InitVar = new llvm::GlobalVariable(TheModule, LoadFunction->getType(),
1554 /*isConstant*/true, llvm::GlobalValue::LinkOnceAnyLinkage,
1555 LoadFunction, ".objc_ctor");
1556 // Check that this hasn't been renamed. This shouldn't happen, because
1557 // this function should be called precisely once.
1558 assert(InitVar->getName() == ".objc_ctor")((InitVar->getName() == ".objc_ctor") ? static_cast<void
> (0) : __assert_fail ("InitVar->getName() == \".objc_ctor\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 1558, __PRETTY_FUNCTION__))
;
1559 // In Windows, initialisers are sorted by the suffix. XCL is for library
1560 // initialisers, which run before user initialisers. We are running
1561 // Objective-C loads at the end of library load. This means +load methods
1562 // will run before any other static constructors, but that static
1563 // constructors can see a fully initialised Objective-C state.
1564 if (CGM.getTriple().isOSBinFormatCOFF())
1565 InitVar->setSection(".CRT$XCLz");
1566 else
1567 {
1568 if (CGM.getCodeGenOpts().UseInitArray)
1569 InitVar->setSection(".init_array");
1570 else
1571 InitVar->setSection(".ctors");
1572 }
1573 InitVar->setVisibility(llvm::GlobalValue::HiddenVisibility);
1574 InitVar->setComdat(TheModule.getOrInsertComdat(".objc_ctor"));
1575 CGM.addUsedGlobal(InitVar);
1576 for (auto *C : Categories) {
1577 auto *Cat = cast<llvm::GlobalVariable>(C->stripPointerCasts());
1578 Cat->setSection(sectionName<CategorySection>());
1579 CGM.addUsedGlobal(Cat);
1580 }
1581 auto createNullGlobal = [&](StringRef Name, ArrayRef<llvm::Constant*> Init,
1582 StringRef Section) {
1583 auto nullBuilder = builder.beginStruct();
1584 for (auto *F : Init)
1585 nullBuilder.add(F);
1586 auto GV = nullBuilder.finishAndCreateGlobal(Name, CGM.getPointerAlign(),
1587 false, llvm::GlobalValue::LinkOnceODRLinkage);
1588 GV->setSection(Section);
1589 GV->setComdat(TheModule.getOrInsertComdat(Name));
1590 GV->setVisibility(llvm::GlobalValue::HiddenVisibility);
1591 CGM.addUsedGlobal(GV);
1592 return GV;
1593 };
1594 for (auto clsAlias : ClassAliases)
1595 createNullGlobal(std::string(".objc_class_alias") +
1596 clsAlias.second, { MakeConstantString(clsAlias.second),
1597 GetClassVar(clsAlias.first) }, sectionName<ClassAliasSection>());
1598 // On ELF platforms, add a null value for each special section so that we
1599 // can always guarantee that the _start and _stop symbols will exist and be
1600 // meaningful. This is not required on COFF platforms, where our start and
1601 // stop symbols will create the section.
1602 if (!CGM.getTriple().isOSBinFormatCOFF()) {
1603 createNullGlobal(".objc_null_selector", {NULLPtr, NULLPtr},
1604 sectionName<SelectorSection>());
1605 if (Categories.empty())
1606 createNullGlobal(".objc_null_category", {NULLPtr, NULLPtr,
1607 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr},
1608 sectionName<CategorySection>());
1609 if (!EmittedClass) {
1610 createNullGlobal(".objc_null_cls_init_ref", NULLPtr,
1611 sectionName<ClassSection>());
1612 createNullGlobal(".objc_null_class_ref", { NULLPtr, NULLPtr },
1613 sectionName<ClassReferenceSection>());
1614 }
1615 if (!EmittedProtocol)
1616 createNullGlobal(".objc_null_protocol", {NULLPtr, NULLPtr, NULLPtr,
1617 NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr, NULLPtr,
1618 NULLPtr}, sectionName<ProtocolSection>());
1619 if (!EmittedProtocolRef)
1620 createNullGlobal(".objc_null_protocol_ref", {NULLPtr},
1621 sectionName<ProtocolReferenceSection>());
1622 if (ClassAliases.empty())
1623 createNullGlobal(".objc_null_class_alias", { NULLPtr, NULLPtr },
1624 sectionName<ClassAliasSection>());
1625 if (ConstantStrings.empty()) {
1626 auto i32Zero = llvm::ConstantInt::get(Int32Ty, 0);
1627 createNullGlobal(".objc_null_constant_string", { NULLPtr, i32Zero,
1628 i32Zero, i32Zero, i32Zero, NULLPtr },
1629 sectionName<ConstantStringSection>());
1630 }
1631 }
1632 ConstantStrings.clear();
1633 Categories.clear();
1634 Classes.clear();
1635
1636 if (EarlyInitList.size() > 0) {
1637 auto *Init = llvm::Function::Create(llvm::FunctionType::get(CGM.VoidTy,
1638 {}), llvm::GlobalValue::InternalLinkage, ".objc_early_init",
1639 &CGM.getModule());
1640 llvm::IRBuilder<> b(llvm::BasicBlock::Create(CGM.getLLVMContext(), "entry",
1641 Init));
1642 for (const auto &lateInit : EarlyInitList) {
1643 auto *global = TheModule.getGlobalVariable(lateInit.first);
1644 if (global) {
1645 b.CreateAlignedStore(global,
1646 b.CreateStructGEP(lateInit.second.first, lateInit.second.second), CGM.getPointerAlign().getQuantity());
1647 }
1648 }
1649 b.CreateRetVoid();
1650 // We can't use the normal LLVM global initialisation array, because we
1651 // need to specify that this runs early in library initialisation.
1652 auto *InitVar = new llvm::GlobalVariable(CGM.getModule(), Init->getType(),
1653 /*isConstant*/true, llvm::GlobalValue::InternalLinkage,
1654 Init, ".objc_early_init_ptr");
1655 InitVar->setSection(".CRT$XCLb");
1656 CGM.addUsedGlobal(InitVar);
1657 }
1658 return nullptr;
1659 }
1660 /// In the v2 ABI, ivar offset variables use the type encoding in their name
1661 /// to trigger linker failures if the types don't match.
1662 std::string GetIVarOffsetVariableName(const ObjCInterfaceDecl *ID,
1663 const ObjCIvarDecl *Ivar) override {
1664 std::string TypeEncoding;
1665 CGM.getContext().getObjCEncodingForType(Ivar->getType(), TypeEncoding);
1666 // Prevent the @ from being interpreted as a symbol version.
1667 std::replace(TypeEncoding.begin(), TypeEncoding.end(),
1668 '@', '\1');
1669 const std::string Name = "__objc_ivar_offset_" + ID->getNameAsString()
1670 + '.' + Ivar->getNameAsString() + '.' + TypeEncoding;
1671 return Name;
1672 }
1673 llvm::Value *EmitIvarOffset(CodeGenFunction &CGF,
1674 const ObjCInterfaceDecl *Interface,
1675 const ObjCIvarDecl *Ivar) override {
1676 const std::string Name = GetIVarOffsetVariableName(Ivar->getContainingInterface(), Ivar);
1677 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
1678 if (!IvarOffsetPointer)
1679 IvarOffsetPointer = new llvm::GlobalVariable(TheModule, IntTy, false,
1680 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
1681 CharUnits Align = CGM.getIntAlign();
1682 llvm::Value *Offset = CGF.Builder.CreateAlignedLoad(IvarOffsetPointer, Align);
1683 if (Offset->getType() != PtrDiffTy)
1684 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
1685 return Offset;
1686 }
1687 void GenerateClass(const ObjCImplementationDecl *OID) override {
1688 ASTContext &Context = CGM.getContext();
1689 bool IsCOFF = CGM.getTriple().isOSBinFormatCOFF();
1690
1691 // Get the class name
1692 ObjCInterfaceDecl *classDecl =
1693 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
1694 std::string className = classDecl->getNameAsString();
1695 auto *classNameConstant = MakeConstantString(className);
1696
1697 ConstantInitBuilder builder(CGM);
1698 auto metaclassFields = builder.beginStruct();
1699 // struct objc_class *isa;
1700 metaclassFields.addNullPointer(PtrTy);
1701 // struct objc_class *super_class;
1702 metaclassFields.addNullPointer(PtrTy);
1703 // const char *name;
1704 metaclassFields.add(classNameConstant);
1705 // long version;
1706 metaclassFields.addInt(LongTy, 0);
1707 // unsigned long info;
1708 // objc_class_flag_meta
1709 metaclassFields.addInt(LongTy, 1);
1710 // long instance_size;
1711 // Setting this to zero is consistent with the older ABI, but it might be
1712 // more sensible to set this to sizeof(struct objc_class)
1713 metaclassFields.addInt(LongTy, 0);
1714 // struct objc_ivar_list *ivars;
1715 metaclassFields.addNullPointer(PtrTy);
1716 // struct objc_method_list *methods
1717 // FIXME: Almost identical code is copied and pasted below for the
1718 // class, but refactoring it cleanly requires C++14 generic lambdas.
1719 if (OID->classmeth_begin() == OID->classmeth_end())
1720 metaclassFields.addNullPointer(PtrTy);
1721 else {
1722 SmallVector<ObjCMethodDecl*, 16> ClassMethods;
1723 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
1724 OID->classmeth_end());
1725 metaclassFields.addBitCast(
1726 GenerateMethodList(className, "", ClassMethods, true),
1727 PtrTy);
1728 }
1729 // void *dtable;
1730 metaclassFields.addNullPointer(PtrTy);
1731 // IMP cxx_construct;
1732 metaclassFields.addNullPointer(PtrTy);
1733 // IMP cxx_destruct;
1734 metaclassFields.addNullPointer(PtrTy);
1735 // struct objc_class *subclass_list
1736 metaclassFields.addNullPointer(PtrTy);
1737 // struct objc_class *sibling_class
1738 metaclassFields.addNullPointer(PtrTy);
1739 // struct objc_protocol_list *protocols;
1740 metaclassFields.addNullPointer(PtrTy);
1741 // struct reference_list *extra_data;
1742 metaclassFields.addNullPointer(PtrTy);
1743 // long abi_version;
1744 metaclassFields.addInt(LongTy, 0);
1745 // struct objc_property_list *properties
1746 metaclassFields.add(GeneratePropertyList(OID, classDecl, /*isClassProperty*/true));
1747
1748 auto *metaclass = metaclassFields.finishAndCreateGlobal(
1749 ManglePublicSymbol("OBJC_METACLASS_") + className,
1750 CGM.getPointerAlign());
1751
1752 auto classFields = builder.beginStruct();
1753 // struct objc_class *isa;
1754 classFields.add(metaclass);
1755 // struct objc_class *super_class;
1756 // Get the superclass name.
1757 const ObjCInterfaceDecl * SuperClassDecl =
1758 OID->getClassInterface()->getSuperClass();
1759 llvm::Constant *SuperClass = nullptr;
1760 if (SuperClassDecl) {
1761 auto SuperClassName = SymbolForClass(SuperClassDecl->getNameAsString());
1762 SuperClass = TheModule.getNamedGlobal(SuperClassName);
1763 if (!SuperClass)
1764 {
1765 SuperClass = new llvm::GlobalVariable(TheModule, PtrTy, false,
1766 llvm::GlobalValue::ExternalLinkage, nullptr, SuperClassName);
1767 if (IsCOFF) {
1768 auto Storage = llvm::GlobalValue::DefaultStorageClass;
1769 if (SuperClassDecl->hasAttr<DLLImportAttr>())
1770 Storage = llvm::GlobalValue::DLLImportStorageClass;
1771 else if (SuperClassDecl->hasAttr<DLLExportAttr>())
1772 Storage = llvm::GlobalValue::DLLExportStorageClass;
1773
1774 cast<llvm::GlobalValue>(SuperClass)->setDLLStorageClass(Storage);
1775 }
1776 }
1777 if (!IsCOFF)
1778 classFields.add(llvm::ConstantExpr::getBitCast(SuperClass, PtrTy));
1779 else
1780 classFields.addNullPointer(PtrTy);
1781 } else
1782 classFields.addNullPointer(PtrTy);
1783 // const char *name;
1784 classFields.add(classNameConstant);
1785 // long version;
1786 classFields.addInt(LongTy, 0);
1787 // unsigned long info;
1788 // !objc_class_flag_meta
1789 classFields.addInt(LongTy, 0);
1790 // long instance_size;
1791 int superInstanceSize = !SuperClassDecl ? 0 :
1792 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
1793 // Instance size is negative for classes that have not yet had their ivar
1794 // layout calculated.
1795 classFields.addInt(LongTy,
1796 0 - (Context.getASTObjCImplementationLayout(OID).getSize().getQuantity() -
1797 superInstanceSize));
1798
1799 if (classDecl->all_declared_ivar_begin() == nullptr)
1800 classFields.addNullPointer(PtrTy);
1801 else {
1802 int ivar_count = 0;
1803 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1804 IVD = IVD->getNextIvar()) ivar_count++;
1805 llvm::DataLayout td(&TheModule);
1806 // struct objc_ivar_list *ivars;
1807 ConstantInitBuilder b(CGM);
1808 auto ivarListBuilder = b.beginStruct();
1809 // int count;
1810 ivarListBuilder.addInt(IntTy, ivar_count);
1811 // size_t size;
1812 llvm::StructType *ObjCIvarTy = llvm::StructType::get(
1813 PtrToInt8Ty,
1814 PtrToInt8Ty,
1815 PtrToInt8Ty,
1816 Int32Ty,
1817 Int32Ty);
1818 ivarListBuilder.addInt(SizeTy, td.getTypeSizeInBits(ObjCIvarTy) /
1819 CGM.getContext().getCharWidth());
1820 // struct objc_ivar ivars[]
1821 auto ivarArrayBuilder = ivarListBuilder.beginArray();
1822 for (const ObjCIvarDecl *IVD = classDecl->all_declared_ivar_begin(); IVD;
1823 IVD = IVD->getNextIvar()) {
1824 auto ivarTy = IVD->getType();
1825 auto ivarBuilder = ivarArrayBuilder.beginStruct();
1826 // const char *name;
1827 ivarBuilder.add(MakeConstantString(IVD->getNameAsString()));
1828 // const char *type;
1829 std::string TypeStr;
1830 //Context.getObjCEncodingForType(ivarTy, TypeStr, IVD, true);
1831 Context.getObjCEncodingForMethodParameter(Decl::OBJC_TQ_None, ivarTy, TypeStr, true);
1832 ivarBuilder.add(MakeConstantString(TypeStr));
1833 // int *offset;
1834 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
1835 uint64_t Offset = BaseOffset - superInstanceSize;
1836 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
1837 std::string OffsetName = GetIVarOffsetVariableName(classDecl, IVD);
1838 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
1839 if (OffsetVar)
1840 OffsetVar->setInitializer(OffsetValue);
1841 else
1842 OffsetVar = new llvm::GlobalVariable(TheModule, IntTy,
1843 false, llvm::GlobalValue::ExternalLinkage,
1844 OffsetValue, OffsetName);
1845 auto ivarVisibility =
1846 (IVD->getAccessControl() == ObjCIvarDecl::Private ||
1847 IVD->getAccessControl() == ObjCIvarDecl::Package ||
1848 classDecl->getVisibility() == HiddenVisibility) ?
1849 llvm::GlobalValue::HiddenVisibility :
1850 llvm::GlobalValue::DefaultVisibility;
1851 OffsetVar->setVisibility(ivarVisibility);
1852 ivarBuilder.add(OffsetVar);
1853 // Ivar size
1854 ivarBuilder.addInt(Int32Ty,
1855 CGM.getContext().getTypeSizeInChars(ivarTy).getQuantity());
1856 // Alignment will be stored as a base-2 log of the alignment.
1857 unsigned align =
1858 llvm::Log2_32(Context.getTypeAlignInChars(ivarTy).getQuantity());
1859 // Objects that require more than 2^64-byte alignment should be impossible!
1860 assert(align < 64)((align < 64) ? static_cast<void> (0) : __assert_fail
("align < 64", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 1860, __PRETTY_FUNCTION__))
;
1861 // uint32_t flags;
1862 // Bits 0-1 are ownership.
1863 // Bit 2 indicates an extended type encoding
1864 // Bits 3-8 contain log2(aligment)
1865 ivarBuilder.addInt(Int32Ty,
1866 (align << 3) | (1<<2) |
1867 FlagsForOwnership(ivarTy.getQualifiers().getObjCLifetime()));
1868 ivarBuilder.finishAndAddTo(ivarArrayBuilder);
1869 }
1870 ivarArrayBuilder.finishAndAddTo(ivarListBuilder);
1871 auto ivarList = ivarListBuilder.finishAndCreateGlobal(".objc_ivar_list",
1872 CGM.getPointerAlign(), /*constant*/ false,
1873 llvm::GlobalValue::PrivateLinkage);
1874 classFields.add(ivarList);
1875 }
1876 // struct objc_method_list *methods
1877 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
1878 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
1879 OID->instmeth_end());
1880 for (auto *propImpl : OID->property_impls())
1881 if (propImpl->getPropertyImplementation() ==
1882 ObjCPropertyImplDecl::Synthesize) {
1883 auto addIfExists = [&](const ObjCMethodDecl *OMD) {
1884 if (OMD && OMD->hasBody())
1885 InstanceMethods.push_back(OMD);
1886 };
1887 addIfExists(propImpl->getGetterMethodDecl());
1888 addIfExists(propImpl->getSetterMethodDecl());
1889 }
1890
1891 if (InstanceMethods.size() == 0)
1892 classFields.addNullPointer(PtrTy);
1893 else
1894 classFields.addBitCast(
1895 GenerateMethodList(className, "", InstanceMethods, false),
1896 PtrTy);
1897 // void *dtable;
1898 classFields.addNullPointer(PtrTy);
1899 // IMP cxx_construct;
1900 classFields.addNullPointer(PtrTy);
1901 // IMP cxx_destruct;
1902 classFields.addNullPointer(PtrTy);
1903 // struct objc_class *subclass_list
1904 classFields.addNullPointer(PtrTy);
1905 // struct objc_class *sibling_class
1906 classFields.addNullPointer(PtrTy);
1907 // struct objc_protocol_list *protocols;
1908 SmallVector<llvm::Constant*, 16> Protocols;
1909 for (const auto *I : classDecl->protocols())
1910 Protocols.push_back(
1911 llvm::ConstantExpr::getBitCast(GenerateProtocolRef(I),
1912 ProtocolPtrTy));
1913 if (Protocols.empty())
1914 classFields.addNullPointer(PtrTy);
1915 else
1916 classFields.add(GenerateProtocolList(Protocols));
1917 // struct reference_list *extra_data;
1918 classFields.addNullPointer(PtrTy);
1919 // long abi_version;
1920 classFields.addInt(LongTy, 0);
1921 // struct objc_property_list *properties
1922 classFields.add(GeneratePropertyList(OID, classDecl));
1923
1924 auto *classStruct =
1925 classFields.finishAndCreateGlobal(SymbolForClass(className),
1926 CGM.getPointerAlign(), false, llvm::GlobalValue::ExternalLinkage);
1927
1928 auto *classRefSymbol = GetClassVar(className);
1929 classRefSymbol->setSection(sectionName<ClassReferenceSection>());
1930 classRefSymbol->setInitializer(llvm::ConstantExpr::getBitCast(classStruct, IdTy));
1931
1932 if (IsCOFF) {
1933 // we can't import a class struct.
1934 if (OID->getClassInterface()->hasAttr<DLLExportAttr>()) {
1935 cast<llvm::GlobalValue>(classStruct)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1936 cast<llvm::GlobalValue>(classRefSymbol)->setDLLStorageClass(llvm::GlobalValue::DLLExportStorageClass);
1937 }
1938
1939 if (SuperClass) {
1940 std::pair<llvm::Constant*, int> v{classStruct, 1};
1941 EarlyInitList.emplace_back(SuperClass->getName(), std::move(v));
1942 }
1943
1944 }
1945
1946
1947 // Resolve the class aliases, if they exist.
1948 // FIXME: Class pointer aliases shouldn't exist!
1949 if (ClassPtrAlias) {
1950 ClassPtrAlias->replaceAllUsesWith(
1951 llvm::ConstantExpr::getBitCast(classStruct, IdTy));
1952 ClassPtrAlias->eraseFromParent();
1953 ClassPtrAlias = nullptr;
1954 }
1955 if (auto Placeholder =
1956 TheModule.getNamedGlobal(SymbolForClass(className)))
1957 if (Placeholder != classStruct) {
1958 Placeholder->replaceAllUsesWith(
1959 llvm::ConstantExpr::getBitCast(classStruct, Placeholder->getType()));
1960 Placeholder->eraseFromParent();
1961 classStruct->setName(SymbolForClass(className));
1962 }
1963 if (MetaClassPtrAlias) {
1964 MetaClassPtrAlias->replaceAllUsesWith(
1965 llvm::ConstantExpr::getBitCast(metaclass, IdTy));
1966 MetaClassPtrAlias->eraseFromParent();
1967 MetaClassPtrAlias = nullptr;
1968 }
1969 assert(classStruct->getName() == SymbolForClass(className))((classStruct->getName() == SymbolForClass(className)) ? static_cast
<void> (0) : __assert_fail ("classStruct->getName() == SymbolForClass(className)"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 1969, __PRETTY_FUNCTION__))
;
1970
1971 auto classInitRef = new llvm::GlobalVariable(TheModule,
1972 classStruct->getType(), false, llvm::GlobalValue::ExternalLinkage,
1973 classStruct, ManglePublicSymbol("OBJC_INIT_CLASS_") + className);
1974 classInitRef->setSection(sectionName<ClassSection>());
1975 CGM.addUsedGlobal(classInitRef);
1976
1977 EmittedClass = true;
1978 }
1979 public:
1980 CGObjCGNUstep2(CodeGenModule &Mod) : CGObjCGNUstep(Mod, 10, 4, 2) {
1981 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
1982 PtrToObjCSuperTy, SelectorTy);
1983 // struct objc_property
1984 // {
1985 // const char *name;
1986 // const char *attributes;
1987 // const char *type;
1988 // SEL getter;
1989 // SEL setter;
1990 // }
1991 PropertyMetadataTy =
1992 llvm::StructType::get(CGM.getLLVMContext(),
1993 { PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty, PtrToInt8Ty });
1994 }
1995
1996};
1997
1998const char *const CGObjCGNUstep2::SectionsBaseNames[8] =
1999{
2000"__objc_selectors",
2001"__objc_classes",
2002"__objc_class_refs",
2003"__objc_cats",
2004"__objc_protocols",
2005"__objc_protocol_refs",
2006"__objc_class_aliases",
2007"__objc_constant_string"
2008};
2009
2010const char *const CGObjCGNUstep2::PECOFFSectionsBaseNames[8] =
2011{
2012".objcrt$SEL",
2013".objcrt$CLS",
2014".objcrt$CLR",
2015".objcrt$CAT",
2016".objcrt$PCL",
2017".objcrt$PCR",
2018".objcrt$CAL",
2019".objcrt$STR"
2020};
2021
2022/// Support for the ObjFW runtime.
2023class CGObjCObjFW: public CGObjCGNU {
2024protected:
2025 /// The GCC ABI message lookup function. Returns an IMP pointing to the
2026 /// method implementation for this message.
2027 LazyRuntimeFunction MsgLookupFn;
2028 /// stret lookup function. While this does not seem to make sense at the
2029 /// first look, this is required to call the correct forwarding function.
2030 LazyRuntimeFunction MsgLookupFnSRet;
2031 /// The GCC ABI superclass message lookup function. Takes a pointer to a
2032 /// structure describing the receiver and the class, and a selector as
2033 /// arguments. Returns the IMP for the corresponding method.
2034 LazyRuntimeFunction MsgLookupSuperFn, MsgLookupSuperFnSRet;
2035
2036 llvm::Value *LookupIMP(CodeGenFunction &CGF, llvm::Value *&Receiver,
2037 llvm::Value *cmd, llvm::MDNode *node,
2038 MessageSendInfo &MSI) override {
2039 CGBuilderTy &Builder = CGF.Builder;
2040 llvm::Value *args[] = {
2041 EnforceType(Builder, Receiver, IdTy),
2042 EnforceType(Builder, cmd, SelectorTy) };
2043
2044 llvm::CallBase *imp;
2045 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2046 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFnSRet, args);
2047 else
2048 imp = CGF.EmitRuntimeCallOrInvoke(MsgLookupFn, args);
2049
2050 imp->setMetadata(msgSendMDKind, node);
2051 return imp;
2052 }
2053
2054 llvm::Value *LookupIMPSuper(CodeGenFunction &CGF, Address ObjCSuper,
2055 llvm::Value *cmd, MessageSendInfo &MSI) override {
2056 CGBuilderTy &Builder = CGF.Builder;
2057 llvm::Value *lookupArgs[] = {
2058 EnforceType(Builder, ObjCSuper.getPointer(), PtrToObjCSuperTy), cmd,
2059 };
2060
2061 if (CGM.ReturnTypeUsesSRet(MSI.CallInfo))
2062 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFnSRet, lookupArgs);
2063 else
2064 return CGF.EmitNounwindRuntimeCall(MsgLookupSuperFn, lookupArgs);
2065 }
2066
2067 llvm::Value *GetClassNamed(CodeGenFunction &CGF, const std::string &Name,
2068 bool isWeak) override {
2069 if (isWeak)
2070 return CGObjCGNU::GetClassNamed(CGF, Name, isWeak);
2071
2072 EmitClassRef(Name);
2073 std::string SymbolName = "_OBJC_CLASS_" + Name;
2074 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(SymbolName);
2075 if (!ClassSymbol)
2076 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
2077 llvm::GlobalValue::ExternalLinkage,
2078 nullptr, SymbolName);
2079 return ClassSymbol;
2080 }
2081
2082public:
2083 CGObjCObjFW(CodeGenModule &Mod): CGObjCGNU(Mod, 9, 3) {
2084 // IMP objc_msg_lookup(id, SEL);
2085 MsgLookupFn.init(&CGM, "objc_msg_lookup", IMPTy, IdTy, SelectorTy);
2086 MsgLookupFnSRet.init(&CGM, "objc_msg_lookup_stret", IMPTy, IdTy,
2087 SelectorTy);
2088 // IMP objc_msg_lookup_super(struct objc_super*, SEL);
2089 MsgLookupSuperFn.init(&CGM, "objc_msg_lookup_super", IMPTy,
2090 PtrToObjCSuperTy, SelectorTy);
2091 MsgLookupSuperFnSRet.init(&CGM, "objc_msg_lookup_super_stret", IMPTy,
2092 PtrToObjCSuperTy, SelectorTy);
2093 }
2094};
2095} // end anonymous namespace
2096
2097/// Emits a reference to a dummy variable which is emitted with each class.
2098/// This ensures that a linker error will be generated when trying to link
2099/// together modules where a referenced class is not defined.
2100void CGObjCGNU::EmitClassRef(const std::string &className) {
2101 std::string symbolRef = "__objc_class_ref_" + className;
2102 // Don't emit two copies of the same symbol
2103 if (TheModule.getGlobalVariable(symbolRef))
2104 return;
2105 std::string symbolName = "__objc_class_name_" + className;
2106 llvm::GlobalVariable *ClassSymbol = TheModule.getGlobalVariable(symbolName);
2107 if (!ClassSymbol) {
2108 ClassSymbol = new llvm::GlobalVariable(TheModule, LongTy, false,
2109 llvm::GlobalValue::ExternalLinkage,
2110 nullptr, symbolName);
2111 }
2112 new llvm::GlobalVariable(TheModule, ClassSymbol->getType(), true,
2113 llvm::GlobalValue::WeakAnyLinkage, ClassSymbol, symbolRef);
2114}
2115
2116CGObjCGNU::CGObjCGNU(CodeGenModule &cgm, unsigned runtimeABIVersion,
2117 unsigned protocolClassVersion, unsigned classABI)
2118 : CGObjCRuntime(cgm), TheModule(CGM.getModule()),
2119 VMContext(cgm.getLLVMContext()), ClassPtrAlias(nullptr),
2120 MetaClassPtrAlias(nullptr), RuntimeVersion(runtimeABIVersion),
2121 ProtocolVersion(protocolClassVersion), ClassABIVersion(classABI) {
2122
2123 msgSendMDKind = VMContext.getMDKindID("GNUObjCMessageSend");
2124 usesSEHExceptions =
2125 cgm.getContext().getTargetInfo().getTriple().isWindowsMSVCEnvironment();
2126
2127 CodeGenTypes &Types = CGM.getTypes();
2128 IntTy = cast<llvm::IntegerType>(
2129 Types.ConvertType(CGM.getContext().IntTy));
2130 LongTy = cast<llvm::IntegerType>(
2131 Types.ConvertType(CGM.getContext().LongTy));
2132 SizeTy = cast<llvm::IntegerType>(
2133 Types.ConvertType(CGM.getContext().getSizeType()));
2134 PtrDiffTy = cast<llvm::IntegerType>(
2135 Types.ConvertType(CGM.getContext().getPointerDiffType()));
2136 BoolTy = CGM.getTypes().ConvertType(CGM.getContext().BoolTy);
2137
2138 Int8Ty = llvm::Type::getInt8Ty(VMContext);
2139 // C string type. Used in lots of places.
2140 PtrToInt8Ty = llvm::PointerType::getUnqual(Int8Ty);
2141 ProtocolPtrTy = llvm::PointerType::getUnqual(
2142 Types.ConvertType(CGM.getContext().getObjCProtoType()));
2143
2144 Zeros[0] = llvm::ConstantInt::get(LongTy, 0);
2145 Zeros[1] = Zeros[0];
2146 NULLPtr = llvm::ConstantPointerNull::get(PtrToInt8Ty);
2147 // Get the selector Type.
2148 QualType selTy = CGM.getContext().getObjCSelType();
2149 if (QualType() == selTy) {
2150 SelectorTy = PtrToInt8Ty;
2151 } else {
2152 SelectorTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(selTy));
2153 }
2154
2155 PtrToIntTy = llvm::PointerType::getUnqual(IntTy);
2156 PtrTy = PtrToInt8Ty;
2157
2158 Int32Ty = llvm::Type::getInt32Ty(VMContext);
2159 Int64Ty = llvm::Type::getInt64Ty(VMContext);
2160
2161 IntPtrTy =
2162 CGM.getDataLayout().getPointerSizeInBits() == 32 ? Int32Ty : Int64Ty;
2163
2164 // Object type
2165 QualType UnqualIdTy = CGM.getContext().getObjCIdType();
2166 ASTIdTy = CanQualType();
2167 if (UnqualIdTy != QualType()) {
2168 ASTIdTy = CGM.getContext().getCanonicalType(UnqualIdTy);
2169 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
2170 } else {
2171 IdTy = PtrToInt8Ty;
2172 }
2173 PtrToIdTy = llvm::PointerType::getUnqual(IdTy);
2174 ProtocolTy = llvm::StructType::get(IdTy,
2175 PtrToInt8Ty, // name
2176 PtrToInt8Ty, // protocols
2177 PtrToInt8Ty, // instance methods
2178 PtrToInt8Ty, // class methods
2179 PtrToInt8Ty, // optional instance methods
2180 PtrToInt8Ty, // optional class methods
2181 PtrToInt8Ty, // properties
2182 PtrToInt8Ty);// optional properties
2183
2184 // struct objc_property_gsv1
2185 // {
2186 // const char *name;
2187 // char attributes;
2188 // char attributes2;
2189 // char unused1;
2190 // char unused2;
2191 // const char *getter_name;
2192 // const char *getter_types;
2193 // const char *setter_name;
2194 // const char *setter_types;
2195 // }
2196 PropertyMetadataTy = llvm::StructType::get(CGM.getLLVMContext(), {
2197 PtrToInt8Ty, Int8Ty, Int8Ty, Int8Ty, Int8Ty, PtrToInt8Ty, PtrToInt8Ty,
2198 PtrToInt8Ty, PtrToInt8Ty });
2199
2200 ObjCSuperTy = llvm::StructType::get(IdTy, IdTy);
2201 PtrToObjCSuperTy = llvm::PointerType::getUnqual(ObjCSuperTy);
2202
2203 llvm::Type *VoidTy = llvm::Type::getVoidTy(VMContext);
2204
2205 // void objc_exception_throw(id);
2206 ExceptionThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
2207 ExceptionReThrowFn.init(&CGM, "objc_exception_throw", VoidTy, IdTy);
2208 // int objc_sync_enter(id);
2209 SyncEnterFn.init(&CGM, "objc_sync_enter", IntTy, IdTy);
2210 // int objc_sync_exit(id);
2211 SyncExitFn.init(&CGM, "objc_sync_exit", IntTy, IdTy);
2212
2213 // void objc_enumerationMutation (id)
2214 EnumerationMutationFn.init(&CGM, "objc_enumerationMutation", VoidTy, IdTy);
2215
2216 // id objc_getProperty(id, SEL, ptrdiff_t, BOOL)
2217 GetPropertyFn.init(&CGM, "objc_getProperty", IdTy, IdTy, SelectorTy,
2218 PtrDiffTy, BoolTy);
2219 // void objc_setProperty(id, SEL, ptrdiff_t, id, BOOL, BOOL)
2220 SetPropertyFn.init(&CGM, "objc_setProperty", VoidTy, IdTy, SelectorTy,
2221 PtrDiffTy, IdTy, BoolTy, BoolTy);
2222 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
2223 GetStructPropertyFn.init(&CGM, "objc_getPropertyStruct", VoidTy, PtrTy, PtrTy,
2224 PtrDiffTy, BoolTy, BoolTy);
2225 // void objc_setPropertyStruct(void*, void*, ptrdiff_t, BOOL, BOOL)
2226 SetStructPropertyFn.init(&CGM, "objc_setPropertyStruct", VoidTy, PtrTy, PtrTy,
2227 PtrDiffTy, BoolTy, BoolTy);
2228
2229 // IMP type
2230 llvm::Type *IMPArgs[] = { IdTy, SelectorTy };
2231 IMPTy = llvm::PointerType::getUnqual(llvm::FunctionType::get(IdTy, IMPArgs,
2232 true));
2233
2234 const LangOptions &Opts = CGM.getLangOpts();
2235 if ((Opts.getGC() != LangOptions::NonGC) || Opts.ObjCAutoRefCount)
2236 RuntimeVersion = 10;
2237
2238 // Don't bother initialising the GC stuff unless we're compiling in GC mode
2239 if (Opts.getGC() != LangOptions::NonGC) {
2240 // This is a bit of an hack. We should sort this out by having a proper
2241 // CGObjCGNUstep subclass for GC, but we may want to really support the old
2242 // ABI and GC added in ObjectiveC2.framework, so we fudge it a bit for now
2243 // Get selectors needed in GC mode
2244 RetainSel = GetNullarySelector("retain", CGM.getContext());
2245 ReleaseSel = GetNullarySelector("release", CGM.getContext());
2246 AutoreleaseSel = GetNullarySelector("autorelease", CGM.getContext());
2247
2248 // Get functions needed in GC mode
2249
2250 // id objc_assign_ivar(id, id, ptrdiff_t);
2251 IvarAssignFn.init(&CGM, "objc_assign_ivar", IdTy, IdTy, IdTy, PtrDiffTy);
2252 // id objc_assign_strongCast (id, id*)
2253 StrongCastAssignFn.init(&CGM, "objc_assign_strongCast", IdTy, IdTy,
2254 PtrToIdTy);
2255 // id objc_assign_global(id, id*);
2256 GlobalAssignFn.init(&CGM, "objc_assign_global", IdTy, IdTy, PtrToIdTy);
2257 // id objc_assign_weak(id, id*);
2258 WeakAssignFn.init(&CGM, "objc_assign_weak", IdTy, IdTy, PtrToIdTy);
2259 // id objc_read_weak(id*);
2260 WeakReadFn.init(&CGM, "objc_read_weak", IdTy, PtrToIdTy);
2261 // void *objc_memmove_collectable(void*, void *, size_t);
2262 MemMoveFn.init(&CGM, "objc_memmove_collectable", PtrTy, PtrTy, PtrTy,
2263 SizeTy);
2264 }
2265}
2266
2267llvm::Value *CGObjCGNU::GetClassNamed(CodeGenFunction &CGF,
2268 const std::string &Name, bool isWeak) {
2269 llvm::Constant *ClassName = MakeConstantString(Name);
2270 // With the incompatible ABI, this will need to be replaced with a direct
2271 // reference to the class symbol. For the compatible nonfragile ABI we are
2272 // still performing this lookup at run time but emitting the symbol for the
2273 // class externally so that we can make the switch later.
2274 //
2275 // Libobjc2 contains an LLVM pass that replaces calls to objc_lookup_class
2276 // with memoized versions or with static references if it's safe to do so.
2277 if (!isWeak)
2278 EmitClassRef(Name);
2279
2280 llvm::FunctionCallee ClassLookupFn = CGM.CreateRuntimeFunction(
2281 llvm::FunctionType::get(IdTy, PtrToInt8Ty, true), "objc_lookup_class");
2282 return CGF.EmitNounwindRuntimeCall(ClassLookupFn, ClassName);
2283}
2284
2285// This has to perform the lookup every time, since posing and related
2286// techniques can modify the name -> class mapping.
2287llvm::Value *CGObjCGNU::GetClass(CodeGenFunction &CGF,
2288 const ObjCInterfaceDecl *OID) {
2289 auto *Value =
2290 GetClassNamed(CGF, OID->getNameAsString(), OID->isWeakImported());
2291 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value))
2292 CGM.setGVProperties(ClassSymbol, OID);
2293 return Value;
2294}
2295
2296llvm::Value *CGObjCGNU::EmitNSAutoreleasePoolClassRef(CodeGenFunction &CGF) {
2297 auto *Value = GetClassNamed(CGF, "NSAutoreleasePool", false);
2298 if (CGM.getTriple().isOSBinFormatCOFF()) {
2299 if (auto *ClassSymbol = dyn_cast<llvm::GlobalVariable>(Value)) {
2300 IdentifierInfo &II = CGF.CGM.getContext().Idents.get("NSAutoreleasePool");
2301 TranslationUnitDecl *TUDecl = CGM.getContext().getTranslationUnitDecl();
2302 DeclContext *DC = TranslationUnitDecl::castToDeclContext(TUDecl);
2303
2304 const VarDecl *VD = nullptr;
2305 for (const auto &Result : DC->lookup(&II))
2306 if ((VD = dyn_cast<VarDecl>(Result)))
2307 break;
2308
2309 CGM.setGVProperties(ClassSymbol, VD);
2310 }
2311 }
2312 return Value;
2313}
2314
2315llvm::Value *CGObjCGNU::GetTypedSelector(CodeGenFunction &CGF, Selector Sel,
2316 const std::string &TypeEncoding) {
2317 SmallVectorImpl<TypedSelector> &Types = SelectorTable[Sel];
2318 llvm::GlobalAlias *SelValue = nullptr;
2319
2320 for (SmallVectorImpl<TypedSelector>::iterator i = Types.begin(),
2321 e = Types.end() ; i!=e ; i++) {
2322 if (i->first == TypeEncoding) {
2323 SelValue = i->second;
2324 break;
2325 }
2326 }
2327 if (!SelValue) {
2328 SelValue = llvm::GlobalAlias::create(
2329 SelectorTy->getElementType(), 0, llvm::GlobalValue::PrivateLinkage,
2330 ".objc_selector_" + Sel.getAsString(), &TheModule);
2331 Types.emplace_back(TypeEncoding, SelValue);
2332 }
2333
2334 return SelValue;
2335}
2336
2337Address CGObjCGNU::GetAddrOfSelector(CodeGenFunction &CGF, Selector Sel) {
2338 llvm::Value *SelValue = GetSelector(CGF, Sel);
2339
2340 // Store it to a temporary. Does this satisfy the semantics of
2341 // GetAddrOfSelector? Hopefully.
2342 Address tmp = CGF.CreateTempAlloca(SelValue->getType(),
2343 CGF.getPointerAlign());
2344 CGF.Builder.CreateStore(SelValue, tmp);
2345 return tmp;
2346}
2347
2348llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF, Selector Sel) {
2349 return GetTypedSelector(CGF, Sel, std::string());
2350}
2351
2352llvm::Value *CGObjCGNU::GetSelector(CodeGenFunction &CGF,
2353 const ObjCMethodDecl *Method) {
2354 std::string SelTypes = CGM.getContext().getObjCEncodingForMethodDecl(Method);
2355 return GetTypedSelector(CGF, Method->getSelector(), SelTypes);
2356}
2357
2358llvm::Constant *CGObjCGNU::GetEHType(QualType T) {
2359 if (T->isObjCIdType() || T->isObjCQualifiedIdType()) {
2360 // With the old ABI, there was only one kind of catchall, which broke
2361 // foreign exceptions. With the new ABI, we use __objc_id_typeinfo as
2362 // a pointer indicating object catchalls, and NULL to indicate real
2363 // catchalls
2364 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
2365 return MakeConstantString("@id");
2366 } else {
2367 return nullptr;
2368 }
2369 }
2370
2371 // All other types should be Objective-C interface pointer types.
2372 const ObjCObjectPointerType *OPT = T->getAs<ObjCObjectPointerType>();
2373 assert(OPT && "Invalid @catch type.")((OPT && "Invalid @catch type.") ? static_cast<void
> (0) : __assert_fail ("OPT && \"Invalid @catch type.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 2373, __PRETTY_FUNCTION__))
;
2374 const ObjCInterfaceDecl *IDecl = OPT->getObjectType()->getInterface();
2375 assert(IDecl && "Invalid @catch type.")((IDecl && "Invalid @catch type.") ? static_cast<void
> (0) : __assert_fail ("IDecl && \"Invalid @catch type.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 2375, __PRETTY_FUNCTION__))
;
2376 return MakeConstantString(IDecl->getIdentifier()->getName());
2377}
2378
2379llvm::Constant *CGObjCGNUstep::GetEHType(QualType T) {
2380 if (usesSEHExceptions)
2381 return CGM.getCXXABI().getAddrOfRTTIDescriptor(T);
2382
2383 if (!CGM.getLangOpts().CPlusPlus)
2384 return CGObjCGNU::GetEHType(T);
2385
2386 // For Objective-C++, we want to provide the ability to catch both C++ and
2387 // Objective-C objects in the same function.
2388
2389 // There's a particular fixed type info for 'id'.
2390 if (T->isObjCIdType() ||
2391 T->isObjCQualifiedIdType()) {
2392 llvm::Constant *IDEHType =
2393 CGM.getModule().getGlobalVariable("__objc_id_type_info");
2394 if (!IDEHType)
2395 IDEHType =
2396 new llvm::GlobalVariable(CGM.getModule(), PtrToInt8Ty,
2397 false,
2398 llvm::GlobalValue::ExternalLinkage,
2399 nullptr, "__objc_id_type_info");
2400 return llvm::ConstantExpr::getBitCast(IDEHType, PtrToInt8Ty);
2401 }
2402
2403 const ObjCObjectPointerType *PT =
2404 T->getAs<ObjCObjectPointerType>();
2405 assert(PT && "Invalid @catch type.")((PT && "Invalid @catch type.") ? static_cast<void
> (0) : __assert_fail ("PT && \"Invalid @catch type.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 2405, __PRETTY_FUNCTION__))
;
2406 const ObjCInterfaceType *IT = PT->getInterfaceType();
2407 assert(IT && "Invalid @catch type.")((IT && "Invalid @catch type.") ? static_cast<void
> (0) : __assert_fail ("IT && \"Invalid @catch type.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 2407, __PRETTY_FUNCTION__))
;
2408 std::string className = IT->getDecl()->getIdentifier()->getName();
2409
2410 std::string typeinfoName = "__objc_eh_typeinfo_" + className;
2411
2412 // Return the existing typeinfo if it exists
2413 llvm::Constant *typeinfo = TheModule.getGlobalVariable(typeinfoName);
2414 if (typeinfo)
2415 return llvm::ConstantExpr::getBitCast(typeinfo, PtrToInt8Ty);
2416
2417 // Otherwise create it.
2418
2419 // vtable for gnustep::libobjc::__objc_class_type_info
2420 // It's quite ugly hard-coding this. Ideally we'd generate it using the host
2421 // platform's name mangling.
2422 const char *vtableName = "_ZTVN7gnustep7libobjc22__objc_class_type_infoE";
2423 auto *Vtable = TheModule.getGlobalVariable(vtableName);
2424 if (!Vtable) {
2425 Vtable = new llvm::GlobalVariable(TheModule, PtrToInt8Ty, true,
2426 llvm::GlobalValue::ExternalLinkage,
2427 nullptr, vtableName);
2428 }
2429 llvm::Constant *Two = llvm::ConstantInt::get(IntTy, 2);
2430 auto *BVtable = llvm::ConstantExpr::getBitCast(
2431 llvm::ConstantExpr::getGetElementPtr(Vtable->getValueType(), Vtable, Two),
2432 PtrToInt8Ty);
2433
2434 llvm::Constant *typeName =
2435 ExportUniqueString(className, "__objc_eh_typename_");
2436
2437 ConstantInitBuilder builder(CGM);
2438 auto fields = builder.beginStruct();
2439 fields.add(BVtable);
2440 fields.add(typeName);
2441 llvm::Constant *TI =
2442 fields.finishAndCreateGlobal("__objc_eh_typeinfo_" + className,
2443 CGM.getPointerAlign(),
2444 /*constant*/ false,
2445 llvm::GlobalValue::LinkOnceODRLinkage);
2446 return llvm::ConstantExpr::getBitCast(TI, PtrToInt8Ty);
2447}
2448
2449/// Generate an NSConstantString object.
2450ConstantAddress CGObjCGNU::GenerateConstantString(const StringLiteral *SL) {
2451
2452 std::string Str = SL->getString().str();
2453 CharUnits Align = CGM.getPointerAlign();
2454
2455 // Look for an existing one
2456 llvm::StringMap<llvm::Constant*>::iterator old = ObjCStrings.find(Str);
2457 if (old != ObjCStrings.end())
2458 return ConstantAddress(old->getValue(), Align);
2459
2460 StringRef StringClass = CGM.getLangOpts().ObjCConstantStringClass;
2461
2462 if (StringClass.empty()) StringClass = "NSConstantString";
2463
2464 std::string Sym = "_OBJC_CLASS_";
2465 Sym += StringClass;
2466
2467 llvm::Constant *isa = TheModule.getNamedGlobal(Sym);
2468
2469 if (!isa)
2470 isa = new llvm::GlobalVariable(TheModule, IdTy, /* isConstant */false,
2471 llvm::GlobalValue::ExternalWeakLinkage, nullptr, Sym);
2472 else if (isa->getType() != PtrToIdTy)
2473 isa = llvm::ConstantExpr::getBitCast(isa, PtrToIdTy);
2474
2475 ConstantInitBuilder Builder(CGM);
2476 auto Fields = Builder.beginStruct();
2477 Fields.add(isa);
2478 Fields.add(MakeConstantString(Str));
2479 Fields.addInt(IntTy, Str.size());
2480 llvm::Constant *ObjCStr =
2481 Fields.finishAndCreateGlobal(".objc_str", Align);
2482 ObjCStr = llvm::ConstantExpr::getBitCast(ObjCStr, PtrToInt8Ty);
2483 ObjCStrings[Str] = ObjCStr;
2484 ConstantStrings.push_back(ObjCStr);
2485 return ConstantAddress(ObjCStr, Align);
2486}
2487
2488///Generates a message send where the super is the receiver. This is a message
2489///send to self with special delivery semantics indicating which class's method
2490///should be called.
2491RValue
2492CGObjCGNU::GenerateMessageSendSuper(CodeGenFunction &CGF,
2493 ReturnValueSlot Return,
2494 QualType ResultType,
2495 Selector Sel,
2496 const ObjCInterfaceDecl *Class,
2497 bool isCategoryImpl,
2498 llvm::Value *Receiver,
2499 bool IsClassMessage,
2500 const CallArgList &CallArgs,
2501 const ObjCMethodDecl *Method) {
2502 CGBuilderTy &Builder = CGF.Builder;
2503 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
2504 if (Sel == RetainSel || Sel == AutoreleaseSel) {
2505 return RValue::get(EnforceType(Builder, Receiver,
2506 CGM.getTypes().ConvertType(ResultType)));
2507 }
2508 if (Sel == ReleaseSel) {
2509 return RValue::get(nullptr);
2510 }
2511 }
2512
2513 llvm::Value *cmd = GetSelector(CGF, Sel);
2514 CallArgList ActualArgs;
2515
2516 ActualArgs.add(RValue::get(EnforceType(Builder, Receiver, IdTy)), ASTIdTy);
2517 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
2518 ActualArgs.addFrom(CallArgs);
2519
2520 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2521
2522 llvm::Value *ReceiverClass = nullptr;
2523 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2524 if (isV2ABI) {
2525 ReceiverClass = GetClassNamed(CGF,
2526 Class->getSuperClass()->getNameAsString(), /*isWeak*/false);
2527 if (IsClassMessage) {
2528 // Load the isa pointer of the superclass is this is a class method.
2529 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2530 llvm::PointerType::getUnqual(IdTy));
2531 ReceiverClass =
2532 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
2533 }
2534 ReceiverClass = EnforceType(Builder, ReceiverClass, IdTy);
2535 } else {
2536 if (isCategoryImpl) {
2537 llvm::FunctionCallee classLookupFunction = nullptr;
2538 if (IsClassMessage) {
2539 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2540 IdTy, PtrTy, true), "objc_get_meta_class");
2541 } else {
2542 classLookupFunction = CGM.CreateRuntimeFunction(llvm::FunctionType::get(
2543 IdTy, PtrTy, true), "objc_get_class");
2544 }
2545 ReceiverClass = Builder.CreateCall(classLookupFunction,
2546 MakeConstantString(Class->getNameAsString()));
2547 } else {
2548 // Set up global aliases for the metaclass or class pointer if they do not
2549 // already exist. These will are forward-references which will be set to
2550 // pointers to the class and metaclass structure created for the runtime
2551 // load function. To send a message to super, we look up the value of the
2552 // super_class pointer from either the class or metaclass structure.
2553 if (IsClassMessage) {
2554 if (!MetaClassPtrAlias) {
2555 MetaClassPtrAlias = llvm::GlobalAlias::create(
2556 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
2557 ".objc_metaclass_ref" + Class->getNameAsString(), &TheModule);
2558 }
2559 ReceiverClass = MetaClassPtrAlias;
2560 } else {
2561 if (!ClassPtrAlias) {
2562 ClassPtrAlias = llvm::GlobalAlias::create(
2563 IdTy->getElementType(), 0, llvm::GlobalValue::InternalLinkage,
2564 ".objc_class_ref" + Class->getNameAsString(), &TheModule);
2565 }
2566 ReceiverClass = ClassPtrAlias;
2567 }
2568 }
2569 // Cast the pointer to a simplified version of the class structure
2570 llvm::Type *CastTy = llvm::StructType::get(IdTy, IdTy);
2571 ReceiverClass = Builder.CreateBitCast(ReceiverClass,
2572 llvm::PointerType::getUnqual(CastTy));
2573 // Get the superclass pointer
2574 ReceiverClass = Builder.CreateStructGEP(CastTy, ReceiverClass, 1);
2575 // Load the superclass pointer
2576 ReceiverClass =
2577 Builder.CreateAlignedLoad(ReceiverClass, CGF.getPointerAlign());
2578 }
2579 // Construct the structure used to look up the IMP
2580 llvm::StructType *ObjCSuperTy =
2581 llvm::StructType::get(Receiver->getType(), IdTy);
2582
2583 Address ObjCSuper = CGF.CreateTempAlloca(ObjCSuperTy,
2584 CGF.getPointerAlign());
2585
2586 Builder.CreateStore(Receiver, Builder.CreateStructGEP(ObjCSuper, 0));
2587 Builder.CreateStore(ReceiverClass, Builder.CreateStructGEP(ObjCSuper, 1));
2588
2589 ObjCSuper = EnforceType(Builder, ObjCSuper, PtrToObjCSuperTy);
2590
2591 // Get the IMP
2592 llvm::Value *imp = LookupIMPSuper(CGF, ObjCSuper, cmd, MSI);
2593 imp = EnforceType(Builder, imp, MSI.MessengerType);
2594
2595 llvm::Metadata *impMD[] = {
2596 llvm::MDString::get(VMContext, Sel.getAsString()),
2597 llvm::MDString::get(VMContext, Class->getSuperClass()->getNameAsString()),
2598 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2599 llvm::Type::getInt1Ty(VMContext), IsClassMessage))};
2600 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
2601
2602 CGCallee callee(CGCalleeInfo(), imp);
2603
2604 llvm::CallBase *call;
2605 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
2606 call->setMetadata(msgSendMDKind, node);
2607 return msgRet;
2608}
2609
2610/// Generate code for a message send expression.
2611RValue
2612CGObjCGNU::GenerateMessageSend(CodeGenFunction &CGF,
2613 ReturnValueSlot Return,
2614 QualType ResultType,
2615 Selector Sel,
2616 llvm::Value *Receiver,
2617 const CallArgList &CallArgs,
2618 const ObjCInterfaceDecl *Class,
2619 const ObjCMethodDecl *Method) {
2620 CGBuilderTy &Builder = CGF.Builder;
2621
2622 // Strip out message sends to retain / release in GC mode
2623 if (CGM.getLangOpts().getGC() == LangOptions::GCOnly) {
2624 if (Sel == RetainSel || Sel == AutoreleaseSel) {
2625 return RValue::get(EnforceType(Builder, Receiver,
2626 CGM.getTypes().ConvertType(ResultType)));
2627 }
2628 if (Sel == ReleaseSel) {
2629 return RValue::get(nullptr);
2630 }
2631 }
2632
2633 // If the return type is something that goes in an integer register, the
2634 // runtime will handle 0 returns. For other cases, we fill in the 0 value
2635 // ourselves.
2636 //
2637 // The language spec says the result of this kind of message send is
2638 // undefined, but lots of people seem to have forgotten to read that
2639 // paragraph and insist on sending messages to nil that have structure
2640 // returns. With GCC, this generates a random return value (whatever happens
2641 // to be on the stack / in those registers at the time) on most platforms,
2642 // and generates an illegal instruction trap on SPARC. With LLVM it corrupts
2643 // the stack.
2644 bool isPointerSizedReturn = (ResultType->isAnyPointerType() ||
2645 ResultType->isIntegralOrEnumerationType() || ResultType->isVoidType());
2646
2647 llvm::BasicBlock *startBB = nullptr;
2648 llvm::BasicBlock *messageBB = nullptr;
2649 llvm::BasicBlock *continueBB = nullptr;
2650
2651 if (!isPointerSizedReturn) {
2652 startBB = Builder.GetInsertBlock();
2653 messageBB = CGF.createBasicBlock("msgSend");
2654 continueBB = CGF.createBasicBlock("continue");
2655
2656 llvm::Value *isNil = Builder.CreateICmpEQ(Receiver,
2657 llvm::Constant::getNullValue(Receiver->getType()));
2658 Builder.CreateCondBr(isNil, continueBB, messageBB);
2659 CGF.EmitBlock(messageBB);
2660 }
2661
2662 IdTy = cast<llvm::PointerType>(CGM.getTypes().ConvertType(ASTIdTy));
2663 llvm::Value *cmd;
2664 if (Method)
2665 cmd = GetSelector(CGF, Method);
2666 else
2667 cmd = GetSelector(CGF, Sel);
2668 cmd = EnforceType(Builder, cmd, SelectorTy);
2669 Receiver = EnforceType(Builder, Receiver, IdTy);
2670
2671 llvm::Metadata *impMD[] = {
2672 llvm::MDString::get(VMContext, Sel.getAsString()),
2673 llvm::MDString::get(VMContext, Class ? Class->getNameAsString() : ""),
2674 llvm::ConstantAsMetadata::get(llvm::ConstantInt::get(
2675 llvm::Type::getInt1Ty(VMContext), Class != nullptr))};
2676 llvm::MDNode *node = llvm::MDNode::get(VMContext, impMD);
2677
2678 CallArgList ActualArgs;
2679 ActualArgs.add(RValue::get(Receiver), ASTIdTy);
2680 ActualArgs.add(RValue::get(cmd), CGF.getContext().getObjCSelType());
2681 ActualArgs.addFrom(CallArgs);
2682
2683 MessageSendInfo MSI = getMessageSendInfo(Method, ResultType, ActualArgs);
2684
2685 // Get the IMP to call
2686 llvm::Value *imp;
2687
2688 // If we have non-legacy dispatch specified, we try using the objc_msgSend()
2689 // functions. These are not supported on all platforms (or all runtimes on a
2690 // given platform), so we
2691 switch (CGM.getCodeGenOpts().getObjCDispatchMethod()) {
2692 case CodeGenOptions::Legacy:
2693 imp = LookupIMP(CGF, Receiver, cmd, node, MSI);
2694 break;
2695 case CodeGenOptions::Mixed:
2696 case CodeGenOptions::NonLegacy:
2697 if (CGM.ReturnTypeUsesFPRet(ResultType)) {
2698 imp =
2699 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2700 "objc_msgSend_fpret")
2701 .getCallee();
2702 } else if (CGM.ReturnTypeUsesSRet(MSI.CallInfo)) {
2703 // The actual types here don't matter - we're going to bitcast the
2704 // function anyway
2705 imp =
2706 CGM.CreateRuntimeFunction(llvm::FunctionType::get(IdTy, IdTy, true),
2707 "objc_msgSend_stret")
2708 .getCallee();
2709 } else {
2710 imp = CGM.CreateRuntimeFunction(
2711 llvm::FunctionType::get(IdTy, IdTy, true), "objc_msgSend")
2712 .getCallee();
2713 }
2714 }
2715
2716 // Reset the receiver in case the lookup modified it
2717 ActualArgs[0] = CallArg(RValue::get(Receiver), ASTIdTy);
2718
2719 imp = EnforceType(Builder, imp, MSI.MessengerType);
2720
2721 llvm::CallBase *call;
2722 CGCallee callee(CGCalleeInfo(), imp);
2723 RValue msgRet = CGF.EmitCall(MSI.CallInfo, callee, Return, ActualArgs, &call);
2724 call->setMetadata(msgSendMDKind, node);
2725
2726
2727 if (!isPointerSizedReturn) {
2728 messageBB = CGF.Builder.GetInsertBlock();
2729 CGF.Builder.CreateBr(continueBB);
2730 CGF.EmitBlock(continueBB);
2731 if (msgRet.isScalar()) {
2732 llvm::Value *v = msgRet.getScalarVal();
2733 llvm::PHINode *phi = Builder.CreatePHI(v->getType(), 2);
2734 phi->addIncoming(v, messageBB);
2735 phi->addIncoming(llvm::Constant::getNullValue(v->getType()), startBB);
2736 msgRet = RValue::get(phi);
2737 } else if (msgRet.isAggregate()) {
2738 Address v = msgRet.getAggregateAddress();
2739 llvm::PHINode *phi = Builder.CreatePHI(v.getType(), 2);
2740 llvm::Type *RetTy = v.getElementType();
2741 Address NullVal = CGF.CreateTempAlloca(RetTy, v.getAlignment(), "null");
2742 CGF.InitTempAlloca(NullVal, llvm::Constant::getNullValue(RetTy));
2743 phi->addIncoming(v.getPointer(), messageBB);
2744 phi->addIncoming(NullVal.getPointer(), startBB);
2745 msgRet = RValue::getAggregate(Address(phi, v.getAlignment()));
2746 } else /* isComplex() */ {
2747 std::pair<llvm::Value*,llvm::Value*> v = msgRet.getComplexVal();
2748 llvm::PHINode *phi = Builder.CreatePHI(v.first->getType(), 2);
2749 phi->addIncoming(v.first, messageBB);
2750 phi->addIncoming(llvm::Constant::getNullValue(v.first->getType()),
2751 startBB);
2752 llvm::PHINode *phi2 = Builder.CreatePHI(v.second->getType(), 2);
2753 phi2->addIncoming(v.second, messageBB);
2754 phi2->addIncoming(llvm::Constant::getNullValue(v.second->getType()),
2755 startBB);
2756 msgRet = RValue::getComplex(phi, phi2);
2757 }
2758 }
2759 return msgRet;
2760}
2761
2762/// Generates a MethodList. Used in construction of a objc_class and
2763/// objc_category structures.
2764llvm::Constant *CGObjCGNU::
2765GenerateMethodList(StringRef ClassName,
2766 StringRef CategoryName,
2767 ArrayRef<const ObjCMethodDecl*> Methods,
2768 bool isClassMethodList) {
2769 if (Methods.empty())
2770 return NULLPtr;
2771
2772 ConstantInitBuilder Builder(CGM);
2773
2774 auto MethodList = Builder.beginStruct();
2775 MethodList.addNullPointer(CGM.Int8PtrTy);
2776 MethodList.addInt(Int32Ty, Methods.size());
2777
2778 // Get the method structure type.
2779 llvm::StructType *ObjCMethodTy =
2780 llvm::StructType::get(CGM.getLLVMContext(), {
2781 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2782 PtrToInt8Ty, // Method types
2783 IMPTy // Method pointer
2784 });
2785 bool isV2ABI = isRuntime(ObjCRuntime::GNUstep, 2);
2786 if (isV2ABI) {
2787 // size_t size;
2788 llvm::DataLayout td(&TheModule);
2789 MethodList.addInt(SizeTy, td.getTypeSizeInBits(ObjCMethodTy) /
2790 CGM.getContext().getCharWidth());
2791 ObjCMethodTy =
2792 llvm::StructType::get(CGM.getLLVMContext(), {
2793 IMPTy, // Method pointer
2794 PtrToInt8Ty, // Selector
2795 PtrToInt8Ty // Extended type encoding
2796 });
2797 } else {
2798 ObjCMethodTy =
2799 llvm::StructType::get(CGM.getLLVMContext(), {
2800 PtrToInt8Ty, // Really a selector, but the runtime creates it us.
2801 PtrToInt8Ty, // Method types
2802 IMPTy // Method pointer
2803 });
2804 }
2805 auto MethodArray = MethodList.beginArray();
2806 ASTContext &Context = CGM.getContext();
2807 for (const auto *OMD : Methods) {
2808 llvm::Constant *FnPtr =
2809 TheModule.getFunction(SymbolNameForMethod(ClassName, CategoryName,
2810 OMD->getSelector(),
2811 isClassMethodList));
2812 assert(FnPtr && "Can't generate metadata for method that doesn't exist")((FnPtr && "Can't generate metadata for method that doesn't exist"
) ? static_cast<void> (0) : __assert_fail ("FnPtr && \"Can't generate metadata for method that doesn't exist\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 2812, __PRETTY_FUNCTION__))
;
2813 auto Method = MethodArray.beginStruct(ObjCMethodTy);
2814 if (isV2ABI) {
2815 Method.addBitCast(FnPtr, IMPTy);
2816 Method.add(GetConstantSelector(OMD->getSelector(),
2817 Context.getObjCEncodingForMethodDecl(OMD)));
2818 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD, true)));
2819 } else {
2820 Method.add(MakeConstantString(OMD->getSelector().getAsString()));
2821 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(OMD)));
2822 Method.addBitCast(FnPtr, IMPTy);
2823 }
2824 Method.finishAndAddTo(MethodArray);
2825 }
2826 MethodArray.finishAndAddTo(MethodList);
2827
2828 // Create an instance of the structure
2829 return MethodList.finishAndCreateGlobal(".objc_method_list",
2830 CGM.getPointerAlign());
2831}
2832
2833/// Generates an IvarList. Used in construction of a objc_class.
2834llvm::Constant *CGObjCGNU::
2835GenerateIvarList(ArrayRef<llvm::Constant *> IvarNames,
2836 ArrayRef<llvm::Constant *> IvarTypes,
2837 ArrayRef<llvm::Constant *> IvarOffsets,
2838 ArrayRef<llvm::Constant *> IvarAlign,
2839 ArrayRef<Qualifiers::ObjCLifetime> IvarOwnership) {
2840 if (IvarNames.empty())
2841 return NULLPtr;
2842
2843 ConstantInitBuilder Builder(CGM);
2844
2845 // Structure containing array count followed by array.
2846 auto IvarList = Builder.beginStruct();
2847 IvarList.addInt(IntTy, (int)IvarNames.size());
2848
2849 // Get the ivar structure type.
2850 llvm::StructType *ObjCIvarTy =
2851 llvm::StructType::get(PtrToInt8Ty, PtrToInt8Ty, IntTy);
2852
2853 // Array of ivar structures.
2854 auto Ivars = IvarList.beginArray(ObjCIvarTy);
2855 for (unsigned int i = 0, e = IvarNames.size() ; i < e ; i++) {
2856 auto Ivar = Ivars.beginStruct(ObjCIvarTy);
2857 Ivar.add(IvarNames[i]);
2858 Ivar.add(IvarTypes[i]);
2859 Ivar.add(IvarOffsets[i]);
2860 Ivar.finishAndAddTo(Ivars);
2861 }
2862 Ivars.finishAndAddTo(IvarList);
2863
2864 // Create an instance of the structure
2865 return IvarList.finishAndCreateGlobal(".objc_ivar_list",
2866 CGM.getPointerAlign());
2867}
2868
2869/// Generate a class structure
2870llvm::Constant *CGObjCGNU::GenerateClassStructure(
2871 llvm::Constant *MetaClass,
2872 llvm::Constant *SuperClass,
2873 unsigned info,
2874 const char *Name,
2875 llvm::Constant *Version,
2876 llvm::Constant *InstanceSize,
2877 llvm::Constant *IVars,
2878 llvm::Constant *Methods,
2879 llvm::Constant *Protocols,
2880 llvm::Constant *IvarOffsets,
2881 llvm::Constant *Properties,
2882 llvm::Constant *StrongIvarBitmap,
2883 llvm::Constant *WeakIvarBitmap,
2884 bool isMeta) {
2885 // Set up the class structure
2886 // Note: Several of these are char*s when they should be ids. This is
2887 // because the runtime performs this translation on load.
2888 //
2889 // Fields marked New ABI are part of the GNUstep runtime. We emit them
2890 // anyway; the classes will still work with the GNU runtime, they will just
2891 // be ignored.
2892 llvm::StructType *ClassTy = llvm::StructType::get(
2893 PtrToInt8Ty, // isa
2894 PtrToInt8Ty, // super_class
2895 PtrToInt8Ty, // name
2896 LongTy, // version
2897 LongTy, // info
2898 LongTy, // instance_size
2899 IVars->getType(), // ivars
2900 Methods->getType(), // methods
2901 // These are all filled in by the runtime, so we pretend
2902 PtrTy, // dtable
2903 PtrTy, // subclass_list
2904 PtrTy, // sibling_class
2905 PtrTy, // protocols
2906 PtrTy, // gc_object_type
2907 // New ABI:
2908 LongTy, // abi_version
2909 IvarOffsets->getType(), // ivar_offsets
2910 Properties->getType(), // properties
2911 IntPtrTy, // strong_pointers
2912 IntPtrTy // weak_pointers
2913 );
2914
2915 ConstantInitBuilder Builder(CGM);
2916 auto Elements = Builder.beginStruct(ClassTy);
2917
2918 // Fill in the structure
2919
2920 // isa
2921 Elements.addBitCast(MetaClass, PtrToInt8Ty);
2922 // super_class
2923 Elements.add(SuperClass);
2924 // name
2925 Elements.add(MakeConstantString(Name, ".class_name"));
2926 // version
2927 Elements.addInt(LongTy, 0);
2928 // info
2929 Elements.addInt(LongTy, info);
2930 // instance_size
2931 if (isMeta) {
2932 llvm::DataLayout td(&TheModule);
2933 Elements.addInt(LongTy,
2934 td.getTypeSizeInBits(ClassTy) /
2935 CGM.getContext().getCharWidth());
2936 } else
2937 Elements.add(InstanceSize);
2938 // ivars
2939 Elements.add(IVars);
2940 // methods
2941 Elements.add(Methods);
2942 // These are all filled in by the runtime, so we pretend
2943 // dtable
2944 Elements.add(NULLPtr);
2945 // subclass_list
2946 Elements.add(NULLPtr);
2947 // sibling_class
2948 Elements.add(NULLPtr);
2949 // protocols
2950 Elements.addBitCast(Protocols, PtrTy);
2951 // gc_object_type
2952 Elements.add(NULLPtr);
2953 // abi_version
2954 Elements.addInt(LongTy, ClassABIVersion);
2955 // ivar_offsets
2956 Elements.add(IvarOffsets);
2957 // properties
2958 Elements.add(Properties);
2959 // strong_pointers
2960 Elements.add(StrongIvarBitmap);
2961 // weak_pointers
2962 Elements.add(WeakIvarBitmap);
2963 // Create an instance of the structure
2964 // This is now an externally visible symbol, so that we can speed up class
2965 // messages in the next ABI. We may already have some weak references to
2966 // this, so check and fix them properly.
2967 std::string ClassSym((isMeta ? "_OBJC_METACLASS_": "_OBJC_CLASS_") +
2968 std::string(Name));
2969 llvm::GlobalVariable *ClassRef = TheModule.getNamedGlobal(ClassSym);
2970 llvm::Constant *Class =
2971 Elements.finishAndCreateGlobal(ClassSym, CGM.getPointerAlign(), false,
2972 llvm::GlobalValue::ExternalLinkage);
2973 if (ClassRef) {
2974 ClassRef->replaceAllUsesWith(llvm::ConstantExpr::getBitCast(Class,
2975 ClassRef->getType()));
2976 ClassRef->removeFromParent();
2977 Class->setName(ClassSym);
2978 }
2979 return Class;
2980}
2981
2982llvm::Constant *CGObjCGNU::
2983GenerateProtocolMethodList(ArrayRef<const ObjCMethodDecl*> Methods) {
2984 // Get the method structure type.
2985 llvm::StructType *ObjCMethodDescTy =
2986 llvm::StructType::get(CGM.getLLVMContext(), { PtrToInt8Ty, PtrToInt8Ty });
2987 ASTContext &Context = CGM.getContext();
2988 ConstantInitBuilder Builder(CGM);
2989 auto MethodList = Builder.beginStruct();
2990 MethodList.addInt(IntTy, Methods.size());
2991 auto MethodArray = MethodList.beginArray(ObjCMethodDescTy);
2992 for (auto *M : Methods) {
2993 auto Method = MethodArray.beginStruct(ObjCMethodDescTy);
2994 Method.add(MakeConstantString(M->getSelector().getAsString()));
2995 Method.add(MakeConstantString(Context.getObjCEncodingForMethodDecl(M)));
2996 Method.finishAndAddTo(MethodArray);
2997 }
2998 MethodArray.finishAndAddTo(MethodList);
2999 return MethodList.finishAndCreateGlobal(".objc_method_list",
3000 CGM.getPointerAlign());
3001}
3002
3003// Create the protocol list structure used in classes, categories and so on
3004llvm::Constant *
3005CGObjCGNU::GenerateProtocolList(ArrayRef<std::string> Protocols) {
3006
3007 ConstantInitBuilder Builder(CGM);
3008 auto ProtocolList = Builder.beginStruct();
3009 ProtocolList.add(NULLPtr);
3010 ProtocolList.addInt(LongTy, Protocols.size());
3011
3012 auto Elements = ProtocolList.beginArray(PtrToInt8Ty);
3013 for (const std::string *iter = Protocols.begin(), *endIter = Protocols.end();
3014 iter != endIter ; iter++) {
3015 llvm::Constant *protocol = nullptr;
3016 llvm::StringMap<llvm::Constant*>::iterator value =
3017 ExistingProtocols.find(*iter);
3018 if (value == ExistingProtocols.end()) {
3019 protocol = GenerateEmptyProtocol(*iter);
3020 } else {
3021 protocol = value->getValue();
3022 }
3023 Elements.addBitCast(protocol, PtrToInt8Ty);
3024 }
3025 Elements.finishAndAddTo(ProtocolList);
3026 return ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3027 CGM.getPointerAlign());
3028}
3029
3030llvm::Value *CGObjCGNU::GenerateProtocolRef(CodeGenFunction &CGF,
3031 const ObjCProtocolDecl *PD) {
3032 llvm::Constant *&protocol = ExistingProtocols[PD->getNameAsString()];
3033 if (!protocol)
3034 GenerateProtocol(PD);
3035 llvm::Type *T =
3036 CGM.getTypes().ConvertType(CGM.getContext().getObjCProtoType());
3037 return CGF.Builder.CreateBitCast(protocol, llvm::PointerType::getUnqual(T));
3038}
3039
3040llvm::Constant *
3041CGObjCGNU::GenerateEmptyProtocol(StringRef ProtocolName) {
3042 llvm::Constant *ProtocolList = GenerateProtocolList({});
3043 llvm::Constant *MethodList = GenerateProtocolMethodList({});
3044 MethodList = llvm::ConstantExpr::getBitCast(MethodList, PtrToInt8Ty);
3045 // Protocols are objects containing lists of the methods implemented and
3046 // protocols adopted.
3047 ConstantInitBuilder Builder(CGM);
3048 auto Elements = Builder.beginStruct();
3049
3050 // The isa pointer must be set to a magic number so the runtime knows it's
3051 // the correct layout.
3052 Elements.add(llvm::ConstantExpr::getIntToPtr(
3053 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
3054
3055 Elements.add(MakeConstantString(ProtocolName, ".objc_protocol_name"));
3056 Elements.add(ProtocolList); /* .protocol_list */
3057 Elements.add(MethodList); /* .instance_methods */
3058 Elements.add(MethodList); /* .class_methods */
3059 Elements.add(MethodList); /* .optional_instance_methods */
3060 Elements.add(MethodList); /* .optional_class_methods */
3061 Elements.add(NULLPtr); /* .properties */
3062 Elements.add(NULLPtr); /* .optional_properties */
3063 return Elements.finishAndCreateGlobal(SymbolForProtocol(ProtocolName),
3064 CGM.getPointerAlign());
3065}
3066
3067void CGObjCGNU::GenerateProtocol(const ObjCProtocolDecl *PD) {
3068 std::string ProtocolName = PD->getNameAsString();
3069
3070 // Use the protocol definition, if there is one.
3071 if (const ObjCProtocolDecl *Def = PD->getDefinition())
3072 PD = Def;
3073
3074 SmallVector<std::string, 16> Protocols;
3075 for (const auto *PI : PD->protocols())
3076 Protocols.push_back(PI->getNameAsString());
3077 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3078 SmallVector<const ObjCMethodDecl*, 16> OptionalInstanceMethods;
3079 for (const auto *I : PD->instance_methods())
3080 if (I->isOptional())
3081 OptionalInstanceMethods.push_back(I);
3082 else
3083 InstanceMethods.push_back(I);
3084 // Collect information about class methods:
3085 SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3086 SmallVector<const ObjCMethodDecl*, 16> OptionalClassMethods;
3087 for (const auto *I : PD->class_methods())
3088 if (I->isOptional())
3089 OptionalClassMethods.push_back(I);
3090 else
3091 ClassMethods.push_back(I);
3092
3093 llvm::Constant *ProtocolList = GenerateProtocolList(Protocols);
3094 llvm::Constant *InstanceMethodList =
3095 GenerateProtocolMethodList(InstanceMethods);
3096 llvm::Constant *ClassMethodList =
3097 GenerateProtocolMethodList(ClassMethods);
3098 llvm::Constant *OptionalInstanceMethodList =
3099 GenerateProtocolMethodList(OptionalInstanceMethods);
3100 llvm::Constant *OptionalClassMethodList =
3101 GenerateProtocolMethodList(OptionalClassMethods);
3102
3103 // Property metadata: name, attributes, isSynthesized, setter name, setter
3104 // types, getter name, getter types.
3105 // The isSynthesized value is always set to 0 in a protocol. It exists to
3106 // simplify the runtime library by allowing it to use the same data
3107 // structures for protocol metadata everywhere.
3108
3109 llvm::Constant *PropertyList =
3110 GeneratePropertyList(nullptr, PD, false, false);
3111 llvm::Constant *OptionalPropertyList =
3112 GeneratePropertyList(nullptr, PD, false, true);
3113
3114 // Protocols are objects containing lists of the methods implemented and
3115 // protocols adopted.
3116 // The isa pointer must be set to a magic number so the runtime knows it's
3117 // the correct layout.
3118 ConstantInitBuilder Builder(CGM);
3119 auto Elements = Builder.beginStruct();
3120 Elements.add(
3121 llvm::ConstantExpr::getIntToPtr(
3122 llvm::ConstantInt::get(Int32Ty, ProtocolVersion), IdTy));
3123 Elements.add(MakeConstantString(ProtocolName));
3124 Elements.add(ProtocolList);
3125 Elements.add(InstanceMethodList);
3126 Elements.add(ClassMethodList);
3127 Elements.add(OptionalInstanceMethodList);
3128 Elements.add(OptionalClassMethodList);
3129 Elements.add(PropertyList);
3130 Elements.add(OptionalPropertyList);
3131 ExistingProtocols[ProtocolName] =
3132 llvm::ConstantExpr::getBitCast(
3133 Elements.finishAndCreateGlobal(".objc_protocol", CGM.getPointerAlign()),
3134 IdTy);
3135}
3136void CGObjCGNU::GenerateProtocolHolderCategory() {
3137 // Collect information about instance methods
3138
3139 ConstantInitBuilder Builder(CGM);
3140 auto Elements = Builder.beginStruct();
3141
3142 const std::string ClassName = "__ObjC_Protocol_Holder_Ugly_Hack";
3143 const std::string CategoryName = "AnotherHack";
3144 Elements.add(MakeConstantString(CategoryName));
3145 Elements.add(MakeConstantString(ClassName));
3146 // Instance method list
3147 Elements.addBitCast(GenerateMethodList(
3148 ClassName, CategoryName, {}, false), PtrTy);
3149 // Class method list
3150 Elements.addBitCast(GenerateMethodList(
3151 ClassName, CategoryName, {}, true), PtrTy);
3152
3153 // Protocol list
3154 ConstantInitBuilder ProtocolListBuilder(CGM);
3155 auto ProtocolList = ProtocolListBuilder.beginStruct();
3156 ProtocolList.add(NULLPtr);
3157 ProtocolList.addInt(LongTy, ExistingProtocols.size());
3158 auto ProtocolElements = ProtocolList.beginArray(PtrTy);
3159 for (auto iter = ExistingProtocols.begin(), endIter = ExistingProtocols.end();
3160 iter != endIter ; iter++) {
3161 ProtocolElements.addBitCast(iter->getValue(), PtrTy);
3162 }
3163 ProtocolElements.finishAndAddTo(ProtocolList);
3164 Elements.addBitCast(
3165 ProtocolList.finishAndCreateGlobal(".objc_protocol_list",
3166 CGM.getPointerAlign()),
3167 PtrTy);
3168 Categories.push_back(llvm::ConstantExpr::getBitCast(
3169 Elements.finishAndCreateGlobal("", CGM.getPointerAlign()),
3170 PtrTy));
3171}
3172
3173/// Libobjc2 uses a bitfield representation where small(ish) bitfields are
3174/// stored in a 64-bit value with the low bit set to 1 and the remaining 63
3175/// bits set to their values, LSB first, while larger ones are stored in a
3176/// structure of this / form:
3177///
3178/// struct { int32_t length; int32_t values[length]; };
3179///
3180/// The values in the array are stored in host-endian format, with the least
3181/// significant bit being assumed to come first in the bitfield. Therefore, a
3182/// bitfield with the 64th bit set will be (int64_t)&{ 2, [0, 1<<31] }, while a
3183/// bitfield / with the 63rd bit set will be 1<<64.
3184llvm::Constant *CGObjCGNU::MakeBitField(ArrayRef<bool> bits) {
3185 int bitCount = bits.size();
3186 int ptrBits = CGM.getDataLayout().getPointerSizeInBits();
3187 if (bitCount < ptrBits) {
3188 uint64_t val = 1;
3189 for (int i=0 ; i<bitCount ; ++i) {
3190 if (bits[i]) val |= 1ULL<<(i+1);
3191 }
3192 return llvm::ConstantInt::get(IntPtrTy, val);
3193 }
3194 SmallVector<llvm::Constant *, 8> values;
3195 int v=0;
3196 while (v < bitCount) {
3197 int32_t word = 0;
3198 for (int i=0 ; (i<32) && (v<bitCount) ; ++i) {
3199 if (bits[v]) word |= 1<<i;
3200 v++;
3201 }
3202 values.push_back(llvm::ConstantInt::get(Int32Ty, word));
3203 }
3204
3205 ConstantInitBuilder builder(CGM);
3206 auto fields = builder.beginStruct();
3207 fields.addInt(Int32Ty, values.size());
3208 auto array = fields.beginArray();
3209 for (auto v : values) array.add(v);
3210 array.finishAndAddTo(fields);
3211
3212 llvm::Constant *GS =
3213 fields.finishAndCreateGlobal("", CharUnits::fromQuantity(4));
3214 llvm::Constant *ptr = llvm::ConstantExpr::getPtrToInt(GS, IntPtrTy);
3215 return ptr;
3216}
3217
3218llvm::Constant *CGObjCGNU::GenerateCategoryProtocolList(const
3219 ObjCCategoryDecl *OCD) {
3220 SmallVector<std::string, 16> Protocols;
3221 for (const auto *PD : OCD->getReferencedProtocols())
3222 Protocols.push_back(PD->getNameAsString());
3223 return GenerateProtocolList(Protocols);
3224}
3225
3226void CGObjCGNU::GenerateCategory(const ObjCCategoryImplDecl *OCD) {
3227 const ObjCInterfaceDecl *Class = OCD->getClassInterface();
3228 std::string ClassName = Class->getNameAsString();
3229 std::string CategoryName = OCD->getNameAsString();
3230
3231 // Collect the names of referenced protocols
3232 const ObjCCategoryDecl *CatDecl = OCD->getCategoryDecl();
3233
3234 ConstantInitBuilder Builder(CGM);
3235 auto Elements = Builder.beginStruct();
3236 Elements.add(MakeConstantString(CategoryName));
3237 Elements.add(MakeConstantString(ClassName));
3238 // Instance method list
3239 SmallVector<ObjCMethodDecl*, 16> InstanceMethods;
3240 InstanceMethods.insert(InstanceMethods.begin(), OCD->instmeth_begin(),
3241 OCD->instmeth_end());
3242 Elements.addBitCast(
3243 GenerateMethodList(ClassName, CategoryName, InstanceMethods, false),
3244 PtrTy);
3245 // Class method list
3246
3247 SmallVector<ObjCMethodDecl*, 16> ClassMethods;
3248 ClassMethods.insert(ClassMethods.begin(), OCD->classmeth_begin(),
3249 OCD->classmeth_end());
3250 Elements.addBitCast(
3251 GenerateMethodList(ClassName, CategoryName, ClassMethods, true),
3252 PtrTy);
3253 // Protocol list
3254 Elements.addBitCast(GenerateCategoryProtocolList(CatDecl), PtrTy);
3255 if (isRuntime(ObjCRuntime::GNUstep, 2)) {
3256 const ObjCCategoryDecl *Category =
3257 Class->FindCategoryDeclaration(OCD->getIdentifier());
3258 if (Category) {
3259 // Instance properties
3260 Elements.addBitCast(GeneratePropertyList(OCD, Category, false), PtrTy);
3261 // Class properties
3262 Elements.addBitCast(GeneratePropertyList(OCD, Category, true), PtrTy);
3263 } else {
3264 Elements.addNullPointer(PtrTy);
3265 Elements.addNullPointer(PtrTy);
3266 }
3267 }
3268
3269 Categories.push_back(llvm::ConstantExpr::getBitCast(
3270 Elements.finishAndCreateGlobal(
3271 std::string(".objc_category_")+ClassName+CategoryName,
3272 CGM.getPointerAlign()),
3273 PtrTy));
3274}
3275
3276llvm::Constant *CGObjCGNU::GeneratePropertyList(const Decl *Container,
3277 const ObjCContainerDecl *OCD,
3278 bool isClassProperty,
3279 bool protocolOptionalProperties) {
3280
3281 SmallVector<const ObjCPropertyDecl *, 16> Properties;
3282 llvm::SmallPtrSet<const IdentifierInfo*, 16> PropertySet;
3283 bool isProtocol = isa<ObjCProtocolDecl>(OCD);
3284 ASTContext &Context = CGM.getContext();
3285
3286 std::function<void(const ObjCProtocolDecl *Proto)> collectProtocolProperties
3287 = [&](const ObjCProtocolDecl *Proto) {
3288 for (const auto *P : Proto->protocols())
3289 collectProtocolProperties(P);
3290 for (const auto *PD : Proto->properties()) {
3291 if (isClassProperty != PD->isClassProperty())
3292 continue;
3293 // Skip any properties that are declared in protocols that this class
3294 // conforms to but are not actually implemented by this class.
3295 if (!isProtocol && !Context.getObjCPropertyImplDeclForPropertyDecl(PD, Container))
3296 continue;
3297 if (!PropertySet.insert(PD->getIdentifier()).second)
3298 continue;
3299 Properties.push_back(PD);
3300 }
3301 };
3302
3303 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3304 for (const ObjCCategoryDecl *ClassExt : OID->known_extensions())
3305 for (auto *PD : ClassExt->properties()) {
3306 if (isClassProperty != PD->isClassProperty())
3307 continue;
3308 PropertySet.insert(PD->getIdentifier());
3309 Properties.push_back(PD);
3310 }
3311
3312 for (const auto *PD : OCD->properties()) {
3313 if (isClassProperty != PD->isClassProperty())
3314 continue;
3315 // If we're generating a list for a protocol, skip optional / required ones
3316 // when generating the other list.
3317 if (isProtocol && (protocolOptionalProperties != PD->isOptional()))
3318 continue;
3319 // Don't emit duplicate metadata for properties that were already in a
3320 // class extension.
3321 if (!PropertySet.insert(PD->getIdentifier()).second)
3322 continue;
3323
3324 Properties.push_back(PD);
3325 }
3326
3327 if (const ObjCInterfaceDecl *OID = dyn_cast<ObjCInterfaceDecl>(OCD))
3328 for (const auto *P : OID->all_referenced_protocols())
3329 collectProtocolProperties(P);
3330 else if (const ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(OCD))
3331 for (const auto *P : CD->protocols())
3332 collectProtocolProperties(P);
3333
3334 auto numProperties = Properties.size();
3335
3336 if (numProperties == 0)
3337 return NULLPtr;
3338
3339 ConstantInitBuilder builder(CGM);
3340 auto propertyList = builder.beginStruct();
3341 auto properties = PushPropertyListHeader(propertyList, numProperties);
3342
3343 // Add all of the property methods need adding to the method list and to the
3344 // property metadata list.
3345 for (auto *property : Properties) {
3346 bool isSynthesized = false;
3347 bool isDynamic = false;
3348 if (!isProtocol) {
3349 auto *propertyImpl = Context.getObjCPropertyImplDeclForPropertyDecl(property, Container);
3350 if (propertyImpl) {
3351 isSynthesized = (propertyImpl->getPropertyImplementation() ==
3352 ObjCPropertyImplDecl::Synthesize);
3353 isDynamic = (propertyImpl->getPropertyImplementation() ==
3354 ObjCPropertyImplDecl::Dynamic);
3355 }
3356 }
3357 PushProperty(properties, property, Container, isSynthesized, isDynamic);
3358 }
3359 properties.finishAndAddTo(propertyList);
3360
3361 return propertyList.finishAndCreateGlobal(".objc_property_list",
3362 CGM.getPointerAlign());
3363}
3364
3365void CGObjCGNU::RegisterAlias(const ObjCCompatibleAliasDecl *OAD) {
3366 // Get the class declaration for which the alias is specified.
3367 ObjCInterfaceDecl *ClassDecl =
3368 const_cast<ObjCInterfaceDecl *>(OAD->getClassInterface());
3369 ClassAliases.emplace_back(ClassDecl->getNameAsString(),
3370 OAD->getNameAsString());
3371}
3372
3373void CGObjCGNU::GenerateClass(const ObjCImplementationDecl *OID) {
3374 ASTContext &Context = CGM.getContext();
3375
3376 // Get the superclass name.
3377 const ObjCInterfaceDecl * SuperClassDecl =
3378 OID->getClassInterface()->getSuperClass();
3379 std::string SuperClassName;
3380 if (SuperClassDecl) {
3381 SuperClassName = SuperClassDecl->getNameAsString();
3382 EmitClassRef(SuperClassName);
3383 }
3384
3385 // Get the class name
3386 ObjCInterfaceDecl *ClassDecl =
3387 const_cast<ObjCInterfaceDecl *>(OID->getClassInterface());
3388 std::string ClassName = ClassDecl->getNameAsString();
3389
3390 // Emit the symbol that is used to generate linker errors if this class is
3391 // referenced in other modules but not declared.
3392 std::string classSymbolName = "__objc_class_name_" + ClassName;
3393 if (auto *symbol = TheModule.getGlobalVariable(classSymbolName)) {
3394 symbol->setInitializer(llvm::ConstantInt::get(LongTy, 0));
3395 } else {
3396 new llvm::GlobalVariable(TheModule, LongTy, false,
3397 llvm::GlobalValue::ExternalLinkage,
3398 llvm::ConstantInt::get(LongTy, 0),
3399 classSymbolName);
3400 }
3401
3402 // Get the size of instances.
3403 int instanceSize =
3404 Context.getASTObjCImplementationLayout(OID).getSize().getQuantity();
3405
3406 // Collect information about instance variables.
3407 SmallVector<llvm::Constant*, 16> IvarNames;
3408 SmallVector<llvm::Constant*, 16> IvarTypes;
3409 SmallVector<llvm::Constant*, 16> IvarOffsets;
3410 SmallVector<llvm::Constant*, 16> IvarAligns;
3411 SmallVector<Qualifiers::ObjCLifetime, 16> IvarOwnership;
3412
3413 ConstantInitBuilder IvarOffsetBuilder(CGM);
3414 auto IvarOffsetValues = IvarOffsetBuilder.beginArray(PtrToIntTy);
3415 SmallVector<bool, 16> WeakIvars;
3416 SmallVector<bool, 16> StrongIvars;
3417
3418 int superInstanceSize = !SuperClassDecl ? 0 :
3419 Context.getASTObjCInterfaceLayout(SuperClassDecl).getSize().getQuantity();
3420 // For non-fragile ivars, set the instance size to 0 - {the size of just this
3421 // class}. The runtime will then set this to the correct value on load.
3422 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3423 instanceSize = 0 - (instanceSize - superInstanceSize);
3424 }
3425
3426 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3427 IVD = IVD->getNextIvar()) {
3428 // Store the name
3429 IvarNames.push_back(MakeConstantString(IVD->getNameAsString()));
3430 // Get the type encoding for this ivar
3431 std::string TypeStr;
3432 Context.getObjCEncodingForType(IVD->getType(), TypeStr, IVD);
3433 IvarTypes.push_back(MakeConstantString(TypeStr));
3434 IvarAligns.push_back(llvm::ConstantInt::get(IntTy,
3435 Context.getTypeSize(IVD->getType())));
3436 // Get the offset
3437 uint64_t BaseOffset = ComputeIvarBaseOffset(CGM, OID, IVD);
3438 uint64_t Offset = BaseOffset;
3439 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
3440 Offset = BaseOffset - superInstanceSize;
3441 }
3442 llvm::Constant *OffsetValue = llvm::ConstantInt::get(IntTy, Offset);
3443 // Create the direct offset value
3444 std::string OffsetName = "__objc_ivar_offset_value_" + ClassName +"." +
3445 IVD->getNameAsString();
3446
3447 llvm::GlobalVariable *OffsetVar = TheModule.getGlobalVariable(OffsetName);
3448 if (OffsetVar) {
3449 OffsetVar->setInitializer(OffsetValue);
3450 // If this is the real definition, change its linkage type so that
3451 // different modules will use this one, rather than their private
3452 // copy.
3453 OffsetVar->setLinkage(llvm::GlobalValue::ExternalLinkage);
3454 } else
3455 OffsetVar = new llvm::GlobalVariable(TheModule, Int32Ty,
3456 false, llvm::GlobalValue::ExternalLinkage,
3457 OffsetValue, OffsetName);
3458 IvarOffsets.push_back(OffsetValue);
3459 IvarOffsetValues.add(OffsetVar);
3460 Qualifiers::ObjCLifetime lt = IVD->getType().getQualifiers().getObjCLifetime();
3461 IvarOwnership.push_back(lt);
3462 switch (lt) {
3463 case Qualifiers::OCL_Strong:
3464 StrongIvars.push_back(true);
3465 WeakIvars.push_back(false);
3466 break;
3467 case Qualifiers::OCL_Weak:
3468 StrongIvars.push_back(false);
3469 WeakIvars.push_back(true);
3470 break;
3471 default:
3472 StrongIvars.push_back(false);
3473 WeakIvars.push_back(false);
3474 }
3475 }
3476 llvm::Constant *StrongIvarBitmap = MakeBitField(StrongIvars);
3477 llvm::Constant *WeakIvarBitmap = MakeBitField(WeakIvars);
3478 llvm::GlobalVariable *IvarOffsetArray =
3479 IvarOffsetValues.finishAndCreateGlobal(".ivar.offsets",
3480 CGM.getPointerAlign());
3481
3482 // Collect information about instance methods
3483 SmallVector<const ObjCMethodDecl*, 16> InstanceMethods;
3484 InstanceMethods.insert(InstanceMethods.begin(), OID->instmeth_begin(),
3485 OID->instmeth_end());
3486
3487 SmallVector<const ObjCMethodDecl*, 16> ClassMethods;
3488 ClassMethods.insert(ClassMethods.begin(), OID->classmeth_begin(),
3489 OID->classmeth_end());
3490
3491 // Collect the same information about synthesized properties, which don't
3492 // show up in the instance method lists.
3493 for (auto *propertyImpl : OID->property_impls())
3494 if (propertyImpl->getPropertyImplementation() ==
3495 ObjCPropertyImplDecl::Synthesize) {
3496 auto addPropertyMethod = [&](const ObjCMethodDecl *accessor) {
3497 if (accessor)
3498 InstanceMethods.push_back(accessor);
3499 };
3500 addPropertyMethod(propertyImpl->getGetterMethodDecl());
3501 addPropertyMethod(propertyImpl->getSetterMethodDecl());
3502 }
3503
3504 llvm::Constant *Properties = GeneratePropertyList(OID, ClassDecl);
3505
3506 // Collect the names of referenced protocols
3507 SmallVector<std::string, 16> Protocols;
3508 for (const auto *I : ClassDecl->protocols())
3509 Protocols.push_back(I->getNameAsString());
3510
3511 // Get the superclass pointer.
3512 llvm::Constant *SuperClass;
3513 if (!SuperClassName.empty()) {
3514 SuperClass = MakeConstantString(SuperClassName, ".super_class_name");
3515 } else {
3516 SuperClass = llvm::ConstantPointerNull::get(PtrToInt8Ty);
3517 }
3518 // Empty vector used to construct empty method lists
3519 SmallVector<llvm::Constant*, 1> empty;
3520 // Generate the method and instance variable lists
3521 llvm::Constant *MethodList = GenerateMethodList(ClassName, "",
3522 InstanceMethods, false);
3523 llvm::Constant *ClassMethodList = GenerateMethodList(ClassName, "",
3524 ClassMethods, true);
3525 llvm::Constant *IvarList = GenerateIvarList(IvarNames, IvarTypes,
3526 IvarOffsets, IvarAligns, IvarOwnership);
3527 // Irrespective of whether we are compiling for a fragile or non-fragile ABI,
3528 // we emit a symbol containing the offset for each ivar in the class. This
3529 // allows code compiled for the non-Fragile ABI to inherit from code compiled
3530 // for the legacy ABI, without causing problems. The converse is also
3531 // possible, but causes all ivar accesses to be fragile.
3532
3533 // Offset pointer for getting at the correct field in the ivar list when
3534 // setting up the alias. These are: The base address for the global, the
3535 // ivar array (second field), the ivar in this list (set for each ivar), and
3536 // the offset (third field in ivar structure)
3537 llvm::Type *IndexTy = Int32Ty;
3538 llvm::Constant *offsetPointerIndexes[] = {Zeros[0],
3539 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 2 : 1), nullptr,
3540 llvm::ConstantInt::get(IndexTy, ClassABIVersion > 1 ? 3 : 2) };
3541
3542 unsigned ivarIndex = 0;
3543 for (const ObjCIvarDecl *IVD = ClassDecl->all_declared_ivar_begin(); IVD;
3544 IVD = IVD->getNextIvar()) {
3545 const std::string Name = GetIVarOffsetVariableName(ClassDecl, IVD);
3546 offsetPointerIndexes[2] = llvm::ConstantInt::get(IndexTy, ivarIndex);
3547 // Get the correct ivar field
3548 llvm::Constant *offsetValue = llvm::ConstantExpr::getGetElementPtr(
3549 cast<llvm::GlobalVariable>(IvarList)->getValueType(), IvarList,
3550 offsetPointerIndexes);
3551 // Get the existing variable, if one exists.
3552 llvm::GlobalVariable *offset = TheModule.getNamedGlobal(Name);
3553 if (offset) {
3554 offset->setInitializer(offsetValue);
3555 // If this is the real definition, change its linkage type so that
3556 // different modules will use this one, rather than their private
3557 // copy.
3558 offset->setLinkage(llvm::GlobalValue::ExternalLinkage);
3559 } else
3560 // Add a new alias if there isn't one already.
3561 new llvm::GlobalVariable(TheModule, offsetValue->getType(),
3562 false, llvm::GlobalValue::ExternalLinkage, offsetValue, Name);
3563 ++ivarIndex;
3564 }
3565 llvm::Constant *ZeroPtr = llvm::ConstantInt::get(IntPtrTy, 0);
3566
3567 //Generate metaclass for class methods
3568 llvm::Constant *MetaClassStruct = GenerateClassStructure(
3569 NULLPtr, NULLPtr, 0x12L, ClassName.c_str(), nullptr, Zeros[0],
3570 NULLPtr, ClassMethodList, NULLPtr, NULLPtr,
3571 GeneratePropertyList(OID, ClassDecl, true), ZeroPtr, ZeroPtr, true);
3572 CGM.setGVProperties(cast<llvm::GlobalValue>(MetaClassStruct),
3573 OID->getClassInterface());
3574
3575 // Generate the class structure
3576 llvm::Constant *ClassStruct = GenerateClassStructure(
3577 MetaClassStruct, SuperClass, 0x11L, ClassName.c_str(), nullptr,
3578 llvm::ConstantInt::get(LongTy, instanceSize), IvarList, MethodList,
3579 GenerateProtocolList(Protocols), IvarOffsetArray, Properties,
3580 StrongIvarBitmap, WeakIvarBitmap);
3581 CGM.setGVProperties(cast<llvm::GlobalValue>(ClassStruct),
3582 OID->getClassInterface());
3583
3584 // Resolve the class aliases, if they exist.
3585 if (ClassPtrAlias) {
3586 ClassPtrAlias->replaceAllUsesWith(
3587 llvm::ConstantExpr::getBitCast(ClassStruct, IdTy));
3588 ClassPtrAlias->eraseFromParent();
3589 ClassPtrAlias = nullptr;
3590 }
3591 if (MetaClassPtrAlias) {
3592 MetaClassPtrAlias->replaceAllUsesWith(
3593 llvm::ConstantExpr::getBitCast(MetaClassStruct, IdTy));
3594 MetaClassPtrAlias->eraseFromParent();
3595 MetaClassPtrAlias = nullptr;
3596 }
3597
3598 // Add class structure to list to be added to the symtab later
3599 ClassStruct = llvm::ConstantExpr::getBitCast(ClassStruct, PtrToInt8Ty);
3600 Classes.push_back(ClassStruct);
3601}
3602
3603llvm::Function *CGObjCGNU::ModuleInitFunction() {
3604 // Only emit an ObjC load function if no Objective-C stuff has been called
3605 if (Classes.empty() && Categories.empty() && ConstantStrings.empty() &&
3606 ExistingProtocols.empty() && SelectorTable.empty())
3607 return nullptr;
3608
3609 // Add all referenced protocols to a category.
3610 GenerateProtocolHolderCategory();
3611
3612 llvm::StructType *selStructTy =
3613 dyn_cast<llvm::StructType>(SelectorTy->getElementType());
3614 llvm::Type *selStructPtrTy = SelectorTy;
3615 if (!selStructTy) {
3616 selStructTy = llvm::StructType::get(CGM.getLLVMContext(),
3617 { PtrToInt8Ty, PtrToInt8Ty });
3618 selStructPtrTy = llvm::PointerType::getUnqual(selStructTy);
3619 }
3620
3621 // Generate statics list:
3622 llvm::Constant *statics = NULLPtr;
3623 if (!ConstantStrings.empty()) {
3624 llvm::GlobalVariable *fileStatics = [&] {
3625 ConstantInitBuilder builder(CGM);
3626 auto staticsStruct = builder.beginStruct();
3627
3628 StringRef stringClass = CGM.getLangOpts().ObjCConstantStringClass;
3629 if (stringClass.empty()) stringClass = "NXConstantString";
3630 staticsStruct.add(MakeConstantString(stringClass,
3631 ".objc_static_class_name"));
3632
3633 auto array = staticsStruct.beginArray();
3634 array.addAll(ConstantStrings);
3635 array.add(NULLPtr);
3636 array.finishAndAddTo(staticsStruct);
3637
3638 return staticsStruct.finishAndCreateGlobal(".objc_statics",
3639 CGM.getPointerAlign());
3640 }();
3641
3642 ConstantInitBuilder builder(CGM);
3643 auto allStaticsArray = builder.beginArray(fileStatics->getType());
3644 allStaticsArray.add(fileStatics);
3645 allStaticsArray.addNullPointer(fileStatics->getType());
3646
3647 statics = allStaticsArray.finishAndCreateGlobal(".objc_statics_ptr",
3648 CGM.getPointerAlign());
3649 statics = llvm::ConstantExpr::getBitCast(statics, PtrTy);
3650 }
3651
3652 // Array of classes, categories, and constant objects.
3653
3654 SmallVector<llvm::GlobalAlias*, 16> selectorAliases;
3655 unsigned selectorCount;
3656
3657 // Pointer to an array of selectors used in this module.
3658 llvm::GlobalVariable *selectorList = [&] {
3659 ConstantInitBuilder builder(CGM);
3660 auto selectors = builder.beginArray(selStructTy);
3661 auto &table = SelectorTable; // MSVC workaround
3662 std::vector<Selector> allSelectors;
3663 for (auto &entry : table)
3664 allSelectors.push_back(entry.first);
3665 llvm::sort(allSelectors);
3666
3667 for (auto &untypedSel : allSelectors) {
3668 std::string selNameStr = untypedSel.getAsString();
3669 llvm::Constant *selName = ExportUniqueString(selNameStr, ".objc_sel_name");
3670
3671 for (TypedSelector &sel : table[untypedSel]) {
3672 llvm::Constant *selectorTypeEncoding = NULLPtr;
3673 if (!sel.first.empty())
3674 selectorTypeEncoding =
3675 MakeConstantString(sel.first, ".objc_sel_types");
3676
3677 auto selStruct = selectors.beginStruct(selStructTy);
3678 selStruct.add(selName);
3679 selStruct.add(selectorTypeEncoding);
3680 selStruct.finishAndAddTo(selectors);
3681
3682 // Store the selector alias for later replacement
3683 selectorAliases.push_back(sel.second);
3684 }
3685 }
3686
3687 // Remember the number of entries in the selector table.
3688 selectorCount = selectors.size();
3689
3690 // NULL-terminate the selector list. This should not actually be required,
3691 // because the selector list has a length field. Unfortunately, the GCC
3692 // runtime decides to ignore the length field and expects a NULL terminator,
3693 // and GCC cooperates with this by always setting the length to 0.
3694 auto selStruct = selectors.beginStruct(selStructTy);
3695 selStruct.add(NULLPtr);
3696 selStruct.add(NULLPtr);
3697 selStruct.finishAndAddTo(selectors);
3698
3699 return selectors.finishAndCreateGlobal(".objc_selector_list",
3700 CGM.getPointerAlign());
3701 }();
3702
3703 // Now that all of the static selectors exist, create pointers to them.
3704 for (unsigned i = 0; i < selectorCount; ++i) {
3705 llvm::Constant *idxs[] = {
3706 Zeros[0],
3707 llvm::ConstantInt::get(Int32Ty, i)
3708 };
3709 // FIXME: We're generating redundant loads and stores here!
3710 llvm::Constant *selPtr = llvm::ConstantExpr::getGetElementPtr(
3711 selectorList->getValueType(), selectorList, idxs);
3712 // If selectors are defined as an opaque type, cast the pointer to this
3713 // type.
3714 selPtr = llvm::ConstantExpr::getBitCast(selPtr, SelectorTy);
3715 selectorAliases[i]->replaceAllUsesWith(selPtr);
3716 selectorAliases[i]->eraseFromParent();
3717 }
3718
3719 llvm::GlobalVariable *symtab = [&] {
3720 ConstantInitBuilder builder(CGM);
3721 auto symtab = builder.beginStruct();
3722
3723 // Number of static selectors
3724 symtab.addInt(LongTy, selectorCount);
3725
3726 symtab.addBitCast(selectorList, selStructPtrTy);
3727
3728 // Number of classes defined.
3729 symtab.addInt(CGM.Int16Ty, Classes.size());
3730 // Number of categories defined
3731 symtab.addInt(CGM.Int16Ty, Categories.size());
3732
3733 // Create an array of classes, then categories, then static object instances
3734 auto classList = symtab.beginArray(PtrToInt8Ty);
3735 classList.addAll(Classes);
3736 classList.addAll(Categories);
3737 // NULL-terminated list of static object instances (mainly constant strings)
3738 classList.add(statics);
3739 classList.add(NULLPtr);
3740 classList.finishAndAddTo(symtab);
3741
3742 // Construct the symbol table.
3743 return symtab.finishAndCreateGlobal("", CGM.getPointerAlign());
3744 }();
3745
3746 // The symbol table is contained in a module which has some version-checking
3747 // constants
3748 llvm::Constant *module = [&] {
3749 llvm::Type *moduleEltTys[] = {
3750 LongTy, LongTy, PtrToInt8Ty, symtab->getType(), IntTy
3751 };
3752 llvm::StructType *moduleTy =
3753 llvm::StructType::get(CGM.getLLVMContext(),
3754 makeArrayRef(moduleEltTys).drop_back(unsigned(RuntimeVersion < 10)));
3755
3756 ConstantInitBuilder builder(CGM);
3757 auto module = builder.beginStruct(moduleTy);
3758 // Runtime version, used for ABI compatibility checking.
3759 module.addInt(LongTy, RuntimeVersion);
3760 // sizeof(ModuleTy)
3761 module.addInt(LongTy, CGM.getDataLayout().getTypeStoreSize(moduleTy));
3762
3763 // The path to the source file where this module was declared
3764 SourceManager &SM = CGM.getContext().getSourceManager();
3765 const FileEntry *mainFile = SM.getFileEntryForID(SM.getMainFileID());
3766 std::string path =
3767 (Twine(mainFile->getDir()->getName()) + "/" + mainFile->getName()).str();
3768 module.add(MakeConstantString(path, ".objc_source_file_name"));
3769 module.add(symtab);
3770
3771 if (RuntimeVersion >= 10) {
3772 switch (CGM.getLangOpts().getGC()) {
3773 case LangOptions::GCOnly:
3774 module.addInt(IntTy, 2);
3775 break;
3776 case LangOptions::NonGC:
3777 if (CGM.getLangOpts().ObjCAutoRefCount)
3778 module.addInt(IntTy, 1);
3779 else
3780 module.addInt(IntTy, 0);
3781 break;
3782 case LangOptions::HybridGC:
3783 module.addInt(IntTy, 1);
3784 break;
3785 }
3786 }
3787
3788 return module.finishAndCreateGlobal("", CGM.getPointerAlign());
3789 }();
3790
3791 // Create the load function calling the runtime entry point with the module
3792 // structure
3793 llvm::Function * LoadFunction = llvm::Function::Create(
3794 llvm::FunctionType::get(llvm::Type::getVoidTy(VMContext), false),
3795 llvm::GlobalValue::InternalLinkage, ".objc_load_function",
3796 &TheModule);
3797 llvm::BasicBlock *EntryBB =
3798 llvm::BasicBlock::Create(VMContext, "entry", LoadFunction);
3799 CGBuilderTy Builder(CGM, VMContext);
3800 Builder.SetInsertPoint(EntryBB);
3801
3802 llvm::FunctionType *FT =
3803 llvm::FunctionType::get(Builder.getVoidTy(), module->getType(), true);
3804 llvm::FunctionCallee Register =
3805 CGM.CreateRuntimeFunction(FT, "__objc_exec_class");
3806 Builder.CreateCall(Register, module);
3807
3808 if (!ClassAliases.empty()) {
3809 llvm::Type *ArgTypes[2] = {PtrTy, PtrToInt8Ty};
3810 llvm::FunctionType *RegisterAliasTy =
3811 llvm::FunctionType::get(Builder.getVoidTy(),
3812 ArgTypes, false);
3813 llvm::Function *RegisterAlias = llvm::Function::Create(
3814 RegisterAliasTy,
3815 llvm::GlobalValue::ExternalWeakLinkage, "class_registerAlias_np",
3816 &TheModule);
3817 llvm::BasicBlock *AliasBB =
3818 llvm::BasicBlock::Create(VMContext, "alias", LoadFunction);
3819 llvm::BasicBlock *NoAliasBB =
3820 llvm::BasicBlock::Create(VMContext, "no_alias", LoadFunction);
3821
3822 // Branch based on whether the runtime provided class_registerAlias_np()
3823 llvm::Value *HasRegisterAlias = Builder.CreateICmpNE(RegisterAlias,
3824 llvm::Constant::getNullValue(RegisterAlias->getType()));
3825 Builder.CreateCondBr(HasRegisterAlias, AliasBB, NoAliasBB);
3826
3827 // The true branch (has alias registration function):
3828 Builder.SetInsertPoint(AliasBB);
3829 // Emit alias registration calls:
3830 for (std::vector<ClassAliasPair>::iterator iter = ClassAliases.begin();
3831 iter != ClassAliases.end(); ++iter) {
3832 llvm::Constant *TheClass =
3833 TheModule.getGlobalVariable("_OBJC_CLASS_" + iter->first, true);
3834 if (TheClass) {
3835 TheClass = llvm::ConstantExpr::getBitCast(TheClass, PtrTy);
3836 Builder.CreateCall(RegisterAlias,
3837 {TheClass, MakeConstantString(iter->second)});
3838 }
3839 }
3840 // Jump to end:
3841 Builder.CreateBr(NoAliasBB);
3842
3843 // Missing alias registration function, just return from the function:
3844 Builder.SetInsertPoint(NoAliasBB);
3845 }
3846 Builder.CreateRetVoid();
3847
3848 return LoadFunction;
3849}
3850
3851llvm::Function *CGObjCGNU::GenerateMethod(const ObjCMethodDecl *OMD,
3852 const ObjCContainerDecl *CD) {
3853 const ObjCCategoryImplDecl *OCD =
3854 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext());
3855 StringRef CategoryName = OCD ? OCD->getName() : "";
3856 StringRef ClassName = CD->getName();
3857 Selector MethodName = OMD->getSelector();
3858 bool isClassMethod = !OMD->isInstanceMethod();
3859
3860 CodeGenTypes &Types = CGM.getTypes();
3861 llvm::FunctionType *MethodTy =
3862 Types.GetFunctionType(Types.arrangeObjCMethodDeclaration(OMD));
3863 std::string FunctionName = SymbolNameForMethod(ClassName, CategoryName,
3864 MethodName, isClassMethod);
3865
3866 llvm::Function *Method
3867 = llvm::Function::Create(MethodTy,
3868 llvm::GlobalValue::InternalLinkage,
3869 FunctionName,
3870 &TheModule);
3871 return Method;
3872}
3873
3874llvm::FunctionCallee CGObjCGNU::GetPropertyGetFunction() {
3875 return GetPropertyFn;
3876}
3877
3878llvm::FunctionCallee CGObjCGNU::GetPropertySetFunction() {
3879 return SetPropertyFn;
3880}
3881
3882llvm::FunctionCallee CGObjCGNU::GetOptimizedPropertySetFunction(bool atomic,
3883 bool copy) {
3884 return nullptr;
3885}
3886
3887llvm::FunctionCallee CGObjCGNU::GetGetStructFunction() {
3888 return GetStructPropertyFn;
3889}
3890
3891llvm::FunctionCallee CGObjCGNU::GetSetStructFunction() {
3892 return SetStructPropertyFn;
3893}
3894
3895llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectGetFunction() {
3896 return nullptr;
3897}
3898
3899llvm::FunctionCallee CGObjCGNU::GetCppAtomicObjectSetFunction() {
3900 return nullptr;
3901}
3902
3903llvm::FunctionCallee CGObjCGNU::EnumerationMutationFunction() {
3904 return EnumerationMutationFn;
3905}
3906
3907void CGObjCGNU::EmitSynchronizedStmt(CodeGenFunction &CGF,
3908 const ObjCAtSynchronizedStmt &S) {
3909 EmitAtSynchronizedStmt(CGF, S, SyncEnterFn, SyncExitFn);
3910}
3911
3912
3913void CGObjCGNU::EmitTryStmt(CodeGenFunction &CGF,
3914 const ObjCAtTryStmt &S) {
3915 // Unlike the Apple non-fragile runtimes, which also uses
3916 // unwind-based zero cost exceptions, the GNU Objective C runtime's
3917 // EH support isn't a veneer over C++ EH. Instead, exception
3918 // objects are created by objc_exception_throw and destroyed by
3919 // the personality function; this avoids the need for bracketing
3920 // catch handlers with calls to __blah_begin_catch/__blah_end_catch
3921 // (or even _Unwind_DeleteException), but probably doesn't
3922 // interoperate very well with foreign exceptions.
3923 //
3924 // In Objective-C++ mode, we actually emit something equivalent to the C++
3925 // exception handler.
3926 EmitTryCatchStmt(CGF, S, EnterCatchFn, ExitCatchFn, ExceptionReThrowFn);
3927}
3928
3929void CGObjCGNU::EmitThrowStmt(CodeGenFunction &CGF,
3930 const ObjCAtThrowStmt &S,
3931 bool ClearInsertionPoint) {
3932 llvm::Value *ExceptionAsObject;
3933 bool isRethrow = false;
3934
3935 if (const Expr *ThrowExpr = S.getThrowExpr()) {
3936 llvm::Value *Exception = CGF.EmitObjCThrowOperand(ThrowExpr);
3937 ExceptionAsObject = Exception;
3938 } else {
3939 assert((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) &&(((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack
.back()) && "Unexpected rethrow outside @catch block."
) ? static_cast<void> (0) : __assert_fail ("(!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) && \"Unexpected rethrow outside @catch block.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 3940, __PRETTY_FUNCTION__))
3940 "Unexpected rethrow outside @catch block.")(((!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack
.back()) && "Unexpected rethrow outside @catch block."
) ? static_cast<void> (0) : __assert_fail ("(!CGF.ObjCEHValueStack.empty() && CGF.ObjCEHValueStack.back()) && \"Unexpected rethrow outside @catch block.\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 3940, __PRETTY_FUNCTION__))
;
3941 ExceptionAsObject = CGF.ObjCEHValueStack.back();
3942 isRethrow = true;
3943 }
3944 if (isRethrow && usesSEHExceptions) {
3945 // For SEH, ExceptionAsObject may be undef, because the catch handler is
3946 // not passed it for catchalls and so it is not visible to the catch
3947 // funclet. The real thrown object will still be live on the stack at this
3948 // point and will be rethrown. If we are explicitly rethrowing the object
3949 // that was passed into the `@catch` block, then this code path is not
3950 // reached and we will instead call `objc_exception_throw` with an explicit
3951 // argument.
3952 llvm::CallBase *Throw = CGF.EmitRuntimeCallOrInvoke(ExceptionReThrowFn);
3953 Throw->setDoesNotReturn();
3954 }
3955 else {
3956 ExceptionAsObject = CGF.Builder.CreateBitCast(ExceptionAsObject, IdTy);
3957 llvm::CallBase *Throw =
3958 CGF.EmitRuntimeCallOrInvoke(ExceptionThrowFn, ExceptionAsObject);
3959 Throw->setDoesNotReturn();
3960 }
3961 CGF.Builder.CreateUnreachable();
3962 if (ClearInsertionPoint)
3963 CGF.Builder.ClearInsertionPoint();
3964}
3965
3966llvm::Value * CGObjCGNU::EmitObjCWeakRead(CodeGenFunction &CGF,
3967 Address AddrWeakObj) {
3968 CGBuilderTy &B = CGF.Builder;
3969 AddrWeakObj = EnforceType(B, AddrWeakObj, PtrToIdTy);
3970 return B.CreateCall(WeakReadFn, AddrWeakObj.getPointer());
3971}
3972
3973void CGObjCGNU::EmitObjCWeakAssign(CodeGenFunction &CGF,
3974 llvm::Value *src, Address dst) {
3975 CGBuilderTy &B = CGF.Builder;
3976 src = EnforceType(B, src, IdTy);
3977 dst = EnforceType(B, dst, PtrToIdTy);
3978 B.CreateCall(WeakAssignFn, {src, dst.getPointer()});
3979}
3980
3981void CGObjCGNU::EmitObjCGlobalAssign(CodeGenFunction &CGF,
3982 llvm::Value *src, Address dst,
3983 bool threadlocal) {
3984 CGBuilderTy &B = CGF.Builder;
3985 src = EnforceType(B, src, IdTy);
3986 dst = EnforceType(B, dst, PtrToIdTy);
3987 // FIXME. Add threadloca assign API
3988 assert(!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI")((!threadlocal && "EmitObjCGlobalAssign - Threal Local API NYI"
) ? static_cast<void> (0) : __assert_fail ("!threadlocal && \"EmitObjCGlobalAssign - Threal Local API NYI\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 3988, __PRETTY_FUNCTION__))
;
3989 B.CreateCall(GlobalAssignFn, {src, dst.getPointer()});
3990}
3991
3992void CGObjCGNU::EmitObjCIvarAssign(CodeGenFunction &CGF,
3993 llvm::Value *src, Address dst,
3994 llvm::Value *ivarOffset) {
3995 CGBuilderTy &B = CGF.Builder;
3996 src = EnforceType(B, src, IdTy);
3997 dst = EnforceType(B, dst, IdTy);
3998 B.CreateCall(IvarAssignFn, {src, dst.getPointer(), ivarOffset});
3999}
4000
4001void CGObjCGNU::EmitObjCStrongCastAssign(CodeGenFunction &CGF,
4002 llvm::Value *src, Address dst) {
4003 CGBuilderTy &B = CGF.Builder;
4004 src = EnforceType(B, src, IdTy);
4005 dst = EnforceType(B, dst, PtrToIdTy);
4006 B.CreateCall(StrongCastAssignFn, {src, dst.getPointer()});
4007}
4008
4009void CGObjCGNU::EmitGCMemmoveCollectable(CodeGenFunction &CGF,
4010 Address DestPtr,
4011 Address SrcPtr,
4012 llvm::Value *Size) {
4013 CGBuilderTy &B = CGF.Builder;
4014 DestPtr = EnforceType(B, DestPtr, PtrTy);
4015 SrcPtr = EnforceType(B, SrcPtr, PtrTy);
4016
4017 B.CreateCall(MemMoveFn, {DestPtr.getPointer(), SrcPtr.getPointer(), Size});
4018}
4019
4020llvm::GlobalVariable *CGObjCGNU::ObjCIvarOffsetVariable(
4021 const ObjCInterfaceDecl *ID,
4022 const ObjCIvarDecl *Ivar) {
4023 const std::string Name = GetIVarOffsetVariableName(ID, Ivar);
4024 // Emit the variable and initialize it with what we think the correct value
4025 // is. This allows code compiled with non-fragile ivars to work correctly
4026 // when linked against code which isn't (most of the time).
4027 llvm::GlobalVariable *IvarOffsetPointer = TheModule.getNamedGlobal(Name);
4028 if (!IvarOffsetPointer)
4029 IvarOffsetPointer = new llvm::GlobalVariable(TheModule,
4030 llvm::Type::getInt32PtrTy(VMContext), false,
4031 llvm::GlobalValue::ExternalLinkage, nullptr, Name);
4032 return IvarOffsetPointer;
4033}
4034
4035LValue CGObjCGNU::EmitObjCValueForIvar(CodeGenFunction &CGF,
4036 QualType ObjectTy,
4037 llvm::Value *BaseValue,
4038 const ObjCIvarDecl *Ivar,
4039 unsigned CVRQualifiers) {
4040 const ObjCInterfaceDecl *ID =
4041 ObjectTy->castAs<ObjCObjectType>()->getInterface();
4042 return EmitValueForIvarAtOffset(CGF, ID, BaseValue, Ivar, CVRQualifiers,
4043 EmitIvarOffset(CGF, ID, Ivar));
4044}
4045
4046static const ObjCInterfaceDecl *FindIvarInterface(ASTContext &Context,
4047 const ObjCInterfaceDecl *OID,
4048 const ObjCIvarDecl *OIVD) {
4049 for (const ObjCIvarDecl *next = OID->all_declared_ivar_begin(); next;
4050 next = next->getNextIvar()) {
4051 if (OIVD == next)
4052 return OID;
4053 }
4054
4055 // Otherwise check in the super class.
4056 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
4057 return FindIvarInterface(Context, Super, OIVD);
4058
4059 return nullptr;
4060}
4061
4062llvm::Value *CGObjCGNU::EmitIvarOffset(CodeGenFunction &CGF,
4063 const ObjCInterfaceDecl *Interface,
4064 const ObjCIvarDecl *Ivar) {
4065 if (CGM.getLangOpts().ObjCRuntime.isNonFragile()) {
4066 Interface = FindIvarInterface(CGM.getContext(), Interface, Ivar);
4067
4068 // The MSVC linker cannot have a single global defined as LinkOnceAnyLinkage
4069 // and ExternalLinkage, so create a reference to the ivar global and rely on
4070 // the definition being created as part of GenerateClass.
4071 if (RuntimeVersion < 10 ||
4072 CGF.CGM.getTarget().getTriple().isKnownWindowsMSVCEnvironment())
4073 return CGF.Builder.CreateZExtOrBitCast(
4074 CGF.Builder.CreateAlignedLoad(
4075 Int32Ty, CGF.Builder.CreateAlignedLoad(
4076 ObjCIvarOffsetVariable(Interface, Ivar),
4077 CGF.getPointerAlign(), "ivar"),
4078 CharUnits::fromQuantity(4)),
4079 PtrDiffTy);
4080 std::string name = "__objc_ivar_offset_value_" +
4081 Interface->getNameAsString() +"." + Ivar->getNameAsString();
4082 CharUnits Align = CGM.getIntAlign();
4083 llvm::Value *Offset = TheModule.getGlobalVariable(name);
4084 if (!Offset) {
4085 auto GV = new llvm::GlobalVariable(TheModule, IntTy,
4086 false, llvm::GlobalValue::LinkOnceAnyLinkage,
4087 llvm::Constant::getNullValue(IntTy), name);
4088 GV->setAlignment(Align.getAsAlign());
4089 Offset = GV;
4090 }
4091 Offset = CGF.Builder.CreateAlignedLoad(Offset, Align);
4092 if (Offset->getType() != PtrDiffTy)
4093 Offset = CGF.Builder.CreateZExtOrBitCast(Offset, PtrDiffTy);
4094 return Offset;
4095 }
4096 uint64_t Offset = ComputeIvarBaseOffset(CGF.CGM, Interface, Ivar);
4097 return llvm::ConstantInt::get(PtrDiffTy, Offset, /*isSigned*/true);
4098}
4099
4100CGObjCRuntime *
4101clang::CodeGen::CreateGNUObjCRuntime(CodeGenModule &CGM) {
4102 auto Runtime = CGM.getLangOpts().ObjCRuntime;
4103 switch (Runtime.getKind()) {
4104 case ObjCRuntime::GNUstep:
4105 if (Runtime.getVersion() >= VersionTuple(2, 0))
4106 return new CGObjCGNUstep2(CGM);
4107 return new CGObjCGNUstep(CGM);
4108
4109 case ObjCRuntime::GCC:
4110 return new CGObjCGCC(CGM);
4111
4112 case ObjCRuntime::ObjFW:
4113 return new CGObjCObjFW(CGM);
4114
4115 case ObjCRuntime::FragileMacOSX:
4116 case ObjCRuntime::MacOSX:
4117 case ObjCRuntime::iOS:
4118 case ObjCRuntime::WatchOS:
4119 llvm_unreachable("these runtimes are not GNU runtimes")::llvm::llvm_unreachable_internal("these runtimes are not GNU runtimes"
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 4119)
;
4120 }
4121 llvm_unreachable("bad runtime")::llvm::llvm_unreachable_internal("bad runtime", "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/clang/lib/CodeGen/CGObjCGNU.cpp"
, 4121)
;
4122}

/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/ADT/Triple.h

1//===-- llvm/ADT/Triple.h - Target triple helper class ----------*- 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#ifndef LLVM_ADT_TRIPLE_H
10#define LLVM_ADT_TRIPLE_H
11
12#include "llvm/ADT/Twine.h"
13
14// Some system headers or GCC predefined macros conflict with identifiers in
15// this file. Undefine them here.
16#undef NetBSD
17#undef mips
18#undef sparc
19
20namespace llvm {
21
22/// Triple - Helper class for working with autoconf configuration names. For
23/// historical reasons, we also call these 'triples' (they used to contain
24/// exactly three fields).
25///
26/// Configuration names are strings in the canonical form:
27/// ARCHITECTURE-VENDOR-OPERATING_SYSTEM
28/// or
29/// ARCHITECTURE-VENDOR-OPERATING_SYSTEM-ENVIRONMENT
30///
31/// This class is used for clients which want to support arbitrary
32/// configuration names, but also want to implement certain special
33/// behavior for particular configurations. This class isolates the mapping
34/// from the components of the configuration name to well known IDs.
35///
36/// At its core the Triple class is designed to be a wrapper for a triple
37/// string; the constructor does not change or normalize the triple string.
38/// Clients that need to handle the non-canonical triples that users often
39/// specify should use the normalize method.
40///
41/// See autoconf/config.guess for a glimpse into what configuration names
42/// look like in practice.
43class Triple {
44public:
45 enum ArchType {
46 UnknownArch,
47
48 arm, // ARM (little endian): arm, armv.*, xscale
49 armeb, // ARM (big endian): armeb
50 aarch64, // AArch64 (little endian): aarch64
51 aarch64_be, // AArch64 (big endian): aarch64_be
52 aarch64_32, // AArch64 (little endian) ILP32: aarch64_32
53 arc, // ARC: Synopsys ARC
54 avr, // AVR: Atmel AVR microcontroller
55 bpfel, // eBPF or extended BPF or 64-bit BPF (little endian)
56 bpfeb, // eBPF or extended BPF or 64-bit BPF (big endian)
57 hexagon, // Hexagon: hexagon
58 mips, // MIPS: mips, mipsallegrex, mipsr6
59 mipsel, // MIPSEL: mipsel, mipsallegrexe, mipsr6el
60 mips64, // MIPS64: mips64, mips64r6, mipsn32, mipsn32r6
61 mips64el, // MIPS64EL: mips64el, mips64r6el, mipsn32el, mipsn32r6el
62 msp430, // MSP430: msp430
63 ppc, // PPC: powerpc
64 ppc64, // PPC64: powerpc64, ppu
65 ppc64le, // PPC64LE: powerpc64le
66 r600, // R600: AMD GPUs HD2XXX - HD6XXX
67 amdgcn, // AMDGCN: AMD GCN GPUs
68 riscv32, // RISC-V (32-bit): riscv32
69 riscv64, // RISC-V (64-bit): riscv64
70 sparc, // Sparc: sparc
71 sparcv9, // Sparcv9: Sparcv9
72 sparcel, // Sparc: (endianness = little). NB: 'Sparcle' is a CPU variant
73 systemz, // SystemZ: s390x
74 tce, // TCE (http://tce.cs.tut.fi/): tce
75 tcele, // TCE little endian (http://tce.cs.tut.fi/): tcele
76 thumb, // Thumb (little endian): thumb, thumbv.*
77 thumbeb, // Thumb (big endian): thumbeb
78 x86, // X86: i[3-9]86
79 x86_64, // X86-64: amd64, x86_64
80 xcore, // XCore: xcore
81 nvptx, // NVPTX: 32-bit
82 nvptx64, // NVPTX: 64-bit
83 le32, // le32: generic little-endian 32-bit CPU (PNaCl)
84 le64, // le64: generic little-endian 64-bit CPU (PNaCl)
85 amdil, // AMDIL
86 amdil64, // AMDIL with 64-bit pointers
87 hsail, // AMD HSAIL
88 hsail64, // AMD HSAIL with 64-bit pointers
89 spir, // SPIR: standard portable IR for OpenCL 32-bit version
90 spir64, // SPIR: standard portable IR for OpenCL 64-bit version
91 kalimba, // Kalimba: generic kalimba
92 shave, // SHAVE: Movidius vector VLIW processors
93 lanai, // Lanai: Lanai 32-bit
94 wasm32, // WebAssembly with 32-bit pointers
95 wasm64, // WebAssembly with 64-bit pointers
96 renderscript32, // 32-bit RenderScript
97 renderscript64, // 64-bit RenderScript
98 LastArchType = renderscript64
99 };
100 enum SubArchType {
101 NoSubArch,
102
103 ARMSubArch_v8_5a,
104 ARMSubArch_v8_4a,
105 ARMSubArch_v8_3a,
106 ARMSubArch_v8_2a,
107 ARMSubArch_v8_1a,
108 ARMSubArch_v8,
109 ARMSubArch_v8r,
110 ARMSubArch_v8m_baseline,
111 ARMSubArch_v8m_mainline,
112 ARMSubArch_v8_1m_mainline,
113 ARMSubArch_v7,
114 ARMSubArch_v7em,
115 ARMSubArch_v7m,
116 ARMSubArch_v7s,
117 ARMSubArch_v7k,
118 ARMSubArch_v7ve,
119 ARMSubArch_v6,
120 ARMSubArch_v6m,
121 ARMSubArch_v6k,
122 ARMSubArch_v6t2,
123 ARMSubArch_v5,
124 ARMSubArch_v5te,
125 ARMSubArch_v4t,
126
127 KalimbaSubArch_v3,
128 KalimbaSubArch_v4,
129 KalimbaSubArch_v5,
130
131 MipsSubArch_r6
132 };
133 enum VendorType {
134 UnknownVendor,
135
136 Apple,
137 PC,
138 SCEI,
139 BGP,
140 BGQ,
141 Freescale,
142 IBM,
143 ImaginationTechnologies,
144 MipsTechnologies,
145 NVIDIA,
146 CSR,
147 Myriad,
148 AMD,
149 Mesa,
150 SUSE,
151 OpenEmbedded,
152 LastVendorType = OpenEmbedded
153 };
154 enum OSType {
155 UnknownOS,
156
157 Ananas,
158 CloudABI,
159 Darwin,
160 DragonFly,
161 FreeBSD,
162 Fuchsia,
163 IOS,
164 KFreeBSD,
165 Linux,
166 Lv2, // PS3
167 MacOSX,
168 NetBSD,
169 OpenBSD,
170 Solaris,
171 Win32,
172 Haiku,
173 Minix,
174 RTEMS,
175 NaCl, // Native Client
176 CNK, // BG/P Compute-Node Kernel
177 AIX,
178 CUDA, // NVIDIA CUDA
179 NVCL, // NVIDIA OpenCL
180 AMDHSA, // AMD HSA Runtime
181 PS4,
182 ELFIAMCU,
183 TvOS, // Apple tvOS
184 WatchOS, // Apple watchOS
185 Mesa3D,
186 Contiki,
187 AMDPAL, // AMD PAL Runtime
188 HermitCore, // HermitCore Unikernel/Multikernel
189 Hurd, // GNU/Hurd
190 WASI, // Experimental WebAssembly OS
191 Emscripten,
192 LastOSType = Emscripten
193 };
194 enum EnvironmentType {
195 UnknownEnvironment,
196
197 GNU,
198 GNUABIN32,
199 GNUABI64,
200 GNUEABI,
201 GNUEABIHF,
202 GNUX32,
203 CODE16,
204 EABI,
205 EABIHF,
206 ELFv1,
207 ELFv2,
208 Android,
209 Musl,
210 MuslEABI,
211 MuslEABIHF,
212
213 MSVC,
214 Itanium,
215 Cygnus,
216 CoreCLR,
217 Simulator, // Simulator variants of other systems, e.g., Apple's iOS
218 MacABI, // Mac Catalyst variant of Apple's iOS deployment target.
219 LastEnvironmentType = MacABI
220 };
221 enum ObjectFormatType {
222 UnknownObjectFormat,
223
224 COFF,
225 ELF,
226 MachO,
227 Wasm,
228 XCOFF,
229 };
230
231private:
232 std::string Data;
233
234 /// The parsed arch type.
235 ArchType Arch;
236
237 /// The parsed subarchitecture type.
238 SubArchType SubArch;
239
240 /// The parsed vendor type.
241 VendorType Vendor;
242
243 /// The parsed OS type.
244 OSType OS;
245
246 /// The parsed Environment type.
247 EnvironmentType Environment;
248
249 /// The object format type.
250 ObjectFormatType ObjectFormat;
251
252public:
253 /// @name Constructors
254 /// @{
255
256 /// Default constructor is the same as an empty string and leaves all
257 /// triple fields unknown.
258 Triple()
259 : Data(), Arch(), SubArch(), Vendor(), OS(), Environment(),
260 ObjectFormat() {}
261
262 explicit Triple(const Twine &Str);
263 Triple(const Twine &ArchStr, const Twine &VendorStr, const Twine &OSStr);
264 Triple(const Twine &ArchStr, const Twine &VendorStr, const Twine &OSStr,
265 const Twine &EnvironmentStr);
266
267 bool operator==(const Triple &Other) const {
268 return Arch == Other.Arch && SubArch == Other.SubArch &&
269 Vendor == Other.Vendor && OS == Other.OS &&
270 Environment == Other.Environment &&
271 ObjectFormat == Other.ObjectFormat;
272 }
273
274 bool operator!=(const Triple &Other) const {
275 return !(*this == Other);
276 }
277
278 /// @}
279 /// @name Normalization
280 /// @{
281
282 /// normalize - Turn an arbitrary machine specification into the canonical
283 /// triple form (or something sensible that the Triple class understands if
284 /// nothing better can reasonably be done). In particular, it handles the
285 /// common case in which otherwise valid components are in the wrong order.
286 static std::string normalize(StringRef Str);
287
288 /// Return the normalized form of this triple's string.
289 std::string normalize() const { return normalize(Data); }
290
291 /// @}
292 /// @name Typed Component Access
293 /// @{
294
295 /// getArch - Get the parsed architecture type of this triple.
296 ArchType getArch() const { return Arch; }
297
298 /// getSubArch - get the parsed subarchitecture type for this triple.
299 SubArchType getSubArch() const { return SubArch; }
300
301 /// getVendor - Get the parsed vendor type of this triple.
302 VendorType getVendor() const { return Vendor; }
303
304 /// getOS - Get the parsed operating system type of this triple.
305 OSType getOS() const { return OS; }
306
307 /// hasEnvironment - Does this triple have the optional environment
308 /// (fourth) component?
309 bool hasEnvironment() const {
310 return getEnvironmentName() != "";
311 }
312
313 /// getEnvironment - Get the parsed environment type of this triple.
314 EnvironmentType getEnvironment() const { return Environment; }
315
316 /// Parse the version number from the OS name component of the
317 /// triple, if present.
318 ///
319 /// For example, "fooos1.2.3" would return (1, 2, 3).
320 ///
321 /// If an entry is not defined, it will be returned as 0.
322 void getEnvironmentVersion(unsigned &Major, unsigned &Minor,
323 unsigned &Micro) const;
324
325 /// getFormat - Get the object format for this triple.
326 ObjectFormatType getObjectFormat() const { return ObjectFormat; }
327
328 /// getOSVersion - Parse the version number from the OS name component of the
329 /// triple, if present.
330 ///
331 /// For example, "fooos1.2.3" would return (1, 2, 3).
332 ///
333 /// If an entry is not defined, it will be returned as 0.
334 void getOSVersion(unsigned &Major, unsigned &Minor, unsigned &Micro) const;
335
336 /// getOSMajorVersion - Return just the major version number, this is
337 /// specialized because it is a common query.
338 unsigned getOSMajorVersion() const {
339 unsigned Maj, Min, Micro;
340 getOSVersion(Maj, Min, Micro);
341 return Maj;
342 }
343
344 /// getMacOSXVersion - Parse the version number as with getOSVersion and then
345 /// translate generic "darwin" versions to the corresponding OS X versions.
346 /// This may also be called with IOS triples but the OS X version number is
347 /// just set to a constant 10.4.0 in that case. Returns true if successful.
348 bool getMacOSXVersion(unsigned &Major, unsigned &Minor,
349 unsigned &Micro) const;
350
351 /// getiOSVersion - Parse the version number as with getOSVersion. This should
352 /// only be called with IOS or generic triples.
353 void getiOSVersion(unsigned &Major, unsigned &Minor,
354 unsigned &Micro) const;
355
356 /// getWatchOSVersion - Parse the version number as with getOSVersion. This
357 /// should only be called with WatchOS or generic triples.
358 void getWatchOSVersion(unsigned &Major, unsigned &Minor,
359 unsigned &Micro) const;
360
361 /// @}
362 /// @name Direct Component Access
363 /// @{
364
365 const std::string &str() const { return Data; }
366
367 const std::string &getTriple() const { return Data; }
368
369 /// getArchName - Get the architecture (first) component of the
370 /// triple.
371 StringRef getArchName() const;
372
373 /// getVendorName - Get the vendor (second) component of the triple.
374 StringRef getVendorName() const;
375
376 /// getOSName - Get the operating system (third) component of the
377 /// triple.
378 StringRef getOSName() const;
379
380 /// getEnvironmentName - Get the optional environment (fourth)
381 /// component of the triple, or "" if empty.
382 StringRef getEnvironmentName() const;
383
384 /// getOSAndEnvironmentName - Get the operating system and optional
385 /// environment components as a single string (separated by a '-'
386 /// if the environment component is present).
387 StringRef getOSAndEnvironmentName() const;
388
389 /// @}
390 /// @name Convenience Predicates
391 /// @{
392
393 /// Test whether the architecture is 64-bit
394 ///
395 /// Note that this tests for 64-bit pointer width, and nothing else. Note
396 /// that we intentionally expose only three predicates, 64-bit, 32-bit, and
397 /// 16-bit. The inner details of pointer width for particular architectures
398 /// is not summed up in the triple, and so only a coarse grained predicate
399 /// system is provided.
400 bool isArch64Bit() const;
401
402 /// Test whether the architecture is 32-bit
403 ///
404 /// Note that this tests for 32-bit pointer width, and nothing else.
405 bool isArch32Bit() const;
406
407 /// Test whether the architecture is 16-bit
408 ///
409 /// Note that this tests for 16-bit pointer width, and nothing else.
410 bool isArch16Bit() const;
411
412 /// isOSVersionLT - Helper function for doing comparisons against version
413 /// numbers included in the target triple.
414 bool isOSVersionLT(unsigned Major, unsigned Minor = 0,
415 unsigned Micro = 0) const {
416 unsigned LHS[3];
417 getOSVersion(LHS[0], LHS[1], LHS[2]);
418
419 if (LHS[0] != Major)
420 return LHS[0] < Major;
421 if (LHS[1] != Minor)
422 return LHS[1] < Minor;
423 if (LHS[2] != Micro)
424 return LHS[2] < Micro;
425
426 return false;
427 }
428
429 bool isOSVersionLT(const Triple &Other) const {
430 unsigned RHS[3];
431 Other.getOSVersion(RHS[0], RHS[1], RHS[2]);
432 return isOSVersionLT(RHS[0], RHS[1], RHS[2]);
433 }
434
435 /// isMacOSXVersionLT - Comparison function for checking OS X version
436 /// compatibility, which handles supporting skewed version numbering schemes
437 /// used by the "darwin" triples.
438 bool isMacOSXVersionLT(unsigned Major, unsigned Minor = 0,
439 unsigned Micro = 0) const {
440 assert(isMacOSX() && "Not an OS X triple!")((isMacOSX() && "Not an OS X triple!") ? static_cast<
void> (0) : __assert_fail ("isMacOSX() && \"Not an OS X triple!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/ADT/Triple.h"
, 440, __PRETTY_FUNCTION__))
;
441
442 // If this is OS X, expect a sane version number.
443 if (getOS() == Triple::MacOSX)
444 return isOSVersionLT(Major, Minor, Micro);
445
446 // Otherwise, compare to the "Darwin" number.
447 assert(Major == 10 && "Unexpected major version")((Major == 10 && "Unexpected major version") ? static_cast
<void> (0) : __assert_fail ("Major == 10 && \"Unexpected major version\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/ADT/Triple.h"
, 447, __PRETTY_FUNCTION__))
;
448 return isOSVersionLT(Minor + 4, Micro, 0);
449 }
450
451 /// isMacOSX - Is this a Mac OS X triple. For legacy reasons, we support both
452 /// "darwin" and "osx" as OS X triples.
453 bool isMacOSX() const {
454 return getOS() == Triple::Darwin || getOS() == Triple::MacOSX;
455 }
456
457 /// Is this an iOS triple.
458 /// Note: This identifies tvOS as a variant of iOS. If that ever
459 /// changes, i.e., if the two operating systems diverge or their version
460 /// numbers get out of sync, that will need to be changed.
461 /// watchOS has completely different version numbers so it is not included.
462 bool isiOS() const {
463 return getOS() == Triple::IOS || isTvOS();
464 }
465
466 /// Is this an Apple tvOS triple.
467 bool isTvOS() const {
468 return getOS() == Triple::TvOS;
469 }
470
471 /// Is this an Apple watchOS triple.
472 bool isWatchOS() const {
473 return getOS() == Triple::WatchOS;
474 }
475
476 bool isWatchABI() const {
477 return getSubArch() == Triple::ARMSubArch_v7k;
478 }
479
480 /// isOSDarwin - Is this a "Darwin" OS (OS X, iOS, or watchOS).
481 bool isOSDarwin() const {
482 return isMacOSX() || isiOS() || isWatchOS();
483 }
484
485 bool isSimulatorEnvironment() const {
486 return getEnvironment() == Triple::Simulator;
487 }
488
489 bool isMacCatalystEnvironment() const {
490 return getEnvironment() == Triple::MacABI;
491 }
492
493 bool isOSNetBSD() const {
494 return getOS() == Triple::NetBSD;
495 }
496
497 bool isOSOpenBSD() const {
498 return getOS() == Triple::OpenBSD;
499 }
500
501 bool isOSFreeBSD() const {
502 return getOS() == Triple::FreeBSD;
503 }
504
505 bool isOSFuchsia() const {
506 return getOS() == Triple::Fuchsia;
507 }
508
509 bool isOSDragonFly() const { return getOS() == Triple::DragonFly; }
510
511 bool isOSSolaris() const {
512 return getOS() == Triple::Solaris;
513 }
514
515 bool isOSIAMCU() const {
516 return getOS() == Triple::ELFIAMCU;
517 }
518
519 bool isOSUnknown() const { return getOS() == Triple::UnknownOS; }
520
521 bool isGNUEnvironment() const {
522 EnvironmentType Env = getEnvironment();
523 return Env == Triple::GNU || Env == Triple::GNUABIN32 ||
524 Env == Triple::GNUABI64 || Env == Triple::GNUEABI ||
525 Env == Triple::GNUEABIHF || Env == Triple::GNUX32;
526 }
527
528 bool isOSContiki() const {
529 return getOS() == Triple::Contiki;
530 }
531
532 /// Tests whether the OS is Haiku.
533 bool isOSHaiku() const {
534 return getOS() == Triple::Haiku;
535 }
536
537 /// Tests whether the OS is Windows.
538 bool isOSWindows() const {
539 return getOS() == Triple::Win32;
540 }
541
542 /// Checks if the environment is MSVC.
543 bool isKnownWindowsMSVCEnvironment() const {
544 return isOSWindows() && getEnvironment() == Triple::MSVC;
545 }
546
547 /// Checks if the environment could be MSVC.
548 bool isWindowsMSVCEnvironment() const {
549 return isKnownWindowsMSVCEnvironment() ||
550 (isOSWindows() && getEnvironment() == Triple::UnknownEnvironment);
551 }
552
553 bool isWindowsCoreCLREnvironment() const {
554 return isOSWindows() && getEnvironment() == Triple::CoreCLR;
555 }
556
557 bool isWindowsItaniumEnvironment() const {
558 return isOSWindows() && getEnvironment() == Triple::Itanium;
559 }
560
561 bool isWindowsCygwinEnvironment() const {
562 return isOSWindows() && getEnvironment() == Triple::Cygnus;
563 }
564
565 bool isWindowsGNUEnvironment() const {
566 return isOSWindows() && getEnvironment() == Triple::GNU;
567 }
568
569 /// Tests for either Cygwin or MinGW OS
570 bool isOSCygMing() const {
571 return isWindowsCygwinEnvironment() || isWindowsGNUEnvironment();
572 }
573
574 /// Is this a "Windows" OS targeting a "MSVCRT.dll" environment.
575 bool isOSMSVCRT() const {
576 return isWindowsMSVCEnvironment() || isWindowsGNUEnvironment() ||
577 isWindowsItaniumEnvironment();
578 }
579
580 /// Tests whether the OS is NaCl (Native Client)
581 bool isOSNaCl() const {
582 return getOS() == Triple::NaCl;
583 }
584
585 /// Tests whether the OS is Linux.
586 bool isOSLinux() const {
587 return getOS() == Triple::Linux;
588 }
589
590 /// Tests whether the OS is kFreeBSD.
591 bool isOSKFreeBSD() const {
592 return getOS() == Triple::KFreeBSD;
593 }
594
595 /// Tests whether the OS is Hurd.
596 bool isOSHurd() const {
597 return getOS() == Triple::Hurd;
598 }
599
600 /// Tests whether the OS is WASI.
601 bool isOSWASI() const {
602 return getOS() == Triple::WASI;
603 }
604
605 /// Tests whether the OS is Emscripten.
606 bool isOSEmscripten() const {
607 return getOS() == Triple::Emscripten;
608 }
609
610 /// Tests whether the OS uses glibc.
611 bool isOSGlibc() const {
612 return (getOS() == Triple::Linux || getOS() == Triple::KFreeBSD ||
613 getOS() == Triple::Hurd) &&
614 !isAndroid();
615 }
616
617 /// Tests whether the OS is AIX.
618 bool isOSAIX() const {
619 return getOS() == Triple::AIX;
620 }
621
622 /// Tests whether the OS uses the ELF binary format.
623 bool isOSBinFormatELF() const {
624 return getObjectFormat() == Triple::ELF;
625 }
626
627 /// Tests whether the OS uses the COFF binary format.
628 bool isOSBinFormatCOFF() const {
629 return getObjectFormat() == Triple::COFF;
10
Returning the value 1, which participates in a condition later
630 }
631
632 /// Tests whether the environment is MachO.
633 bool isOSBinFormatMachO() const {
634 return getObjectFormat() == Triple::MachO;
635 }
636
637 /// Tests whether the OS uses the Wasm binary format.
638 bool isOSBinFormatWasm() const {
639 return getObjectFormat() == Triple::Wasm;
640 }
641
642 /// Tests whether the OS uses the XCOFF binary format.
643 bool isOSBinFormatXCOFF() const {
644 return getObjectFormat() == Triple::XCOFF;
645 }
646
647 /// Tests whether the target is the PS4 CPU
648 bool isPS4CPU() const {
649 return getArch() == Triple::x86_64 &&
650 getVendor() == Triple::SCEI &&
651 getOS() == Triple::PS4;
652 }
653
654 /// Tests whether the target is the PS4 platform
655 bool isPS4() const {
656 return getVendor() == Triple::SCEI &&
657 getOS() == Triple::PS4;
658 }
659
660 /// Tests whether the target is Android
661 bool isAndroid() const { return getEnvironment() == Triple::Android; }
662
663 bool isAndroidVersionLT(unsigned Major) const {
664 assert(isAndroid() && "Not an Android triple!")((isAndroid() && "Not an Android triple!") ? static_cast
<void> (0) : __assert_fail ("isAndroid() && \"Not an Android triple!\""
, "/build/llvm-toolchain-snapshot-10~+201911111502510600c19528f1809/llvm/include/llvm/ADT/Triple.h"
, 664, __PRETTY_FUNCTION__))
;
665
666 unsigned Env[3];
667 getEnvironmentVersion(Env[0], Env[1], Env[2]);
668
669 // 64-bit targets did not exist before API level 21 (Lollipop).
670 if (isArch64Bit() && Env[0] < 21)
671 Env[0] = 21;
672
673 return Env[0] < Major;
674 }
675
676 /// Tests whether the environment is musl-libc
677 bool isMusl() const {
678 return getEnvironment() == Triple::Musl ||
679 getEnvironment() == Triple::MuslEABI ||
680 getEnvironment() == Triple::MuslEABIHF;
681 }
682
683 /// Tests whether the target is SPIR (32- or 64-bit).
684 bool isSPIR() const {
685 return getArch() == Triple::spir || getArch() == Triple::spir64;
686 }
687
688 /// Tests whether the target is NVPTX (32- or 64-bit).
689 bool isNVPTX() const {
690 return getArch() == Triple::nvptx || getArch() == Triple::nvptx64;
691 }
692
693 /// Tests whether the target is Thumb (little and big endian).
694 bool isThumb() const {
695 return getArch() == Triple::thumb || getArch() == Triple::thumbeb;
696 }
697
698 /// Tests whether the target is ARM (little and big endian).
699 bool isARM() const {
700 return getArch() == Triple::arm || getArch() == Triple::armeb;
701 }
702
703 /// Tests whether the target is AArch64 (little and big endian).
704 bool isAArch64() const {
705 return getArch() == Triple::aarch64 || getArch() == Triple::aarch64_be;
706 }
707
708 /// Tests whether the target is MIPS 32-bit (little and big endian).
709 bool isMIPS32() const {
710 return getArch() == Triple::mips || getArch() == Triple::mipsel;
711 }
712
713 /// Tests whether the target is MIPS 64-bit (little and big endian).
714 bool isMIPS64() const {
715 return getArch() == Triple::mips64 || getArch() == Triple::mips64el;
716 }
717
718 /// Tests whether the target is MIPS (little and big endian, 32- or 64-bit).
719 bool isMIPS() const {
720 return isMIPS32() || isMIPS64();
721 }
722
723 /// Tests whether the target is 64-bit PowerPC (little and big endian).
724 bool isPPC64() const {
725 return getArch() == Triple::ppc64 || getArch() == Triple::ppc64le;
726 }
727
728 /// Tests whether the target is RISC-V (32- and 64-bit).
729 bool isRISCV() const {
730 return getArch() == Triple::riscv32 || getArch() == Triple::riscv64;
731 }
732
733 /// Tests whether the target supports comdat
734 bool supportsCOMDAT() const {
735 return !isOSBinFormatMachO();
736 }
737
738 /// Tests whether the target uses emulated TLS as default.
739 bool hasDefaultEmulatedTLS() const {
740 return isAndroid() || isOSOpenBSD() || isWindowsCygwinEnvironment();
741 }
742
743 /// @}
744 /// @name Mutators
745 /// @{
746
747 /// setArch - Set the architecture (first) component of the triple
748 /// to a known type.
749 void setArch(ArchType Kind);
750
751 /// setVendor - Set the vendor (second) component of the triple to a
752 /// known type.
753 void setVendor(VendorType Kind);
754
755 /// setOS - Set the operating system (third) component of the triple
756 /// to a known type.
757 void setOS(OSType Kind);
758
759 /// setEnvironment - Set the environment (fourth) component of the triple
760 /// to a known type.
761 void setEnvironment(EnvironmentType Kind);
762
763 /// setObjectFormat - Set the object file format
764 void setObjectFormat(ObjectFormatType Kind);
765
766 /// setTriple - Set all components to the new triple \p Str.
767 void setTriple(const Twine &Str);
768
769 /// setArchName - Set the architecture (first) component of the
770 /// triple by name.
771 void setArchName(StringRef Str);
772
773 /// setVendorName - Set the vendor (second) component of the triple
774 /// by name.
775 void setVendorName(StringRef Str);
776
777 /// setOSName - Set the operating system (third) component of the
778 /// triple by name.
779 void setOSName(StringRef Str);
780
781 /// setEnvironmentName - Set the optional environment (fourth)
782 /// component of the triple by name.
783 void setEnvironmentName(StringRef Str);
784
785 /// setOSAndEnvironmentName - Set the operating system and optional
786 /// environment components with a single string.
787 void setOSAndEnvironmentName(StringRef Str);
788
789 /// @}
790 /// @name Helpers to build variants of a particular triple.
791 /// @{
792
793 /// Form a triple with a 32-bit variant of the current architecture.
794 ///
795 /// This can be used to move across "families" of architectures where useful.
796 ///
797 /// \returns A new triple with a 32-bit architecture or an unknown
798 /// architecture if no such variant can be found.
799 llvm::Triple get32BitArchVariant() const;
800
801 /// Form a triple with a 64-bit variant of the current architecture.
802 ///
803 /// This can be used to move across "families" of architectures where useful.
804 ///
805 /// \returns A new triple with a 64-bit architecture or an unknown
806 /// architecture if no such variant can be found.
807 llvm::Triple get64BitArchVariant() const;
808
809 /// Form a triple with a big endian variant of the current architecture.
810 ///
811 /// This can be used to move across "families" of architectures where useful.
812 ///
813 /// \returns A new triple with a big endian architecture or an unknown
814 /// architecture if no such variant can be found.
815 llvm::Triple getBigEndianArchVariant() const;
816
817 /// Form a triple with a little endian variant of the current architecture.
818 ///
819 /// This can be used to move across "families" of architectures where useful.
820 ///
821 /// \returns A new triple with a little endian architecture or an unknown
822 /// architecture if no such variant can be found.
823 llvm::Triple getLittleEndianArchVariant() const;
824
825 /// Get the (LLVM) name of the minimum ARM CPU for the arch we are targeting.
826 ///
827 /// \param Arch the architecture name (e.g., "armv7s"). If it is an empty
828 /// string then the triple's arch name is used.
829 StringRef getARMCPUForArch(StringRef Arch = StringRef()) const;
830
831 /// Tests whether the target triple is little endian.
832 ///
833 /// \returns true if the triple is little endian, false otherwise.
834 bool isLittleEndian() const;
835
836 /// Test whether target triples are compatible.
837 bool isCompatibleWith(const Triple &Other) const;
838
839 /// Merge target triples.
840 std::string merge(const Triple &Other) const;
841
842 /// @}
843 /// @name Static helpers for IDs.
844 /// @{
845
846 /// getArchTypeName - Get the canonical name for the \p Kind architecture.
847 static StringRef getArchTypeName(ArchType Kind);
848
849 /// getArchTypePrefix - Get the "prefix" canonical name for the \p Kind
850 /// architecture. This is the prefix used by the architecture specific
851 /// builtins, and is suitable for passing to \see
852 /// Intrinsic::getIntrinsicForGCCBuiltin().
853 ///
854 /// \return - The architecture prefix, or 0 if none is defined.
855 static StringRef getArchTypePrefix(ArchType Kind);
856
857 /// getVendorTypeName - Get the canonical name for the \p Kind vendor.
858 static StringRef getVendorTypeName(VendorType Kind);
859
860 /// getOSTypeName - Get the canonical name for the \p Kind operating system.
861 static StringRef getOSTypeName(OSType Kind);
862
863 /// getEnvironmentTypeName - Get the canonical name for the \p Kind
864 /// environment.
865 static StringRef getEnvironmentTypeName(EnvironmentType Kind);
866
867 /// @}
868 /// @name Static helpers for converting alternate architecture names.
869 /// @{
870
871 /// getArchTypeForLLVMName - The canonical type for the given LLVM
872 /// architecture name (e.g., "x86").
873 static ArchType getArchTypeForLLVMName(StringRef Str);
874
875 /// @}
876};
877
878} // End llvm namespace
879
880
881#endif