Bug Summary

File:include/llvm/IR/IRBuilder.h
Warning:line 1680, column 9
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 -mrelocation-model pic -pic-level 2 -mthread-model posix -relaxed-aliasing -fmath-errno -masm-verbose -mconstructor-aliases -munwind-tables -fuse-init-array -target-cpu x86-64 -dwarf-column-info -debugger-tuning=gdb -momit-leaf-frame-pointer -ffunction-sections -fdata-sections -resource-dir /usr/lib/llvm-8/lib/clang/8.0.0 -D _DEBUG -D _GNU_SOURCE -D __STDC_CONSTANT_MACROS -D __STDC_FORMAT_MACROS -D __STDC_LIMIT_MACROS -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen -I /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/clang/include -I /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/include -I /build/llvm-toolchain-snapshot-8~svn345461/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/include/clang/8.0.0/include/ -internal-isystem /usr/local/include -internal-isystem /usr/lib/llvm-8/lib/clang/8.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++11 -fdeprecated-macro -fdebug-compilation-dir /build/llvm-toolchain-snapshot-8~svn345461/build-llvm/tools/clang/lib/CodeGen -ferror-limit 19 -fmessage-length 0 -fvisibility-inlines-hidden -fobjc-runtime=gcc -fno-common -fdiagnostics-show-option -vectorize-loops -vectorize-slp -analyzer-output=html -analyzer-config stable-report-filename=true -o /tmp/scan-build-2018-10-27-211344-32123-1 -x c++ /build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CGObjCGNU.cpp -faddrsig

/build/llvm-toolchain-snapshot-8~svn345461/tools/clang/lib/CodeGen/CGObjCGNU.cpp

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

/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/IRBuilder.h

1//===- llvm/IRBuilder.h - Builder for LLVM Instructions ---------*- C++ -*-===//
2//
3// The LLVM Compiler Infrastructure
4//
5// This file is distributed under the University of Illinois Open Source
6// License. See LICENSE.TXT for details.
7//
8//===----------------------------------------------------------------------===//
9//
10// This file defines the IRBuilder class, which is used as a convenient way
11// to create LLVM instructions with a consistent and simplified interface.
12//
13//===----------------------------------------------------------------------===//
14
15#ifndef LLVM_IR_IRBUILDER_H
16#define LLVM_IR_IRBUILDER_H
17
18#include "llvm-c/Types.h"
19#include "llvm/ADT/ArrayRef.h"
20#include "llvm/ADT/None.h"
21#include "llvm/ADT/StringRef.h"
22#include "llvm/ADT/Twine.h"
23#include "llvm/IR/BasicBlock.h"
24#include "llvm/IR/Constant.h"
25#include "llvm/IR/ConstantFolder.h"
26#include "llvm/IR/Constants.h"
27#include "llvm/IR/DataLayout.h"
28#include "llvm/IR/DebugLoc.h"
29#include "llvm/IR/DerivedTypes.h"
30#include "llvm/IR/Function.h"
31#include "llvm/IR/GlobalVariable.h"
32#include "llvm/IR/InstrTypes.h"
33#include "llvm/IR/Instruction.h"
34#include "llvm/IR/Instructions.h"
35#include "llvm/IR/Intrinsics.h"
36#include "llvm/IR/LLVMContext.h"
37#include "llvm/IR/Module.h"
38#include "llvm/IR/Operator.h"
39#include "llvm/IR/Type.h"
40#include "llvm/IR/Value.h"
41#include "llvm/IR/ValueHandle.h"
42#include "llvm/Support/AtomicOrdering.h"
43#include "llvm/Support/CBindingWrapping.h"
44#include "llvm/Support/Casting.h"
45#include <cassert>
46#include <cstddef>
47#include <cstdint>
48#include <functional>
49#include <utility>
50
51namespace llvm {
52
53class APInt;
54class MDNode;
55class Use;
56
57/// This provides the default implementation of the IRBuilder
58/// 'InsertHelper' method that is called whenever an instruction is created by
59/// IRBuilder and needs to be inserted.
60///
61/// By default, this inserts the instruction at the insertion point.
62class IRBuilderDefaultInserter {
63protected:
64 void InsertHelper(Instruction *I, const Twine &Name,
65 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
66 if (BB) BB->getInstList().insert(InsertPt, I);
67 I->setName(Name);
68 }
69};
70
71/// Provides an 'InsertHelper' that calls a user-provided callback after
72/// performing the default insertion.
73class IRBuilderCallbackInserter : IRBuilderDefaultInserter {
74 std::function<void(Instruction *)> Callback;
75
76public:
77 IRBuilderCallbackInserter(std::function<void(Instruction *)> Callback)
78 : Callback(std::move(Callback)) {}
79
80protected:
81 void InsertHelper(Instruction *I, const Twine &Name,
82 BasicBlock *BB, BasicBlock::iterator InsertPt) const {
83 IRBuilderDefaultInserter::InsertHelper(I, Name, BB, InsertPt);
84 Callback(I);
85 }
86};
87
88/// Common base class shared among various IRBuilders.
89class IRBuilderBase {
90 DebugLoc CurDbgLocation;
91
92protected:
93 BasicBlock *BB;
94 BasicBlock::iterator InsertPt;
95 LLVMContext &Context;
96
97 MDNode *DefaultFPMathTag;
98 FastMathFlags FMF;
99
100 ArrayRef<OperandBundleDef> DefaultOperandBundles;
101
102public:
103 IRBuilderBase(LLVMContext &context, MDNode *FPMathTag = nullptr,
104 ArrayRef<OperandBundleDef> OpBundles = None)
105 : Context(context), DefaultFPMathTag(FPMathTag),
106 DefaultOperandBundles(OpBundles) {
107 ClearInsertionPoint();
108 }
109
110 //===--------------------------------------------------------------------===//
111 // Builder configuration methods
112 //===--------------------------------------------------------------------===//
113
114 /// Clear the insertion point: created instructions will not be
115 /// inserted into a block.
116 void ClearInsertionPoint() {
117 BB = nullptr;
118 InsertPt = BasicBlock::iterator();
119 }
120
121 BasicBlock *GetInsertBlock() const { return BB; }
122 BasicBlock::iterator GetInsertPoint() const { return InsertPt; }
123 LLVMContext &getContext() const { return Context; }
124
125 /// This specifies that created instructions should be appended to the
126 /// end of the specified block.
127 void SetInsertPoint(BasicBlock *TheBB) {
128 BB = TheBB;
129 InsertPt = BB->end();
130 }
131
132 /// This specifies that created instructions should be inserted before
133 /// the specified instruction.
134 void SetInsertPoint(Instruction *I) {
135 BB = I->getParent();
136 InsertPt = I->getIterator();
137 assert(InsertPt != BB->end() && "Can't read debug loc from end()")((InsertPt != BB->end() && "Can't read debug loc from end()"
) ? static_cast<void> (0) : __assert_fail ("InsertPt != BB->end() && \"Can't read debug loc from end()\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/IRBuilder.h"
, 137, __PRETTY_FUNCTION__))
;
138 SetCurrentDebugLocation(I->getDebugLoc());
139 }
140
141 /// This specifies that created instructions should be inserted at the
142 /// specified point.
143 void SetInsertPoint(BasicBlock *TheBB, BasicBlock::iterator IP) {
144 BB = TheBB;
145 InsertPt = IP;
146 if (IP != TheBB->end())
147 SetCurrentDebugLocation(IP->getDebugLoc());
148 }
149
150 /// Set location information used by debugging information.
151 void SetCurrentDebugLocation(DebugLoc L) { CurDbgLocation = std::move(L); }
152
153 /// Get location information used by debugging information.
154 const DebugLoc &getCurrentDebugLocation() const { return CurDbgLocation; }
155
156 /// If this builder has a current debug location, set it on the
157 /// specified instruction.
158 void SetInstDebugLocation(Instruction *I) const {
159 if (CurDbgLocation)
160 I->setDebugLoc(CurDbgLocation);
161 }
162
163 /// Get the return type of the current function that we're emitting
164 /// into.
165 Type *getCurrentFunctionReturnType() const;
166
167 /// InsertPoint - A saved insertion point.
168 class InsertPoint {
169 BasicBlock *Block = nullptr;
170 BasicBlock::iterator Point;
171
172 public:
173 /// Creates a new insertion point which doesn't point to anything.
174 InsertPoint() = default;
175
176 /// Creates a new insertion point at the given location.
177 InsertPoint(BasicBlock *InsertBlock, BasicBlock::iterator InsertPoint)
178 : Block(InsertBlock), Point(InsertPoint) {}
179
180 /// Returns true if this insert point is set.
181 bool isSet() const { return (Block != nullptr); }
182
183 BasicBlock *getBlock() const { return Block; }
184 BasicBlock::iterator getPoint() const { return Point; }
185 };
186
187 /// Returns the current insert point.
188 InsertPoint saveIP() const {
189 return InsertPoint(GetInsertBlock(), GetInsertPoint());
190 }
191
192 /// Returns the current insert point, clearing it in the process.
193 InsertPoint saveAndClearIP() {
194 InsertPoint IP(GetInsertBlock(), GetInsertPoint());
195 ClearInsertionPoint();
196 return IP;
197 }
198
199 /// Sets the current insert point to a previously-saved location.
200 void restoreIP(InsertPoint IP) {
201 if (IP.isSet())
202 SetInsertPoint(IP.getBlock(), IP.getPoint());
203 else
204 ClearInsertionPoint();
205 }
206
207 /// Get the floating point math metadata being used.
208 MDNode *getDefaultFPMathTag() const { return DefaultFPMathTag; }
209
210 /// Get the flags to be applied to created floating point ops
211 FastMathFlags getFastMathFlags() const { return FMF; }
212
213 /// Clear the fast-math flags.
214 void clearFastMathFlags() { FMF.clear(); }
215
216 /// Set the floating point math metadata to be used.
217 void setDefaultFPMathTag(MDNode *FPMathTag) { DefaultFPMathTag = FPMathTag; }
218
219 /// Set the fast-math flags to be used with generated fp-math operators
220 void setFastMathFlags(FastMathFlags NewFMF) { FMF = NewFMF; }
221
222 //===--------------------------------------------------------------------===//
223 // RAII helpers.
224 //===--------------------------------------------------------------------===//
225
226 // RAII object that stores the current insertion point and restores it
227 // when the object is destroyed. This includes the debug location.
228 class InsertPointGuard {
229 IRBuilderBase &Builder;
230 AssertingVH<BasicBlock> Block;
231 BasicBlock::iterator Point;
232 DebugLoc DbgLoc;
233
234 public:
235 InsertPointGuard(IRBuilderBase &B)
236 : Builder(B), Block(B.GetInsertBlock()), Point(B.GetInsertPoint()),
237 DbgLoc(B.getCurrentDebugLocation()) {}
238
239 InsertPointGuard(const InsertPointGuard &) = delete;
240 InsertPointGuard &operator=(const InsertPointGuard &) = delete;
241
242 ~InsertPointGuard() {
243 Builder.restoreIP(InsertPoint(Block, Point));
244 Builder.SetCurrentDebugLocation(DbgLoc);
245 }
246 };
247
248 // RAII object that stores the current fast math settings and restores
249 // them when the object is destroyed.
250 class FastMathFlagGuard {
251 IRBuilderBase &Builder;
252 FastMathFlags FMF;
253 MDNode *FPMathTag;
254
255 public:
256 FastMathFlagGuard(IRBuilderBase &B)
257 : Builder(B), FMF(B.FMF), FPMathTag(B.DefaultFPMathTag) {}
258
259 FastMathFlagGuard(const FastMathFlagGuard &) = delete;
260 FastMathFlagGuard &operator=(const FastMathFlagGuard &) = delete;
261
262 ~FastMathFlagGuard() {
263 Builder.FMF = FMF;
264 Builder.DefaultFPMathTag = FPMathTag;
265 }
266 };
267
268 //===--------------------------------------------------------------------===//
269 // Miscellaneous creation methods.
270 //===--------------------------------------------------------------------===//
271
272 /// Make a new global variable with initializer type i8*
273 ///
274 /// Make a new global variable with an initializer that has array of i8 type
275 /// filled in with the null terminated string value specified. The new global
276 /// variable will be marked mergable with any others of the same contents. If
277 /// Name is specified, it is the name of the global variable created.
278 GlobalVariable *CreateGlobalString(StringRef Str, const Twine &Name = "",
279 unsigned AddressSpace = 0);
280
281 /// Get a constant value representing either true or false.
282 ConstantInt *getInt1(bool V) {
283 return ConstantInt::get(getInt1Ty(), V);
284 }
285
286 /// Get the constant value for i1 true.
287 ConstantInt *getTrue() {
288 return ConstantInt::getTrue(Context);
289 }
290
291 /// Get the constant value for i1 false.
292 ConstantInt *getFalse() {
293 return ConstantInt::getFalse(Context);
294 }
295
296 /// Get a constant 8-bit value.
297 ConstantInt *getInt8(uint8_t C) {
298 return ConstantInt::get(getInt8Ty(), C);
299 }
300
301 /// Get a constant 16-bit value.
302 ConstantInt *getInt16(uint16_t C) {
303 return ConstantInt::get(getInt16Ty(), C);
304 }
305
306 /// Get a constant 32-bit value.
307 ConstantInt *getInt32(uint32_t C) {
308 return ConstantInt::get(getInt32Ty(), C);
309 }
310
311 /// Get a constant 64-bit value.
312 ConstantInt *getInt64(uint64_t C) {
313 return ConstantInt::get(getInt64Ty(), C);
314 }
315
316 /// Get a constant N-bit value, zero extended or truncated from
317 /// a 64-bit value.
318 ConstantInt *getIntN(unsigned N, uint64_t C) {
319 return ConstantInt::get(getIntNTy(N), C);
320 }
321
322 /// Get a constant integer value.
323 ConstantInt *getInt(const APInt &AI) {
324 return ConstantInt::get(Context, AI);
325 }
326
327 //===--------------------------------------------------------------------===//
328 // Type creation methods
329 //===--------------------------------------------------------------------===//
330
331 /// Fetch the type representing a single bit
332 IntegerType *getInt1Ty() {
333 return Type::getInt1Ty(Context);
334 }
335
336 /// Fetch the type representing an 8-bit integer.
337 IntegerType *getInt8Ty() {
338 return Type::getInt8Ty(Context);
339 }
340
341 /// Fetch the type representing a 16-bit integer.
342 IntegerType *getInt16Ty() {
343 return Type::getInt16Ty(Context);
344 }
345
346 /// Fetch the type representing a 32-bit integer.
347 IntegerType *getInt32Ty() {
348 return Type::getInt32Ty(Context);
349 }
350
351 /// Fetch the type representing a 64-bit integer.
352 IntegerType *getInt64Ty() {
353 return Type::getInt64Ty(Context);
354 }
355
356 /// Fetch the type representing a 128-bit integer.
357 IntegerType *getInt128Ty() { return Type::getInt128Ty(Context); }
358
359 /// Fetch the type representing an N-bit integer.
360 IntegerType *getIntNTy(unsigned N) {
361 return Type::getIntNTy(Context, N);
362 }
363
364 /// Fetch the type representing a 16-bit floating point value.
365 Type *getHalfTy() {
366 return Type::getHalfTy(Context);
367 }
368
369 /// Fetch the type representing a 32-bit floating point value.
370 Type *getFloatTy() {
371 return Type::getFloatTy(Context);
372 }
373
374 /// Fetch the type representing a 64-bit floating point value.
375 Type *getDoubleTy() {
376 return Type::getDoubleTy(Context);
377 }
378
379 /// Fetch the type representing void.
380 Type *getVoidTy() {
381 return Type::getVoidTy(Context);
382 }
383
384 /// Fetch the type representing a pointer to an 8-bit integer value.
385 PointerType *getInt8PtrTy(unsigned AddrSpace = 0) {
386 return Type::getInt8PtrTy(Context, AddrSpace);
387 }
388
389 /// Fetch the type representing a pointer to an integer value.
390 IntegerType *getIntPtrTy(const DataLayout &DL, unsigned AddrSpace = 0) {
391 return DL.getIntPtrType(Context, AddrSpace);
392 }
393
394 //===--------------------------------------------------------------------===//
395 // Intrinsic creation methods
396 //===--------------------------------------------------------------------===//
397
398 /// Create and insert a memset to the specified pointer and the
399 /// specified value.
400 ///
401 /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
402 /// specified, it will be added to the instruction. Likewise with alias.scope
403 /// and noalias tags.
404 CallInst *CreateMemSet(Value *Ptr, Value *Val, uint64_t Size, unsigned Align,
405 bool isVolatile = false, MDNode *TBAATag = nullptr,
406 MDNode *ScopeTag = nullptr,
407 MDNode *NoAliasTag = nullptr) {
408 return CreateMemSet(Ptr, Val, getInt64(Size), Align, isVolatile,
409 TBAATag, ScopeTag, NoAliasTag);
410 }
411
412 CallInst *CreateMemSet(Value *Ptr, Value *Val, Value *Size, unsigned Align,
413 bool isVolatile = false, MDNode *TBAATag = nullptr,
414 MDNode *ScopeTag = nullptr,
415 MDNode *NoAliasTag = nullptr);
416
417 /// Create and insert an element unordered-atomic memset of the region of
418 /// memory starting at the given pointer to the given value.
419 ///
420 /// If the pointer isn't an i8*, it will be converted. If a TBAA tag is
421 /// specified, it will be added to the instruction. Likewise with alias.scope
422 /// and noalias tags.
423 CallInst *CreateElementUnorderedAtomicMemSet(Value *Ptr, Value *Val,
424 uint64_t Size, unsigned Align,
425 uint32_t ElementSize,
426 MDNode *TBAATag = nullptr,
427 MDNode *ScopeTag = nullptr,
428 MDNode *NoAliasTag = nullptr) {
429 return CreateElementUnorderedAtomicMemSet(Ptr, Val, getInt64(Size), Align,
430 ElementSize, TBAATag, ScopeTag,
431 NoAliasTag);
432 }
433
434 CallInst *CreateElementUnorderedAtomicMemSet(Value *Ptr, Value *Val,
435 Value *Size, unsigned Align,
436 uint32_t ElementSize,
437 MDNode *TBAATag = nullptr,
438 MDNode *ScopeTag = nullptr,
439 MDNode *NoAliasTag = nullptr);
440
441 /// Create and insert a memcpy between the specified pointers.
442 ///
443 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
444 /// specified, it will be added to the instruction. Likewise with alias.scope
445 /// and noalias tags.
446 CallInst *CreateMemCpy(Value *Dst, unsigned DstAlign, Value *Src,
447 unsigned SrcAlign, uint64_t Size,
448 bool isVolatile = false, MDNode *TBAATag = nullptr,
449 MDNode *TBAAStructTag = nullptr,
450 MDNode *ScopeTag = nullptr,
451 MDNode *NoAliasTag = nullptr) {
452 return CreateMemCpy(Dst, DstAlign, Src, SrcAlign, getInt64(Size),
453 isVolatile, TBAATag, TBAAStructTag, ScopeTag,
454 NoAliasTag);
455 }
456
457 CallInst *CreateMemCpy(Value *Dst, unsigned DstAlign, Value *Src,
458 unsigned SrcAlign, Value *Size,
459 bool isVolatile = false, MDNode *TBAATag = nullptr,
460 MDNode *TBAAStructTag = nullptr,
461 MDNode *ScopeTag = nullptr,
462 MDNode *NoAliasTag = nullptr);
463
464 /// Create and insert an element unordered-atomic memcpy between the
465 /// specified pointers.
466 ///
467 /// DstAlign/SrcAlign are the alignments of the Dst/Src pointers, respectively.
468 ///
469 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
470 /// specified, it will be added to the instruction. Likewise with alias.scope
471 /// and noalias tags.
472 CallInst *CreateElementUnorderedAtomicMemCpy(
473 Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign,
474 uint64_t Size, uint32_t ElementSize, MDNode *TBAATag = nullptr,
475 MDNode *TBAAStructTag = nullptr, MDNode *ScopeTag = nullptr,
476 MDNode *NoAliasTag = nullptr) {
477 return CreateElementUnorderedAtomicMemCpy(
478 Dst, DstAlign, Src, SrcAlign, getInt64(Size), ElementSize, TBAATag,
479 TBAAStructTag, ScopeTag, NoAliasTag);
480 }
481
482 CallInst *CreateElementUnorderedAtomicMemCpy(
483 Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign, Value *Size,
484 uint32_t ElementSize, MDNode *TBAATag = nullptr,
485 MDNode *TBAAStructTag = nullptr, MDNode *ScopeTag = nullptr,
486 MDNode *NoAliasTag = nullptr);
487
488 /// Create and insert a memmove between the specified
489 /// pointers.
490 ///
491 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
492 /// specified, it will be added to the instruction. Likewise with alias.scope
493 /// and noalias tags.
494 CallInst *CreateMemMove(Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign,
495 uint64_t Size, bool isVolatile = false,
496 MDNode *TBAATag = nullptr, MDNode *ScopeTag = nullptr,
497 MDNode *NoAliasTag = nullptr) {
498 return CreateMemMove(Dst, DstAlign, Src, SrcAlign, getInt64(Size), isVolatile,
499 TBAATag, ScopeTag, NoAliasTag);
500 }
501
502 CallInst *CreateMemMove(Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign,
503 Value *Size, bool isVolatile = false, MDNode *TBAATag = nullptr,
504 MDNode *ScopeTag = nullptr,
505 MDNode *NoAliasTag = nullptr);
506
507 /// \brief Create and insert an element unordered-atomic memmove between the
508 /// specified pointers.
509 ///
510 /// DstAlign/SrcAlign are the alignments of the Dst/Src pointers,
511 /// respectively.
512 ///
513 /// If the pointers aren't i8*, they will be converted. If a TBAA tag is
514 /// specified, it will be added to the instruction. Likewise with alias.scope
515 /// and noalias tags.
516 CallInst *CreateElementUnorderedAtomicMemMove(
517 Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign,
518 uint64_t Size, uint32_t ElementSize, MDNode *TBAATag = nullptr,
519 MDNode *TBAAStructTag = nullptr, MDNode *ScopeTag = nullptr,
520 MDNode *NoAliasTag = nullptr) {
521 return CreateElementUnorderedAtomicMemMove(
522 Dst, DstAlign, Src, SrcAlign, getInt64(Size), ElementSize, TBAATag,
523 TBAAStructTag, ScopeTag, NoAliasTag);
524 }
525
526 CallInst *CreateElementUnorderedAtomicMemMove(
527 Value *Dst, unsigned DstAlign, Value *Src, unsigned SrcAlign, Value *Size,
528 uint32_t ElementSize, MDNode *TBAATag = nullptr,
529 MDNode *TBAAStructTag = nullptr, MDNode *ScopeTag = nullptr,
530 MDNode *NoAliasTag = nullptr);
531
532 /// Create a vector fadd reduction intrinsic of the source vector.
533 /// The first parameter is a scalar accumulator value for ordered reductions.
534 CallInst *CreateFAddReduce(Value *Acc, Value *Src);
535
536 /// Create a vector fmul reduction intrinsic of the source vector.
537 /// The first parameter is a scalar accumulator value for ordered reductions.
538 CallInst *CreateFMulReduce(Value *Acc, Value *Src);
539
540 /// Create a vector int add reduction intrinsic of the source vector.
541 CallInst *CreateAddReduce(Value *Src);
542
543 /// Create a vector int mul reduction intrinsic of the source vector.
544 CallInst *CreateMulReduce(Value *Src);
545
546 /// Create a vector int AND reduction intrinsic of the source vector.
547 CallInst *CreateAndReduce(Value *Src);
548
549 /// Create a vector int OR reduction intrinsic of the source vector.
550 CallInst *CreateOrReduce(Value *Src);
551
552 /// Create a vector int XOR reduction intrinsic of the source vector.
553 CallInst *CreateXorReduce(Value *Src);
554
555 /// Create a vector integer max reduction intrinsic of the source
556 /// vector.
557 CallInst *CreateIntMaxReduce(Value *Src, bool IsSigned = false);
558
559 /// Create a vector integer min reduction intrinsic of the source
560 /// vector.
561 CallInst *CreateIntMinReduce(Value *Src, bool IsSigned = false);
562
563 /// Create a vector float max reduction intrinsic of the source
564 /// vector.
565 CallInst *CreateFPMaxReduce(Value *Src, bool NoNaN = false);
566
567 /// Create a vector float min reduction intrinsic of the source
568 /// vector.
569 CallInst *CreateFPMinReduce(Value *Src, bool NoNaN = false);
570
571 /// Create a lifetime.start intrinsic.
572 ///
573 /// If the pointer isn't i8* it will be converted.
574 CallInst *CreateLifetimeStart(Value *Ptr, ConstantInt *Size = nullptr);
575
576 /// Create a lifetime.end intrinsic.
577 ///
578 /// If the pointer isn't i8* it will be converted.
579 CallInst *CreateLifetimeEnd(Value *Ptr, ConstantInt *Size = nullptr);
580
581 /// Create a call to invariant.start intrinsic.
582 ///
583 /// If the pointer isn't i8* it will be converted.
584 CallInst *CreateInvariantStart(Value *Ptr, ConstantInt *Size = nullptr);
585
586 /// Create a call to Masked Load intrinsic
587 CallInst *CreateMaskedLoad(Value *Ptr, unsigned Align, Value *Mask,
588 Value *PassThru = nullptr, const Twine &Name = "");
589
590 /// Create a call to Masked Store intrinsic
591 CallInst *CreateMaskedStore(Value *Val, Value *Ptr, unsigned Align,
592 Value *Mask);
593
594 /// Create a call to Masked Gather intrinsic
595 CallInst *CreateMaskedGather(Value *Ptrs, unsigned Align,
596 Value *Mask = nullptr,
597 Value *PassThru = nullptr,
598 const Twine& Name = "");
599
600 /// Create a call to Masked Scatter intrinsic
601 CallInst *CreateMaskedScatter(Value *Val, Value *Ptrs, unsigned Align,
602 Value *Mask = nullptr);
603
604 /// Create an assume intrinsic call that allows the optimizer to
605 /// assume that the provided condition will be true.
606 CallInst *CreateAssumption(Value *Cond);
607
608 /// Create a call to the experimental.gc.statepoint intrinsic to
609 /// start a new statepoint sequence.
610 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
611 Value *ActualCallee,
612 ArrayRef<Value *> CallArgs,
613 ArrayRef<Value *> DeoptArgs,
614 ArrayRef<Value *> GCArgs,
615 const Twine &Name = "");
616
617 /// Create a call to the experimental.gc.statepoint intrinsic to
618 /// start a new statepoint sequence.
619 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
620 Value *ActualCallee, uint32_t Flags,
621 ArrayRef<Use> CallArgs,
622 ArrayRef<Use> TransitionArgs,
623 ArrayRef<Use> DeoptArgs,
624 ArrayRef<Value *> GCArgs,
625 const Twine &Name = "");
626
627 /// Conveninence function for the common case when CallArgs are filled
628 /// in using makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be
629 /// .get()'ed to get the Value pointer.
630 CallInst *CreateGCStatepointCall(uint64_t ID, uint32_t NumPatchBytes,
631 Value *ActualCallee, ArrayRef<Use> CallArgs,
632 ArrayRef<Value *> DeoptArgs,
633 ArrayRef<Value *> GCArgs,
634 const Twine &Name = "");
635
636 /// Create an invoke to the experimental.gc.statepoint intrinsic to
637 /// start a new statepoint sequence.
638 InvokeInst *
639 CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
640 Value *ActualInvokee, BasicBlock *NormalDest,
641 BasicBlock *UnwindDest, ArrayRef<Value *> InvokeArgs,
642 ArrayRef<Value *> DeoptArgs,
643 ArrayRef<Value *> GCArgs, const Twine &Name = "");
644
645 /// Create an invoke to the experimental.gc.statepoint intrinsic to
646 /// start a new statepoint sequence.
647 InvokeInst *CreateGCStatepointInvoke(
648 uint64_t ID, uint32_t NumPatchBytes, Value *ActualInvokee,
649 BasicBlock *NormalDest, BasicBlock *UnwindDest, uint32_t Flags,
650 ArrayRef<Use> InvokeArgs, ArrayRef<Use> TransitionArgs,
651 ArrayRef<Use> DeoptArgs, ArrayRef<Value *> GCArgs,
652 const Twine &Name = "");
653
654 // Convenience function for the common case when CallArgs are filled in using
655 // makeArrayRef(CS.arg_begin(), CS.arg_end()); Use needs to be .get()'ed to
656 // get the Value *.
657 InvokeInst *
658 CreateGCStatepointInvoke(uint64_t ID, uint32_t NumPatchBytes,
659 Value *ActualInvokee, BasicBlock *NormalDest,
660 BasicBlock *UnwindDest, ArrayRef<Use> InvokeArgs,
661 ArrayRef<Value *> DeoptArgs,
662 ArrayRef<Value *> GCArgs, const Twine &Name = "");
663
664 /// Create a call to the experimental.gc.result intrinsic to extract
665 /// the result from a call wrapped in a statepoint.
666 CallInst *CreateGCResult(Instruction *Statepoint,
667 Type *ResultType,
668 const Twine &Name = "");
669
670 /// Create a call to the experimental.gc.relocate intrinsics to
671 /// project the relocated value of one pointer from the statepoint.
672 CallInst *CreateGCRelocate(Instruction *Statepoint,
673 int BaseOffset,
674 int DerivedOffset,
675 Type *ResultType,
676 const Twine &Name = "");
677
678 /// Create a call to intrinsic \p ID with 1 operand which is mangled on its
679 /// type.
680 CallInst *CreateUnaryIntrinsic(Intrinsic::ID ID, Value *V,
681 Instruction *FMFSource = nullptr,
682 const Twine &Name = "");
683
684 /// Create a call to intrinsic \p ID with 2 operands which is mangled on the
685 /// first type.
686 CallInst *CreateBinaryIntrinsic(Intrinsic::ID ID, Value *LHS, Value *RHS,
687 Instruction *FMFSource = nullptr,
688 const Twine &Name = "");
689
690 /// Create a call to intrinsic \p ID with \p args, mangled using \p Types. If
691 /// \p FMFSource is provided, copy fast-math-flags from that instruction to
692 /// the intrinsic.
693 CallInst *CreateIntrinsic(Intrinsic::ID ID, ArrayRef<Type *> Types,
694 ArrayRef<Value *> Args,
695 Instruction *FMFSource = nullptr,
696 const Twine &Name = "");
697
698 /// Create call to the minnum intrinsic.
699 CallInst *CreateMinNum(Value *LHS, Value *RHS, const Twine &Name = "") {
700 return CreateBinaryIntrinsic(Intrinsic::minnum, LHS, RHS, nullptr, Name);
701 }
702
703 /// Create call to the maxnum intrinsic.
704 CallInst *CreateMaxNum(Value *LHS, Value *RHS, const Twine &Name = "") {
705 return CreateBinaryIntrinsic(Intrinsic::maxnum, LHS, RHS, nullptr, Name);
706 }
707
708 /// Create call to the minimum intrinsic.
709 CallInst *CreateMinimum(Value *LHS, Value *RHS, const Twine &Name = "") {
710 return CreateBinaryIntrinsic(Intrinsic::minimum, LHS, RHS, nullptr, Name);
711 }
712
713 /// Create call to the maximum intrinsic.
714 CallInst *CreateMaximum(Value *LHS, Value *RHS, const Twine &Name = "") {
715 return CreateBinaryIntrinsic(Intrinsic::maximum, LHS, RHS, nullptr, Name);
716 }
717
718private:
719 /// Create a call to a masked intrinsic with given Id.
720 CallInst *CreateMaskedIntrinsic(Intrinsic::ID Id, ArrayRef<Value *> Ops,
721 ArrayRef<Type *> OverloadedTypes,
722 const Twine &Name = "");
723
724 Value *getCastedInt8PtrValue(Value *Ptr);
725};
726
727/// This provides a uniform API for creating instructions and inserting
728/// them into a basic block: either at the end of a BasicBlock, or at a specific
729/// iterator location in a block.
730///
731/// Note that the builder does not expose the full generality of LLVM
732/// instructions. For access to extra instruction properties, use the mutators
733/// (e.g. setVolatile) on the instructions after they have been
734/// created. Convenience state exists to specify fast-math flags and fp-math
735/// tags.
736///
737/// The first template argument specifies a class to use for creating constants.
738/// This defaults to creating minimally folded constants. The second template
739/// argument allows clients to specify custom insertion hooks that are called on
740/// every newly created insertion.
741template <typename T = ConstantFolder,
742 typename Inserter = IRBuilderDefaultInserter>
743class IRBuilder : public IRBuilderBase, public Inserter {
744 T Folder;
745
746public:
747 IRBuilder(LLVMContext &C, const T &F, Inserter I = Inserter(),
748 MDNode *FPMathTag = nullptr,
749 ArrayRef<OperandBundleDef> OpBundles = None)
750 : IRBuilderBase(C, FPMathTag, OpBundles), Inserter(std::move(I)),
751 Folder(F) {}
752
753 explicit IRBuilder(LLVMContext &C, MDNode *FPMathTag = nullptr,
754 ArrayRef<OperandBundleDef> OpBundles = None)
755 : IRBuilderBase(C, FPMathTag, OpBundles) {}
756
757 explicit IRBuilder(BasicBlock *TheBB, const T &F, MDNode *FPMathTag = nullptr,
758 ArrayRef<OperandBundleDef> OpBundles = None)
759 : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles), Folder(F) {
760 SetInsertPoint(TheBB);
761 }
762
763 explicit IRBuilder(BasicBlock *TheBB, MDNode *FPMathTag = nullptr,
764 ArrayRef<OperandBundleDef> OpBundles = None)
765 : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles) {
766 SetInsertPoint(TheBB);
767 }
768
769 explicit IRBuilder(Instruction *IP, MDNode *FPMathTag = nullptr,
770 ArrayRef<OperandBundleDef> OpBundles = None)
771 : IRBuilderBase(IP->getContext(), FPMathTag, OpBundles) {
772 SetInsertPoint(IP);
773 }
774
775 IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP, const T &F,
776 MDNode *FPMathTag = nullptr,
777 ArrayRef<OperandBundleDef> OpBundles = None)
778 : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles), Folder(F) {
779 SetInsertPoint(TheBB, IP);
780 }
781
782 IRBuilder(BasicBlock *TheBB, BasicBlock::iterator IP,
783 MDNode *FPMathTag = nullptr,
784 ArrayRef<OperandBundleDef> OpBundles = None)
785 : IRBuilderBase(TheBB->getContext(), FPMathTag, OpBundles) {
786 SetInsertPoint(TheBB, IP);
787 }
788
789 /// Get the constant folder being used.
790 const T &getFolder() { return Folder; }
791
792 /// Insert and return the specified instruction.
793 template<typename InstTy>
794 InstTy *Insert(InstTy *I, const Twine &Name = "") const {
795 this->InsertHelper(I, Name, BB, InsertPt);
796 this->SetInstDebugLocation(I);
797 return I;
798 }
799
800 /// No-op overload to handle constants.
801 Constant *Insert(Constant *C, const Twine& = "") const {
802 return C;
803 }
804
805 //===--------------------------------------------------------------------===//
806 // Instruction creation methods: Terminators
807 //===--------------------------------------------------------------------===//
808
809private:
810 /// Helper to add branch weight and unpredictable metadata onto an
811 /// instruction.
812 /// \returns The annotated instruction.
813 template <typename InstTy>
814 InstTy *addBranchMetadata(InstTy *I, MDNode *Weights, MDNode *Unpredictable) {
815 if (Weights)
816 I->setMetadata(LLVMContext::MD_prof, Weights);
817 if (Unpredictable)
818 I->setMetadata(LLVMContext::MD_unpredictable, Unpredictable);
819 return I;
820 }
821
822public:
823 /// Create a 'ret void' instruction.
824 ReturnInst *CreateRetVoid() {
825 return Insert(ReturnInst::Create(Context));
826 }
827
828 /// Create a 'ret <val>' instruction.
829 ReturnInst *CreateRet(Value *V) {
830 return Insert(ReturnInst::Create(Context, V));
831 }
832
833 /// Create a sequence of N insertvalue instructions,
834 /// with one Value from the retVals array each, that build a aggregate
835 /// return value one value at a time, and a ret instruction to return
836 /// the resulting aggregate value.
837 ///
838 /// This is a convenience function for code that uses aggregate return values
839 /// as a vehicle for having multiple return values.
840 ReturnInst *CreateAggregateRet(Value *const *retVals, unsigned N) {
841 Value *V = UndefValue::get(getCurrentFunctionReturnType());
842 for (unsigned i = 0; i != N; ++i)
843 V = CreateInsertValue(V, retVals[i], i, "mrv");
844 return Insert(ReturnInst::Create(Context, V));
845 }
846
847 /// Create an unconditional 'br label X' instruction.
848 BranchInst *CreateBr(BasicBlock *Dest) {
849 return Insert(BranchInst::Create(Dest));
850 }
851
852 /// Create a conditional 'br Cond, TrueDest, FalseDest'
853 /// instruction.
854 BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
855 MDNode *BranchWeights = nullptr,
856 MDNode *Unpredictable = nullptr) {
857 return Insert(addBranchMetadata(BranchInst::Create(True, False, Cond),
858 BranchWeights, Unpredictable));
859 }
860
861 /// Create a conditional 'br Cond, TrueDest, FalseDest'
862 /// instruction. Copy branch meta data if available.
863 BranchInst *CreateCondBr(Value *Cond, BasicBlock *True, BasicBlock *False,
864 Instruction *MDSrc) {
865 BranchInst *Br = BranchInst::Create(True, False, Cond);
866 if (MDSrc) {
867 unsigned WL[4] = {LLVMContext::MD_prof, LLVMContext::MD_unpredictable,
868 LLVMContext::MD_make_implicit, LLVMContext::MD_dbg};
869 Br->copyMetadata(*MDSrc, makeArrayRef(&WL[0], 4));
870 }
871 return Insert(Br);
872 }
873
874 /// Create a switch instruction with the specified value, default dest,
875 /// and with a hint for the number of cases that will be added (for efficient
876 /// allocation).
877 SwitchInst *CreateSwitch(Value *V, BasicBlock *Dest, unsigned NumCases = 10,
878 MDNode *BranchWeights = nullptr,
879 MDNode *Unpredictable = nullptr) {
880 return Insert(addBranchMetadata(SwitchInst::Create(V, Dest, NumCases),
881 BranchWeights, Unpredictable));
882 }
883
884 /// Create an indirect branch instruction with the specified address
885 /// operand, with an optional hint for the number of destinations that will be
886 /// added (for efficient allocation).
887 IndirectBrInst *CreateIndirectBr(Value *Addr, unsigned NumDests = 10) {
888 return Insert(IndirectBrInst::Create(Addr, NumDests));
889 }
890
891 /// Create an invoke instruction.
892 InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
893 BasicBlock *UnwindDest,
894 ArrayRef<Value *> Args = None,
895 const Twine &Name = "") {
896 return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args),
897 Name);
898 }
899 InvokeInst *CreateInvoke(Value *Callee, BasicBlock *NormalDest,
900 BasicBlock *UnwindDest, ArrayRef<Value *> Args,
901 ArrayRef<OperandBundleDef> OpBundles,
902 const Twine &Name = "") {
903 return Insert(InvokeInst::Create(Callee, NormalDest, UnwindDest, Args,
904 OpBundles), Name);
905 }
906
907 ResumeInst *CreateResume(Value *Exn) {
908 return Insert(ResumeInst::Create(Exn));
909 }
910
911 CleanupReturnInst *CreateCleanupRet(CleanupPadInst *CleanupPad,
912 BasicBlock *UnwindBB = nullptr) {
913 return Insert(CleanupReturnInst::Create(CleanupPad, UnwindBB));
914 }
915
916 CatchSwitchInst *CreateCatchSwitch(Value *ParentPad, BasicBlock *UnwindBB,
917 unsigned NumHandlers,
918 const Twine &Name = "") {
919 return Insert(CatchSwitchInst::Create(ParentPad, UnwindBB, NumHandlers),
920 Name);
921 }
922
923 CatchPadInst *CreateCatchPad(Value *ParentPad, ArrayRef<Value *> Args,
924 const Twine &Name = "") {
925 return Insert(CatchPadInst::Create(ParentPad, Args), Name);
926 }
927
928 CleanupPadInst *CreateCleanupPad(Value *ParentPad,
929 ArrayRef<Value *> Args = None,
930 const Twine &Name = "") {
931 return Insert(CleanupPadInst::Create(ParentPad, Args), Name);
932 }
933
934 CatchReturnInst *CreateCatchRet(CatchPadInst *CatchPad, BasicBlock *BB) {
935 return Insert(CatchReturnInst::Create(CatchPad, BB));
936 }
937
938 UnreachableInst *CreateUnreachable() {
939 return Insert(new UnreachableInst(Context));
940 }
941
942 //===--------------------------------------------------------------------===//
943 // Instruction creation methods: Binary Operators
944 //===--------------------------------------------------------------------===//
945private:
946 BinaryOperator *CreateInsertNUWNSWBinOp(BinaryOperator::BinaryOps Opc,
947 Value *LHS, Value *RHS,
948 const Twine &Name,
949 bool HasNUW, bool HasNSW) {
950 BinaryOperator *BO = Insert(BinaryOperator::Create(Opc, LHS, RHS), Name);
951 if (HasNUW) BO->setHasNoUnsignedWrap();
952 if (HasNSW) BO->setHasNoSignedWrap();
953 return BO;
954 }
955
956 Instruction *setFPAttrs(Instruction *I, MDNode *FPMD,
957 FastMathFlags FMF) const {
958 if (!FPMD)
959 FPMD = DefaultFPMathTag;
960 if (FPMD)
961 I->setMetadata(LLVMContext::MD_fpmath, FPMD);
962 I->setFastMathFlags(FMF);
963 return I;
964 }
965
966 Value *foldConstant(Instruction::BinaryOps Opc, Value *L,
967 Value *R, const Twine &Name = nullptr) const {
968 auto *LC = dyn_cast<Constant>(L);
969 auto *RC = dyn_cast<Constant>(R);
970 return (LC && RC) ? Insert(Folder.CreateBinOp(Opc, LC, RC), Name) : nullptr;
971 }
972
973public:
974 Value *CreateAdd(Value *LHS, Value *RHS, const Twine &Name = "",
975 bool HasNUW = false, bool HasNSW = false) {
976 if (auto *LC = dyn_cast<Constant>(LHS))
977 if (auto *RC = dyn_cast<Constant>(RHS))
978 return Insert(Folder.CreateAdd(LC, RC, HasNUW, HasNSW), Name);
979 return CreateInsertNUWNSWBinOp(Instruction::Add, LHS, RHS, Name,
980 HasNUW, HasNSW);
981 }
982
983 Value *CreateNSWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
984 return CreateAdd(LHS, RHS, Name, false, true);
985 }
986
987 Value *CreateNUWAdd(Value *LHS, Value *RHS, const Twine &Name = "") {
988 return CreateAdd(LHS, RHS, Name, true, false);
989 }
990
991 Value *CreateSub(Value *LHS, Value *RHS, const Twine &Name = "",
992 bool HasNUW = false, bool HasNSW = false) {
993 if (auto *LC = dyn_cast<Constant>(LHS))
994 if (auto *RC = dyn_cast<Constant>(RHS))
995 return Insert(Folder.CreateSub(LC, RC, HasNUW, HasNSW), Name);
996 return CreateInsertNUWNSWBinOp(Instruction::Sub, LHS, RHS, Name,
997 HasNUW, HasNSW);
998 }
999
1000 Value *CreateNSWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
1001 return CreateSub(LHS, RHS, Name, false, true);
1002 }
1003
1004 Value *CreateNUWSub(Value *LHS, Value *RHS, const Twine &Name = "") {
1005 return CreateSub(LHS, RHS, Name, true, false);
1006 }
1007
1008 Value *CreateMul(Value *LHS, Value *RHS, const Twine &Name = "",
1009 bool HasNUW = false, bool HasNSW = false) {
1010 if (auto *LC = dyn_cast<Constant>(LHS))
1011 if (auto *RC = dyn_cast<Constant>(RHS))
1012 return Insert(Folder.CreateMul(LC, RC, HasNUW, HasNSW), Name);
1013 return CreateInsertNUWNSWBinOp(Instruction::Mul, LHS, RHS, Name,
1014 HasNUW, HasNSW);
1015 }
1016
1017 Value *CreateNSWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
1018 return CreateMul(LHS, RHS, Name, false, true);
1019 }
1020
1021 Value *CreateNUWMul(Value *LHS, Value *RHS, const Twine &Name = "") {
1022 return CreateMul(LHS, RHS, Name, true, false);
1023 }
1024
1025 Value *CreateUDiv(Value *LHS, Value *RHS, const Twine &Name = "",
1026 bool isExact = false) {
1027 if (auto *LC = dyn_cast<Constant>(LHS))
1028 if (auto *RC = dyn_cast<Constant>(RHS))
1029 return Insert(Folder.CreateUDiv(LC, RC, isExact), Name);
1030 if (!isExact)
1031 return Insert(BinaryOperator::CreateUDiv(LHS, RHS), Name);
1032 return Insert(BinaryOperator::CreateExactUDiv(LHS, RHS), Name);
1033 }
1034
1035 Value *CreateExactUDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
1036 return CreateUDiv(LHS, RHS, Name, true);
1037 }
1038
1039 Value *CreateSDiv(Value *LHS, Value *RHS, const Twine &Name = "",
1040 bool isExact = false) {
1041 if (auto *LC = dyn_cast<Constant>(LHS))
1042 if (auto *RC = dyn_cast<Constant>(RHS))
1043 return Insert(Folder.CreateSDiv(LC, RC, isExact), Name);
1044 if (!isExact)
1045 return Insert(BinaryOperator::CreateSDiv(LHS, RHS), Name);
1046 return Insert(BinaryOperator::CreateExactSDiv(LHS, RHS), Name);
1047 }
1048
1049 Value *CreateExactSDiv(Value *LHS, Value *RHS, const Twine &Name = "") {
1050 return CreateSDiv(LHS, RHS, Name, true);
1051 }
1052
1053 Value *CreateURem(Value *LHS, Value *RHS, const Twine &Name = "") {
1054 if (Value *V = foldConstant(Instruction::URem, LHS, RHS, Name)) return V;
1055 return Insert(BinaryOperator::CreateURem(LHS, RHS), Name);
1056 }
1057
1058 Value *CreateSRem(Value *LHS, Value *RHS, const Twine &Name = "") {
1059 if (Value *V = foldConstant(Instruction::SRem, LHS, RHS, Name)) return V;
1060 return Insert(BinaryOperator::CreateSRem(LHS, RHS), Name);
1061 }
1062
1063 Value *CreateShl(Value *LHS, Value *RHS, const Twine &Name = "",
1064 bool HasNUW = false, bool HasNSW = false) {
1065 if (auto *LC = dyn_cast<Constant>(LHS))
1066 if (auto *RC = dyn_cast<Constant>(RHS))
1067 return Insert(Folder.CreateShl(LC, RC, HasNUW, HasNSW), Name);
1068 return CreateInsertNUWNSWBinOp(Instruction::Shl, LHS, RHS, Name,
1069 HasNUW, HasNSW);
1070 }
1071
1072 Value *CreateShl(Value *LHS, const APInt &RHS, const Twine &Name = "",
1073 bool HasNUW = false, bool HasNSW = false) {
1074 return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
1075 HasNUW, HasNSW);
1076 }
1077
1078 Value *CreateShl(Value *LHS, uint64_t RHS, const Twine &Name = "",
1079 bool HasNUW = false, bool HasNSW = false) {
1080 return CreateShl(LHS, ConstantInt::get(LHS->getType(), RHS), Name,
1081 HasNUW, HasNSW);
1082 }
1083
1084 Value *CreateLShr(Value *LHS, Value *RHS, const Twine &Name = "",
1085 bool isExact = false) {
1086 if (auto *LC = dyn_cast<Constant>(LHS))
1087 if (auto *RC = dyn_cast<Constant>(RHS))
1088 return Insert(Folder.CreateLShr(LC, RC, isExact), Name);
1089 if (!isExact)
1090 return Insert(BinaryOperator::CreateLShr(LHS, RHS), Name);
1091 return Insert(BinaryOperator::CreateExactLShr(LHS, RHS), Name);
1092 }
1093
1094 Value *CreateLShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
1095 bool isExact = false) {
1096 return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1097 }
1098
1099 Value *CreateLShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
1100 bool isExact = false) {
1101 return CreateLShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1102 }
1103
1104 Value *CreateAShr(Value *LHS, Value *RHS, const Twine &Name = "",
1105 bool isExact = false) {
1106 if (auto *LC = dyn_cast<Constant>(LHS))
1107 if (auto *RC = dyn_cast<Constant>(RHS))
1108 return Insert(Folder.CreateAShr(LC, RC, isExact), Name);
1109 if (!isExact)
1110 return Insert(BinaryOperator::CreateAShr(LHS, RHS), Name);
1111 return Insert(BinaryOperator::CreateExactAShr(LHS, RHS), Name);
1112 }
1113
1114 Value *CreateAShr(Value *LHS, const APInt &RHS, const Twine &Name = "",
1115 bool isExact = false) {
1116 return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1117 }
1118
1119 Value *CreateAShr(Value *LHS, uint64_t RHS, const Twine &Name = "",
1120 bool isExact = false) {
1121 return CreateAShr(LHS, ConstantInt::get(LHS->getType(), RHS), Name,isExact);
1122 }
1123
1124 Value *CreateAnd(Value *LHS, Value *RHS, const Twine &Name = "") {
1125 if (auto *RC = dyn_cast<Constant>(RHS)) {
1126 if (isa<ConstantInt>(RC) && cast<ConstantInt>(RC)->isMinusOne())
1127 return LHS; // LHS & -1 -> LHS
1128 if (auto *LC = dyn_cast<Constant>(LHS))
1129 return Insert(Folder.CreateAnd(LC, RC), Name);
1130 }
1131 return Insert(BinaryOperator::CreateAnd(LHS, RHS), Name);
1132 }
1133
1134 Value *CreateAnd(Value *LHS, const APInt &RHS, const Twine &Name = "") {
1135 return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1136 }
1137
1138 Value *CreateAnd(Value *LHS, uint64_t RHS, const Twine &Name = "") {
1139 return CreateAnd(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1140 }
1141
1142 Value *CreateOr(Value *LHS, Value *RHS, const Twine &Name = "") {
1143 if (auto *RC = dyn_cast<Constant>(RHS)) {
1144 if (RC->isNullValue())
1145 return LHS; // LHS | 0 -> LHS
1146 if (auto *LC = dyn_cast<Constant>(LHS))
1147 return Insert(Folder.CreateOr(LC, RC), Name);
1148 }
1149 return Insert(BinaryOperator::CreateOr(LHS, RHS), Name);
1150 }
1151
1152 Value *CreateOr(Value *LHS, const APInt &RHS, const Twine &Name = "") {
1153 return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1154 }
1155
1156 Value *CreateOr(Value *LHS, uint64_t RHS, const Twine &Name = "") {
1157 return CreateOr(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1158 }
1159
1160 Value *CreateXor(Value *LHS, Value *RHS, const Twine &Name = "") {
1161 if (Value *V = foldConstant(Instruction::Xor, LHS, RHS, Name)) return V;
1162 return Insert(BinaryOperator::CreateXor(LHS, RHS), Name);
1163 }
1164
1165 Value *CreateXor(Value *LHS, const APInt &RHS, const Twine &Name = "") {
1166 return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1167 }
1168
1169 Value *CreateXor(Value *LHS, uint64_t RHS, const Twine &Name = "") {
1170 return CreateXor(LHS, ConstantInt::get(LHS->getType(), RHS), Name);
1171 }
1172
1173 Value *CreateFAdd(Value *L, Value *R, const Twine &Name = "",
1174 MDNode *FPMD = nullptr) {
1175 if (Value *V = foldConstant(Instruction::FAdd, L, R, Name)) return V;
1176 Instruction *I = setFPAttrs(BinaryOperator::CreateFAdd(L, R), FPMD, FMF);
1177 return Insert(I, Name);
1178 }
1179
1180 /// Copy fast-math-flags from an instruction rather than using the builder's
1181 /// default FMF.
1182 Value *CreateFAddFMF(Value *L, Value *R, Instruction *FMFSource,
1183 const Twine &Name = "") {
1184 if (Value *V = foldConstant(Instruction::FAdd, L, R, Name)) return V;
1185 Instruction *I = setFPAttrs(BinaryOperator::CreateFAdd(L, R), nullptr,
1186 FMFSource->getFastMathFlags());
1187 return Insert(I, Name);
1188 }
1189
1190 Value *CreateFSub(Value *L, Value *R, const Twine &Name = "",
1191 MDNode *FPMD = nullptr) {
1192 if (Value *V = foldConstant(Instruction::FSub, L, R, Name)) return V;
1193 Instruction *I = setFPAttrs(BinaryOperator::CreateFSub(L, R), FPMD, FMF);
1194 return Insert(I, Name);
1195 }
1196
1197 /// Copy fast-math-flags from an instruction rather than using the builder's
1198 /// default FMF.
1199 Value *CreateFSubFMF(Value *L, Value *R, Instruction *FMFSource,
1200 const Twine &Name = "") {
1201 if (Value *V = foldConstant(Instruction::FSub, L, R, Name)) return V;
1202 Instruction *I = setFPAttrs(BinaryOperator::CreateFSub(L, R), nullptr,
1203 FMFSource->getFastMathFlags());
1204 return Insert(I, Name);
1205 }
1206
1207 Value *CreateFMul(Value *L, Value *R, const Twine &Name = "",
1208 MDNode *FPMD = nullptr) {
1209 if (Value *V = foldConstant(Instruction::FMul, L, R, Name)) return V;
1210 Instruction *I = setFPAttrs(BinaryOperator::CreateFMul(L, R), FPMD, FMF);
1211 return Insert(I, Name);
1212 }
1213
1214 /// Copy fast-math-flags from an instruction rather than using the builder's
1215 /// default FMF.
1216 Value *CreateFMulFMF(Value *L, Value *R, Instruction *FMFSource,
1217 const Twine &Name = "") {
1218 if (Value *V = foldConstant(Instruction::FMul, L, R, Name)) return V;
1219 Instruction *I = setFPAttrs(BinaryOperator::CreateFMul(L, R), nullptr,
1220 FMFSource->getFastMathFlags());
1221 return Insert(I, Name);
1222 }
1223
1224 Value *CreateFDiv(Value *L, Value *R, const Twine &Name = "",
1225 MDNode *FPMD = nullptr) {
1226 if (Value *V = foldConstant(Instruction::FDiv, L, R, Name)) return V;
1227 Instruction *I = setFPAttrs(BinaryOperator::CreateFDiv(L, R), FPMD, FMF);
1228 return Insert(I, Name);
1229 }
1230
1231 /// Copy fast-math-flags from an instruction rather than using the builder's
1232 /// default FMF.
1233 Value *CreateFDivFMF(Value *L, Value *R, Instruction *FMFSource,
1234 const Twine &Name = "") {
1235 if (Value *V = foldConstant(Instruction::FDiv, L, R, Name)) return V;
1236 Instruction *I = setFPAttrs(BinaryOperator::CreateFDiv(L, R), nullptr,
1237 FMFSource->getFastMathFlags());
1238 return Insert(I, Name);
1239 }
1240
1241 Value *CreateFRem(Value *L, Value *R, const Twine &Name = "",
1242 MDNode *FPMD = nullptr) {
1243 if (Value *V = foldConstant(Instruction::FRem, L, R, Name)) return V;
1244 Instruction *I = setFPAttrs(BinaryOperator::CreateFRem(L, R), FPMD, FMF);
1245 return Insert(I, Name);
1246 }
1247
1248 /// Copy fast-math-flags from an instruction rather than using the builder's
1249 /// default FMF.
1250 Value *CreateFRemFMF(Value *L, Value *R, Instruction *FMFSource,
1251 const Twine &Name = "") {
1252 if (Value *V = foldConstant(Instruction::FRem, L, R, Name)) return V;
1253 Instruction *I = setFPAttrs(BinaryOperator::CreateFRem(L, R), nullptr,
1254 FMFSource->getFastMathFlags());
1255 return Insert(I, Name);
1256 }
1257
1258 Value *CreateBinOp(Instruction::BinaryOps Opc,
1259 Value *LHS, Value *RHS, const Twine &Name = "",
1260 MDNode *FPMathTag = nullptr) {
1261 if (Value *V = foldConstant(Opc, LHS, RHS, Name)) return V;
1262 Instruction *BinOp = BinaryOperator::Create(Opc, LHS, RHS);
1263 if (isa<FPMathOperator>(BinOp))
1264 BinOp = setFPAttrs(BinOp, FPMathTag, FMF);
1265 return Insert(BinOp, Name);
1266 }
1267
1268 Value *CreateNeg(Value *V, const Twine &Name = "",
1269 bool HasNUW = false, bool HasNSW = false) {
1270 if (auto *VC = dyn_cast<Constant>(V))
1271 return Insert(Folder.CreateNeg(VC, HasNUW, HasNSW), Name);
1272 BinaryOperator *BO = Insert(BinaryOperator::CreateNeg(V), Name);
1273 if (HasNUW) BO->setHasNoUnsignedWrap();
1274 if (HasNSW) BO->setHasNoSignedWrap();
1275 return BO;
1276 }
1277
1278 Value *CreateNSWNeg(Value *V, const Twine &Name = "") {
1279 return CreateNeg(V, Name, false, true);
1280 }
1281
1282 Value *CreateNUWNeg(Value *V, const Twine &Name = "") {
1283 return CreateNeg(V, Name, true, false);
1284 }
1285
1286 Value *CreateFNeg(Value *V, const Twine &Name = "",
1287 MDNode *FPMathTag = nullptr) {
1288 if (auto *VC = dyn_cast<Constant>(V))
1289 return Insert(Folder.CreateFNeg(VC), Name);
1290 return Insert(setFPAttrs(BinaryOperator::CreateFNeg(V), FPMathTag, FMF),
1291 Name);
1292 }
1293
1294 Value *CreateNot(Value *V, const Twine &Name = "") {
1295 if (auto *VC = dyn_cast<Constant>(V))
1296 return Insert(Folder.CreateNot(VC), Name);
1297 return Insert(BinaryOperator::CreateNot(V), Name);
1298 }
1299
1300 //===--------------------------------------------------------------------===//
1301 // Instruction creation methods: Memory Instructions
1302 //===--------------------------------------------------------------------===//
1303
1304 AllocaInst *CreateAlloca(Type *Ty, unsigned AddrSpace,
1305 Value *ArraySize = nullptr, const Twine &Name = "") {
1306 return Insert(new AllocaInst(Ty, AddrSpace, ArraySize), Name);
1307 }
1308
1309 AllocaInst *CreateAlloca(Type *Ty, Value *ArraySize = nullptr,
1310 const Twine &Name = "") {
1311 const DataLayout &DL = BB->getParent()->getParent()->getDataLayout();
1312 return Insert(new AllocaInst(Ty, DL.getAllocaAddrSpace(), ArraySize), Name);
1313 }
1314
1315 /// Provided to resolve 'CreateLoad(Ptr, "...")' correctly, instead of
1316 /// converting the string to 'bool' for the isVolatile parameter.
1317 LoadInst *CreateLoad(Value *Ptr, const char *Name) {
1318 return Insert(new LoadInst(Ptr), Name);
1319 }
1320
1321 LoadInst *CreateLoad(Value *Ptr, const Twine &Name = "") {
1322 return Insert(new LoadInst(Ptr), Name);
1323 }
1324
1325 LoadInst *CreateLoad(Type *Ty, Value *Ptr, const Twine &Name = "") {
1326 return Insert(new LoadInst(Ty, Ptr), Name);
1327 }
1328
1329 LoadInst *CreateLoad(Value *Ptr, bool isVolatile, const Twine &Name = "") {
1330 return Insert(new LoadInst(Ptr, nullptr, isVolatile), Name);
1331 }
1332
1333 StoreInst *CreateStore(Value *Val, Value *Ptr, bool isVolatile = false) {
1334 return Insert(new StoreInst(Val, Ptr, isVolatile));
1335 }
1336
1337 /// Provided to resolve 'CreateAlignedLoad(Ptr, Align, "...")'
1338 /// correctly, instead of converting the string to 'bool' for the isVolatile
1339 /// parameter.
1340 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, const char *Name) {
1341 LoadInst *LI = CreateLoad(Ptr, Name);
1342 LI->setAlignment(Align);
1343 return LI;
1344 }
1345 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align,
1346 const Twine &Name = "") {
1347 LoadInst *LI = CreateLoad(Ptr, Name);
1348 LI->setAlignment(Align);
1349 return LI;
1350 }
1351 LoadInst *CreateAlignedLoad(Value *Ptr, unsigned Align, bool isVolatile,
1352 const Twine &Name = "") {
1353 LoadInst *LI = CreateLoad(Ptr, isVolatile, Name);
1354 LI->setAlignment(Align);
1355 return LI;
1356 }
1357
1358 StoreInst *CreateAlignedStore(Value *Val, Value *Ptr, unsigned Align,
1359 bool isVolatile = false) {
1360 StoreInst *SI = CreateStore(Val, Ptr, isVolatile);
1361 SI->setAlignment(Align);
1362 return SI;
1363 }
1364
1365 FenceInst *CreateFence(AtomicOrdering Ordering,
1366 SyncScope::ID SSID = SyncScope::System,
1367 const Twine &Name = "") {
1368 return Insert(new FenceInst(Context, Ordering, SSID), Name);
1369 }
1370
1371 AtomicCmpXchgInst *
1372 CreateAtomicCmpXchg(Value *Ptr, Value *Cmp, Value *New,
1373 AtomicOrdering SuccessOrdering,
1374 AtomicOrdering FailureOrdering,
1375 SyncScope::ID SSID = SyncScope::System) {
1376 return Insert(new AtomicCmpXchgInst(Ptr, Cmp, New, SuccessOrdering,
1377 FailureOrdering, SSID));
1378 }
1379
1380 AtomicRMWInst *CreateAtomicRMW(AtomicRMWInst::BinOp Op, Value *Ptr, Value *Val,
1381 AtomicOrdering Ordering,
1382 SyncScope::ID SSID = SyncScope::System) {
1383 return Insert(new AtomicRMWInst(Op, Ptr, Val, Ordering, SSID));
1384 }
1385
1386 Value *CreateGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1387 const Twine &Name = "") {
1388 return CreateGEP(nullptr, Ptr, IdxList, Name);
1389 }
1390
1391 Value *CreateGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1392 const Twine &Name = "") {
1393 if (auto *PC = dyn_cast<Constant>(Ptr)) {
1394 // Every index must be constant.
1395 size_t i, e;
1396 for (i = 0, e = IdxList.size(); i != e; ++i)
1397 if (!isa<Constant>(IdxList[i]))
1398 break;
1399 if (i == e)
1400 return Insert(Folder.CreateGetElementPtr(Ty, PC, IdxList), Name);
1401 }
1402 return Insert(GetElementPtrInst::Create(Ty, Ptr, IdxList), Name);
1403 }
1404
1405 Value *CreateInBoundsGEP(Value *Ptr, ArrayRef<Value *> IdxList,
1406 const Twine &Name = "") {
1407 return CreateInBoundsGEP(nullptr, Ptr, IdxList, Name);
1408 }
1409
1410 Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, ArrayRef<Value *> IdxList,
1411 const Twine &Name = "") {
1412 if (auto *PC = dyn_cast<Constant>(Ptr)) {
1413 // Every index must be constant.
1414 size_t i, e;
1415 for (i = 0, e = IdxList.size(); i != e; ++i)
1416 if (!isa<Constant>(IdxList[i]))
1417 break;
1418 if (i == e)
1419 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IdxList),
1420 Name);
1421 }
1422 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, IdxList), Name);
1423 }
1424
1425 Value *CreateGEP(Value *Ptr, Value *Idx, const Twine &Name = "") {
1426 return CreateGEP(nullptr, Ptr, Idx, Name);
1427 }
1428
1429 Value *CreateGEP(Type *Ty, Value *Ptr, Value *Idx, const Twine &Name = "") {
1430 if (auto *PC = dyn_cast<Constant>(Ptr))
1431 if (auto *IC = dyn_cast<Constant>(Idx))
1432 return Insert(Folder.CreateGetElementPtr(Ty, PC, IC), Name);
1433 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1434 }
1435
1436 Value *CreateInBoundsGEP(Type *Ty, Value *Ptr, Value *Idx,
1437 const Twine &Name = "") {
1438 if (auto *PC = dyn_cast<Constant>(Ptr))
1439 if (auto *IC = dyn_cast<Constant>(Idx))
1440 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, IC), Name);
1441 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1442 }
1443
1444 Value *CreateConstGEP1_32(Value *Ptr, unsigned Idx0, const Twine &Name = "") {
1445 return CreateConstGEP1_32(nullptr, Ptr, Idx0, Name);
1446 }
1447
1448 Value *CreateConstGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1449 const Twine &Name = "") {
1450 Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1451
1452 if (auto *PC = dyn_cast<Constant>(Ptr))
1453 return Insert(Folder.CreateGetElementPtr(Ty, PC, Idx), Name);
1454
1455 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idx), Name);
1456 }
1457
1458 Value *CreateConstInBoundsGEP1_32(Type *Ty, Value *Ptr, unsigned Idx0,
1459 const Twine &Name = "") {
1460 Value *Idx = ConstantInt::get(Type::getInt32Ty(Context), Idx0);
1461
1462 if (auto *PC = dyn_cast<Constant>(Ptr))
1463 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idx), Name);
1464
1465 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idx), Name);
1466 }
1467
1468 Value *CreateConstGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0, unsigned Idx1,
1469 const Twine &Name = "") {
1470 Value *Idxs[] = {
1471 ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1472 ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1473 };
1474
1475 if (auto *PC = dyn_cast<Constant>(Ptr))
1476 return Insert(Folder.CreateGetElementPtr(Ty, PC, Idxs), Name);
1477
1478 return Insert(GetElementPtrInst::Create(Ty, Ptr, Idxs), Name);
1479 }
1480
1481 Value *CreateConstInBoundsGEP2_32(Type *Ty, Value *Ptr, unsigned Idx0,
1482 unsigned Idx1, const Twine &Name = "") {
1483 Value *Idxs[] = {
1484 ConstantInt::get(Type::getInt32Ty(Context), Idx0),
1485 ConstantInt::get(Type::getInt32Ty(Context), Idx1)
1486 };
1487
1488 if (auto *PC = dyn_cast<Constant>(Ptr))
1489 return Insert(Folder.CreateInBoundsGetElementPtr(Ty, PC, Idxs), Name);
1490
1491 return Insert(GetElementPtrInst::CreateInBounds(Ty, Ptr, Idxs), Name);
1492 }
1493
1494 Value *CreateConstGEP1_64(Value *Ptr, uint64_t Idx0, const Twine &Name = "") {
1495 Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1496
1497 if (auto *PC = dyn_cast<Constant>(Ptr))
1498 return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idx), Name);
1499
1500 return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idx), Name);
1501 }
1502
1503 Value *CreateConstInBoundsGEP1_64(Value *Ptr, uint64_t Idx0,
1504 const Twine &Name = "") {
1505 Value *Idx = ConstantInt::get(Type::getInt64Ty(Context), Idx0);
1506
1507 if (auto *PC = dyn_cast<Constant>(Ptr))
1508 return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idx), Name);
1509
1510 return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idx), Name);
1511 }
1512
1513 Value *CreateConstGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1514 const Twine &Name = "") {
1515 Value *Idxs[] = {
1516 ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1517 ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1518 };
1519
1520 if (auto *PC = dyn_cast<Constant>(Ptr))
1521 return Insert(Folder.CreateGetElementPtr(nullptr, PC, Idxs), Name);
1522
1523 return Insert(GetElementPtrInst::Create(nullptr, Ptr, Idxs), Name);
1524 }
1525
1526 Value *CreateConstInBoundsGEP2_64(Value *Ptr, uint64_t Idx0, uint64_t Idx1,
1527 const Twine &Name = "") {
1528 Value *Idxs[] = {
1529 ConstantInt::get(Type::getInt64Ty(Context), Idx0),
1530 ConstantInt::get(Type::getInt64Ty(Context), Idx1)
1531 };
1532
1533 if (auto *PC = dyn_cast<Constant>(Ptr))
1534 return Insert(Folder.CreateInBoundsGetElementPtr(nullptr, PC, Idxs),
1535 Name);
1536
1537 return Insert(GetElementPtrInst::CreateInBounds(nullptr, Ptr, Idxs), Name);
1538 }
1539
1540 Value *CreateStructGEP(Type *Ty, Value *Ptr, unsigned Idx,
1541 const Twine &Name = "") {
1542 return CreateConstInBoundsGEP2_32(Ty, Ptr, 0, Idx, Name);
1543 }
1544
1545 Value *CreateStructGEP(Value *Ptr, unsigned Idx, const Twine &Name = "") {
1546 return CreateConstInBoundsGEP2_32(nullptr, Ptr, 0, Idx, Name);
1547 }
1548
1549 /// Same as CreateGlobalString, but return a pointer with "i8*" type
1550 /// instead of a pointer to array of i8.
1551 Constant *CreateGlobalStringPtr(StringRef Str, const Twine &Name = "",
1552 unsigned AddressSpace = 0) {
1553 GlobalVariable *GV = CreateGlobalString(Str, Name, AddressSpace);
1554 Constant *Zero = ConstantInt::get(Type::getInt32Ty(Context), 0);
1555 Constant *Indices[] = {Zero, Zero};
1556 return ConstantExpr::getInBoundsGetElementPtr(GV->getValueType(), GV,
1557 Indices);
1558 }
1559
1560 //===--------------------------------------------------------------------===//
1561 // Instruction creation methods: Cast/Conversion Operators
1562 //===--------------------------------------------------------------------===//
1563
1564 Value *CreateTrunc(Value *V, Type *DestTy, const Twine &Name = "") {
1565 return CreateCast(Instruction::Trunc, V, DestTy, Name);
1566 }
1567
1568 Value *CreateZExt(Value *V, Type *DestTy, const Twine &Name = "") {
1569 return CreateCast(Instruction::ZExt, V, DestTy, Name);
1570 }
1571
1572 Value *CreateSExt(Value *V, Type *DestTy, const Twine &Name = "") {
1573 return CreateCast(Instruction::SExt, V, DestTy, Name);
1574 }
1575
1576 /// Create a ZExt or Trunc from the integer value V to DestTy. Return
1577 /// the value untouched if the type of V is already DestTy.
1578 Value *CreateZExtOrTrunc(Value *V, Type *DestTy,
1579 const Twine &Name = "") {
1580 assert(V->getType()->isIntOrIntVectorTy() &&((V->getType()->isIntOrIntVectorTy() && DestTy->
isIntOrIntVectorTy() && "Can only zero extend/truncate integers!"
) ? static_cast<void> (0) : __assert_fail ("V->getType()->isIntOrIntVectorTy() && DestTy->isIntOrIntVectorTy() && \"Can only zero extend/truncate integers!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/IRBuilder.h"
, 1582, __PRETTY_FUNCTION__))
1581 DestTy->isIntOrIntVectorTy() &&((V->getType()->isIntOrIntVectorTy() && DestTy->
isIntOrIntVectorTy() && "Can only zero extend/truncate integers!"
) ? static_cast<void> (0) : __assert_fail ("V->getType()->isIntOrIntVectorTy() && DestTy->isIntOrIntVectorTy() && \"Can only zero extend/truncate integers!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/IRBuilder.h"
, 1582, __PRETTY_FUNCTION__))
1582 "Can only zero extend/truncate integers!")((V->getType()->isIntOrIntVectorTy() && DestTy->
isIntOrIntVectorTy() && "Can only zero extend/truncate integers!"
) ? static_cast<void> (0) : __assert_fail ("V->getType()->isIntOrIntVectorTy() && DestTy->isIntOrIntVectorTy() && \"Can only zero extend/truncate integers!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/IRBuilder.h"
, 1582, __PRETTY_FUNCTION__))
;
1583 Type *VTy = V->getType();
1584 if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1585 return CreateZExt(V, DestTy, Name);
1586 if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1587 return CreateTrunc(V, DestTy, Name);
1588 return V;
1589 }
1590
1591 /// Create a SExt or Trunc from the integer value V to DestTy. Return
1592 /// the value untouched if the type of V is already DestTy.
1593 Value *CreateSExtOrTrunc(Value *V, Type *DestTy,
1594 const Twine &Name = "") {
1595 assert(V->getType()->isIntOrIntVectorTy() &&((V->getType()->isIntOrIntVectorTy() && DestTy->
isIntOrIntVectorTy() && "Can only sign extend/truncate integers!"
) ? static_cast<void> (0) : __assert_fail ("V->getType()->isIntOrIntVectorTy() && DestTy->isIntOrIntVectorTy() && \"Can only sign extend/truncate integers!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/IRBuilder.h"
, 1597, __PRETTY_FUNCTION__))
1596 DestTy->isIntOrIntVectorTy() &&((V->getType()->isIntOrIntVectorTy() && DestTy->
isIntOrIntVectorTy() && "Can only sign extend/truncate integers!"
) ? static_cast<void> (0) : __assert_fail ("V->getType()->isIntOrIntVectorTy() && DestTy->isIntOrIntVectorTy() && \"Can only sign extend/truncate integers!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/IRBuilder.h"
, 1597, __PRETTY_FUNCTION__))
1597 "Can only sign extend/truncate integers!")((V->getType()->isIntOrIntVectorTy() && DestTy->
isIntOrIntVectorTy() && "Can only sign extend/truncate integers!"
) ? static_cast<void> (0) : __assert_fail ("V->getType()->isIntOrIntVectorTy() && DestTy->isIntOrIntVectorTy() && \"Can only sign extend/truncate integers!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/IRBuilder.h"
, 1597, __PRETTY_FUNCTION__))
;
1598 Type *VTy = V->getType();
1599 if (VTy->getScalarSizeInBits() < DestTy->getScalarSizeInBits())
1600 return CreateSExt(V, DestTy, Name);
1601 if (VTy->getScalarSizeInBits() > DestTy->getScalarSizeInBits())
1602 return CreateTrunc(V, DestTy, Name);
1603 return V;
1604 }
1605
1606 Value *CreateFPToUI(Value *V, Type *DestTy, const Twine &Name = ""){
1607 return CreateCast(Instruction::FPToUI, V, DestTy, Name);
1608 }
1609
1610 Value *CreateFPToSI(Value *V, Type *DestTy, const Twine &Name = ""){
1611 return CreateCast(Instruction::FPToSI, V, DestTy, Name);
1612 }
1613
1614 Value *CreateUIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1615 return CreateCast(Instruction::UIToFP, V, DestTy, Name);
1616 }
1617
1618 Value *CreateSIToFP(Value *V, Type *DestTy, const Twine &Name = ""){
1619 return CreateCast(Instruction::SIToFP, V, DestTy, Name);
1620 }
1621
1622 Value *CreateFPTrunc(Value *V, Type *DestTy,
1623 const Twine &Name = "") {
1624 return CreateCast(Instruction::FPTrunc, V, DestTy, Name);
1625 }
1626
1627 Value *CreateFPExt(Value *V, Type *DestTy, const Twine &Name = "") {
1628 return CreateCast(Instruction::FPExt, V, DestTy, Name);
1629 }
1630
1631 Value *CreatePtrToInt(Value *V, Type *DestTy,
1632 const Twine &Name = "") {
1633 return CreateCast(Instruction::PtrToInt, V, DestTy, Name);
1634 }
1635
1636 Value *CreateIntToPtr(Value *V, Type *DestTy,
1637 const Twine &Name = "") {
1638 return CreateCast(Instruction::IntToPtr, V, DestTy, Name);
1639 }
1640
1641 Value *CreateBitCast(Value *V, Type *DestTy,
1642 const Twine &Name = "") {
1643 return CreateCast(Instruction::BitCast, V, DestTy, Name);
6
Passing null pointer value via 2nd parameter 'V'
7
Calling 'IRBuilder::CreateCast'
1644 }
1645
1646 Value *CreateAddrSpaceCast(Value *V, Type *DestTy,
1647 const Twine &Name = "") {
1648 return CreateCast(Instruction::AddrSpaceCast, V, DestTy, Name);
1649 }
1650
1651 Value *CreateZExtOrBitCast(Value *V, Type *DestTy,
1652 const Twine &Name = "") {
1653 if (V->getType() == DestTy)
1654 return V;
1655 if (auto *VC = dyn_cast<Constant>(V))
1656 return Insert(Folder.CreateZExtOrBitCast(VC, DestTy), Name);
1657 return Insert(CastInst::CreateZExtOrBitCast(V, DestTy), Name);
1658 }
1659
1660 Value *CreateSExtOrBitCast(Value *V, Type *DestTy,
1661 const Twine &Name = "") {
1662 if (V->getType() == DestTy)
1663 return V;
1664 if (auto *VC = dyn_cast<Constant>(V))
1665 return Insert(Folder.CreateSExtOrBitCast(VC, DestTy), Name);
1666 return Insert(CastInst::CreateSExtOrBitCast(V, DestTy), Name);
1667 }
1668
1669 Value *CreateTruncOrBitCast(Value *V, Type *DestTy,
1670 const Twine &Name = "") {
1671 if (V->getType() == DestTy)
1672 return V;
1673 if (auto *VC = dyn_cast<Constant>(V))
1674 return Insert(Folder.CreateTruncOrBitCast(VC, DestTy), Name);
1675 return Insert(CastInst::CreateTruncOrBitCast(V, DestTy), Name);
1676 }
1677
1678 Value *CreateCast(Instruction::CastOps Op, Value *V, Type *DestTy,
1679 const Twine &Name = "") {
1680 if (V->getType() == DestTy)
8
Called C++ object pointer is null
1681 return V;
1682 if (auto *VC = dyn_cast<Constant>(V))
1683 return Insert(Folder.CreateCast(Op, VC, DestTy), Name);
1684 return Insert(CastInst::Create(Op, V, DestTy), Name);
1685 }
1686
1687 Value *CreatePointerCast(Value *V, Type *DestTy,
1688 const Twine &Name = "") {
1689 if (V->getType() == DestTy)
1690 return V;
1691 if (auto *VC = dyn_cast<Constant>(V))
1692 return Insert(Folder.CreatePointerCast(VC, DestTy), Name);
1693 return Insert(CastInst::CreatePointerCast(V, DestTy), Name);
1694 }
1695
1696 Value *CreatePointerBitCastOrAddrSpaceCast(Value *V, Type *DestTy,
1697 const Twine &Name = "") {
1698 if (V->getType() == DestTy)
1699 return V;
1700
1701 if (auto *VC = dyn_cast<Constant>(V)) {
1702 return Insert(Folder.CreatePointerBitCastOrAddrSpaceCast(VC, DestTy),
1703 Name);
1704 }
1705
1706 return Insert(CastInst::CreatePointerBitCastOrAddrSpaceCast(V, DestTy),
1707 Name);
1708 }
1709
1710 Value *CreateIntCast(Value *V, Type *DestTy, bool isSigned,
1711 const Twine &Name = "") {
1712 if (V->getType() == DestTy)
1713 return V;
1714 if (auto *VC = dyn_cast<Constant>(V))
1715 return Insert(Folder.CreateIntCast(VC, DestTy, isSigned), Name);
1716 return Insert(CastInst::CreateIntegerCast(V, DestTy, isSigned), Name);
1717 }
1718
1719 Value *CreateBitOrPointerCast(Value *V, Type *DestTy,
1720 const Twine &Name = "") {
1721 if (V->getType() == DestTy)
1722 return V;
1723 if (V->getType()->isPtrOrPtrVectorTy() && DestTy->isIntOrIntVectorTy())
1724 return CreatePtrToInt(V, DestTy, Name);
1725 if (V->getType()->isIntOrIntVectorTy() && DestTy->isPtrOrPtrVectorTy())
1726 return CreateIntToPtr(V, DestTy, Name);
1727
1728 return CreateBitCast(V, DestTy, Name);
1729 }
1730
1731 Value *CreateFPCast(Value *V, Type *DestTy, const Twine &Name = "") {
1732 if (V->getType() == DestTy)
1733 return V;
1734 if (auto *VC = dyn_cast<Constant>(V))
1735 return Insert(Folder.CreateFPCast(VC, DestTy), Name);
1736 return Insert(CastInst::CreateFPCast(V, DestTy), Name);
1737 }
1738
1739 // Provided to resolve 'CreateIntCast(Ptr, Ptr, "...")', giving a
1740 // compile time error, instead of converting the string to bool for the
1741 // isSigned parameter.
1742 Value *CreateIntCast(Value *, Type *, const char *) = delete;
1743
1744 //===--------------------------------------------------------------------===//
1745 // Instruction creation methods: Compare Instructions
1746 //===--------------------------------------------------------------------===//
1747
1748 Value *CreateICmpEQ(Value *LHS, Value *RHS, const Twine &Name = "") {
1749 return CreateICmp(ICmpInst::ICMP_EQ, LHS, RHS, Name);
1750 }
1751
1752 Value *CreateICmpNE(Value *LHS, Value *RHS, const Twine &Name = "") {
1753 return CreateICmp(ICmpInst::ICMP_NE, LHS, RHS, Name);
1754 }
1755
1756 Value *CreateICmpUGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1757 return CreateICmp(ICmpInst::ICMP_UGT, LHS, RHS, Name);
1758 }
1759
1760 Value *CreateICmpUGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1761 return CreateICmp(ICmpInst::ICMP_UGE, LHS, RHS, Name);
1762 }
1763
1764 Value *CreateICmpULT(Value *LHS, Value *RHS, const Twine &Name = "") {
1765 return CreateICmp(ICmpInst::ICMP_ULT, LHS, RHS, Name);
1766 }
1767
1768 Value *CreateICmpULE(Value *LHS, Value *RHS, const Twine &Name = "") {
1769 return CreateICmp(ICmpInst::ICMP_ULE, LHS, RHS, Name);
1770 }
1771
1772 Value *CreateICmpSGT(Value *LHS, Value *RHS, const Twine &Name = "") {
1773 return CreateICmp(ICmpInst::ICMP_SGT, LHS, RHS, Name);
1774 }
1775
1776 Value *CreateICmpSGE(Value *LHS, Value *RHS, const Twine &Name = "") {
1777 return CreateICmp(ICmpInst::ICMP_SGE, LHS, RHS, Name);
1778 }
1779
1780 Value *CreateICmpSLT(Value *LHS, Value *RHS, const Twine &Name = "") {
1781 return CreateICmp(ICmpInst::ICMP_SLT, LHS, RHS, Name);
1782 }
1783
1784 Value *CreateICmpSLE(Value *LHS, Value *RHS, const Twine &Name = "") {
1785 return CreateICmp(ICmpInst::ICMP_SLE, LHS, RHS, Name);
1786 }
1787
1788 Value *CreateFCmpOEQ(Value *LHS, Value *RHS, const Twine &Name = "",
1789 MDNode *FPMathTag = nullptr) {
1790 return CreateFCmp(FCmpInst::FCMP_OEQ, LHS, RHS, Name, FPMathTag);
1791 }
1792
1793 Value *CreateFCmpOGT(Value *LHS, Value *RHS, const Twine &Name = "",
1794 MDNode *FPMathTag = nullptr) {
1795 return CreateFCmp(FCmpInst::FCMP_OGT, LHS, RHS, Name, FPMathTag);
1796 }
1797
1798 Value *CreateFCmpOGE(Value *LHS, Value *RHS, const Twine &Name = "",
1799 MDNode *FPMathTag = nullptr) {
1800 return CreateFCmp(FCmpInst::FCMP_OGE, LHS, RHS, Name, FPMathTag);
1801 }
1802
1803 Value *CreateFCmpOLT(Value *LHS, Value *RHS, const Twine &Name = "",
1804 MDNode *FPMathTag = nullptr) {
1805 return CreateFCmp(FCmpInst::FCMP_OLT, LHS, RHS, Name, FPMathTag);
1806 }
1807
1808 Value *CreateFCmpOLE(Value *LHS, Value *RHS, const Twine &Name = "",
1809 MDNode *FPMathTag = nullptr) {
1810 return CreateFCmp(FCmpInst::FCMP_OLE, LHS, RHS, Name, FPMathTag);
1811 }
1812
1813 Value *CreateFCmpONE(Value *LHS, Value *RHS, const Twine &Name = "",
1814 MDNode *FPMathTag = nullptr) {
1815 return CreateFCmp(FCmpInst::FCMP_ONE, LHS, RHS, Name, FPMathTag);
1816 }
1817
1818 Value *CreateFCmpORD(Value *LHS, Value *RHS, const Twine &Name = "",
1819 MDNode *FPMathTag = nullptr) {
1820 return CreateFCmp(FCmpInst::FCMP_ORD, LHS, RHS, Name, FPMathTag);
1821 }
1822
1823 Value *CreateFCmpUNO(Value *LHS, Value *RHS, const Twine &Name = "",
1824 MDNode *FPMathTag = nullptr) {
1825 return CreateFCmp(FCmpInst::FCMP_UNO, LHS, RHS, Name, FPMathTag);
1826 }
1827
1828 Value *CreateFCmpUEQ(Value *LHS, Value *RHS, const Twine &Name = "",
1829 MDNode *FPMathTag = nullptr) {
1830 return CreateFCmp(FCmpInst::FCMP_UEQ, LHS, RHS, Name, FPMathTag);
1831 }
1832
1833 Value *CreateFCmpUGT(Value *LHS, Value *RHS, const Twine &Name = "",
1834 MDNode *FPMathTag = nullptr) {
1835 return CreateFCmp(FCmpInst::FCMP_UGT, LHS, RHS, Name, FPMathTag);
1836 }
1837
1838 Value *CreateFCmpUGE(Value *LHS, Value *RHS, const Twine &Name = "",
1839 MDNode *FPMathTag = nullptr) {
1840 return CreateFCmp(FCmpInst::FCMP_UGE, LHS, RHS, Name, FPMathTag);
1841 }
1842
1843 Value *CreateFCmpULT(Value *LHS, Value *RHS, const Twine &Name = "",
1844 MDNode *FPMathTag = nullptr) {
1845 return CreateFCmp(FCmpInst::FCMP_ULT, LHS, RHS, Name, FPMathTag);
1846 }
1847
1848 Value *CreateFCmpULE(Value *LHS, Value *RHS, const Twine &Name = "",
1849 MDNode *FPMathTag = nullptr) {
1850 return CreateFCmp(FCmpInst::FCMP_ULE, LHS, RHS, Name, FPMathTag);
1851 }
1852
1853 Value *CreateFCmpUNE(Value *LHS, Value *RHS, const Twine &Name = "",
1854 MDNode *FPMathTag = nullptr) {
1855 return CreateFCmp(FCmpInst::FCMP_UNE, LHS, RHS, Name, FPMathTag);
1856 }
1857
1858 Value *CreateICmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1859 const Twine &Name = "") {
1860 if (auto *LC = dyn_cast<Constant>(LHS))
1861 if (auto *RC = dyn_cast<Constant>(RHS))
1862 return Insert(Folder.CreateICmp(P, LC, RC), Name);
1863 return Insert(new ICmpInst(P, LHS, RHS), Name);
1864 }
1865
1866 Value *CreateFCmp(CmpInst::Predicate P, Value *LHS, Value *RHS,
1867 const Twine &Name = "", MDNode *FPMathTag = nullptr) {
1868 if (auto *LC = dyn_cast<Constant>(LHS))
1869 if (auto *RC = dyn_cast<Constant>(RHS))
1870 return Insert(Folder.CreateFCmp(P, LC, RC), Name);
1871 return Insert(setFPAttrs(new FCmpInst(P, LHS, RHS), FPMathTag, FMF), Name);
1872 }
1873
1874 //===--------------------------------------------------------------------===//
1875 // Instruction creation methods: Other Instructions
1876 //===--------------------------------------------------------------------===//
1877
1878 PHINode *CreatePHI(Type *Ty, unsigned NumReservedValues,
1879 const Twine &Name = "") {
1880 return Insert(PHINode::Create(Ty, NumReservedValues), Name);
1881 }
1882
1883 CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args = None,
1884 const Twine &Name = "", MDNode *FPMathTag = nullptr) {
1885 auto *PTy = cast<PointerType>(Callee->getType());
1886 auto *FTy = cast<FunctionType>(PTy->getElementType());
1887 return CreateCall(FTy, Callee, Args, Name, FPMathTag);
1888 }
1889
1890 CallInst *CreateCall(FunctionType *FTy, Value *Callee,
1891 ArrayRef<Value *> Args, const Twine &Name = "",
1892 MDNode *FPMathTag = nullptr) {
1893 CallInst *CI = CallInst::Create(FTy, Callee, Args, DefaultOperandBundles);
1894 if (isa<FPMathOperator>(CI))
1895 CI = cast<CallInst>(setFPAttrs(CI, FPMathTag, FMF));
1896 return Insert(CI, Name);
1897 }
1898
1899 CallInst *CreateCall(Value *Callee, ArrayRef<Value *> Args,
1900 ArrayRef<OperandBundleDef> OpBundles,
1901 const Twine &Name = "", MDNode *FPMathTag = nullptr) {
1902 CallInst *CI = CallInst::Create(Callee, Args, OpBundles);
1903 if (isa<FPMathOperator>(CI))
1904 CI = cast<CallInst>(setFPAttrs(CI, FPMathTag, FMF));
1905 return Insert(CI, Name);
1906 }
1907
1908 CallInst *CreateCall(Function *Callee, ArrayRef<Value *> Args,
1909 const Twine &Name = "", MDNode *FPMathTag = nullptr) {
1910 return CreateCall(Callee->getFunctionType(), Callee, Args, Name, FPMathTag);
1911 }
1912
1913 Value *CreateSelect(Value *C, Value *True, Value *False,
1914 const Twine &Name = "", Instruction *MDFrom = nullptr) {
1915 if (auto *CC = dyn_cast<Constant>(C))
1916 if (auto *TC = dyn_cast<Constant>(True))
1917 if (auto *FC = dyn_cast<Constant>(False))
1918 return Insert(Folder.CreateSelect(CC, TC, FC), Name);
1919
1920 SelectInst *Sel = SelectInst::Create(C, True, False);
1921 if (MDFrom) {
1922 MDNode *Prof = MDFrom->getMetadata(LLVMContext::MD_prof);
1923 MDNode *Unpred = MDFrom->getMetadata(LLVMContext::MD_unpredictable);
1924 Sel = addBranchMetadata(Sel, Prof, Unpred);
1925 }
1926 return Insert(Sel, Name);
1927 }
1928
1929 VAArgInst *CreateVAArg(Value *List, Type *Ty, const Twine &Name = "") {
1930 return Insert(new VAArgInst(List, Ty), Name);
1931 }
1932
1933 Value *CreateExtractElement(Value *Vec, Value *Idx,
1934 const Twine &Name = "") {
1935 if (auto *VC = dyn_cast<Constant>(Vec))
1936 if (auto *IC = dyn_cast<Constant>(Idx))
1937 return Insert(Folder.CreateExtractElement(VC, IC), Name);
1938 return Insert(ExtractElementInst::Create(Vec, Idx), Name);
1939 }
1940
1941 Value *CreateExtractElement(Value *Vec, uint64_t Idx,
1942 const Twine &Name = "") {
1943 return CreateExtractElement(Vec, getInt64(Idx), Name);
1944 }
1945
1946 Value *CreateInsertElement(Value *Vec, Value *NewElt, Value *Idx,
1947 const Twine &Name = "") {
1948 if (auto *VC = dyn_cast<Constant>(Vec))
1949 if (auto *NC = dyn_cast<Constant>(NewElt))
1950 if (auto *IC = dyn_cast<Constant>(Idx))
1951 return Insert(Folder.CreateInsertElement(VC, NC, IC), Name);
1952 return Insert(InsertElementInst::Create(Vec, NewElt, Idx), Name);
1953 }
1954
1955 Value *CreateInsertElement(Value *Vec, Value *NewElt, uint64_t Idx,
1956 const Twine &Name = "") {
1957 return CreateInsertElement(Vec, NewElt, getInt64(Idx), Name);
1958 }
1959
1960 Value *CreateShuffleVector(Value *V1, Value *V2, Value *Mask,
1961 const Twine &Name = "") {
1962 if (auto *V1C = dyn_cast<Constant>(V1))
1963 if (auto *V2C = dyn_cast<Constant>(V2))
1964 if (auto *MC = dyn_cast<Constant>(Mask))
1965 return Insert(Folder.CreateShuffleVector(V1C, V2C, MC), Name);
1966 return Insert(new ShuffleVectorInst(V1, V2, Mask), Name);
1967 }
1968
1969 Value *CreateShuffleVector(Value *V1, Value *V2, ArrayRef<uint32_t> IntMask,
1970 const Twine &Name = "") {
1971 Value *Mask = ConstantDataVector::get(Context, IntMask);
1972 return CreateShuffleVector(V1, V2, Mask, Name);
1973 }
1974
1975 Value *CreateExtractValue(Value *Agg,
1976 ArrayRef<unsigned> Idxs,
1977 const Twine &Name = "") {
1978 if (auto *AggC = dyn_cast<Constant>(Agg))
1979 return Insert(Folder.CreateExtractValue(AggC, Idxs), Name);
1980 return Insert(ExtractValueInst::Create(Agg, Idxs), Name);
1981 }
1982
1983 Value *CreateInsertValue(Value *Agg, Value *Val,
1984 ArrayRef<unsigned> Idxs,
1985 const Twine &Name = "") {
1986 if (auto *AggC = dyn_cast<Constant>(Agg))
1987 if (auto *ValC = dyn_cast<Constant>(Val))
1988 return Insert(Folder.CreateInsertValue(AggC, ValC, Idxs), Name);
1989 return Insert(InsertValueInst::Create(Agg, Val, Idxs), Name);
1990 }
1991
1992 LandingPadInst *CreateLandingPad(Type *Ty, unsigned NumClauses,
1993 const Twine &Name = "") {
1994 return Insert(LandingPadInst::Create(Ty, NumClauses), Name);
1995 }
1996
1997 //===--------------------------------------------------------------------===//
1998 // Utility creation methods
1999 //===--------------------------------------------------------------------===//
2000
2001 /// Return an i1 value testing if \p Arg is null.
2002 Value *CreateIsNull(Value *Arg, const Twine &Name = "") {
2003 return CreateICmpEQ(Arg, Constant::getNullValue(Arg->getType()),
2004 Name);
2005 }
2006
2007 /// Return an i1 value testing if \p Arg is not null.
2008 Value *CreateIsNotNull(Value *Arg, const Twine &Name = "") {
2009 return CreateICmpNE(Arg, Constant::getNullValue(Arg->getType()),
2010 Name);
2011 }
2012
2013 /// Return the i64 difference between two pointer values, dividing out
2014 /// the size of the pointed-to objects.
2015 ///
2016 /// This is intended to implement C-style pointer subtraction. As such, the
2017 /// pointers must be appropriately aligned for their element types and
2018 /// pointing into the same object.
2019 Value *CreatePtrDiff(Value *LHS, Value *RHS, const Twine &Name = "") {
2020 assert(LHS->getType() == RHS->getType() &&((LHS->getType() == RHS->getType() && "Pointer subtraction operand types must match!"
) ? static_cast<void> (0) : __assert_fail ("LHS->getType() == RHS->getType() && \"Pointer subtraction operand types must match!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/IRBuilder.h"
, 2021, __PRETTY_FUNCTION__))
2021 "Pointer subtraction operand types must match!")((LHS->getType() == RHS->getType() && "Pointer subtraction operand types must match!"
) ? static_cast<void> (0) : __assert_fail ("LHS->getType() == RHS->getType() && \"Pointer subtraction operand types must match!\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/IRBuilder.h"
, 2021, __PRETTY_FUNCTION__))
;
2022 auto *ArgType = cast<PointerType>(LHS->getType());
2023 Value *LHS_int = CreatePtrToInt(LHS, Type::getInt64Ty(Context));
2024 Value *RHS_int = CreatePtrToInt(RHS, Type::getInt64Ty(Context));
2025 Value *Difference = CreateSub(LHS_int, RHS_int);
2026 return CreateExactSDiv(Difference,
2027 ConstantExpr::getSizeOf(ArgType->getElementType()),
2028 Name);
2029 }
2030
2031 /// Create a launder.invariant.group intrinsic call. If Ptr type is
2032 /// different from pointer to i8, it's casted to pointer to i8 in the same
2033 /// address space before call and casted back to Ptr type after call.
2034 Value *CreateLaunderInvariantGroup(Value *Ptr) {
2035 assert(isa<PointerType>(Ptr->getType()) &&((isa<PointerType>(Ptr->getType()) && "launder.invariant.group only applies to pointers."
) ? static_cast<void> (0) : __assert_fail ("isa<PointerType>(Ptr->getType()) && \"launder.invariant.group only applies to pointers.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/IRBuilder.h"
, 2036, __PRETTY_FUNCTION__))
2036 "launder.invariant.group only applies to pointers.")((isa<PointerType>(Ptr->getType()) && "launder.invariant.group only applies to pointers."
) ? static_cast<void> (0) : __assert_fail ("isa<PointerType>(Ptr->getType()) && \"launder.invariant.group only applies to pointers.\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/IRBuilder.h"
, 2036, __PRETTY_FUNCTION__))
;
2037 // FIXME: we could potentially avoid casts to/from i8*.
2038 auto *PtrType = Ptr->getType();
2039 auto *Int8PtrTy = getInt8PtrTy(PtrType->getPointerAddressSpace());
2040 if (PtrType != Int8PtrTy)
2041 Ptr = CreateBitCast(Ptr, Int8PtrTy);
2042 Module *M = BB->getParent()->getParent();
2043 Function *FnLaunderInvariantGroup = Intrinsic::getDeclaration(
2044 M, Intrinsic::launder_invariant_group, {Int8PtrTy});
2045
2046 assert(FnLaunderInvariantGroup->getReturnType() == Int8PtrTy &&((FnLaunderInvariantGroup->getReturnType() == Int8PtrTy &&
FnLaunderInvariantGroup->getFunctionType()->getParamType
(0) == Int8PtrTy && "LaunderInvariantGroup should take and return the same type"
) ? static_cast<void> (0) : __assert_fail ("FnLaunderInvariantGroup->getReturnType() == Int8PtrTy && FnLaunderInvariantGroup->getFunctionType()->getParamType(0) == Int8PtrTy && \"LaunderInvariantGroup should take and return the same type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/IRBuilder.h"
, 2049, __PRETTY_FUNCTION__))
2047 FnLaunderInvariantGroup->getFunctionType()->getParamType(0) ==((FnLaunderInvariantGroup->getReturnType() == Int8PtrTy &&
FnLaunderInvariantGroup->getFunctionType()->getParamType
(0) == Int8PtrTy && "LaunderInvariantGroup should take and return the same type"
) ? static_cast<void> (0) : __assert_fail ("FnLaunderInvariantGroup->getReturnType() == Int8PtrTy && FnLaunderInvariantGroup->getFunctionType()->getParamType(0) == Int8PtrTy && \"LaunderInvariantGroup should take and return the same type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/IRBuilder.h"
, 2049, __PRETTY_FUNCTION__))
2048 Int8PtrTy &&((FnLaunderInvariantGroup->getReturnType() == Int8PtrTy &&
FnLaunderInvariantGroup->getFunctionType()->getParamType
(0) == Int8PtrTy && "LaunderInvariantGroup should take and return the same type"
) ? static_cast<void> (0) : __assert_fail ("FnLaunderInvariantGroup->getReturnType() == Int8PtrTy && FnLaunderInvariantGroup->getFunctionType()->getParamType(0) == Int8PtrTy && \"LaunderInvariantGroup should take and return the same type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/IRBuilder.h"
, 2049, __PRETTY_FUNCTION__))
2049 "LaunderInvariantGroup should take and return the same type")((FnLaunderInvariantGroup->getReturnType() == Int8PtrTy &&
FnLaunderInvariantGroup->getFunctionType()->getParamType
(0) == Int8PtrTy && "LaunderInvariantGroup should take and return the same type"
) ? static_cast<void> (0) : __assert_fail ("FnLaunderInvariantGroup->getReturnType() == Int8PtrTy && FnLaunderInvariantGroup->getFunctionType()->getParamType(0) == Int8PtrTy && \"LaunderInvariantGroup should take and return the same type\""
, "/build/llvm-toolchain-snapshot-8~svn345461/include/llvm/IR/IRBuilder.h"
, 2049, __PRETTY_FUNCTION__))
;
2050
2051 CallInst *Fn = CreateCall(FnLaunderInvariantGroup, {Ptr});
2052
2053 if (PtrType != Int8PtrTy)
2054 return CreateBitCast(Fn, PtrType);</