blob: 8801a3c8c73a01f4a2fff2ecb85373b306320c23 [file] [log] [blame]
Fariborz Jahanian11671902012-02-07 17:11:38 +00001//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
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// Hacks and fun related to the code rewriter.
11//
12//===----------------------------------------------------------------------===//
13
Ted Kremenekcdf81492012-09-01 05:09:24 +000014#include "clang/Rewrite/Frontend/ASTConsumers.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000015#include "clang/AST/AST.h"
16#include "clang/AST/ASTConsumer.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000018#include "clang/AST/ParentMap.h"
Jordan Rosea7d03842013-02-08 22:30:41 +000019#include "clang/Basic/CharInfo.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000020#include "clang/Basic/Diagnostic.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000021#include "clang/Basic/IdentifierTable.h"
22#include "clang/Basic/SourceManager.h"
Benjamin Kramerd7d2b1f2012-12-01 16:35:25 +000023#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000024#include "clang/Lex/Lexer.h"
Chandler Carruth3a022472012-12-04 09:13:33 +000025#include "clang/Rewrite/Core/Rewriter.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000026#include "llvm/ADT/DenseSet.h"
Benjamin Kramerea70eb32012-12-01 15:09:41 +000027#include "llvm/ADT/SmallPtrSet.h"
28#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000029#include "llvm/Support/MemoryBuffer.h"
30#include "llvm/Support/raw_ostream.h"
Ahmed Charlesdfca6f92014-03-09 11:36:40 +000031#include <memory>
Fariborz Jahanian11671902012-02-07 17:11:38 +000032
33using namespace clang;
34using llvm::utostr;
35
36namespace {
37 class RewriteModernObjC : public ASTConsumer {
38 protected:
39
40 enum {
41 BLOCK_FIELD_IS_OBJECT = 3, /* id, NSObject, __attribute__((NSObject)),
42 block, ... */
43 BLOCK_FIELD_IS_BLOCK = 7, /* a block variable */
44 BLOCK_FIELD_IS_BYREF = 8, /* the on stack structure holding the
45 __block variable */
46 BLOCK_FIELD_IS_WEAK = 16, /* declared __weak, only used in byref copy
47 helpers */
48 BLOCK_BYREF_CALLER = 128, /* called from __block (byref) copy/dispose
49 support routines */
50 BLOCK_BYREF_CURRENT_MAX = 256
51 };
52
53 enum {
54 BLOCK_NEEDS_FREE = (1 << 24),
55 BLOCK_HAS_COPY_DISPOSE = (1 << 25),
56 BLOCK_HAS_CXX_OBJ = (1 << 26),
57 BLOCK_IS_GC = (1 << 27),
58 BLOCK_IS_GLOBAL = (1 << 28),
59 BLOCK_HAS_DESCRIPTOR = (1 << 29)
60 };
Fariborz Jahanian11671902012-02-07 17:11:38 +000061
62 Rewriter Rewrite;
63 DiagnosticsEngine &Diags;
64 const LangOptions &LangOpts;
65 ASTContext *Context;
66 SourceManager *SM;
67 TranslationUnitDecl *TUDecl;
68 FileID MainFileID;
69 const char *MainFileStart, *MainFileEnd;
70 Stmt *CurrentBody;
71 ParentMap *PropParentMap; // created lazily.
72 std::string InFileName;
73 raw_ostream* OutFile;
74 std::string Preamble;
75
76 TypeDecl *ProtocolTypeDecl;
77 VarDecl *GlobalVarDecl;
Fariborz Jahaniane0050702012-03-23 00:00:49 +000078 Expr *GlobalConstructionExp;
Fariborz Jahanian11671902012-02-07 17:11:38 +000079 unsigned RewriteFailedDiag;
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +000080 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian11671902012-02-07 17:11:38 +000081 // ObjC string constant support.
82 unsigned NumObjCStringLiterals;
83 VarDecl *ConstantStringClassReference;
84 RecordDecl *NSStringRecord;
85
86 // ObjC foreach break/continue generation support.
87 int BcLabelCount;
88
89 unsigned TryFinallyContainsReturnDiag;
90 // Needed for super.
91 ObjCMethodDecl *CurMethodDef;
92 RecordDecl *SuperStructDecl;
93 RecordDecl *ConstantStringDecl;
94
95 FunctionDecl *MsgSendFunctionDecl;
96 FunctionDecl *MsgSendSuperFunctionDecl;
97 FunctionDecl *MsgSendStretFunctionDecl;
98 FunctionDecl *MsgSendSuperStretFunctionDecl;
99 FunctionDecl *MsgSendFpretFunctionDecl;
100 FunctionDecl *GetClassFunctionDecl;
101 FunctionDecl *GetMetaClassFunctionDecl;
102 FunctionDecl *GetSuperClassFunctionDecl;
103 FunctionDecl *SelGetUidFunctionDecl;
104 FunctionDecl *CFStringFunctionDecl;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000105 FunctionDecl *SuperConstructorFunctionDecl;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000106 FunctionDecl *CurFunctionDef;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000107
108 /* Misc. containers needed for meta-data rewrite. */
109 SmallVector<ObjCImplementationDecl *, 8> ClassImplementation;
110 SmallVector<ObjCCategoryImplDecl *, 8> CategoryImplementation;
111 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCSynthesizedStructs;
112 llvm::SmallPtrSet<ObjCProtocolDecl*, 8> ObjCSynthesizedProtocols;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000113 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000114 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000115 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000116 /// DefinedNonLazyClasses - List of defined "non-lazy" classes.
117 SmallVector<ObjCInterfaceDecl*, 8> DefinedNonLazyClasses;
118
119 /// DefinedNonLazyCategories - List of defined "non-lazy" categories.
Dmitri Gribenkof8579502013-01-12 19:30:44 +0000120 SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000121
Fariborz Jahanian11671902012-02-07 17:11:38 +0000122 SmallVector<Stmt *, 32> Stmts;
123 SmallVector<int, 8> ObjCBcLabelNo;
124 // Remember all the @protocol(<expr>) expressions.
125 llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
126
127 llvm::DenseSet<uint64_t> CopyDestroyCache;
128
129 // Block expressions.
130 SmallVector<BlockExpr *, 32> Blocks;
131 SmallVector<int, 32> InnerDeclRefsCount;
John McCall113bee02012-03-10 09:33:50 +0000132 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000133
John McCall113bee02012-03-10 09:33:50 +0000134 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000135
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000136
Fariborz Jahanian11671902012-02-07 17:11:38 +0000137 // Block related declarations.
138 SmallVector<ValueDecl *, 8> BlockByCopyDecls;
139 llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
140 SmallVector<ValueDecl *, 8> BlockByRefDecls;
141 llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
142 llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
143 llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
144 llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
145
146 llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +0000147 llvm::DenseMap<ObjCInterfaceDecl *,
148 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
149
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000150 // ivar bitfield grouping containers
151 llvm::DenseSet<const ObjCInterfaceDecl *> ObjCInterefaceHasBitfieldGroups;
152 llvm::DenseMap<const ObjCIvarDecl* , unsigned> IvarGroupNumber;
153 // This container maps an <class, group number for ivar> tuple to the type
154 // of the struct where the bitfield belongs.
155 llvm::DenseMap<std::pair<const ObjCInterfaceDecl*, unsigned>, QualType> GroupRecordType;
Fariborz Jahaniane4996132013-02-07 22:50:40 +0000156 SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000157
Fariborz Jahanian11671902012-02-07 17:11:38 +0000158 // This maps an original source AST to it's rewritten form. This allows
159 // us to avoid rewriting the same node twice (which is very uncommon).
160 // This is needed to support some of the exotic property rewriting.
161 llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
162
163 // Needed for header files being rewritten
164 bool IsHeader;
165 bool SilenceRewriteMacroWarning;
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000166 bool GenerateLineInfo;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000167 bool objc_impl_method;
168
169 bool DisableReplaceStmt;
170 class DisableReplaceStmtScope {
171 RewriteModernObjC &R;
172 bool SavedValue;
173
174 public:
175 DisableReplaceStmtScope(RewriteModernObjC &R)
176 : R(R), SavedValue(R.DisableReplaceStmt) {
177 R.DisableReplaceStmt = true;
178 }
179 ~DisableReplaceStmtScope() {
180 R.DisableReplaceStmt = SavedValue;
181 }
182 };
183 void InitializeCommon(ASTContext &context);
184
185 public:
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +0000186 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000187 // Top Level Driver code.
Craig Topperfb6b25b2014-03-15 04:29:04 +0000188 bool HandleTopLevelDecl(DeclGroupRef D) override {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000189 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
190 if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
191 if (!Class->isThisDeclarationADefinition()) {
192 RewriteForwardClassDecl(D);
193 break;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000194 } else {
195 // Keep track of all interface declarations seen.
Fariborz Jahanian0ed6cb72012-02-24 21:42:38 +0000196 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +0000197 break;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000198 }
199 }
200
201 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
202 if (!Proto->isThisDeclarationADefinition()) {
203 RewriteForwardProtocolDecl(D);
204 break;
205 }
206 }
207
Fariborz Jahaniane4996132013-02-07 22:50:40 +0000208 if (FunctionDecl *FDecl = dyn_cast<FunctionDecl>(*I)) {
209 // Under modern abi, we cannot translate body of the function
210 // yet until all class extensions and its implementation is seen.
211 // This is because they may introduce new bitfields which must go
212 // into their grouping struct.
213 if (FDecl->isThisDeclarationADefinition() &&
214 // Not c functions defined inside an objc container.
215 !FDecl->isTopLevelDeclInObjCContainer()) {
216 FunctionDefinitionsSeen.push_back(FDecl);
217 break;
218 }
219 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000220 HandleTopLevelSingleDecl(*I);
221 }
222 return true;
223 }
Craig Topperfb6b25b2014-03-15 04:29:04 +0000224
225 void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) override {
Fariborz Jahaniand2940622013-10-07 19:54:22 +0000226 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
227 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(*I)) {
228 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
229 RewriteBlockPointerDecl(TD);
230 else if (TD->getUnderlyingType()->isFunctionPointerType())
231 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
232 else
233 RewriteObjCQualifiedInterfaceTypes(TD);
234 }
235 }
236 return;
237 }
238
Fariborz Jahanian11671902012-02-07 17:11:38 +0000239 void HandleTopLevelSingleDecl(Decl *D);
240 void HandleDeclInMainFile(Decl *D);
241 RewriteModernObjC(std::string inFile, raw_ostream *OS,
242 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000243 bool silenceMacroWarn, bool LineInfo);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000244
245 ~RewriteModernObjC() {}
Craig Topperfb6b25b2014-03-15 04:29:04 +0000246
247 void HandleTranslationUnit(ASTContext &C) override;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000248
249 void ReplaceStmt(Stmt *Old, Stmt *New) {
250 Stmt *ReplacingStmt = ReplacedNodes[Old];
251
252 if (ReplacingStmt)
253 return; // We can't rewrite the same node twice.
254
255 if (DisableReplaceStmt)
256 return;
257
258 // If replacement succeeded or warning disabled return with no warning.
259 if (!Rewrite.ReplaceStmt(Old, New)) {
260 ReplacedNodes[Old] = New;
261 return;
262 }
263 if (SilenceRewriteMacroWarning)
264 return;
265 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
266 << Old->getSourceRange();
267 }
268
269 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
270 if (DisableReplaceStmt)
271 return;
272
273 // Measure the old text.
274 int Size = Rewrite.getRangeSize(SrcRange);
275 if (Size == -1) {
276 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
277 << Old->getSourceRange();
278 return;
279 }
280 // Get the new text.
281 std::string SStr;
282 llvm::raw_string_ostream S(SStr);
Richard Smith235341b2012-08-16 03:56:14 +0000283 New->printPretty(S, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +0000284 const std::string &Str = S.str();
285
286 // If replacement succeeded or warning disabled return with no warning.
287 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
288 ReplacedNodes[Old] = New;
289 return;
290 }
291 if (SilenceRewriteMacroWarning)
292 return;
293 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
294 << Old->getSourceRange();
295 }
296
297 void InsertText(SourceLocation Loc, StringRef Str,
298 bool InsertAfter = true) {
299 // If insertion succeeded or warning disabled return with no warning.
300 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
301 SilenceRewriteMacroWarning)
302 return;
303
304 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
305 }
306
307 void ReplaceText(SourceLocation Start, unsigned OrigLength,
308 StringRef Str) {
309 // If removal succeeded or warning disabled return with no warning.
310 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
311 SilenceRewriteMacroWarning)
312 return;
313
314 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
315 }
316
317 // Syntactic Rewriting.
318 void RewriteRecordBody(RecordDecl *RD);
319 void RewriteInclude();
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +0000320 void RewriteLineDirective(const Decl *D);
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +0000321 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
322 std::string &LineString);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000323 void RewriteForwardClassDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000324 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000325 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
326 const std::string &typedefString);
327 void RewriteImplementations();
328 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
329 ObjCImplementationDecl *IMD,
330 ObjCCategoryImplDecl *CID);
331 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
332 void RewriteImplementationDecl(Decl *Dcl);
333 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
334 ObjCMethodDecl *MDecl, std::string &ResultStr);
335 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
336 const FunctionType *&FPRetType);
337 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
338 ValueDecl *VD, bool def=false);
339 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
340 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
341 void RewriteForwardProtocolDecl(DeclGroupRef D);
Craig Topper5603df42013-07-05 19:34:19 +0000342 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000343 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
344 void RewriteProperty(ObjCPropertyDecl *prop);
345 void RewriteFunctionDecl(FunctionDecl *FD);
346 void RewriteBlockPointerType(std::string& Str, QualType Type);
347 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianca357d92012-04-19 00:50:01 +0000348 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000349 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
350 void RewriteTypeOfDecl(VarDecl *VD);
351 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000352
353 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000354
355 // Expression Rewriting.
356 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
357 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
358 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
359 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
360 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
361 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
362 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +0000363 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beard0caa3942012-04-19 00:25:12 +0000364 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +0000365 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000366 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000367 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000368 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +0000369 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000370 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
371 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
372 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
373 SourceLocation OrigEnd);
374 Stmt *RewriteBreakStmt(BreakStmt *S);
375 Stmt *RewriteContinueStmt(ContinueStmt *S);
376 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +0000377 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanian08ed8922012-04-03 17:35:38 +0000378 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000379
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000380 // Computes ivar bitfield group no.
381 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
382 // Names field decl. for ivar bitfield group.
383 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
384 // Names struct type for ivar bitfield group.
385 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
386 // Names symbol for ivar bitfield group field offset.
387 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
388 // Given an ivar bitfield, it builds (or finds) its group record type.
389 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
390 QualType SynthesizeBitfieldGroupStructType(
391 ObjCIvarDecl *IV,
392 SmallVectorImpl<ObjCIvarDecl *> &IVars);
393
Fariborz Jahanian11671902012-02-07 17:11:38 +0000394 // Block rewriting.
395 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
396
397 // Block specific rewrite rules.
398 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian847713a2012-04-24 19:38:45 +0000399 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCall113bee02012-03-10 09:33:50 +0000400 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000401 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
402 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
403
404 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
405 std::string &Result);
406
Fariborz Jahanian265a4212012-02-28 22:45:07 +0000407 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanian144b7222012-05-01 17:46:45 +0000408 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +0000409 bool &IsNamedDefinition);
410 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
411 std::string &Result);
Fariborz Jahanian265a4212012-02-28 22:45:07 +0000412
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +0000413 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
414
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +0000415 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
416 std::string &Result);
Craig Topperfb6b25b2014-03-15 04:29:04 +0000417
418 void Initialize(ASTContext &context) override;
419
Benjamin Kramer474261a2012-06-02 10:20:41 +0000420 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian11671902012-02-07 17:11:38 +0000421 // rewriting routines on the new ASTs.
422 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
423 Expr **args, unsigned nargs,
424 SourceLocation StartLoc=SourceLocation(),
425 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000426
427 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +0000428 QualType returnType,
429 SmallVectorImpl<QualType> &ArgTypes,
430 SmallVectorImpl<Expr*> &MsgExprs,
431 ObjCMethodDecl *Method);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000432
433 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
434 SourceLocation StartLoc=SourceLocation(),
435 SourceLocation EndLoc=SourceLocation());
436
437 void SynthCountByEnumWithState(std::string &buf);
438 void SynthMsgSendFunctionDecl();
439 void SynthMsgSendSuperFunctionDecl();
440 void SynthMsgSendStretFunctionDecl();
441 void SynthMsgSendFpretFunctionDecl();
442 void SynthMsgSendSuperStretFunctionDecl();
443 void SynthGetClassFunctionDecl();
444 void SynthGetMetaClassFunctionDecl();
445 void SynthGetSuperClassFunctionDecl();
446 void SynthSelGetUidFunctionDecl();
Benjamin Kramer60509af2013-09-09 14:48:42 +0000447 void SynthSuperConstructorFunctionDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000448
449 // Rewriting metadata
450 template<typename MethodIterator>
451 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
452 MethodIterator MethodEnd,
453 bool IsInstanceMethod,
454 StringRef prefix,
455 StringRef ClassName,
456 std::string &Result);
Fariborz Jahaniane18961b2012-02-08 19:53:58 +0000457 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
458 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000459 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian11671902012-02-07 17:11:38 +0000460 const ObjCList<ObjCProtocolDecl> &Prots,
461 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000462 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000463 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000464 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +0000465
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000466 void RewriteMetaDataIntoBuffer(std::string &Result);
467 void WriteImageInfo(std::string &Result);
468 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000469 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000470 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000471
472 // Rewriting ivar
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000473 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000474 std::string &Result);
Fariborz Jahanian95badad2012-04-30 16:57:52 +0000475 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000476
477
478 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
479 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
480 StringRef funcName, std::string Tag);
481 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
482 StringRef funcName, std::string Tag);
483 std::string SynthesizeBlockImpl(BlockExpr *CE,
484 std::string Tag, std::string Desc);
485 std::string SynthesizeBlockDescriptor(std::string DescTag,
486 std::string ImplTag,
487 int i, StringRef funcName,
488 unsigned hasCopy);
489 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
490 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
491 StringRef FunName);
492 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
493 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +0000494 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000495
496 // Misc. helper routines.
497 QualType getProtocolType();
498 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000499 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
500 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
501 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
502
503 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
504 void CollectBlockDeclRefInfo(BlockExpr *Exp);
505 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper5603df42013-07-05 19:34:19 +0000506 void GetInnerBlockDeclRefExprs(Stmt *S,
507 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000508 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
509
510 // We avoid calling Type::isBlockPointerType(), since it operates on the
511 // canonical type. We only care if the top-level type is a closure pointer.
512 bool isTopLevelBlockPointerType(QualType T) {
513 return isa<BlockPointerType>(T);
514 }
515
516 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
517 /// to a function pointer type and upon success, returns true; false
518 /// otherwise.
519 bool convertBlockPointerToFunctionPointer(QualType &T) {
520 if (isTopLevelBlockPointerType(T)) {
521 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
522 T = Context->getPointerType(BPT->getPointeeType());
523 return true;
524 }
525 return false;
526 }
527
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +0000528 bool convertObjCTypeToCStyleType(QualType &T);
529
Fariborz Jahanian11671902012-02-07 17:11:38 +0000530 bool needToScanForQualifiers(QualType T);
531 QualType getSuperStructType();
532 QualType getConstantStringStructType();
533 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
534 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
535
536 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +0000537 if (T->isObjCQualifiedIdType()) {
538 bool isConst = T.isConstQualified();
539 T = isConst ? Context->getObjCIdType().withConst()
540 : Context->getObjCIdType();
541 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000542 else if (T->isObjCQualifiedClassType())
543 T = Context->getObjCClassType();
544 else if (T->isObjCObjectPointerType() &&
545 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
546 if (const ObjCObjectPointerType * OBJPT =
547 T->getAsObjCInterfacePointerType()) {
548 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
549 T = QualType(IFaceT, 0);
550 T = Context->getPointerType(T);
551 }
552 }
553 }
554
555 // FIXME: This predicate seems like it would be useful to add to ASTContext.
556 bool isObjCType(QualType T) {
557 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
558 return false;
559
560 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
561
562 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
563 OCT == Context->getCanonicalType(Context->getObjCClassType()))
564 return true;
565
566 if (const PointerType *PT = OCT->getAs<PointerType>()) {
567 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
568 PT->getPointeeType()->isObjCQualifiedIdType())
569 return true;
570 }
571 return false;
572 }
573 bool PointerTypeTakesAnyBlockArguments(QualType QT);
574 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
575 void GetExtentOfArgList(const char *Name, const char *&LParen,
576 const char *&RParen);
577
578 void QuoteDoublequotes(std::string &From, std::string &To) {
579 for (unsigned i = 0; i < From.length(); i++) {
580 if (From[i] == '"')
581 To += "\\\"";
582 else
583 To += From[i];
584 }
585 }
586
587 QualType getSimpleFunctionType(QualType result,
Jordan Rose5c382722013-03-08 21:51:21 +0000588 ArrayRef<QualType> args,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000589 bool variadic = false) {
590 if (result == Context->getObjCInstanceType())
591 result = Context->getObjCIdType();
592 FunctionProtoType::ExtProtoInfo fpi;
593 fpi.Variadic = variadic;
Jordan Rose5c382722013-03-08 21:51:21 +0000594 return Context->getFunctionType(result, args, fpi);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000595 }
596
597 // Helper function: create a CStyleCastExpr with trivial type source info.
598 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
599 CastKind Kind, Expr *E) {
600 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
601 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
602 SourceLocation(), SourceLocation());
603 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +0000604
605 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
606 IdentifierInfo* II = &Context->Idents.get("load");
607 Selector LoadSel = Context->Selectors.getSelector(0, &II);
608 return OD->getClassMethod(LoadSel) != 0;
609 }
Benjamin Kramerfc188422014-02-25 12:26:11 +0000610
611 StringLiteral *getStringLiteral(StringRef Str) {
612 QualType StrType = Context->getConstantArrayType(
613 Context->CharTy, llvm::APInt(32, Str.size() + 1), ArrayType::Normal,
614 0);
615 return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
616 /*Pascal=*/false, StrType, SourceLocation());
617 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000618 };
619
620}
621
622void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
623 NamedDecl *D) {
624 if (const FunctionProtoType *fproto
625 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
Alp Toker9cacbab2014-01-20 20:26:09 +0000626 for (FunctionProtoType::param_type_iterator I = fproto->param_type_begin(),
627 E = fproto->param_type_end();
628 I && (I != E); ++I)
Fariborz Jahanian11671902012-02-07 17:11:38 +0000629 if (isTopLevelBlockPointerType(*I)) {
630 // All the args are checked/rewritten. Don't call twice!
631 RewriteBlockPointerDecl(D);
632 break;
633 }
634 }
635}
636
637void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
638 const PointerType *PT = funcType->getAs<PointerType>();
639 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
640 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
641}
642
643static bool IsHeaderFile(const std::string &Filename) {
644 std::string::size_type DotPos = Filename.rfind('.');
645
646 if (DotPos == std::string::npos) {
647 // no file extension
648 return false;
649 }
650
651 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
652 // C header: .h
653 // C++ header: .hh or .H;
654 return Ext == "h" || Ext == "hh" || Ext == "H";
655}
656
657RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
658 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000659 bool silenceMacroWarn,
660 bool LineInfo)
Fariborz Jahanian11671902012-02-07 17:11:38 +0000661 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000662 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000663 IsHeader = IsHeaderFile(inFile);
664 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
665 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +0000666 // FIXME. This should be an error. But if block is not called, it is OK. And it
667 // may break including some headers.
668 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
669 "rewriting block literal declared in global scope is not implemented");
670
Fariborz Jahanian11671902012-02-07 17:11:38 +0000671 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
672 DiagnosticsEngine::Warning,
673 "rewriter doesn't support user-specified control flow semantics "
674 "for @try/@finally (code may not execute properly)");
675}
676
677ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
678 raw_ostream* OS,
679 DiagnosticsEngine &Diags,
680 const LangOptions &LOpts,
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +0000681 bool SilenceRewriteMacroWarning,
682 bool LineInfo) {
683 return new RewriteModernObjC(InFile, OS, Diags, LOpts,
684 SilenceRewriteMacroWarning, LineInfo);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000685}
686
687void RewriteModernObjC::InitializeCommon(ASTContext &context) {
688 Context = &context;
689 SM = &Context->getSourceManager();
690 TUDecl = Context->getTranslationUnitDecl();
691 MsgSendFunctionDecl = 0;
692 MsgSendSuperFunctionDecl = 0;
693 MsgSendStretFunctionDecl = 0;
694 MsgSendSuperStretFunctionDecl = 0;
695 MsgSendFpretFunctionDecl = 0;
696 GetClassFunctionDecl = 0;
697 GetMetaClassFunctionDecl = 0;
698 GetSuperClassFunctionDecl = 0;
699 SelGetUidFunctionDecl = 0;
700 CFStringFunctionDecl = 0;
701 ConstantStringClassReference = 0;
702 NSStringRecord = 0;
703 CurMethodDef = 0;
704 CurFunctionDef = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000705 GlobalVarDecl = 0;
Fariborz Jahaniane0050702012-03-23 00:00:49 +0000706 GlobalConstructionExp = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000707 SuperStructDecl = 0;
708 ProtocolTypeDecl = 0;
709 ConstantStringDecl = 0;
710 BcLabelCount = 0;
Benjamin Kramer60509af2013-09-09 14:48:42 +0000711 SuperConstructorFunctionDecl = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +0000712 NumObjCStringLiterals = 0;
713 PropParentMap = 0;
714 CurrentBody = 0;
715 DisableReplaceStmt = false;
716 objc_impl_method = false;
717
718 // Get the ID and start/end of the main file.
719 MainFileID = SM->getMainFileID();
720 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
721 MainFileStart = MainBuf->getBufferStart();
722 MainFileEnd = MainBuf->getBufferEnd();
723
David Blaikiebbafb8a2012-03-11 07:00:24 +0000724 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian11671902012-02-07 17:11:38 +0000725}
726
727//===----------------------------------------------------------------------===//
728// Top Level Driver Code
729//===----------------------------------------------------------------------===//
730
731void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
732 if (Diags.hasErrorOccurred())
733 return;
734
735 // Two cases: either the decl could be in the main file, or it could be in a
736 // #included file. If the former, rewrite it now. If the later, check to see
737 // if we rewrote the #include/#import.
738 SourceLocation Loc = D->getLocation();
739 Loc = SM->getExpansionLoc(Loc);
740
741 // If this is for a builtin, ignore it.
742 if (Loc.isInvalid()) return;
743
744 // Look for built-in declarations that we need to refer during the rewrite.
745 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
746 RewriteFunctionDecl(FD);
747 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
748 // declared in <Foundation/NSString.h>
749 if (FVD->getName() == "_NSConstantStringClassReference") {
750 ConstantStringClassReference = FVD;
751 return;
752 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000753 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
754 RewriteCategoryDecl(CD);
755 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
756 if (PD->isThisDeclarationADefinition())
757 RewriteProtocolDecl(PD);
758 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanianf264d5d2012-04-04 17:16:15 +0000759 // FIXME. This will not work in all situations and leaving it out
760 // is harmless.
761 // RewriteLinkageSpec(LSD);
762
Fariborz Jahanian11671902012-02-07 17:11:38 +0000763 // Recurse into linkage specifications
764 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
765 DIEnd = LSD->decls_end();
766 DI != DIEnd; ) {
767 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
768 if (!IFace->isThisDeclarationADefinition()) {
769 SmallVector<Decl *, 8> DG;
770 SourceLocation StartLoc = IFace->getLocStart();
771 do {
772 if (isa<ObjCInterfaceDecl>(*DI) &&
773 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
774 StartLoc == (*DI)->getLocStart())
775 DG.push_back(*DI);
776 else
777 break;
778
779 ++DI;
780 } while (DI != DIEnd);
781 RewriteForwardClassDecl(DG);
782 continue;
783 }
Fariborz Jahanian08ed8922012-04-03 17:35:38 +0000784 else {
785 // Keep track of all interface declarations seen.
786 ObjCInterfacesSeen.push_back(IFace);
787 ++DI;
788 continue;
789 }
Fariborz Jahanian11671902012-02-07 17:11:38 +0000790 }
791
792 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
793 if (!Proto->isThisDeclarationADefinition()) {
794 SmallVector<Decl *, 8> DG;
795 SourceLocation StartLoc = Proto->getLocStart();
796 do {
797 if (isa<ObjCProtocolDecl>(*DI) &&
798 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
799 StartLoc == (*DI)->getLocStart())
800 DG.push_back(*DI);
801 else
802 break;
803
804 ++DI;
805 } while (DI != DIEnd);
806 RewriteForwardProtocolDecl(DG);
807 continue;
808 }
809 }
810
811 HandleTopLevelSingleDecl(*DI);
812 ++DI;
813 }
814 }
815 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman5ba37d52013-08-22 00:27:10 +0000816 if (SM->isWrittenInMainFile(Loc))
Fariborz Jahanian11671902012-02-07 17:11:38 +0000817 return HandleDeclInMainFile(D);
818}
819
820//===----------------------------------------------------------------------===//
821// Syntactic (non-AST) Rewriting Code
822//===----------------------------------------------------------------------===//
823
824void RewriteModernObjC::RewriteInclude() {
825 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
826 StringRef MainBuf = SM->getBufferData(MainFileID);
827 const char *MainBufStart = MainBuf.begin();
828 const char *MainBufEnd = MainBuf.end();
829 size_t ImportLen = strlen("import");
830
831 // Loop over the whole file, looking for includes.
832 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
833 if (*BufPtr == '#') {
834 if (++BufPtr == MainBufEnd)
835 return;
836 while (*BufPtr == ' ' || *BufPtr == '\t')
837 if (++BufPtr == MainBufEnd)
838 return;
839 if (!strncmp(BufPtr, "import", ImportLen)) {
840 // replace import with include
841 SourceLocation ImportLoc =
842 LocStart.getLocWithOffset(BufPtr-MainBufStart);
843 ReplaceText(ImportLoc, ImportLen, "include");
844 BufPtr += ImportLen;
845 }
846 }
847 }
848}
849
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000850static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
851 ObjCIvarDecl *IvarDecl, std::string &Result) {
852 Result += "OBJC_IVAR_$_";
853 Result += IDecl->getName();
854 Result += "$";
855 Result += IvarDecl->getName();
856}
857
858std::string
859RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
860 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
861
862 // Build name of symbol holding ivar offset.
863 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000864 if (D->isBitField())
865 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
866 else
867 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000868
869
870 std::string S = "(*(";
871 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000872 if (D->isBitField())
873 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000874
875 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
876 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
877 RD = RD->getDefinition();
878 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
879 // decltype(((Foo_IMPL*)0)->bar) *
880 ObjCContainerDecl *CDecl =
881 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
882 // ivar in class extensions requires special treatment.
883 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
884 CDecl = CatDecl->getClassInterface();
885 std::string RecName = CDecl->getName();
886 RecName += "_IMPL";
887 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
888 SourceLocation(), SourceLocation(),
889 &Context->Idents.get(RecName.c_str()));
890 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
891 unsigned UnsignedIntSize =
892 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
893 Expr *Zero = IntegerLiteral::Create(*Context,
894 llvm::APInt(UnsignedIntSize, 0),
895 Context->UnsignedIntTy, SourceLocation());
896 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
897 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
898 Zero);
899 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
900 SourceLocation(),
901 &Context->Idents.get(D->getNameAsString()),
902 IvarT, 0,
903 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +0000904 ICIS_NoInit);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000905 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
906 FD->getType(), VK_LValue,
907 OK_Ordinary);
908 IvarT = Context->getDecltypeType(ME, ME->getType());
909 }
910 }
911 convertObjCTypeToCStyleType(IvarT);
912 QualType castT = Context->getPointerType(IvarT);
913 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
914 S += TypeString;
915 S += ")";
916
917 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
918 S += "((char *)self + ";
919 S += IvarOffsetName;
920 S += "))";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +0000921 if (D->isBitField()) {
922 S += ".";
923 S += D->getNameAsString();
924 }
Fariborz Jahanian89919cc2012-05-08 23:54:35 +0000925 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +0000926 return S;
927}
928
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000929/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
930/// been found in the class implementation. In this case, it must be synthesized.
931static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
932 ObjCPropertyDecl *PD,
933 bool getter) {
934 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
935 : !IMP->getInstanceMethod(PD->getSetterName());
936
937}
938
Fariborz Jahanian11671902012-02-07 17:11:38 +0000939void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
940 ObjCImplementationDecl *IMD,
941 ObjCCategoryImplDecl *CID) {
942 static bool objcGetPropertyDefined = false;
943 static bool objcSetPropertyDefined = false;
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000944 SourceLocation startGetterSetterLoc;
945
946 if (PID->getLocStart().isValid()) {
947 SourceLocation startLoc = PID->getLocStart();
948 InsertText(startLoc, "// ");
949 const char *startBuf = SM->getCharacterData(startLoc);
950 assert((*startBuf == '@') && "bogus @synthesize location");
951 const char *semiBuf = strchr(startBuf, ';');
952 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
953 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
954 }
955 else
956 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian11671902012-02-07 17:11:38 +0000957
958 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
959 return; // FIXME: is this correct?
960
961 // Generate the 'getter' function.
962 ObjCPropertyDecl *PD = PID->getPropertyDecl();
963 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Jordan Rose755a2ff2013-03-15 21:41:35 +0000964 assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
Fariborz Jahanian11671902012-02-07 17:11:38 +0000965
Bill Wendling44426052012-12-20 19:22:21 +0000966 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +0000967 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendling44426052012-12-20 19:22:21 +0000968 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
969 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +0000970 ObjCPropertyDecl::OBJC_PR_copy));
971 std::string Getr;
972 if (GenGetProperty && !objcGetPropertyDefined) {
973 objcGetPropertyDefined = true;
974 // FIXME. Is this attribute correct in all cases?
975 Getr = "\nextern \"C\" __declspec(dllimport) "
976 "id objc_getProperty(id, SEL, long, bool);\n";
977 }
978 RewriteObjCMethodDecl(OID->getContainingInterface(),
979 PD->getGetterMethodDecl(), Getr);
980 Getr += "{ ";
981 // Synthesize an explicit cast to gain access to the ivar.
982 // See objc-act.c:objc_synthesize_new_getter() for details.
983 if (GenGetProperty) {
984 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
985 Getr += "typedef ";
986 const FunctionType *FPRetType = 0;
Alp Toker314cc812014-01-25 16:55:45 +0000987 RewriteTypeIntoString(PD->getGetterMethodDecl()->getReturnType(), Getr,
Fariborz Jahanian11671902012-02-07 17:11:38 +0000988 FPRetType);
989 Getr += " _TYPE";
990 if (FPRetType) {
991 Getr += ")"; // close the precedence "scope" for "*".
992
993 // Now, emit the argument types (if any).
994 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
995 Getr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +0000996 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +0000997 if (i) Getr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +0000998 std::string ParamStr =
999 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001000 Getr += ParamStr;
1001 }
1002 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001003 if (FT->getNumParams())
1004 Getr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001005 Getr += "...";
1006 }
1007 Getr += ")";
1008 } else
1009 Getr += "()";
1010 }
1011 Getr += ";\n";
1012 Getr += "return (_TYPE)";
1013 Getr += "objc_getProperty(self, _cmd, ";
1014 RewriteIvarOffsetComputation(OID, Getr);
1015 Getr += ", 1)";
1016 }
1017 else
1018 Getr += "return " + getIvarAccessString(OID);
1019 Getr += "; }";
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001020 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001021 }
1022
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001023 if (PD->isReadOnly() ||
1024 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001025 return;
1026
1027 // Generate the 'setter' function.
1028 std::string Setr;
Bill Wendling44426052012-12-20 19:22:21 +00001029 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian11671902012-02-07 17:11:38 +00001030 ObjCPropertyDecl::OBJC_PR_copy);
1031 if (GenSetProperty && !objcSetPropertyDefined) {
1032 objcSetPropertyDefined = true;
1033 // FIXME. Is this attribute correct in all cases?
1034 Setr = "\nextern \"C\" __declspec(dllimport) "
1035 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1036 }
1037
1038 RewriteObjCMethodDecl(OID->getContainingInterface(),
1039 PD->getSetterMethodDecl(), Setr);
1040 Setr += "{ ";
1041 // Synthesize an explicit cast to initialize the ivar.
1042 // See objc-act.c:objc_synthesize_new_setter() for details.
1043 if (GenSetProperty) {
1044 Setr += "objc_setProperty (self, _cmd, ";
1045 RewriteIvarOffsetComputation(OID, Setr);
1046 Setr += ", (id)";
1047 Setr += PD->getName();
1048 Setr += ", ";
Bill Wendling44426052012-12-20 19:22:21 +00001049 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001050 Setr += "0, ";
1051 else
1052 Setr += "1, ";
Bill Wendling44426052012-12-20 19:22:21 +00001053 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001054 Setr += "1)";
1055 else
1056 Setr += "0)";
1057 }
1058 else {
1059 Setr += getIvarAccessString(OID) + " = ";
1060 Setr += PD->getName();
1061 }
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00001062 Setr += "; }\n";
1063 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001064}
1065
1066static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1067 std::string &typedefString) {
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001068 typedefString += "\n#ifndef _REWRITER_typedef_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001069 typedefString += ForwardDecl->getNameAsString();
1070 typedefString += "\n";
1071 typedefString += "#define _REWRITER_typedef_";
1072 typedefString += ForwardDecl->getNameAsString();
1073 typedefString += "\n";
1074 typedefString += "typedef struct objc_object ";
1075 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001076 // typedef struct { } _objc_exc_Classname;
1077 typedefString += ";\ntypedef struct {} _objc_exc_";
1078 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00001079 typedefString += ";\n#endif\n";
1080}
1081
1082void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1083 const std::string &typedefString) {
1084 SourceLocation startLoc = ClassDecl->getLocStart();
1085 const char *startBuf = SM->getCharacterData(startLoc);
1086 const char *semiPtr = strchr(startBuf, ';');
1087 // Replace the @class with typedefs corresponding to the classes.
1088 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1089}
1090
1091void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1092 std::string typedefString;
1093 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001094 if (ObjCInterfaceDecl *ForwardDecl = dyn_cast<ObjCInterfaceDecl>(*I)) {
1095 if (I == D.begin()) {
1096 // Translate to typedef's that forward reference structs with the same name
1097 // as the class. As a convenience, we include the original declaration
1098 // as a comment.
1099 typedefString += "// @class ";
1100 typedefString += ForwardDecl->getNameAsString();
1101 typedefString += ";";
1102 }
1103 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001104 }
Fariborz Jahanian0dded8a2013-09-24 17:03:07 +00001105 else
1106 HandleTopLevelSingleDecl(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001107 }
1108 DeclGroupRef::iterator I = D.begin();
1109 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1110}
1111
1112void RewriteModernObjC::RewriteForwardClassDecl(
Craig Topper5603df42013-07-05 19:34:19 +00001113 const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001114 std::string typedefString;
1115 for (unsigned i = 0; i < D.size(); i++) {
1116 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1117 if (i == 0) {
1118 typedefString += "// @class ";
1119 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahaniane8730a32013-02-08 17:15:07 +00001120 typedefString += ";";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001121 }
1122 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1123 }
1124 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1125}
1126
1127void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1128 // When method is a synthesized one, such as a getter/setter there is
1129 // nothing to rewrite.
1130 if (Method->isImplicit())
1131 return;
1132 SourceLocation LocStart = Method->getLocStart();
1133 SourceLocation LocEnd = Method->getLocEnd();
1134
1135 if (SM->getExpansionLineNumber(LocEnd) >
1136 SM->getExpansionLineNumber(LocStart)) {
1137 InsertText(LocStart, "#if 0\n");
1138 ReplaceText(LocEnd, 1, ";\n#endif\n");
1139 } else {
1140 InsertText(LocStart, "// ");
1141 }
1142}
1143
1144void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1145 SourceLocation Loc = prop->getAtLoc();
1146
1147 ReplaceText(Loc, 0, "// ");
1148 // FIXME: handle properties that are declared across multiple lines.
1149}
1150
1151void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1152 SourceLocation LocStart = CatDecl->getLocStart();
1153
1154 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001155 if (CatDecl->getIvarRBraceLoc().isValid()) {
1156 ReplaceText(LocStart, 1, "/** ");
1157 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1158 }
1159 else {
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001160 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001161 }
Fariborz Jahaniana7765fe2012-02-20 20:09:20 +00001162
Aaron Ballmand174edf2014-03-13 19:11:50 +00001163 for (auto *I : CatDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001164 RewriteProperty(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001165
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001166 for (auto *I : CatDecl->instance_methods())
1167 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001168 for (auto *I : CatDecl->class_methods())
1169 RewriteMethodDeclaration(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001170
1171 // Lastly, comment out the @end.
1172 ReplaceText(CatDecl->getAtEndRange().getBegin(),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001173 strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001174}
1175
1176void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1177 SourceLocation LocStart = PDecl->getLocStart();
1178 assert(PDecl->isThisDeclarationADefinition());
1179
1180 // FIXME: handle protocol headers that are declared across multiple lines.
1181 ReplaceText(LocStart, 0, "// ");
1182
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001183 for (auto *I : PDecl->instance_methods())
1184 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001185 for (auto *I : PDecl->class_methods())
1186 RewriteMethodDeclaration(I);
Aaron Ballmand174edf2014-03-13 19:11:50 +00001187 for (auto *I : PDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001188 RewriteProperty(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001189
1190 // Lastly, comment out the @end.
1191 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001192 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001193
1194 // Must comment out @optional/@required
1195 const char *startBuf = SM->getCharacterData(LocStart);
1196 const char *endBuf = SM->getCharacterData(LocEnd);
1197 for (const char *p = startBuf; p < endBuf; p++) {
1198 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1199 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1200 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1201
1202 }
1203 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1204 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1205 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1206
1207 }
1208 }
1209}
1210
1211void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1212 SourceLocation LocStart = (*D.begin())->getLocStart();
1213 if (LocStart.isInvalid())
1214 llvm_unreachable("Invalid SourceLocation");
1215 // FIXME: handle forward protocol that are declared across multiple lines.
1216 ReplaceText(LocStart, 0, "// ");
1217}
1218
1219void
Craig Topper5603df42013-07-05 19:34:19 +00001220RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001221 SourceLocation LocStart = DG[0]->getLocStart();
1222 if (LocStart.isInvalid())
1223 llvm_unreachable("Invalid SourceLocation");
1224 // FIXME: handle forward protocol that are declared across multiple lines.
1225 ReplaceText(LocStart, 0, "// ");
1226}
1227
Fariborz Jahanian08ed8922012-04-03 17:35:38 +00001228void
1229RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1230 SourceLocation LocStart = LSD->getExternLoc();
1231 if (LocStart.isInvalid())
1232 llvm_unreachable("Invalid extern SourceLocation");
1233
1234 ReplaceText(LocStart, 0, "// ");
1235 if (!LSD->hasBraces())
1236 return;
1237 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1238 SourceLocation LocRBrace = LSD->getRBraceLoc();
1239 if (LocRBrace.isInvalid())
1240 llvm_unreachable("Invalid rbrace SourceLocation");
1241 ReplaceText(LocRBrace, 0, "// ");
1242}
1243
Fariborz Jahanian11671902012-02-07 17:11:38 +00001244void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1245 const FunctionType *&FPRetType) {
1246 if (T->isObjCQualifiedIdType())
1247 ResultStr += "id";
1248 else if (T->isFunctionPointerType() ||
1249 T->isBlockPointerType()) {
1250 // needs special handling, since pointer-to-functions have special
1251 // syntax (where a decaration models use).
1252 QualType retType = T;
1253 QualType PointeeTy;
1254 if (const PointerType* PT = retType->getAs<PointerType>())
1255 PointeeTy = PT->getPointeeType();
1256 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1257 PointeeTy = BPT->getPointeeType();
1258 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Alp Toker314cc812014-01-25 16:55:45 +00001259 ResultStr +=
1260 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001261 ResultStr += "(*";
1262 }
1263 } else
1264 ResultStr += T.getAsString(Context->getPrintingPolicy());
1265}
1266
1267void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1268 ObjCMethodDecl *OMD,
1269 std::string &ResultStr) {
1270 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1271 const FunctionType *FPRetType = 0;
1272 ResultStr += "\nstatic ";
Alp Toker314cc812014-01-25 16:55:45 +00001273 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001274 ResultStr += " ";
1275
1276 // Unique method name
1277 std::string NameStr;
1278
1279 if (OMD->isInstanceMethod())
1280 NameStr += "_I_";
1281 else
1282 NameStr += "_C_";
1283
1284 NameStr += IDecl->getNameAsString();
1285 NameStr += "_";
1286
1287 if (ObjCCategoryImplDecl *CID =
1288 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1289 NameStr += CID->getNameAsString();
1290 NameStr += "_";
1291 }
1292 // Append selector names, replacing ':' with '_'
1293 {
1294 std::string selString = OMD->getSelector().getAsString();
1295 int len = selString.size();
1296 for (int i = 0; i < len; i++)
1297 if (selString[i] == ':')
1298 selString[i] = '_';
1299 NameStr += selString;
1300 }
1301 // Remember this name for metadata emission
1302 MethodInternalNames[OMD] = NameStr;
1303 ResultStr += NameStr;
1304
1305 // Rewrite arguments
1306 ResultStr += "(";
1307
1308 // invisible arguments
1309 if (OMD->isInstanceMethod()) {
1310 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1311 selfTy = Context->getPointerType(selfTy);
1312 if (!LangOpts.MicrosoftExt) {
1313 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1314 ResultStr += "struct ";
1315 }
1316 // When rewriting for Microsoft, explicitly omit the structure name.
1317 ResultStr += IDecl->getNameAsString();
1318 ResultStr += " *";
1319 }
1320 else
1321 ResultStr += Context->getObjCClassType().getAsString(
1322 Context->getPrintingPolicy());
1323
1324 ResultStr += " self, ";
1325 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1326 ResultStr += " _cmd";
1327
1328 // Method arguments.
Aaron Ballman43b68be2014-03-07 17:50:17 +00001329 for (const auto *PDecl : OMD->params()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001330 ResultStr += ", ";
1331 if (PDecl->getType()->isObjCQualifiedIdType()) {
1332 ResultStr += "id ";
1333 ResultStr += PDecl->getNameAsString();
1334 } else {
1335 std::string Name = PDecl->getNameAsString();
1336 QualType QT = PDecl->getType();
1337 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001338 (void)convertBlockPointerToFunctionPointer(QT);
1339 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001340 ResultStr += Name;
1341 }
1342 }
1343 if (OMD->isVariadic())
1344 ResultStr += ", ...";
1345 ResultStr += ") ";
1346
1347 if (FPRetType) {
1348 ResultStr += ")"; // close the precedence "scope" for "*".
1349
1350 // Now, emit the argument types (if any).
1351 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1352 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001353 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001354 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001355 std::string ParamStr =
1356 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001357 ResultStr += ParamStr;
1358 }
1359 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001360 if (FT->getNumParams())
1361 ResultStr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001362 ResultStr += "...";
1363 }
1364 ResultStr += ")";
1365 } else {
1366 ResultStr += "()";
1367 }
1368 }
1369}
1370void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1371 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1372 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1373
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001374 if (IMD) {
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001375 if (IMD->getIvarRBraceLoc().isValid()) {
1376 ReplaceText(IMD->getLocStart(), 1, "/** ");
1377 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001378 }
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001379 else {
1380 InsertText(IMD->getLocStart(), "// ");
1381 }
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001382 }
1383 else
1384 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001385
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001386 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001387 std::string ResultStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001388 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1389 SourceLocation LocStart = OMD->getLocStart();
1390 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1391
1392 const char *startBuf = SM->getCharacterData(LocStart);
1393 const char *endBuf = SM->getCharacterData(LocEnd);
1394 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1395 }
1396
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001397 for (auto *OMD : IMD ? IMD->class_methods() : CID->class_methods()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001398 std::string ResultStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001399 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1400 SourceLocation LocStart = OMD->getLocStart();
1401 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1402
1403 const char *startBuf = SM->getCharacterData(LocStart);
1404 const char *endBuf = SM->getCharacterData(LocEnd);
1405 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1406 }
Aaron Ballmand85eff42014-03-14 15:02:45 +00001407 for (auto *I : IMD ? IMD->property_impls() : CID->property_impls())
1408 RewritePropertyImplDecl(I, IMD, CID);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001409
1410 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1411}
1412
1413void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian088959a2012-02-11 20:10:52 +00001414 // Do not synthesize more than once.
1415 if (ObjCSynthesizedStructs.count(ClassDecl))
1416 return;
1417 // Make sure super class's are written before current class is written.
1418 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1419 while (SuperClass) {
1420 RewriteInterfaceDecl(SuperClass);
1421 SuperClass = SuperClass->getSuperClass();
1422 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001423 std::string ResultStr;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001424 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001425 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001426 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00001427 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1428
Fariborz Jahanianff513382012-02-15 22:01:47 +00001429 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001430 // Mark this typedef as having been written into its c++ equivalent.
1431 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanianff513382012-02-15 22:01:47 +00001432
Aaron Ballmand174edf2014-03-13 19:11:50 +00001433 for (auto *I : ClassDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001434 RewriteProperty(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001435 for (auto *I : ClassDecl->instance_methods())
1436 RewriteMethodDeclaration(I);
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00001437 for (auto *I : ClassDecl->class_methods())
1438 RewriteMethodDeclaration(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001439
Fariborz Jahanianff513382012-02-15 22:01:47 +00001440 // Lastly, comment out the @end.
1441 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001442 "/* @end */\n");
Fariborz Jahanianff513382012-02-15 22:01:47 +00001443 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001444}
1445
1446Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1447 SourceRange OldRange = PseudoOp->getSourceRange();
1448
1449 // We just magically know some things about the structure of this
1450 // expression.
1451 ObjCMessageExpr *OldMsg =
1452 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1453 PseudoOp->getNumSemanticExprs() - 1));
1454
1455 // Because the rewriter doesn't allow us to rewrite rewritten code,
1456 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001457 Expr *Base;
1458 SmallVector<Expr*, 2> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001459 {
1460 DisableReplaceStmtScope S(*this);
1461
1462 // Rebuild the base expression if we have one.
1463 Base = 0;
1464 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1465 Base = OldMsg->getInstanceReceiver();
1466 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1467 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1468 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001469
1470 unsigned numArgs = OldMsg->getNumArgs();
1471 for (unsigned i = 0; i < numArgs; i++) {
1472 Expr *Arg = OldMsg->getArg(i);
1473 if (isa<OpaqueValueExpr>(Arg))
1474 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1475 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1476 Args.push_back(Arg);
1477 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001478 }
1479
1480 // TODO: avoid this copy.
1481 SmallVector<SourceLocation, 1> SelLocs;
1482 OldMsg->getSelectorLocs(SelLocs);
1483
1484 ObjCMessageExpr *NewMsg = 0;
1485 switch (OldMsg->getReceiverKind()) {
1486 case ObjCMessageExpr::Class:
1487 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1488 OldMsg->getValueKind(),
1489 OldMsg->getLeftLoc(),
1490 OldMsg->getClassReceiverTypeInfo(),
1491 OldMsg->getSelector(),
1492 SelLocs,
1493 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001494 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001495 OldMsg->getRightLoc(),
1496 OldMsg->isImplicit());
1497 break;
1498
1499 case ObjCMessageExpr::Instance:
1500 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1501 OldMsg->getValueKind(),
1502 OldMsg->getLeftLoc(),
1503 Base,
1504 OldMsg->getSelector(),
1505 SelLocs,
1506 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001507 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001508 OldMsg->getRightLoc(),
1509 OldMsg->isImplicit());
1510 break;
1511
1512 case ObjCMessageExpr::SuperClass:
1513 case ObjCMessageExpr::SuperInstance:
1514 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1515 OldMsg->getValueKind(),
1516 OldMsg->getLeftLoc(),
1517 OldMsg->getSuperLoc(),
1518 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1519 OldMsg->getSuperType(),
1520 OldMsg->getSelector(),
1521 SelLocs,
1522 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001523 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001524 OldMsg->getRightLoc(),
1525 OldMsg->isImplicit());
1526 break;
1527 }
1528
1529 Stmt *Replacement = SynthMessageExpr(NewMsg);
1530 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1531 return Replacement;
1532}
1533
1534Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1535 SourceRange OldRange = PseudoOp->getSourceRange();
1536
1537 // We just magically know some things about the structure of this
1538 // expression.
1539 ObjCMessageExpr *OldMsg =
1540 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1541
1542 // Because the rewriter doesn't allow us to rewrite rewritten code,
1543 // we need to suppress rewriting the sub-statements.
1544 Expr *Base = 0;
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001545 SmallVector<Expr*, 1> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001546 {
1547 DisableReplaceStmtScope S(*this);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001548 // Rebuild the base expression if we have one.
1549 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1550 Base = OldMsg->getInstanceReceiver();
1551 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1552 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1553 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001554 unsigned numArgs = OldMsg->getNumArgs();
1555 for (unsigned i = 0; i < numArgs; i++) {
1556 Expr *Arg = OldMsg->getArg(i);
1557 if (isa<OpaqueValueExpr>(Arg))
1558 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1559 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1560 Args.push_back(Arg);
1561 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001562 }
1563
1564 // Intentionally empty.
1565 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001566
1567 ObjCMessageExpr *NewMsg = 0;
1568 switch (OldMsg->getReceiverKind()) {
1569 case ObjCMessageExpr::Class:
1570 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1571 OldMsg->getValueKind(),
1572 OldMsg->getLeftLoc(),
1573 OldMsg->getClassReceiverTypeInfo(),
1574 OldMsg->getSelector(),
1575 SelLocs,
1576 OldMsg->getMethodDecl(),
1577 Args,
1578 OldMsg->getRightLoc(),
1579 OldMsg->isImplicit());
1580 break;
1581
1582 case ObjCMessageExpr::Instance:
1583 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1584 OldMsg->getValueKind(),
1585 OldMsg->getLeftLoc(),
1586 Base,
1587 OldMsg->getSelector(),
1588 SelLocs,
1589 OldMsg->getMethodDecl(),
1590 Args,
1591 OldMsg->getRightLoc(),
1592 OldMsg->isImplicit());
1593 break;
1594
1595 case ObjCMessageExpr::SuperClass:
1596 case ObjCMessageExpr::SuperInstance:
1597 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1598 OldMsg->getValueKind(),
1599 OldMsg->getLeftLoc(),
1600 OldMsg->getSuperLoc(),
1601 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1602 OldMsg->getSuperType(),
1603 OldMsg->getSelector(),
1604 SelLocs,
1605 OldMsg->getMethodDecl(),
1606 Args,
1607 OldMsg->getRightLoc(),
1608 OldMsg->isImplicit());
1609 break;
1610 }
1611
1612 Stmt *Replacement = SynthMessageExpr(NewMsg);
1613 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1614 return Replacement;
1615}
1616
1617/// SynthCountByEnumWithState - To print:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001618/// ((NSUInteger (*)
1619/// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001620/// (void *)objc_msgSend)((id)l_collection,
1621/// sel_registerName(
1622/// "countByEnumeratingWithState:objects:count:"),
1623/// &enumState,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001624/// (id *)__rw_items, (NSUInteger)16)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001625///
1626void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001627 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1628 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001629 buf += "\n\t\t";
1630 buf += "((id)l_collection,\n\t\t";
1631 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1632 buf += "\n\t\t";
1633 buf += "&enumState, "
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001634 "(id *)__rw_items, (_WIN_NSUInteger)16)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001635}
1636
1637/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1638/// statement to exit to its outer synthesized loop.
1639///
1640Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1641 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1642 return S;
1643 // replace break with goto __break_label
1644 std::string buf;
1645
1646 SourceLocation startLoc = S->getLocStart();
1647 buf = "goto __break_label_";
1648 buf += utostr(ObjCBcLabelNo.back());
1649 ReplaceText(startLoc, strlen("break"), buf);
1650
1651 return 0;
1652}
1653
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001654void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1655 SourceLocation Loc,
1656 std::string &LineString) {
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00001657 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001658 LineString += "\n#line ";
1659 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1660 LineString += utostr(PLoc.getLine());
1661 LineString += " \"";
1662 LineString += Lexer::Stringify(PLoc.getFilename());
1663 LineString += "\"\n";
1664 }
1665}
1666
Fariborz Jahanian11671902012-02-07 17:11:38 +00001667/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1668/// statement to continue with its inner synthesized loop.
1669///
1670Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1671 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1672 return S;
1673 // replace continue with goto __continue_label
1674 std::string buf;
1675
1676 SourceLocation startLoc = S->getLocStart();
1677 buf = "goto __continue_label_";
1678 buf += utostr(ObjCBcLabelNo.back());
1679 ReplaceText(startLoc, strlen("continue"), buf);
1680
1681 return 0;
1682}
1683
1684/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1685/// It rewrites:
1686/// for ( type elem in collection) { stmts; }
1687
1688/// Into:
1689/// {
1690/// type elem;
1691/// struct __objcFastEnumerationState enumState = { 0 };
1692/// id __rw_items[16];
1693/// id l_collection = (id)collection;
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001694/// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian11671902012-02-07 17:11:38 +00001695/// objects:__rw_items count:16];
1696/// if (limit) {
1697/// unsigned long startMutations = *enumState.mutationsPtr;
1698/// do {
1699/// unsigned long counter = 0;
1700/// do {
1701/// if (startMutations != *enumState.mutationsPtr)
1702/// objc_enumerationMutation(l_collection);
1703/// elem = (type)enumState.itemsPtr[counter++];
1704/// stmts;
1705/// __continue_label: ;
1706/// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001707/// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1708/// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001709/// elem = nil;
1710/// __break_label: ;
1711/// }
1712/// else
1713/// elem = nil;
1714/// }
1715///
1716Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1717 SourceLocation OrigEnd) {
1718 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1719 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1720 "ObjCForCollectionStmt Statement stack mismatch");
1721 assert(!ObjCBcLabelNo.empty() &&
1722 "ObjCForCollectionStmt - Label No stack empty");
1723
1724 SourceLocation startLoc = S->getLocStart();
1725 const char *startBuf = SM->getCharacterData(startLoc);
1726 StringRef elementName;
1727 std::string elementTypeAsString;
1728 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001729 // line directive first.
1730 SourceLocation ForEachLoc = S->getForLoc();
1731 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1732 buf += "{\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001733 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1734 // type elem;
1735 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1736 QualType ElementType = cast<ValueDecl>(D)->getType();
1737 if (ElementType->isObjCQualifiedIdType() ||
1738 ElementType->isObjCQualifiedInterfaceType())
1739 // Simply use 'id' for all qualified types.
1740 elementTypeAsString = "id";
1741 else
1742 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1743 buf += elementTypeAsString;
1744 buf += " ";
1745 elementName = D->getName();
1746 buf += elementName;
1747 buf += ";\n\t";
1748 }
1749 else {
1750 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1751 elementName = DR->getDecl()->getName();
1752 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1753 if (VD->getType()->isObjCQualifiedIdType() ||
1754 VD->getType()->isObjCQualifiedInterfaceType())
1755 // Simply use 'id' for all qualified types.
1756 elementTypeAsString = "id";
1757 else
1758 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1759 }
1760
1761 // struct __objcFastEnumerationState enumState = { 0 };
1762 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1763 // id __rw_items[16];
1764 buf += "id __rw_items[16];\n\t";
1765 // id l_collection = (id)
1766 buf += "id l_collection = (id)";
1767 // Find start location of 'collection' the hard way!
1768 const char *startCollectionBuf = startBuf;
1769 startCollectionBuf += 3; // skip 'for'
1770 startCollectionBuf = strchr(startCollectionBuf, '(');
1771 startCollectionBuf++; // skip '('
1772 // find 'in' and skip it.
1773 while (*startCollectionBuf != ' ' ||
1774 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1775 (*(startCollectionBuf+3) != ' ' &&
1776 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1777 startCollectionBuf++;
1778 startCollectionBuf += 3;
1779
1780 // Replace: "for (type element in" with string constructed thus far.
1781 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1782 // Replace ')' in for '(' type elem in collection ')' with ';'
1783 SourceLocation rightParenLoc = S->getRParenLoc();
1784 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1785 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1786 buf = ";\n\t";
1787
1788 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1789 // objects:__rw_items count:16];
1790 // which is synthesized into:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001791 // NSUInteger limit =
1792 // ((NSUInteger (*)
1793 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001794 // (void *)objc_msgSend)((id)l_collection,
1795 // sel_registerName(
1796 // "countByEnumeratingWithState:objects:count:"),
1797 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001798 // (id *)__rw_items, (NSUInteger)16);
1799 buf += "_WIN_NSUInteger limit =\n\t\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001800 SynthCountByEnumWithState(buf);
1801 buf += ";\n\t";
1802 /// if (limit) {
1803 /// unsigned long startMutations = *enumState.mutationsPtr;
1804 /// do {
1805 /// unsigned long counter = 0;
1806 /// do {
1807 /// if (startMutations != *enumState.mutationsPtr)
1808 /// objc_enumerationMutation(l_collection);
1809 /// elem = (type)enumState.itemsPtr[counter++];
1810 buf += "if (limit) {\n\t";
1811 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1812 buf += "do {\n\t\t";
1813 buf += "unsigned long counter = 0;\n\t\t";
1814 buf += "do {\n\t\t\t";
1815 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1816 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1817 buf += elementName;
1818 buf += " = (";
1819 buf += elementTypeAsString;
1820 buf += ")enumState.itemsPtr[counter++];";
1821 // Replace ')' in for '(' type elem in collection ')' with all of these.
1822 ReplaceText(lparenLoc, 1, buf);
1823
1824 /// __continue_label: ;
1825 /// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001826 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1827 /// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001828 /// elem = nil;
1829 /// __break_label: ;
1830 /// }
1831 /// else
1832 /// elem = nil;
1833 /// }
1834 ///
1835 buf = ";\n\t";
1836 buf += "__continue_label_";
1837 buf += utostr(ObjCBcLabelNo.back());
1838 buf += ": ;";
1839 buf += "\n\t\t";
1840 buf += "} while (counter < limit);\n\t";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001841 buf += "} while ((limit = ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001842 SynthCountByEnumWithState(buf);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001843 buf += "));\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001844 buf += elementName;
1845 buf += " = ((";
1846 buf += elementTypeAsString;
1847 buf += ")0);\n\t";
1848 buf += "__break_label_";
1849 buf += utostr(ObjCBcLabelNo.back());
1850 buf += ": ;\n\t";
1851 buf += "}\n\t";
1852 buf += "else\n\t\t";
1853 buf += elementName;
1854 buf += " = ((";
1855 buf += elementTypeAsString;
1856 buf += ")0);\n\t";
1857 buf += "}\n";
1858
1859 // Insert all these *after* the statement body.
1860 // FIXME: If this should support Obj-C++, support CXXTryStmt
1861 if (isa<CompoundStmt>(S->getBody())) {
1862 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1863 InsertText(endBodyLoc, buf);
1864 } else {
1865 /* Need to treat single statements specially. For example:
1866 *
1867 * for (A *a in b) if (stuff()) break;
1868 * for (A *a in b) xxxyy;
1869 *
1870 * The following code simply scans ahead to the semi to find the actual end.
1871 */
1872 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1873 const char *semiBuf = strchr(stmtBuf, ';');
1874 assert(semiBuf && "Can't find ';'");
1875 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1876 InsertText(endBodyLoc, buf);
1877 }
1878 Stmts.pop_back();
1879 ObjCBcLabelNo.pop_back();
1880 return 0;
1881}
1882
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001883static void Write_RethrowObject(std::string &buf) {
1884 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1885 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1886 buf += "\tid rethrow;\n";
1887 buf += "\t} _fin_force_rethow(_rethrow);";
1888}
1889
Fariborz Jahanian11671902012-02-07 17:11:38 +00001890/// RewriteObjCSynchronizedStmt -
1891/// This routine rewrites @synchronized(expr) stmt;
1892/// into:
1893/// objc_sync_enter(expr);
1894/// @try stmt @finally { objc_sync_exit(expr); }
1895///
1896Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1897 // Get the start location and compute the semi location.
1898 SourceLocation startLoc = S->getLocStart();
1899 const char *startBuf = SM->getCharacterData(startLoc);
1900
1901 assert((*startBuf == '@') && "bogus @synchronized location");
1902
1903 std::string buf;
Fariborz Jahaniane030a632012-11-07 00:43:05 +00001904 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1905 ConvertSourceLocationToLineDirective(SynchLoc, buf);
Fariborz Jahanianff0c4602013-09-17 17:51:48 +00001906 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001907
Fariborz Jahanian11671902012-02-07 17:11:38 +00001908 const char *lparenBuf = startBuf;
1909 while (*lparenBuf != '(') lparenBuf++;
1910 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001911
1912 buf = "; objc_sync_enter(_sync_obj);\n";
1913 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1914 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1915 buf += "\n\tid sync_exit;";
1916 buf += "\n\t} _sync_exit(_sync_obj);\n";
1917
1918 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1919 // the sync expression is typically a message expression that's already
1920 // been rewritten! (which implies the SourceLocation's are invalid).
1921 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1922 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1923 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1924 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1925
1926 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1927 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1928 assert (*LBraceLocBuf == '{');
1929 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001930
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001931 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay6e177d32012-03-16 22:20:39 +00001932 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1933 "bogus @synchronized block");
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001934
1935 buf = "} catch (id e) {_rethrow = e;}\n";
1936 Write_RethrowObject(buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001937 buf += "}\n";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001938 buf += "}\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001939
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001940 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001941
Fariborz Jahanian11671902012-02-07 17:11:38 +00001942 return 0;
1943}
1944
1945void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1946{
1947 // Perform a bottom up traversal of all children.
1948 for (Stmt::child_range CI = S->children(); CI; ++CI)
1949 if (*CI)
1950 WarnAboutReturnGotoStmts(*CI);
1951
1952 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1953 Diags.Report(Context->getFullLoc(S->getLocStart()),
1954 TryFinallyContainsReturnDiag);
1955 }
1956 return;
1957}
1958
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001959Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1960 SourceLocation startLoc = S->getAtLoc();
1961 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc37a1d62012-05-24 22:59:56 +00001962 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1963 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001964
1965 return 0;
1966}
1967
Fariborz Jahanian11671902012-02-07 17:11:38 +00001968Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001969 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001970 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001971 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001972 SourceLocation TryLocation = S->getAtTryLoc();
1973 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001974
1975 if (finalStmt) {
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001976 if (noCatch)
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001977 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001978 else {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001979 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001980 }
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001981 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001982 // Get the start location and compute the semi location.
1983 SourceLocation startLoc = S->getLocStart();
1984 const char *startBuf = SM->getCharacterData(startLoc);
1985
1986 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001987 if (finalStmt)
1988 ReplaceText(startLoc, 1, buf);
1989 else
1990 // @try -> try
1991 ReplaceText(startLoc, 1, "");
1992
Fariborz Jahanian11671902012-02-07 17:11:38 +00001993 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1994 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001995 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001996
Fariborz Jahanian11671902012-02-07 17:11:38 +00001997 startLoc = Catch->getLocStart();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00001998 bool AtRemoved = false;
1999 if (catchDecl) {
2000 QualType t = catchDecl->getType();
2001 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
2002 // Should be a pointer to a class.
2003 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2004 if (IDecl) {
2005 std::string Result;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002006 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
2007
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002008 startBuf = SM->getCharacterData(startLoc);
2009 assert((*startBuf == '@') && "bogus @catch location");
2010 SourceLocation rParenLoc = Catch->getRParenLoc();
2011 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2012
2013 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002014 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002015 Result += " *_"; Result += catchDecl->getNameAsString();
2016 Result += ")";
2017 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2018 // Foo *e = (Foo *)_e;
2019 Result.clear();
2020 Result = "{ ";
2021 Result += IDecl->getNameAsString();
2022 Result += " *"; Result += catchDecl->getNameAsString();
2023 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2024 Result += "_"; Result += catchDecl->getNameAsString();
2025
2026 Result += "; ";
2027 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2028 ReplaceText(lBraceLoc, 1, Result);
2029 AtRemoved = true;
2030 }
2031 }
2032 }
2033 if (!AtRemoved)
2034 // @catch -> catch
2035 ReplaceText(startLoc, 1, "");
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00002036
Fariborz Jahanian11671902012-02-07 17:11:38 +00002037 }
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002038 if (finalStmt) {
2039 buf.clear();
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002040 SourceLocation FinallyLoc = finalStmt->getLocStart();
2041
2042 if (noCatch) {
2043 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2044 buf += "catch (id e) {_rethrow = e;}\n";
2045 }
2046 else {
2047 buf += "}\n";
2048 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2049 buf += "catch (id e) {_rethrow = e;}\n";
2050 }
2051
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002052 SourceLocation startFinalLoc = finalStmt->getLocStart();
2053 ReplaceText(startFinalLoc, 8, buf);
2054 Stmt *body = finalStmt->getFinallyBody();
2055 SourceLocation startFinalBodyLoc = body->getLocStart();
2056 buf.clear();
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00002057 Write_RethrowObject(buf);
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002058 ReplaceText(startFinalBodyLoc, 1, buf);
2059
2060 SourceLocation endFinalBodyLoc = body->getLocEnd();
2061 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahaniane8810762012-03-17 17:46:02 +00002062 // Now check for any return/continue/go statements within the @try.
2063 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002064 }
2065
Fariborz Jahanian11671902012-02-07 17:11:38 +00002066 return 0;
2067}
2068
2069// This can't be done with ReplaceStmt(S, ThrowExpr), since
2070// the throw expression is typically a message expression that's already
2071// been rewritten! (which implies the SourceLocation's are invalid).
2072Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2073 // Get the start location and compute the semi location.
2074 SourceLocation startLoc = S->getLocStart();
2075 const char *startBuf = SM->getCharacterData(startLoc);
2076
2077 assert((*startBuf == '@') && "bogus @throw location");
2078
2079 std::string buf;
2080 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2081 if (S->getThrowExpr())
2082 buf = "objc_exception_throw(";
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002083 else
2084 buf = "throw";
Fariborz Jahanian11671902012-02-07 17:11:38 +00002085
2086 // handle "@ throw" correctly.
2087 const char *wBuf = strchr(startBuf, 'w');
2088 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2089 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2090
Fariborz Jahanianb0fdab22013-02-11 19:30:33 +00002091 SourceLocation endLoc = S->getLocEnd();
2092 const char *endBuf = SM->getCharacterData(endLoc);
2093 const char *semiBuf = strchr(endBuf, ';');
Fariborz Jahanian11671902012-02-07 17:11:38 +00002094 assert((*semiBuf == ';') && "@throw: can't find ';'");
2095 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002096 if (S->getThrowExpr())
2097 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian11671902012-02-07 17:11:38 +00002098 return 0;
2099}
2100
2101Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2102 // Create a new string expression.
Fariborz Jahanian11671902012-02-07 17:11:38 +00002103 std::string StrEncoding;
2104 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Benjamin Kramerfc188422014-02-25 12:26:11 +00002105 Expr *Replacement = getStringLiteral(StrEncoding);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002106 ReplaceStmt(Exp, Replacement);
2107
2108 // Replace this subexpr in the parent.
2109 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2110 return Replacement;
2111}
2112
2113Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2114 if (!SelGetUidFunctionDecl)
2115 SynthSelGetUidFunctionDecl();
2116 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2117 // Create a call to sel_registerName("selName").
2118 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002119 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002120 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2121 &SelExprs[0], SelExprs.size());
2122 ReplaceStmt(Exp, SelExp);
2123 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2124 return SelExp;
2125}
2126
2127CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2128 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2129 SourceLocation EndLoc) {
2130 // Get the type, we will need to reference it in a couple spots.
2131 QualType msgSendType = FD->getType();
2132
2133 // Create a reference to the objc_msgSend() declaration.
2134 DeclRefExpr *DRE =
John McCall113bee02012-03-10 09:33:50 +00002135 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00002136
2137 // Now, we cast the reference to a pointer to the objc_msgSend type.
2138 QualType pToFunc = Context->getPointerType(msgSendType);
2139 ImplicitCastExpr *ICE =
2140 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2141 DRE, 0, VK_RValue);
2142
2143 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2144
2145 CallExpr *Exp =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002146 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian11671902012-02-07 17:11:38 +00002147 FT->getCallResultType(*Context),
2148 VK_RValue, EndLoc);
2149 return Exp;
2150}
2151
2152static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2153 const char *&startRef, const char *&endRef) {
2154 while (startBuf < endBuf) {
2155 if (*startBuf == '<')
2156 startRef = startBuf; // mark the start.
2157 if (*startBuf == '>') {
2158 if (startRef && *startRef == '<') {
2159 endRef = startBuf; // mark the end.
2160 return true;
2161 }
2162 return false;
2163 }
2164 startBuf++;
2165 }
2166 return false;
2167}
2168
2169static void scanToNextArgument(const char *&argRef) {
2170 int angle = 0;
2171 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2172 if (*argRef == '<')
2173 angle++;
2174 else if (*argRef == '>')
2175 angle--;
2176 argRef++;
2177 }
2178 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2179}
2180
2181bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2182 if (T->isObjCQualifiedIdType())
2183 return true;
2184 if (const PointerType *PT = T->getAs<PointerType>()) {
2185 if (PT->getPointeeType()->isObjCQualifiedIdType())
2186 return true;
2187 }
2188 if (T->isObjCObjectPointerType()) {
2189 T = T->getPointeeType();
2190 return T->isObjCQualifiedInterfaceType();
2191 }
2192 if (T->isArrayType()) {
2193 QualType ElemTy = Context->getBaseElementType(T);
2194 return needToScanForQualifiers(ElemTy);
2195 }
2196 return false;
2197}
2198
2199void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2200 QualType Type = E->getType();
2201 if (needToScanForQualifiers(Type)) {
2202 SourceLocation Loc, EndLoc;
2203
2204 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2205 Loc = ECE->getLParenLoc();
2206 EndLoc = ECE->getRParenLoc();
2207 } else {
2208 Loc = E->getLocStart();
2209 EndLoc = E->getLocEnd();
2210 }
2211 // This will defend against trying to rewrite synthesized expressions.
2212 if (Loc.isInvalid() || EndLoc.isInvalid())
2213 return;
2214
2215 const char *startBuf = SM->getCharacterData(Loc);
2216 const char *endBuf = SM->getCharacterData(EndLoc);
2217 const char *startRef = 0, *endRef = 0;
2218 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2219 // Get the locations of the startRef, endRef.
2220 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2221 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2222 // Comment out the protocol references.
2223 InsertText(LessLoc, "/*");
2224 InsertText(GreaterLoc, "*/");
2225 }
2226 }
2227}
2228
2229void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2230 SourceLocation Loc;
2231 QualType Type;
2232 const FunctionProtoType *proto = 0;
2233 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2234 Loc = VD->getLocation();
2235 Type = VD->getType();
2236 }
2237 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2238 Loc = FD->getLocation();
2239 // Check for ObjC 'id' and class types that have been adorned with protocol
2240 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2241 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2242 assert(funcType && "missing function type");
2243 proto = dyn_cast<FunctionProtoType>(funcType);
2244 if (!proto)
2245 return;
Alp Toker314cc812014-01-25 16:55:45 +00002246 Type = proto->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002247 }
2248 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2249 Loc = FD->getLocation();
2250 Type = FD->getType();
2251 }
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00002252 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2253 Loc = TD->getLocation();
2254 Type = TD->getUnderlyingType();
2255 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002256 else
2257 return;
2258
2259 if (needToScanForQualifiers(Type)) {
2260 // Since types are unique, we need to scan the buffer.
2261
2262 const char *endBuf = SM->getCharacterData(Loc);
2263 const char *startBuf = endBuf;
2264 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2265 startBuf--; // scan backward (from the decl location) for return type.
2266 const char *startRef = 0, *endRef = 0;
2267 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2268 // Get the locations of the startRef, endRef.
2269 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2270 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2271 // Comment out the protocol references.
2272 InsertText(LessLoc, "/*");
2273 InsertText(GreaterLoc, "*/");
2274 }
2275 }
2276 if (!proto)
2277 return; // most likely, was a variable
2278 // Now check arguments.
2279 const char *startBuf = SM->getCharacterData(Loc);
2280 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002281 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2282 if (needToScanForQualifiers(proto->getParamType(i))) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002283 // Since types are unique, we need to scan the buffer.
2284
2285 const char *endBuf = startBuf;
2286 // scan forward (from the decl location) for argument types.
2287 scanToNextArgument(endBuf);
2288 const char *startRef = 0, *endRef = 0;
2289 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2290 // Get the locations of the startRef, endRef.
2291 SourceLocation LessLoc =
2292 Loc.getLocWithOffset(startRef-startFuncBuf);
2293 SourceLocation GreaterLoc =
2294 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2295 // Comment out the protocol references.
2296 InsertText(LessLoc, "/*");
2297 InsertText(GreaterLoc, "*/");
2298 }
2299 startBuf = ++endBuf;
2300 }
2301 else {
2302 // If the function name is derived from a macro expansion, then the
2303 // argument buffer will not follow the name. Need to speak with Chris.
2304 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2305 startBuf++; // scan forward (from the decl location) for argument types.
2306 startBuf++;
2307 }
2308 }
2309}
2310
2311void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2312 QualType QT = ND->getType();
2313 const Type* TypePtr = QT->getAs<Type>();
2314 if (!isa<TypeOfExprType>(TypePtr))
2315 return;
2316 while (isa<TypeOfExprType>(TypePtr)) {
2317 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2318 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2319 TypePtr = QT->getAs<Type>();
2320 }
2321 // FIXME. This will not work for multiple declarators; as in:
2322 // __typeof__(a) b,c,d;
2323 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2324 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2325 const char *startBuf = SM->getCharacterData(DeclLoc);
2326 if (ND->getInit()) {
2327 std::string Name(ND->getNameAsString());
2328 TypeAsString += " " + Name + " = ";
2329 Expr *E = ND->getInit();
2330 SourceLocation startLoc;
2331 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2332 startLoc = ECE->getLParenLoc();
2333 else
2334 startLoc = E->getLocStart();
2335 startLoc = SM->getExpansionLoc(startLoc);
2336 const char *endBuf = SM->getCharacterData(startLoc);
2337 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2338 }
2339 else {
2340 SourceLocation X = ND->getLocEnd();
2341 X = SM->getExpansionLoc(X);
2342 const char *endBuf = SM->getCharacterData(X);
2343 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2344 }
2345}
2346
2347// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2348void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2349 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2350 SmallVector<QualType, 16> ArgTys;
2351 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2352 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002353 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002354 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002355 SourceLocation(),
2356 SourceLocation(),
2357 SelGetUidIdent, getFuncType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002358 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002359}
2360
2361void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2362 // declared in <objc/objc.h>
2363 if (FD->getIdentifier() &&
2364 FD->getName() == "sel_registerName") {
2365 SelGetUidFunctionDecl = FD;
2366 return;
2367 }
2368 RewriteObjCQualifiedInterfaceTypes(FD);
2369}
2370
2371void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2372 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2373 const char *argPtr = TypeString.c_str();
2374 if (!strchr(argPtr, '^')) {
2375 Str += TypeString;
2376 return;
2377 }
2378 while (*argPtr) {
2379 Str += (*argPtr == '^' ? '*' : *argPtr);
2380 argPtr++;
2381 }
2382}
2383
2384// FIXME. Consolidate this routine with RewriteBlockPointerType.
2385void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2386 ValueDecl *VD) {
2387 QualType Type = VD->getType();
2388 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2389 const char *argPtr = TypeString.c_str();
2390 int paren = 0;
2391 while (*argPtr) {
2392 switch (*argPtr) {
2393 case '(':
2394 Str += *argPtr;
2395 paren++;
2396 break;
2397 case ')':
2398 Str += *argPtr;
2399 paren--;
2400 break;
2401 case '^':
2402 Str += '*';
2403 if (paren == 1)
2404 Str += VD->getNameAsString();
2405 break;
2406 default:
2407 Str += *argPtr;
2408 break;
2409 }
2410 argPtr++;
2411 }
2412}
2413
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002414void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2415 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2416 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2417 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2418 if (!proto)
2419 return;
Alp Toker314cc812014-01-25 16:55:45 +00002420 QualType Type = proto->getReturnType();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002421 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2422 FdStr += " ";
2423 FdStr += FD->getName();
2424 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002425 unsigned numArgs = proto->getNumParams();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002426 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002427 QualType ArgType = proto->getParamType(i);
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002428 RewriteBlockPointerType(FdStr, ArgType);
2429 if (i+1 < numArgs)
2430 FdStr += ", ";
2431 }
Fariborz Jahaniandf0577d2012-04-19 16:30:28 +00002432 if (FD->isVariadic()) {
2433 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2434 }
2435 else
2436 FdStr += ");\n";
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002437 InsertText(FunLocStart, FdStr);
2438}
2439
Benjamin Kramer60509af2013-09-09 14:48:42 +00002440// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2441void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2442 if (SuperConstructorFunctionDecl)
Fariborz Jahanian11671902012-02-07 17:11:38 +00002443 return;
2444 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2445 SmallVector<QualType, 16> ArgTys;
2446 QualType argT = Context->getObjCIdType();
2447 assert(!argT.isNull() && "Can't find 'id' type");
2448 ArgTys.push_back(argT);
2449 ArgTys.push_back(argT);
2450 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002451 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002452 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002453 SourceLocation(),
2454 SourceLocation(),
2455 msgSendIdent, msgSendType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002456 0, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002457}
2458
2459// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2460void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2461 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2462 SmallVector<QualType, 16> ArgTys;
2463 QualType argT = Context->getObjCIdType();
2464 assert(!argT.isNull() && "Can't find 'id' type");
2465 ArgTys.push_back(argT);
2466 argT = Context->getObjCSelType();
2467 assert(!argT.isNull() && "Can't find 'SEL' type");
2468 ArgTys.push_back(argT);
2469 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002470 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002471 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002472 SourceLocation(),
2473 SourceLocation(),
2474 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002475 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002476}
2477
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002478// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002479void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2480 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002481 SmallVector<QualType, 2> ArgTys;
2482 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002483 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002484 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002485 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002486 SourceLocation(),
2487 SourceLocation(),
2488 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002489 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002490}
2491
2492// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2493void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2494 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2495 SmallVector<QualType, 16> ArgTys;
2496 QualType argT = Context->getObjCIdType();
2497 assert(!argT.isNull() && "Can't find 'id' type");
2498 ArgTys.push_back(argT);
2499 argT = Context->getObjCSelType();
2500 assert(!argT.isNull() && "Can't find 'SEL' type");
2501 ArgTys.push_back(argT);
2502 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002503 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002504 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002505 SourceLocation(),
2506 SourceLocation(),
2507 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002508 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002509}
2510
2511// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002512// id objc_msgSendSuper_stret(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002513void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2514 IdentifierInfo *msgSendIdent =
2515 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002516 SmallVector<QualType, 2> ArgTys;
2517 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002518 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002519 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002520 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2521 SourceLocation(),
2522 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002523 msgSendIdent,
2524 msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002525 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002526}
2527
2528// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2529void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2530 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2531 SmallVector<QualType, 16> ArgTys;
2532 QualType argT = Context->getObjCIdType();
2533 assert(!argT.isNull() && "Can't find 'id' type");
2534 ArgTys.push_back(argT);
2535 argT = Context->getObjCSelType();
2536 assert(!argT.isNull() && "Can't find 'SEL' type");
2537 ArgTys.push_back(argT);
2538 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002539 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002540 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002541 SourceLocation(),
2542 SourceLocation(),
2543 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002544 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002545}
2546
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002547// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002548void RewriteModernObjC::SynthGetClassFunctionDecl() {
2549 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2550 SmallVector<QualType, 16> ArgTys;
2551 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002552 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002553 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002554 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002555 SourceLocation(),
2556 SourceLocation(),
2557 getClassIdent, getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002558 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002559}
2560
2561// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2562void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2563 IdentifierInfo *getSuperClassIdent =
2564 &Context->Idents.get("class_getSuperclass");
2565 SmallVector<QualType, 16> ArgTys;
2566 ArgTys.push_back(Context->getObjCClassType());
2567 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002568 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002569 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2570 SourceLocation(),
2571 SourceLocation(),
2572 getSuperClassIdent,
2573 getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002574 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002575}
2576
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002577// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002578void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2579 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2580 SmallVector<QualType, 16> ArgTys;
2581 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002582 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002583 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002584 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002585 SourceLocation(),
2586 SourceLocation(),
2587 getClassIdent, getClassType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002588 0, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002589}
2590
2591Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2592 QualType strType = getConstantStringStructType();
2593
2594 std::string S = "__NSConstantStringImpl_";
2595
2596 std::string tmpName = InFileName;
2597 unsigned i;
2598 for (i=0; i < tmpName.length(); i++) {
2599 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002600 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002601 if (!isAlphanumeric(c))
Fariborz Jahanian11671902012-02-07 17:11:38 +00002602 tmpName[i] = '_';
2603 }
2604 S += tmpName;
2605 S += "_";
2606 S += utostr(NumObjCStringLiterals++);
2607
2608 Preamble += "static __NSConstantStringImpl " + S;
2609 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2610 Preamble += "0x000007c8,"; // utf8_str
2611 // The pretty printer for StringLiteral handles escape characters properly.
2612 std::string prettyBufS;
2613 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smith235341b2012-08-16 03:56:14 +00002614 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002615 Preamble += prettyBuf.str();
2616 Preamble += ",";
2617 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2618
2619 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2620 SourceLocation(), &Context->Idents.get(S),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002621 strType, 0, SC_Static);
John McCall113bee02012-03-10 09:33:50 +00002622 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00002623 SourceLocation());
2624 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2625 Context->getPointerType(DRE->getType()),
2626 VK_RValue, OK_Ordinary,
2627 SourceLocation());
2628 // cast to NSConstantString *
2629 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2630 CK_CPointerToObjCPointerCast, Unop);
2631 ReplaceStmt(Exp, cast);
2632 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2633 return cast;
2634}
2635
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002636Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2637 unsigned IntSize =
2638 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2639
2640 Expr *FlagExp = IntegerLiteral::Create(*Context,
2641 llvm::APInt(IntSize, Exp->getValue()),
2642 Context->IntTy, Exp->getLocation());
2643 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2644 CK_BitCast, FlagExp);
2645 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2646 cast);
2647 ReplaceStmt(Exp, PE);
2648 return PE;
2649}
2650
Patrick Beard0caa3942012-04-19 00:25:12 +00002651Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002652 // synthesize declaration of helper functions needed in this routine.
2653 if (!SelGetUidFunctionDecl)
2654 SynthSelGetUidFunctionDecl();
2655 // use objc_msgSend() for all.
2656 if (!MsgSendFunctionDecl)
2657 SynthMsgSendFunctionDecl();
2658 if (!GetClassFunctionDecl)
2659 SynthGetClassFunctionDecl();
2660
2661 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2662 SourceLocation StartLoc = Exp->getLocStart();
2663 SourceLocation EndLoc = Exp->getLocEnd();
2664
2665 // Synthesize a call to objc_msgSend().
2666 SmallVector<Expr*, 4> MsgExprs;
2667 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002668
Patrick Beard0caa3942012-04-19 00:25:12 +00002669 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2670 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2671 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002672
Patrick Beard0caa3942012-04-19 00:25:12 +00002673 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002674 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002675 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2676 &ClsExprs[0],
2677 ClsExprs.size(),
2678 StartLoc, EndLoc);
2679 MsgExprs.push_back(Cls);
2680
Patrick Beard0caa3942012-04-19 00:25:12 +00002681 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002682 // it will be the 2nd argument.
2683 SmallVector<Expr*, 4> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002684 SelExprs.push_back(
2685 getStringLiteral(BoxingMethod->getSelector().getAsString()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002686 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2687 &SelExprs[0], SelExprs.size(),
2688 StartLoc, EndLoc);
2689 MsgExprs.push_back(SelExp);
2690
Patrick Beard0caa3942012-04-19 00:25:12 +00002691 // User provided sub-expression is the 3rd, and last, argument.
2692 Expr *subExpr = Exp->getSubExpr();
2693 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002694 QualType type = ICE->getType();
2695 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2696 CastKind CK = CK_BitCast;
2697 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2698 CK = CK_IntegralToBoolean;
Patrick Beard0caa3942012-04-19 00:25:12 +00002699 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002700 }
Patrick Beard0caa3942012-04-19 00:25:12 +00002701 MsgExprs.push_back(subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002702
2703 SmallVector<QualType, 4> ArgTypes;
2704 ArgTypes.push_back(Context->getObjCIdType());
2705 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002706 for (const auto PI : BoxingMethod->parameters())
2707 ArgTypes.push_back(PI->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +00002708
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002709 QualType returnType = Exp->getType();
2710 // Get the type, we will need to reference it in a couple spots.
2711 QualType msgSendType = MsgSendFlavor->getType();
2712
2713 // Create a reference to the objc_msgSend() declaration.
2714 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2715 VK_LValue, SourceLocation());
2716
2717 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beard0caa3942012-04-19 00:25:12 +00002718 Context->getPointerType(Context->VoidTy),
2719 CK_BitCast, DRE);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002720
2721 // Now do the "normal" pointer to function cast.
2722 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002723 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002724 castType = Context->getPointerType(castType);
2725 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2726 cast);
2727
2728 // Don't forget the parens to enforce the proper binding.
2729 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2730
2731 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002732 CallExpr *CE = new (Context)
2733 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002734 ReplaceStmt(Exp, CE);
2735 return CE;
2736}
2737
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002738Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2739 // synthesize declaration of helper functions needed in this routine.
2740 if (!SelGetUidFunctionDecl)
2741 SynthSelGetUidFunctionDecl();
2742 // use objc_msgSend() for all.
2743 if (!MsgSendFunctionDecl)
2744 SynthMsgSendFunctionDecl();
2745 if (!GetClassFunctionDecl)
2746 SynthGetClassFunctionDecl();
2747
2748 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2749 SourceLocation StartLoc = Exp->getLocStart();
2750 SourceLocation EndLoc = Exp->getLocEnd();
2751
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002752 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002753 QualType IntQT = Context->IntTy;
2754 QualType NSArrayFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002755 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002756 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002757 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2758 DeclRefExpr *NSArrayDRE =
2759 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2760 SourceLocation());
2761
2762 SmallVector<Expr*, 16> InitExprs;
2763 unsigned NumElements = Exp->getNumElements();
2764 unsigned UnsignedIntSize =
2765 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2766 Expr *count = IntegerLiteral::Create(*Context,
2767 llvm::APInt(UnsignedIntSize, NumElements),
2768 Context->UnsignedIntTy, SourceLocation());
2769 InitExprs.push_back(count);
2770 for (unsigned i = 0; i < NumElements; i++)
2771 InitExprs.push_back(Exp->getElement(i));
2772 Expr *NSArrayCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002773 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002774 NSArrayFType, VK_LValue, SourceLocation());
2775
2776 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2777 SourceLocation(),
2778 &Context->Idents.get("arr"),
2779 Context->getPointerType(Context->VoidPtrTy), 0,
2780 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002781 ICIS_NoInit);
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002782 MemberExpr *ArrayLiteralME =
2783 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2784 SourceLocation(),
2785 ARRFD->getType(), VK_LValue,
2786 OK_Ordinary);
2787 QualType ConstIdT = Context->getObjCIdType().withConst();
2788 CStyleCastExpr * ArrayLiteralObjects =
2789 NoTypeInfoCStyleCastExpr(Context,
2790 Context->getPointerType(ConstIdT),
2791 CK_BitCast,
2792 ArrayLiteralME);
2793
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002794 // Synthesize a call to objc_msgSend().
2795 SmallVector<Expr*, 32> MsgExprs;
2796 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002797 QualType expType = Exp->getType();
2798
2799 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2800 ObjCInterfaceDecl *Class =
2801 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2802
2803 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002804 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002805 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2806 &ClsExprs[0],
2807 ClsExprs.size(),
2808 StartLoc, EndLoc);
2809 MsgExprs.push_back(Cls);
2810
2811 // Create a call to sel_registerName("arrayWithObjects:count:").
2812 // it will be the 2nd argument.
2813 SmallVector<Expr*, 4> SelExprs;
2814 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002815 SelExprs.push_back(
2816 getStringLiteral(ArrayMethod->getSelector().getAsString()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002817 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2818 &SelExprs[0], SelExprs.size(),
2819 StartLoc, EndLoc);
2820 MsgExprs.push_back(SelExp);
2821
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002822 // (const id [])objects
2823 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002824
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002825 // (NSUInteger)cnt
2826 Expr *cnt = IntegerLiteral::Create(*Context,
2827 llvm::APInt(UnsignedIntSize, NumElements),
2828 Context->UnsignedIntTy, SourceLocation());
2829 MsgExprs.push_back(cnt);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002830
2831
2832 SmallVector<QualType, 4> ArgTypes;
2833 ArgTypes.push_back(Context->getObjCIdType());
2834 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002835 for (const auto *PI : ArrayMethod->params())
2836 ArgTypes.push_back(PI->getType());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002837
2838 QualType returnType = Exp->getType();
2839 // Get the type, we will need to reference it in a couple spots.
2840 QualType msgSendType = MsgSendFlavor->getType();
2841
2842 // Create a reference to the objc_msgSend() declaration.
2843 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2844 VK_LValue, SourceLocation());
2845
2846 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2847 Context->getPointerType(Context->VoidTy),
2848 CK_BitCast, DRE);
2849
2850 // Now do the "normal" pointer to function cast.
2851 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002852 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002853 castType = Context->getPointerType(castType);
2854 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2855 cast);
2856
2857 // Don't forget the parens to enforce the proper binding.
2858 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2859
2860 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002861 CallExpr *CE = new (Context)
2862 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002863 ReplaceStmt(Exp, CE);
2864 return CE;
2865}
2866
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002867Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2868 // synthesize declaration of helper functions needed in this routine.
2869 if (!SelGetUidFunctionDecl)
2870 SynthSelGetUidFunctionDecl();
2871 // use objc_msgSend() for all.
2872 if (!MsgSendFunctionDecl)
2873 SynthMsgSendFunctionDecl();
2874 if (!GetClassFunctionDecl)
2875 SynthGetClassFunctionDecl();
2876
2877 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2878 SourceLocation StartLoc = Exp->getLocStart();
2879 SourceLocation EndLoc = Exp->getLocEnd();
2880
2881 // Build the expression: __NSContainer_literal(int, ...).arr
2882 QualType IntQT = Context->IntTy;
2883 QualType NSDictFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002884 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002885 std::string NSDictFName("__NSContainer_literal");
2886 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2887 DeclRefExpr *NSDictDRE =
2888 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2889 SourceLocation());
2890
2891 SmallVector<Expr*, 16> KeyExprs;
2892 SmallVector<Expr*, 16> ValueExprs;
2893
2894 unsigned NumElements = Exp->getNumElements();
2895 unsigned UnsignedIntSize =
2896 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2897 Expr *count = IntegerLiteral::Create(*Context,
2898 llvm::APInt(UnsignedIntSize, NumElements),
2899 Context->UnsignedIntTy, SourceLocation());
2900 KeyExprs.push_back(count);
2901 ValueExprs.push_back(count);
2902 for (unsigned i = 0; i < NumElements; i++) {
2903 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2904 KeyExprs.push_back(Element.Key);
2905 ValueExprs.push_back(Element.Value);
2906 }
2907
2908 // (const id [])objects
2909 Expr *NSValueCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002910 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002911 NSDictFType, VK_LValue, SourceLocation());
2912
2913 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2914 SourceLocation(),
2915 &Context->Idents.get("arr"),
2916 Context->getPointerType(Context->VoidPtrTy), 0,
2917 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002918 ICIS_NoInit);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002919 MemberExpr *DictLiteralValueME =
2920 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2921 SourceLocation(),
2922 ARRFD->getType(), VK_LValue,
2923 OK_Ordinary);
2924 QualType ConstIdT = Context->getObjCIdType().withConst();
2925 CStyleCastExpr * DictValueObjects =
2926 NoTypeInfoCStyleCastExpr(Context,
2927 Context->getPointerType(ConstIdT),
2928 CK_BitCast,
2929 DictLiteralValueME);
2930 // (const id <NSCopying> [])keys
2931 Expr *NSKeyCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002932 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002933 NSDictFType, VK_LValue, SourceLocation());
2934
2935 MemberExpr *DictLiteralKeyME =
2936 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2937 SourceLocation(),
2938 ARRFD->getType(), VK_LValue,
2939 OK_Ordinary);
2940
2941 CStyleCastExpr * DictKeyObjects =
2942 NoTypeInfoCStyleCastExpr(Context,
2943 Context->getPointerType(ConstIdT),
2944 CK_BitCast,
2945 DictLiteralKeyME);
2946
2947
2948
2949 // Synthesize a call to objc_msgSend().
2950 SmallVector<Expr*, 32> MsgExprs;
2951 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002952 QualType expType = Exp->getType();
2953
2954 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2955 ObjCInterfaceDecl *Class =
2956 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2957
2958 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002959 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002960 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2961 &ClsExprs[0],
2962 ClsExprs.size(),
2963 StartLoc, EndLoc);
2964 MsgExprs.push_back(Cls);
2965
2966 // Create a call to sel_registerName("arrayWithObjects:count:").
2967 // it will be the 2nd argument.
2968 SmallVector<Expr*, 4> SelExprs;
2969 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002970 SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002971 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2972 &SelExprs[0], SelExprs.size(),
2973 StartLoc, EndLoc);
2974 MsgExprs.push_back(SelExp);
2975
2976 // (const id [])objects
2977 MsgExprs.push_back(DictValueObjects);
2978
2979 // (const id <NSCopying> [])keys
2980 MsgExprs.push_back(DictKeyObjects);
2981
2982 // (NSUInteger)cnt
2983 Expr *cnt = IntegerLiteral::Create(*Context,
2984 llvm::APInt(UnsignedIntSize, NumElements),
2985 Context->UnsignedIntTy, SourceLocation());
2986 MsgExprs.push_back(cnt);
2987
2988
2989 SmallVector<QualType, 8> ArgTypes;
2990 ArgTypes.push_back(Context->getObjCIdType());
2991 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002992 for (const auto *PI : DictMethod->params()) {
2993 QualType T = PI->getType();
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002994 if (const PointerType* PT = T->getAs<PointerType>()) {
2995 QualType PointeeTy = PT->getPointeeType();
2996 convertToUnqualifiedObjCType(PointeeTy);
2997 T = Context->getPointerType(PointeeTy);
2998 }
2999 ArgTypes.push_back(T);
3000 }
3001
3002 QualType returnType = Exp->getType();
3003 // Get the type, we will need to reference it in a couple spots.
3004 QualType msgSendType = MsgSendFlavor->getType();
3005
3006 // Create a reference to the objc_msgSend() declaration.
3007 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3008 VK_LValue, SourceLocation());
3009
3010 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3011 Context->getPointerType(Context->VoidTy),
3012 CK_BitCast, DRE);
3013
3014 // Now do the "normal" pointer to function cast.
3015 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003016 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003017 castType = Context->getPointerType(castType);
3018 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3019 cast);
3020
3021 // Don't forget the parens to enforce the proper binding.
3022 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3023
3024 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003025 CallExpr *CE = new (Context)
3026 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003027 ReplaceStmt(Exp, CE);
3028 return CE;
3029}
3030
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003031// struct __rw_objc_super {
3032// struct objc_object *object; struct objc_object *superClass;
3033// };
Fariborz Jahanian11671902012-02-07 17:11:38 +00003034QualType RewriteModernObjC::getSuperStructType() {
3035 if (!SuperStructDecl) {
3036 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3037 SourceLocation(), SourceLocation(),
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003038 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003039 QualType FieldTypes[2];
3040
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003041 // struct objc_object *object;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003042 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003043 // struct objc_object *superClass;
3044 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003045
3046 // Create fields
3047 for (unsigned i = 0; i < 2; ++i) {
3048 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3049 SourceLocation(),
3050 SourceLocation(), 0,
3051 FieldTypes[i], 0,
3052 /*BitWidth=*/0,
3053 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003054 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003055 }
3056
3057 SuperStructDecl->completeDefinition();
3058 }
3059 return Context->getTagDeclType(SuperStructDecl);
3060}
3061
3062QualType RewriteModernObjC::getConstantStringStructType() {
3063 if (!ConstantStringDecl) {
3064 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3065 SourceLocation(), SourceLocation(),
3066 &Context->Idents.get("__NSConstantStringImpl"));
3067 QualType FieldTypes[4];
3068
3069 // struct objc_object *receiver;
3070 FieldTypes[0] = Context->getObjCIdType();
3071 // int flags;
3072 FieldTypes[1] = Context->IntTy;
3073 // char *str;
3074 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3075 // long length;
3076 FieldTypes[3] = Context->LongTy;
3077
3078 // Create fields
3079 for (unsigned i = 0; i < 4; ++i) {
3080 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3081 ConstantStringDecl,
3082 SourceLocation(),
3083 SourceLocation(), 0,
3084 FieldTypes[i], 0,
3085 /*BitWidth=*/0,
3086 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003087 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003088 }
3089
3090 ConstantStringDecl->completeDefinition();
3091 }
3092 return Context->getTagDeclType(ConstantStringDecl);
3093}
3094
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003095/// getFunctionSourceLocation - returns start location of a function
3096/// definition. Complication arises when function has declared as
3097/// extern "C" or extern "C" {...}
3098static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3099 FunctionDecl *FD) {
3100 if (FD->isExternC() && !FD->isMain()) {
3101 const DeclContext *DC = FD->getDeclContext();
3102 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3103 // if it is extern "C" {...}, return function decl's own location.
3104 if (!LSD->getRBraceLoc().isValid())
3105 return LSD->getExternLoc();
3106 }
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003107 if (FD->getStorageClass() != SC_None)
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003108 R.RewriteBlockLiteralFunctionDecl(FD);
3109 return FD->getTypeSpecStartLoc();
3110}
3111
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003112void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3113
3114 SourceLocation Location = D->getLocation();
3115
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00003116 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian83dadc72012-11-07 18:15:53 +00003117 std::string LineString("\n#line ");
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003118 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3119 LineString += utostr(PLoc.getLine());
3120 LineString += " \"";
NAKAMURA Takumib46a05c2012-11-06 22:45:31 +00003121 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003122 if (isa<ObjCMethodDecl>(D))
3123 LineString += "\"";
3124 else LineString += "\"\n";
3125
3126 Location = D->getLocStart();
3127 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3128 if (FD->isExternC() && !FD->isMain()) {
3129 const DeclContext *DC = FD->getDeclContext();
3130 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3131 // if it is extern "C" {...}, return function decl's own location.
3132 if (!LSD->getRBraceLoc().isValid())
3133 Location = LSD->getExternLoc();
3134 }
3135 }
3136 InsertText(Location, LineString);
3137 }
3138}
3139
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003140/// SynthMsgSendStretCallExpr - This routine translates message expression
3141/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3142/// nil check on receiver must be performed before calling objc_msgSend_stret.
3143/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3144/// msgSendType - function type of objc_msgSend_stret(...)
3145/// returnType - Result type of the method being synthesized.
3146/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3147/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3148/// starting with receiver.
3149/// Method - Method being rewritten.
3150Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003151 QualType returnType,
3152 SmallVectorImpl<QualType> &ArgTypes,
3153 SmallVectorImpl<Expr*> &MsgExprs,
3154 ObjCMethodDecl *Method) {
3155 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003156 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3157 Method ? Method->isVariadic()
3158 : false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003159 castType = Context->getPointerType(castType);
3160
3161 // build type for containing the objc_msgSend_stret object.
3162 static unsigned stretCount=0;
3163 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003164 std::string str =
3165 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003166 str += "namespace {\n";
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003167 str += "struct "; str += name;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003168 str += " {\n\t";
3169 str += name;
3170 str += "(id receiver, SEL sel";
3171 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003172 std::string ArgName = "arg"; ArgName += utostr(i);
3173 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3174 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003175 }
3176 // could be vararg.
3177 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003178 std::string ArgName = "arg"; ArgName += utostr(i);
3179 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3180 Context->getPrintingPolicy());
3181 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003182 }
3183
3184 str += ") {\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003185 str += "\t unsigned size = sizeof(";
3186 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3187
3188 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3189
3190 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3191 str += ")(void *)objc_msgSend)(receiver, sel";
3192 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3193 str += ", arg"; str += utostr(i);
3194 }
3195 // could be vararg.
3196 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3197 str += ", arg"; str += utostr(i);
3198 }
3199 str+= ");\n";
3200
3201 str += "\t else if (receiver == 0)\n";
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003202 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3203 str += "\t else\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003204
3205
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003206 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3207 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3208 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3209 str += ", arg"; str += utostr(i);
3210 }
3211 // could be vararg.
3212 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3213 str += ", arg"; str += utostr(i);
3214 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003215 str += ");\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003216
3217
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003218 str += "\t}\n";
3219 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3220 str += " s;\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003221 str += "};\n};\n\n";
Fariborz Jahanianf1f36c62012-08-21 18:56:50 +00003222 SourceLocation FunLocStart;
3223 if (CurFunctionDef)
3224 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3225 else {
3226 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3227 FunLocStart = CurMethodDef->getLocStart();
3228 }
3229
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003230 InsertText(FunLocStart, str);
3231 ++stretCount;
3232
3233 // AST for __Stretn(receiver, args).s;
3234 IdentifierInfo *ID = &Context->Idents.get(name);
3235 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00003236 SourceLocation(), ID, castType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003237 SC_Extern, false, false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003238 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3239 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003240 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003241 castType, VK_LValue, SourceLocation());
3242
3243 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3244 SourceLocation(),
3245 &Context->Idents.get("s"),
3246 returnType, 0,
3247 /*BitWidth=*/0, /*Mutable=*/true,
3248 ICIS_NoInit);
3249 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3250 FieldD->getType(), VK_LValue,
3251 OK_Ordinary);
3252
3253 return ME;
3254}
3255
Fariborz Jahanian11671902012-02-07 17:11:38 +00003256Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3257 SourceLocation StartLoc,
3258 SourceLocation EndLoc) {
3259 if (!SelGetUidFunctionDecl)
3260 SynthSelGetUidFunctionDecl();
3261 if (!MsgSendFunctionDecl)
3262 SynthMsgSendFunctionDecl();
3263 if (!MsgSendSuperFunctionDecl)
3264 SynthMsgSendSuperFunctionDecl();
3265 if (!MsgSendStretFunctionDecl)
3266 SynthMsgSendStretFunctionDecl();
3267 if (!MsgSendSuperStretFunctionDecl)
3268 SynthMsgSendSuperStretFunctionDecl();
3269 if (!MsgSendFpretFunctionDecl)
3270 SynthMsgSendFpretFunctionDecl();
3271 if (!GetClassFunctionDecl)
3272 SynthGetClassFunctionDecl();
3273 if (!GetSuperClassFunctionDecl)
3274 SynthGetSuperClassFunctionDecl();
3275 if (!GetMetaClassFunctionDecl)
3276 SynthGetMetaClassFunctionDecl();
3277
3278 // default to objc_msgSend().
3279 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3280 // May need to use objc_msgSend_stret() as well.
3281 FunctionDecl *MsgSendStretFlavor = 0;
3282 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003283 QualType resultType = mDecl->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003284 if (resultType->isRecordType())
3285 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3286 else if (resultType->isRealFloatingType())
3287 MsgSendFlavor = MsgSendFpretFunctionDecl;
3288 }
3289
3290 // Synthesize a call to objc_msgSend().
3291 SmallVector<Expr*, 8> MsgExprs;
3292 switch (Exp->getReceiverKind()) {
3293 case ObjCMessageExpr::SuperClass: {
3294 MsgSendFlavor = MsgSendSuperFunctionDecl;
3295 if (MsgSendStretFlavor)
3296 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3297 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3298
3299 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3300
3301 SmallVector<Expr*, 4> InitExprs;
3302
3303 // set the receiver to self, the first argument to all methods.
3304 InitExprs.push_back(
3305 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3306 CK_BitCast,
3307 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003308 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003309 Context->getObjCIdType(),
3310 VK_RValue,
3311 SourceLocation()))
3312 ); // set the 'receiver'.
3313
3314 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3315 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003316 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003317 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003318 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3319 &ClsExprs[0],
3320 ClsExprs.size(),
3321 StartLoc,
3322 EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003323 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003324 ClsExprs.push_back(Cls);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003325 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3326 &ClsExprs[0], ClsExprs.size(),
3327 StartLoc, EndLoc);
3328
3329 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3330 // To turn off a warning, type-cast to 'id'
3331 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3332 NoTypeInfoCStyleCastExpr(Context,
3333 Context->getObjCIdType(),
3334 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003335 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003336 QualType superType = getSuperStructType();
3337 Expr *SuperRep;
3338
3339 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003340 SynthSuperConstructorFunctionDecl();
3341 // Simulate a constructor call...
3342 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003343 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003344 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003345 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003346 superType, VK_LValue,
3347 SourceLocation());
3348 // The code for super is a little tricky to prevent collision with
3349 // the structure definition in the header. The rewriter has it's own
3350 // internal definition (__rw_objc_super) that is uses. This is why
3351 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003352 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003353 //
3354 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3355 Context->getPointerType(SuperRep->getType()),
3356 VK_RValue, OK_Ordinary,
3357 SourceLocation());
3358 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3359 Context->getPointerType(superType),
3360 CK_BitCast, SuperRep);
3361 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003362 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003363 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003364 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003365 SourceLocation());
3366 TypeSourceInfo *superTInfo
3367 = Context->getTrivialTypeSourceInfo(superType);
3368 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3369 superType, VK_LValue,
3370 ILE, false);
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003371 // struct __rw_objc_super *
Fariborz Jahanian11671902012-02-07 17:11:38 +00003372 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3373 Context->getPointerType(SuperRep->getType()),
3374 VK_RValue, OK_Ordinary,
3375 SourceLocation());
3376 }
3377 MsgExprs.push_back(SuperRep);
3378 break;
3379 }
3380
3381 case ObjCMessageExpr::Class: {
3382 SmallVector<Expr*, 8> ClsExprs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003383 ObjCInterfaceDecl *Class
3384 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3385 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00003386 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003387 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3388 &ClsExprs[0],
3389 ClsExprs.size(),
3390 StartLoc, EndLoc);
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003391 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3392 Context->getObjCIdType(),
3393 CK_BitCast, Cls);
3394 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003395 break;
3396 }
3397
3398 case ObjCMessageExpr::SuperInstance:{
3399 MsgSendFlavor = MsgSendSuperFunctionDecl;
3400 if (MsgSendStretFlavor)
3401 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3402 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3403 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3404 SmallVector<Expr*, 4> InitExprs;
3405
3406 InitExprs.push_back(
3407 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3408 CK_BitCast,
3409 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003410 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003411 Context->getObjCIdType(),
3412 VK_RValue, SourceLocation()))
3413 ); // set the 'receiver'.
3414
3415 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3416 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003417 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003418 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003419 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3420 &ClsExprs[0],
3421 ClsExprs.size(),
3422 StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003423 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003424 ClsExprs.push_back(Cls);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003425 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3426 &ClsExprs[0], ClsExprs.size(),
3427 StartLoc, EndLoc);
3428
3429 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3430 // To turn off a warning, type-cast to 'id'
3431 InitExprs.push_back(
3432 // set 'super class', using class_getSuperclass().
3433 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3434 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003435 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003436 QualType superType = getSuperStructType();
3437 Expr *SuperRep;
3438
3439 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003440 SynthSuperConstructorFunctionDecl();
3441 // Simulate a constructor call...
3442 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003443 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003444 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003445 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003446 superType, VK_LValue, SourceLocation());
3447 // The code for super is a little tricky to prevent collision with
3448 // the structure definition in the header. The rewriter has it's own
3449 // internal definition (__rw_objc_super) that is uses. This is why
3450 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003451 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003452 //
3453 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3454 Context->getPointerType(SuperRep->getType()),
3455 VK_RValue, OK_Ordinary,
3456 SourceLocation());
3457 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3458 Context->getPointerType(superType),
3459 CK_BitCast, SuperRep);
3460 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003461 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003462 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003463 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003464 SourceLocation());
3465 TypeSourceInfo *superTInfo
3466 = Context->getTrivialTypeSourceInfo(superType);
3467 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3468 superType, VK_RValue, ILE,
3469 false);
3470 }
3471 MsgExprs.push_back(SuperRep);
3472 break;
3473 }
3474
3475 case ObjCMessageExpr::Instance: {
3476 // Remove all type-casts because it may contain objc-style types; e.g.
3477 // Foo<Proto> *.
3478 Expr *recExpr = Exp->getInstanceReceiver();
3479 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3480 recExpr = CE->getSubExpr();
3481 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3482 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3483 ? CK_BlockPointerToObjCPointerCast
3484 : CK_CPointerToObjCPointerCast;
3485
3486 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3487 CK, recExpr);
3488 MsgExprs.push_back(recExpr);
3489 break;
3490 }
3491 }
3492
3493 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3494 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003495 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003496 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3497 &SelExprs[0], SelExprs.size(),
3498 StartLoc,
3499 EndLoc);
3500 MsgExprs.push_back(SelExp);
3501
3502 // Now push any user supplied arguments.
3503 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3504 Expr *userExpr = Exp->getArg(i);
3505 // Make all implicit casts explicit...ICE comes in handy:-)
3506 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3507 // Reuse the ICE type, it is exactly what the doctor ordered.
3508 QualType type = ICE->getType();
3509 if (needToScanForQualifiers(type))
3510 type = Context->getObjCIdType();
3511 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3512 (void)convertBlockPointerToFunctionPointer(type);
3513 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3514 CastKind CK;
3515 if (SubExpr->getType()->isIntegralType(*Context) &&
3516 type->isBooleanType()) {
3517 CK = CK_IntegralToBoolean;
3518 } else if (type->isObjCObjectPointerType()) {
3519 if (SubExpr->getType()->isBlockPointerType()) {
3520 CK = CK_BlockPointerToObjCPointerCast;
3521 } else if (SubExpr->getType()->isPointerType()) {
3522 CK = CK_CPointerToObjCPointerCast;
3523 } else {
3524 CK = CK_BitCast;
3525 }
3526 } else {
3527 CK = CK_BitCast;
3528 }
3529
3530 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3531 }
3532 // Make id<P...> cast into an 'id' cast.
3533 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3534 if (CE->getType()->isObjCQualifiedIdType()) {
3535 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3536 userExpr = CE->getSubExpr();
3537 CastKind CK;
3538 if (userExpr->getType()->isIntegralType(*Context)) {
3539 CK = CK_IntegralToPointer;
3540 } else if (userExpr->getType()->isBlockPointerType()) {
3541 CK = CK_BlockPointerToObjCPointerCast;
3542 } else if (userExpr->getType()->isPointerType()) {
3543 CK = CK_CPointerToObjCPointerCast;
3544 } else {
3545 CK = CK_BitCast;
3546 }
3547 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3548 CK, userExpr);
3549 }
3550 }
3551 MsgExprs.push_back(userExpr);
3552 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3553 // out the argument in the original expression (since we aren't deleting
3554 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3555 //Exp->setArg(i, 0);
3556 }
3557 // Generate the funky cast.
3558 CastExpr *cast;
3559 SmallVector<QualType, 8> ArgTypes;
3560 QualType returnType;
3561
3562 // Push 'id' and 'SEL', the 2 implicit arguments.
3563 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3564 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3565 else
3566 ArgTypes.push_back(Context->getObjCIdType());
3567 ArgTypes.push_back(Context->getObjCSelType());
3568 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3569 // Push any user argument types.
Aaron Ballman43b68be2014-03-07 17:50:17 +00003570 for (const auto *PI : OMD->params()) {
3571 QualType t = PI->getType()->isObjCQualifiedIdType()
Fariborz Jahanian11671902012-02-07 17:11:38 +00003572 ? Context->getObjCIdType()
Aaron Ballman43b68be2014-03-07 17:50:17 +00003573 : PI->getType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003574 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3575 (void)convertBlockPointerToFunctionPointer(t);
3576 ArgTypes.push_back(t);
3577 }
3578 returnType = Exp->getType();
3579 convertToUnqualifiedObjCType(returnType);
3580 (void)convertBlockPointerToFunctionPointer(returnType);
3581 } else {
3582 returnType = Context->getObjCIdType();
3583 }
3584 // Get the type, we will need to reference it in a couple spots.
3585 QualType msgSendType = MsgSendFlavor->getType();
3586
3587 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00003588 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003589 VK_LValue, SourceLocation());
3590
3591 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3592 // If we don't do this cast, we get the following bizarre warning/note:
3593 // xx.m:13: warning: function called through a non-compatible type
3594 // xx.m:13: note: if this code is reached, the program will abort
3595 cast = NoTypeInfoCStyleCastExpr(Context,
3596 Context->getPointerType(Context->VoidTy),
3597 CK_BitCast, DRE);
3598
3599 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003600 // If we don't have a method decl, force a variadic cast.
3601 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003602 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003603 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003604 castType = Context->getPointerType(castType);
3605 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3606 cast);
3607
3608 // Don't forget the parens to enforce the proper binding.
3609 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3610
3611 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003612 CallExpr *CE = new (Context)
3613 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003614 Stmt *ReplacingStmt = CE;
3615 if (MsgSendStretFlavor) {
3616 // We have the method which returns a struct/union. Must also generate
3617 // call to objc_msgSend_stret and hang both varieties on a conditional
3618 // expression which dictate which one to envoke depending on size of
3619 // method's return type.
3620
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003621 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3622 returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003623 ArgTypes, MsgExprs,
3624 Exp->getMethodDecl());
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003625 ReplacingStmt = STCE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003626 }
3627 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3628 return ReplacingStmt;
3629}
3630
3631Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3632 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3633 Exp->getLocEnd());
3634
3635 // Now do the actual rewrite.
3636 ReplaceStmt(Exp, ReplacingStmt);
3637
3638 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3639 return ReplacingStmt;
3640}
3641
3642// typedef struct objc_object Protocol;
3643QualType RewriteModernObjC::getProtocolType() {
3644 if (!ProtocolTypeDecl) {
3645 TypeSourceInfo *TInfo
3646 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3647 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3648 SourceLocation(), SourceLocation(),
3649 &Context->Idents.get("Protocol"),
3650 TInfo);
3651 }
3652 return Context->getTypeDeclType(ProtocolTypeDecl);
3653}
3654
3655/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3656/// a synthesized/forward data reference (to the protocol's metadata).
3657/// The forward references (and metadata) are generated in
3658/// RewriteModernObjC::HandleTranslationUnit().
3659Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00003660 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3661 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003662 IdentifierInfo *ID = &Context->Idents.get(Name);
3663 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3664 SourceLocation(), ID, getProtocolType(), 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003665 SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00003666 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3667 VK_LValue, SourceLocation());
Fariborz Jahaniand38951a2013-11-22 18:43:41 +00003668 CastExpr *castExpr =
3669 NoTypeInfoCStyleCastExpr(
3670 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003671 ReplaceStmt(Exp, castExpr);
3672 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3673 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3674 return castExpr;
3675
3676}
3677
3678bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3679 const char *endBuf) {
3680 while (startBuf < endBuf) {
3681 if (*startBuf == '#') {
3682 // Skip whitespace.
3683 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3684 ;
3685 if (!strncmp(startBuf, "if", strlen("if")) ||
3686 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3687 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3688 !strncmp(startBuf, "define", strlen("define")) ||
3689 !strncmp(startBuf, "undef", strlen("undef")) ||
3690 !strncmp(startBuf, "else", strlen("else")) ||
3691 !strncmp(startBuf, "elif", strlen("elif")) ||
3692 !strncmp(startBuf, "endif", strlen("endif")) ||
3693 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3694 !strncmp(startBuf, "include", strlen("include")) ||
3695 !strncmp(startBuf, "import", strlen("import")) ||
3696 !strncmp(startBuf, "include_next", strlen("include_next")))
3697 return true;
3698 }
3699 startBuf++;
3700 }
3701 return false;
3702}
3703
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003704/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3705/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003706bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003707 TagDecl *Tag,
3708 bool &IsNamedDefinition) {
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003709 if (!IDecl)
3710 return false;
3711 SourceLocation TagLocation;
3712 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3713 RD = RD->getDefinition();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003714 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003715 return false;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003716 IsNamedDefinition = true;
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003717 TagLocation = RD->getLocation();
3718 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003719 IDecl->getLocation(), TagLocation);
3720 }
3721 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3722 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3723 return false;
3724 IsNamedDefinition = true;
3725 TagLocation = ED->getLocation();
3726 return Context->getSourceManager().isBeforeInTranslationUnit(
3727 IDecl->getLocation(), TagLocation);
3728
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003729 }
3730 return false;
3731}
3732
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003733/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003734/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003735bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3736 std::string &Result) {
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003737 if (isa<TypedefType>(Type)) {
3738 Result += "\t";
3739 return false;
3740 }
3741
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003742 if (Type->isArrayType()) {
3743 QualType ElemTy = Context->getBaseElementType(Type);
3744 return RewriteObjCFieldDeclType(ElemTy, Result);
3745 }
3746 else if (Type->isRecordType()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003747 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3748 if (RD->isCompleteDefinition()) {
3749 if (RD->isStruct())
3750 Result += "\n\tstruct ";
3751 else if (RD->isUnion())
3752 Result += "\n\tunion ";
3753 else
3754 assert(false && "class not allowed as an ivar type");
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003755
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003756 Result += RD->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003757 if (GlobalDefinedTags.count(RD)) {
3758 // struct/union is defined globally, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003759 Result += " ";
3760 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003761 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003762 Result += " {\n";
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003763 for (auto *FD : RD->fields())
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003764 RewriteObjCFieldDecl(FD, Result);
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003765 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003766 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003767 }
3768 }
3769 else if (Type->isEnumeralType()) {
3770 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3771 if (ED->isCompleteDefinition()) {
3772 Result += "\n\tenum ";
3773 Result += ED->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003774 if (GlobalDefinedTags.count(ED)) {
3775 // Enum is globall defined, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003776 Result += " ";
3777 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003778 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003779
3780 Result += " {\n";
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003781 for (const auto *EC : ED->enumerators()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003782 Result += "\t"; Result += EC->getName(); Result += " = ";
3783 llvm::APSInt Val = EC->getInitVal();
3784 Result += Val.toString(10);
3785 Result += ",\n";
3786 }
3787 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003788 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003789 }
3790 }
3791
3792 Result += "\t";
3793 convertObjCTypeToCStyleType(Type);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003794 return false;
3795}
3796
3797
3798/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3799/// It handles elaborated types, as well as enum types in the process.
3800void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3801 std::string &Result) {
3802 QualType Type = fieldDecl->getType();
3803 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003804
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003805 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3806 if (!EleboratedType)
3807 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003808 Result += Name;
3809 if (fieldDecl->isBitField()) {
3810 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3811 }
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003812 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00003813 const ArrayType *AT = Context->getAsArrayType(Type);
3814 do {
3815 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003816 Result += "[";
3817 llvm::APInt Dim = CAT->getSize();
3818 Result += utostr(Dim.getZExtValue());
3819 Result += "]";
3820 }
Eli Friedman07bab732012-12-13 01:43:21 +00003821 AT = Context->getAsArrayType(AT->getElementType());
3822 } while (AT);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003823 }
3824
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003825 Result += ";\n";
3826}
3827
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003828/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3829/// named aggregate types into the input buffer.
3830void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3831 std::string &Result) {
3832 QualType Type = fieldDecl->getType();
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003833 if (isa<TypedefType>(Type))
3834 return;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003835 if (Type->isArrayType())
3836 Type = Context->getBaseElementType(Type);
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003837 ObjCContainerDecl *IDecl =
3838 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003839
3840 TagDecl *TD = 0;
3841 if (Type->isRecordType()) {
3842 TD = Type->getAs<RecordType>()->getDecl();
3843 }
3844 else if (Type->isEnumeralType()) {
3845 TD = Type->getAs<EnumType>()->getDecl();
3846 }
3847
3848 if (TD) {
3849 if (GlobalDefinedTags.count(TD))
3850 return;
3851
3852 bool IsNamedDefinition = false;
3853 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3854 RewriteObjCFieldDeclType(Type, Result);
3855 Result += ";";
3856 }
3857 if (IsNamedDefinition)
3858 GlobalDefinedTags.insert(TD);
3859 }
3860
3861}
3862
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003863unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3864 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3865 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3866 return IvarGroupNumber[IV];
3867 }
3868 unsigned GroupNo = 0;
3869 SmallVector<const ObjCIvarDecl *, 8> IVars;
3870 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3871 IVD; IVD = IVD->getNextIvar())
3872 IVars.push_back(IVD);
3873
3874 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3875 if (IVars[i]->isBitField()) {
3876 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3877 while (i < e && IVars[i]->isBitField())
3878 IvarGroupNumber[IVars[i++]] = GroupNo;
3879 if (i < e)
3880 --i;
3881 }
3882
3883 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3884 return IvarGroupNumber[IV];
3885}
3886
3887QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3888 ObjCIvarDecl *IV,
3889 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3890 std::string StructTagName;
3891 ObjCIvarBitfieldGroupType(IV, StructTagName);
3892 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3893 Context->getTranslationUnitDecl(),
3894 SourceLocation(), SourceLocation(),
3895 &Context->Idents.get(StructTagName));
3896 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3897 ObjCIvarDecl *Ivar = IVars[i];
3898 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3899 &Context->Idents.get(Ivar->getName()),
3900 Ivar->getType(),
3901 0, /*Expr *BW */Ivar->getBitWidth(), false,
3902 ICIS_NoInit));
3903 }
3904 RD->completeDefinition();
3905 return Context->getTagDeclType(RD);
3906}
3907
3908QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3909 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3910 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3911 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3912 if (GroupRecordType.count(tuple))
3913 return GroupRecordType[tuple];
3914
3915 SmallVector<ObjCIvarDecl *, 8> IVars;
3916 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3917 IVD; IVD = IVD->getNextIvar()) {
3918 if (IVD->isBitField())
3919 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3920 else {
3921 if (!IVars.empty()) {
3922 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3923 // Generate the struct type for this group of bitfield ivars.
3924 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3925 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3926 IVars.clear();
3927 }
3928 }
3929 }
3930 if (!IVars.empty()) {
3931 // Do the last one.
3932 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3933 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3934 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3935 }
3936 QualType RetQT = GroupRecordType[tuple];
3937 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3938
3939 return RetQT;
3940}
3941
3942/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3943/// Name would be: classname__GRBF_n where n is the group number for this ivar.
3944void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3945 std::string &Result) {
3946 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3947 Result += CDecl->getName();
3948 Result += "__GRBF_";
3949 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3950 Result += utostr(GroupNo);
3951 return;
3952}
3953
3954/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3955/// Name of the struct would be: classname__T_n where n is the group number for
3956/// this ivar.
3957void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3958 std::string &Result) {
3959 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3960 Result += CDecl->getName();
3961 Result += "__T_";
3962 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3963 Result += utostr(GroupNo);
3964 return;
3965}
3966
3967/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3968/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3969/// this ivar.
3970void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3971 std::string &Result) {
3972 Result += "OBJC_IVAR_$_";
3973 ObjCIvarBitfieldGroupDecl(IV, Result);
3974}
3975
3976#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3977 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
3978 ++IX; \
3979 if (IX < ENDIX) \
3980 --IX; \
3981}
3982
Fariborz Jahanian11671902012-02-07 17:11:38 +00003983/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3984/// an objective-c class with ivars.
3985void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3986 std::string &Result) {
3987 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3988 assert(CDecl->getName() != "" &&
3989 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00003990 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003991 SmallVector<ObjCIvarDecl *, 8> IVars;
3992 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00003993 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003994 IVars.push_back(IVD);
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00003995
Fariborz Jahanian11671902012-02-07 17:11:38 +00003996 SourceLocation LocStart = CDecl->getLocStart();
3997 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00003998
Fariborz Jahanian11671902012-02-07 17:11:38 +00003999 const char *startBuf = SM->getCharacterData(LocStart);
4000 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004001
Fariborz Jahanian11671902012-02-07 17:11:38 +00004002 // If no ivars and no root or if its root, directly or indirectly,
4003 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004004 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00004005 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
4006 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4007 ReplaceText(LocStart, endBuf-startBuf, Result);
4008 return;
4009 }
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004010
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00004011 // Insert named struct/union definitions inside class to
4012 // outer scope. This follows semantics of locally defined
4013 // struct/unions in objective-c classes.
4014 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4015 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004016
4017 // Insert named structs which are syntheized to group ivar bitfields
4018 // to outer scope as well.
4019 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4020 if (IVars[i]->isBitField()) {
4021 ObjCIvarDecl *IV = IVars[i];
4022 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
4023 RewriteObjCFieldDeclType(QT, Result);
4024 Result += ";";
4025 // skip over ivar bitfields in this group.
4026 SKIP_BITFIELDS(i , e, IVars);
4027 }
4028
Fariborz Jahanian11671902012-02-07 17:11:38 +00004029 Result += "\nstruct ";
4030 Result += CDecl->getNameAsString();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004031 Result += "_IMPL {\n";
4032
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004033 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004034 Result += "\tstruct "; Result += RCDecl->getNameAsString();
4035 Result += "_IMPL "; Result += RCDecl->getNameAsString();
4036 Result += "_IVARS;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004037 }
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00004038
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004039 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
4040 if (IVars[i]->isBitField()) {
4041 ObjCIvarDecl *IV = IVars[i];
4042 Result += "\tstruct ";
4043 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
4044 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
4045 // skip over ivar bitfields in this group.
4046 SKIP_BITFIELDS(i , e, IVars);
4047 }
4048 else
4049 RewriteObjCFieldDecl(IVars[i], Result);
4050 }
Fariborz Jahanian245534d2012-02-12 21:36:23 +00004051
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004052 Result += "};\n";
4053 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4054 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004055 // Mark this struct as having been generated.
4056 if (!ObjCSynthesizedStructs.insert(CDecl))
4057 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004058}
4059
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004060/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4061/// have been referenced in an ivar access expression.
4062void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4063 std::string &Result) {
4064 // write out ivar offset symbols which have been referenced in an ivar
4065 // access expression.
4066 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4067 if (Ivars.empty())
4068 return;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004069
4070 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004071 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
4072 e = Ivars.end(); i != e; i++) {
4073 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004074 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4075 unsigned GroupNo = 0;
4076 if (IvarDecl->isBitField()) {
4077 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4078 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4079 continue;
4080 }
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004081 Result += "\n";
4082 if (LangOpts.MicrosoftExt)
4083 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004084 Result += "extern \"C\" ";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004085 if (LangOpts.MicrosoftExt &&
4086 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004087 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4088 Result += "__declspec(dllimport) ";
4089
Fariborz Jahanian38c59102012-03-27 16:21:30 +00004090 Result += "unsigned long ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004091 if (IvarDecl->isBitField()) {
4092 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4093 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4094 }
4095 else
4096 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00004097 Result += ";";
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004098 }
4099}
4100
Fariborz Jahanian11671902012-02-07 17:11:38 +00004101//===----------------------------------------------------------------------===//
4102// Meta Data Emission
4103//===----------------------------------------------------------------------===//
4104
4105
4106/// RewriteImplementations - This routine rewrites all method implementations
4107/// and emits meta-data.
4108
4109void RewriteModernObjC::RewriteImplementations() {
4110 int ClsDefCount = ClassImplementation.size();
4111 int CatDefCount = CategoryImplementation.size();
4112
4113 // Rewrite implemented methods
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004114 for (int i = 0; i < ClsDefCount; i++) {
4115 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4116 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4117 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00004118 assert(false &&
4119 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004120 RewriteImplementationDecl(OIMP);
4121 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004122
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004123 for (int i = 0; i < CatDefCount; i++) {
4124 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4125 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4126 if (CDecl->isImplicitInterfaceDecl())
4127 assert(false &&
4128 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004129 RewriteImplementationDecl(CIMP);
4130 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004131}
4132
4133void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4134 const std::string &Name,
4135 ValueDecl *VD, bool def) {
4136 assert(BlockByRefDeclNo.count(VD) &&
4137 "RewriteByRefString: ByRef decl missing");
4138 if (def)
4139 ResultStr += "struct ";
4140 ResultStr += "__Block_byref_" + Name +
4141 "_" + utostr(BlockByRefDeclNo[VD]) ;
4142}
4143
4144static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4145 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4146 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4147 return false;
4148}
4149
4150std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4151 StringRef funcName,
4152 std::string Tag) {
4153 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00004154 QualType RT = AFT->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004155 std::string StructRef = "struct " + Tag;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004156 SourceLocation BlockLoc = CE->getExprLoc();
4157 std::string S;
4158 ConvertSourceLocationToLineDirective(BlockLoc, S);
4159
4160 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4161 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004162
4163 BlockDecl *BD = CE->getBlockDecl();
4164
4165 if (isa<FunctionNoProtoType>(AFT)) {
4166 // No user-supplied arguments. Still need to pass in a pointer to the
4167 // block (to reference imported block decl refs).
4168 S += "(" + StructRef + " *__cself)";
4169 } else if (BD->param_empty()) {
4170 S += "(" + StructRef + " *__cself)";
4171 } else {
4172 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4173 assert(FT && "SynthesizeBlockFunc: No function proto");
4174 S += '(';
4175 // first add the implicit argument.
4176 S += StructRef + " *__cself, ";
4177 std::string ParamStr;
4178 for (BlockDecl::param_iterator AI = BD->param_begin(),
4179 E = BD->param_end(); AI != E; ++AI) {
4180 if (AI != BD->param_begin()) S += ", ";
4181 ParamStr = (*AI)->getNameAsString();
4182 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00004183 (void)convertBlockPointerToFunctionPointer(QT);
4184 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004185 S += ParamStr;
4186 }
4187 if (FT->isVariadic()) {
4188 if (!BD->param_empty()) S += ", ";
4189 S += "...";
4190 }
4191 S += ')';
4192 }
4193 S += " {\n";
4194
4195 // Create local declarations to avoid rewriting all closure decl ref exprs.
4196 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00004197 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004198 E = BlockByRefDecls.end(); I != E; ++I) {
4199 S += " ";
4200 std::string Name = (*I)->getNameAsString();
4201 std::string TypeString;
4202 RewriteByRefString(TypeString, Name, (*I));
4203 TypeString += " *";
4204 Name = TypeString + Name;
4205 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4206 }
4207 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004208 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004209 E = BlockByCopyDecls.end(); I != E; ++I) {
4210 S += " ";
4211 // Handle nested closure invocation. For example:
4212 //
4213 // void (^myImportedClosure)(void);
4214 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4215 //
4216 // void (^anotherClosure)(void);
4217 // anotherClosure = ^(void) {
4218 // myImportedClosure(); // import and invoke the closure
4219 // };
4220 //
4221 if (isTopLevelBlockPointerType((*I)->getType())) {
4222 RewriteBlockPointerTypeVariable(S, (*I));
4223 S += " = (";
4224 RewriteBlockPointerType(S, (*I)->getType());
4225 S += ")";
4226 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4227 }
4228 else {
4229 std::string Name = (*I)->getNameAsString();
4230 QualType QT = (*I)->getType();
4231 if (HasLocalVariableExternalStorage(*I))
4232 QT = Context->getPointerType(QT);
4233 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4234 S += Name + " = __cself->" +
4235 (*I)->getNameAsString() + "; // bound by copy\n";
4236 }
4237 }
4238 std::string RewrittenStr = RewrittenBlockExprs[CE];
4239 const char *cstr = RewrittenStr.c_str();
4240 while (*cstr++ != '{') ;
4241 S += cstr;
4242 S += "\n";
4243 return S;
4244}
4245
4246std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4247 StringRef funcName,
4248 std::string Tag) {
4249 std::string StructRef = "struct " + Tag;
4250 std::string S = "static void __";
4251
4252 S += funcName;
4253 S += "_block_copy_" + utostr(i);
4254 S += "(" + StructRef;
4255 S += "*dst, " + StructRef;
4256 S += "*src) {";
4257 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4258 E = ImportedBlockDecls.end(); I != E; ++I) {
4259 ValueDecl *VD = (*I);
4260 S += "_Block_object_assign((void*)&dst->";
4261 S += (*I)->getNameAsString();
4262 S += ", (void*)src->";
4263 S += (*I)->getNameAsString();
4264 if (BlockByRefDeclsPtrSet.count((*I)))
4265 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4266 else if (VD->getType()->isBlockPointerType())
4267 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4268 else
4269 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4270 }
4271 S += "}\n";
4272
4273 S += "\nstatic void __";
4274 S += funcName;
4275 S += "_block_dispose_" + utostr(i);
4276 S += "(" + StructRef;
4277 S += "*src) {";
4278 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4279 E = ImportedBlockDecls.end(); I != E; ++I) {
4280 ValueDecl *VD = (*I);
4281 S += "_Block_object_dispose((void*)src->";
4282 S += (*I)->getNameAsString();
4283 if (BlockByRefDeclsPtrSet.count((*I)))
4284 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4285 else if (VD->getType()->isBlockPointerType())
4286 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4287 else
4288 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4289 }
4290 S += "}\n";
4291 return S;
4292}
4293
4294std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4295 std::string Desc) {
4296 std::string S = "\nstruct " + Tag;
4297 std::string Constructor = " " + Tag;
4298
4299 S += " {\n struct __block_impl impl;\n";
4300 S += " struct " + Desc;
4301 S += "* Desc;\n";
4302
4303 Constructor += "(void *fp, "; // Invoke function pointer.
4304 Constructor += "struct " + Desc; // Descriptor pointer.
4305 Constructor += " *desc";
4306
4307 if (BlockDeclRefs.size()) {
4308 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004309 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004310 E = BlockByCopyDecls.end(); I != E; ++I) {
4311 S += " ";
4312 std::string FieldName = (*I)->getNameAsString();
4313 std::string ArgName = "_" + FieldName;
4314 // Handle nested closure invocation. For example:
4315 //
4316 // void (^myImportedBlock)(void);
4317 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4318 //
4319 // void (^anotherBlock)(void);
4320 // anotherBlock = ^(void) {
4321 // myImportedBlock(); // import and invoke the closure
4322 // };
4323 //
4324 if (isTopLevelBlockPointerType((*I)->getType())) {
4325 S += "struct __block_impl *";
4326 Constructor += ", void *" + ArgName;
4327 } else {
4328 QualType QT = (*I)->getType();
4329 if (HasLocalVariableExternalStorage(*I))
4330 QT = Context->getPointerType(QT);
4331 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4332 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4333 Constructor += ", " + ArgName;
4334 }
4335 S += FieldName + ";\n";
4336 }
4337 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004338 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004339 E = BlockByRefDecls.end(); I != E; ++I) {
4340 S += " ";
4341 std::string FieldName = (*I)->getNameAsString();
4342 std::string ArgName = "_" + FieldName;
4343 {
4344 std::string TypeString;
4345 RewriteByRefString(TypeString, FieldName, (*I));
4346 TypeString += " *";
4347 FieldName = TypeString + FieldName;
4348 ArgName = TypeString + ArgName;
4349 Constructor += ", " + ArgName;
4350 }
4351 S += FieldName + "; // by ref\n";
4352 }
4353 // Finish writing the constructor.
4354 Constructor += ", int flags=0)";
4355 // Initialize all "by copy" arguments.
4356 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00004357 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004358 E = BlockByCopyDecls.end(); I != E; ++I) {
4359 std::string Name = (*I)->getNameAsString();
4360 if (firsTime) {
4361 Constructor += " : ";
4362 firsTime = false;
4363 }
4364 else
4365 Constructor += ", ";
4366 if (isTopLevelBlockPointerType((*I)->getType()))
4367 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4368 else
4369 Constructor += Name + "(_" + Name + ")";
4370 }
4371 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00004372 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004373 E = BlockByRefDecls.end(); I != E; ++I) {
4374 std::string Name = (*I)->getNameAsString();
4375 if (firsTime) {
4376 Constructor += " : ";
4377 firsTime = false;
4378 }
4379 else
4380 Constructor += ", ";
4381 Constructor += Name + "(_" + Name + "->__forwarding)";
4382 }
4383
4384 Constructor += " {\n";
4385 if (GlobalVarDecl)
4386 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4387 else
4388 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4389 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4390
4391 Constructor += " Desc = desc;\n";
4392 } else {
4393 // Finish writing the constructor.
4394 Constructor += ", int flags=0) {\n";
4395 if (GlobalVarDecl)
4396 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4397 else
4398 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4399 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4400 Constructor += " Desc = desc;\n";
4401 }
4402 Constructor += " ";
4403 Constructor += "}\n";
4404 S += Constructor;
4405 S += "};\n";
4406 return S;
4407}
4408
4409std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4410 std::string ImplTag, int i,
4411 StringRef FunName,
4412 unsigned hasCopy) {
4413 std::string S = "\nstatic struct " + DescTag;
4414
Fariborz Jahanian2e7f6382012-05-03 21:44:12 +00004415 S += " {\n size_t reserved;\n";
4416 S += " size_t Block_size;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004417 if (hasCopy) {
4418 S += " void (*copy)(struct ";
4419 S += ImplTag; S += "*, struct ";
4420 S += ImplTag; S += "*);\n";
4421
4422 S += " void (*dispose)(struct ";
4423 S += ImplTag; S += "*);\n";
4424 }
4425 S += "} ";
4426
4427 S += DescTag + "_DATA = { 0, sizeof(struct ";
4428 S += ImplTag + ")";
4429 if (hasCopy) {
4430 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4431 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4432 }
4433 S += "};\n";
4434 return S;
4435}
4436
4437void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4438 StringRef FunName) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004439 bool RewriteSC = (GlobalVarDecl &&
4440 !Blocks.empty() &&
4441 GlobalVarDecl->getStorageClass() == SC_Static &&
4442 GlobalVarDecl->getType().getCVRQualifiers());
4443 if (RewriteSC) {
4444 std::string SC(" void __");
4445 SC += GlobalVarDecl->getNameAsString();
4446 SC += "() {}";
4447 InsertText(FunLocStart, SC);
4448 }
4449
4450 // Insert closures that were part of the function.
4451 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4452 CollectBlockDeclRefInfo(Blocks[i]);
4453 // Need to copy-in the inner copied-in variables not actually used in this
4454 // block.
4455 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00004456 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian11671902012-02-07 17:11:38 +00004457 ValueDecl *VD = Exp->getDecl();
4458 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00004459 if (!VD->hasAttr<BlocksAttr>()) {
4460 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4461 BlockByCopyDeclsPtrSet.insert(VD);
4462 BlockByCopyDecls.push_back(VD);
4463 }
4464 continue;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004465 }
John McCall113bee02012-03-10 09:33:50 +00004466
4467 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004468 BlockByRefDeclsPtrSet.insert(VD);
4469 BlockByRefDecls.push_back(VD);
4470 }
John McCall113bee02012-03-10 09:33:50 +00004471
Fariborz Jahanian11671902012-02-07 17:11:38 +00004472 // imported objects in the inner blocks not used in the outer
4473 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00004474 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00004475 VD->getType()->isBlockPointerType())
4476 ImportedBlockDecls.insert(VD);
4477 }
4478
4479 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4480 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4481
4482 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4483
4484 InsertText(FunLocStart, CI);
4485
4486 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4487
4488 InsertText(FunLocStart, CF);
4489
4490 if (ImportedBlockDecls.size()) {
4491 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4492 InsertText(FunLocStart, HF);
4493 }
4494 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4495 ImportedBlockDecls.size() > 0);
4496 InsertText(FunLocStart, BD);
4497
4498 BlockDeclRefs.clear();
4499 BlockByRefDecls.clear();
4500 BlockByRefDeclsPtrSet.clear();
4501 BlockByCopyDecls.clear();
4502 BlockByCopyDeclsPtrSet.clear();
4503 ImportedBlockDecls.clear();
4504 }
4505 if (RewriteSC) {
4506 // Must insert any 'const/volatile/static here. Since it has been
4507 // removed as result of rewriting of block literals.
4508 std::string SC;
4509 if (GlobalVarDecl->getStorageClass() == SC_Static)
4510 SC = "static ";
4511 if (GlobalVarDecl->getType().isConstQualified())
4512 SC += "const ";
4513 if (GlobalVarDecl->getType().isVolatileQualified())
4514 SC += "volatile ";
4515 if (GlobalVarDecl->getType().isRestrictQualified())
4516 SC += "restrict ";
4517 InsertText(FunLocStart, SC);
4518 }
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004519 if (GlobalConstructionExp) {
4520 // extra fancy dance for global literal expression.
4521
4522 // Always the latest block expression on the block stack.
4523 std::string Tag = "__";
4524 Tag += FunName;
4525 Tag += "_block_impl_";
4526 Tag += utostr(Blocks.size()-1);
4527 std::string globalBuf = "static ";
4528 globalBuf += Tag; globalBuf += " ";
4529 std::string SStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004530
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004531 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00004532 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004533 PrintingPolicy(LangOpts));
4534 globalBuf += constructorExprBuf.str();
4535 globalBuf += ";\n";
4536 InsertText(FunLocStart, globalBuf);
4537 GlobalConstructionExp = 0;
4538 }
4539
Fariborz Jahanian11671902012-02-07 17:11:38 +00004540 Blocks.clear();
4541 InnerDeclRefsCount.clear();
4542 InnerDeclRefs.clear();
4543 RewrittenBlockExprs.clear();
4544}
4545
4546void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahaniane49a42c2012-04-25 17:56:48 +00004547 SourceLocation FunLocStart =
4548 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4549 : FD->getTypeSpecStartLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004550 StringRef FuncName = FD->getName();
4551
4552 SynthesizeBlockLiterals(FunLocStart, FuncName);
4553}
4554
4555static void BuildUniqueMethodName(std::string &Name,
4556 ObjCMethodDecl *MD) {
4557 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4558 Name = IFace->getName();
4559 Name += "__" + MD->getSelector().getAsString();
4560 // Convert colons to underscores.
4561 std::string::size_type loc = 0;
4562 while ((loc = Name.find(":", loc)) != std::string::npos)
4563 Name.replace(loc, 1, "_");
4564}
4565
4566void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4567 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4568 //SourceLocation FunLocStart = MD->getLocStart();
4569 SourceLocation FunLocStart = MD->getLocStart();
4570 std::string FuncName;
4571 BuildUniqueMethodName(FuncName, MD);
4572 SynthesizeBlockLiterals(FunLocStart, FuncName);
4573}
4574
4575void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4576 for (Stmt::child_range CI = S->children(); CI; ++CI)
4577 if (*CI) {
4578 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4579 GetBlockDeclRefExprs(CBE->getBody());
4580 else
4581 GetBlockDeclRefExprs(*CI);
4582 }
4583 // Handle specific things.
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004584 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4585 if (DRE->refersToEnclosingLocal()) {
4586 // FIXME: Handle enums.
4587 if (!isa<FunctionDecl>(DRE->getDecl()))
4588 BlockDeclRefs.push_back(DRE);
4589 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4590 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004591 }
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004592 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004593
4594 return;
4595}
4596
Craig Topper5603df42013-07-05 19:34:19 +00004597void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4598 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004599 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4600 for (Stmt::child_range CI = S->children(); CI; ++CI)
4601 if (*CI) {
4602 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4603 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4604 GetInnerBlockDeclRefExprs(CBE->getBody(),
4605 InnerBlockDeclRefs,
4606 InnerContexts);
4607 }
4608 else
4609 GetInnerBlockDeclRefExprs(*CI,
4610 InnerBlockDeclRefs,
4611 InnerContexts);
4612
4613 }
4614 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00004615 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4616 if (DRE->refersToEnclosingLocal()) {
4617 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4618 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4619 InnerBlockDeclRefs.push_back(DRE);
4620 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4621 if (Var->isFunctionOrMethodVarDecl())
4622 ImportedLocalExternalDecls.insert(Var);
4623 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004624 }
4625
4626 return;
4627}
4628
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004629/// convertObjCTypeToCStyleType - This routine converts such objc types
4630/// as qualified objects, and blocks to their closest c/c++ types that
4631/// it can. It returns true if input type was modified.
4632bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4633 QualType oldT = T;
4634 convertBlockPointerToFunctionPointer(T);
4635 if (T->isFunctionPointerType()) {
4636 QualType PointeeTy;
4637 if (const PointerType* PT = T->getAs<PointerType>()) {
4638 PointeeTy = PT->getPointeeType();
4639 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4640 T = convertFunctionTypeOfBlocks(FT);
4641 T = Context->getPointerType(T);
4642 }
4643 }
4644 }
4645
4646 convertToUnqualifiedObjCType(T);
4647 return T != oldT;
4648}
4649
Fariborz Jahanian11671902012-02-07 17:11:38 +00004650/// convertFunctionTypeOfBlocks - This routine converts a function type
4651/// whose result type may be a block pointer or whose argument type(s)
4652/// might be block pointers to an equivalent function type replacing
4653/// all block pointers to function pointers.
4654QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4655 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4656 // FTP will be null for closures that don't take arguments.
4657 // Generate a funky cast.
4658 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00004659 QualType Res = FT->getReturnType();
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004660 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004661
4662 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004663 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4664 E = FTP->param_type_end();
4665 I && (I != E); ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004666 QualType t = *I;
4667 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004668 if (convertObjCTypeToCStyleType(t))
4669 modified = true;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004670 ArgTypes.push_back(t);
4671 }
4672 }
4673 QualType FuncType;
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004674 if (modified)
Jordan Rose5c382722013-03-08 21:51:21 +00004675 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004676 else FuncType = QualType(FT, 0);
4677 return FuncType;
4678}
4679
4680Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4681 // Navigate to relevant type information.
4682 const BlockPointerType *CPT = 0;
4683
4684 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4685 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004686 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4687 CPT = MExpr->getType()->getAs<BlockPointerType>();
4688 }
4689 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4690 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4691 }
4692 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4693 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4694 else if (const ConditionalOperator *CEXPR =
4695 dyn_cast<ConditionalOperator>(BlockExp)) {
4696 Expr *LHSExp = CEXPR->getLHS();
4697 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4698 Expr *RHSExp = CEXPR->getRHS();
4699 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4700 Expr *CONDExp = CEXPR->getCond();
4701 ConditionalOperator *CondExpr =
4702 new (Context) ConditionalOperator(CONDExp,
4703 SourceLocation(), cast<Expr>(LHSStmt),
4704 SourceLocation(), cast<Expr>(RHSStmt),
4705 Exp->getType(), VK_RValue, OK_Ordinary);
4706 return CondExpr;
4707 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4708 CPT = IRE->getType()->getAs<BlockPointerType>();
4709 } else if (const PseudoObjectExpr *POE
4710 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4711 CPT = POE->getType()->castAs<BlockPointerType>();
4712 } else {
4713 assert(1 && "RewriteBlockClass: Bad type");
4714 }
4715 assert(CPT && "RewriteBlockClass: Bad type");
4716 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4717 assert(FT && "RewriteBlockClass: Bad type");
4718 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4719 // FTP will be null for closures that don't take arguments.
4720
4721 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4722 SourceLocation(), SourceLocation(),
4723 &Context->Idents.get("__block_impl"));
4724 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4725
4726 // Generate a funky cast.
4727 SmallVector<QualType, 8> ArgTypes;
4728
4729 // Push the block argument type.
4730 ArgTypes.push_back(PtrBlock);
4731 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004732 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4733 E = FTP->param_type_end();
4734 I && (I != E); ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004735 QualType t = *I;
4736 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4737 if (!convertBlockPointerToFunctionPointer(t))
4738 convertToUnqualifiedObjCType(t);
4739 ArgTypes.push_back(t);
4740 }
4741 }
4742 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00004743 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004744
4745 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4746
4747 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4748 CK_BitCast,
4749 const_cast<Expr*>(BlockExp));
4750 // Don't forget the parens to enforce the proper binding.
4751 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4752 BlkCast);
4753 //PE->dump();
4754
4755 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4756 SourceLocation(),
4757 &Context->Idents.get("FuncPtr"),
4758 Context->VoidPtrTy, 0,
4759 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004760 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004761 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4762 FD->getType(), VK_LValue,
4763 OK_Ordinary);
4764
4765
4766 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4767 CK_BitCast, ME);
4768 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4769
4770 SmallVector<Expr*, 8> BlkExprs;
4771 // Add the implicit argument.
4772 BlkExprs.push_back(BlkCast);
4773 // Add the user arguments.
4774 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4775 E = Exp->arg_end(); I != E; ++I) {
4776 BlkExprs.push_back(*I);
4777 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004778 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004779 Exp->getType(), VK_RValue,
4780 SourceLocation());
4781 return CE;
4782}
4783
4784// We need to return the rewritten expression to handle cases where the
John McCall113bee02012-03-10 09:33:50 +00004785// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian11671902012-02-07 17:11:38 +00004786// For example:
4787//
4788// int main() {
4789// __block Foo *f;
4790// __block int i;
4791//
4792// void (^myblock)() = ^() {
John McCall113bee02012-03-10 09:33:50 +00004793// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian11671902012-02-07 17:11:38 +00004794// i = 77;
4795// };
4796//}
John McCall113bee02012-03-10 09:33:50 +00004797Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004798 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4799 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00004800 ValueDecl *VD = DeclRefExp->getDecl();
4801 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004802
4803 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4804 SourceLocation(),
4805 &Context->Idents.get("__forwarding"),
4806 Context->VoidPtrTy, 0,
4807 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004808 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004809 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4810 FD, SourceLocation(),
4811 FD->getType(), VK_LValue,
4812 OK_Ordinary);
4813
4814 StringRef Name = VD->getName();
4815 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4816 &Context->Idents.get(Name),
4817 Context->VoidPtrTy, 0,
4818 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004819 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004820 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4821 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4822
4823
4824
4825 // Need parens to enforce precedence.
4826 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4827 DeclRefExp->getExprLoc(),
4828 ME);
4829 ReplaceStmt(DeclRefExp, PE);
4830 return PE;
4831}
4832
4833// Rewrites the imported local variable V with external storage
4834// (static, extern, etc.) as *V
4835//
4836Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4837 ValueDecl *VD = DRE->getDecl();
4838 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4839 if (!ImportedLocalExternalDecls.count(Var))
4840 return DRE;
4841 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4842 VK_LValue, OK_Ordinary,
4843 DRE->getLocation());
4844 // Need parens to enforce precedence.
4845 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4846 Exp);
4847 ReplaceStmt(DRE, PE);
4848 return PE;
4849}
4850
4851void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4852 SourceLocation LocStart = CE->getLParenLoc();
4853 SourceLocation LocEnd = CE->getRParenLoc();
4854
4855 // Need to avoid trying to rewrite synthesized casts.
4856 if (LocStart.isInvalid())
4857 return;
4858 // Need to avoid trying to rewrite casts contained in macros.
4859 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4860 return;
4861
4862 const char *startBuf = SM->getCharacterData(LocStart);
4863 const char *endBuf = SM->getCharacterData(LocEnd);
4864 QualType QT = CE->getType();
4865 const Type* TypePtr = QT->getAs<Type>();
4866 if (isa<TypeOfExprType>(TypePtr)) {
4867 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4868 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4869 std::string TypeAsString = "(";
4870 RewriteBlockPointerType(TypeAsString, QT);
4871 TypeAsString += ")";
4872 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4873 return;
4874 }
4875 // advance the location to startArgList.
4876 const char *argPtr = startBuf;
4877
4878 while (*argPtr++ && (argPtr < endBuf)) {
4879 switch (*argPtr) {
4880 case '^':
4881 // Replace the '^' with '*'.
4882 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4883 ReplaceText(LocStart, 1, "*");
4884 break;
4885 }
4886 }
4887 return;
4888}
4889
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004890void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4891 CastKind CastKind = IC->getCastKind();
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004892 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4893 CastKind != CK_AnyPointerToBlockPointerCast)
4894 return;
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004895
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004896 QualType QT = IC->getType();
4897 (void)convertBlockPointerToFunctionPointer(QT);
4898 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4899 std::string Str = "(";
4900 Str += TypeString;
4901 Str += ")";
4902 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4903
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004904 return;
4905}
4906
Fariborz Jahanian11671902012-02-07 17:11:38 +00004907void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4908 SourceLocation DeclLoc = FD->getLocation();
4909 unsigned parenCount = 0;
4910
4911 // We have 1 or more arguments that have closure pointers.
4912 const char *startBuf = SM->getCharacterData(DeclLoc);
4913 const char *startArgList = strchr(startBuf, '(');
4914
4915 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4916
4917 parenCount++;
4918 // advance the location to startArgList.
4919 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4920 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4921
4922 const char *argPtr = startArgList;
4923
4924 while (*argPtr++ && parenCount) {
4925 switch (*argPtr) {
4926 case '^':
4927 // Replace the '^' with '*'.
4928 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4929 ReplaceText(DeclLoc, 1, "*");
4930 break;
4931 case '(':
4932 parenCount++;
4933 break;
4934 case ')':
4935 parenCount--;
4936 break;
4937 }
4938 }
4939 return;
4940}
4941
4942bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4943 const FunctionProtoType *FTP;
4944 const PointerType *PT = QT->getAs<PointerType>();
4945 if (PT) {
4946 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4947 } else {
4948 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4949 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4950 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4951 }
4952 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004953 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4954 E = FTP->param_type_end();
4955 I != E; ++I)
Fariborz Jahanian11671902012-02-07 17:11:38 +00004956 if (isTopLevelBlockPointerType(*I))
4957 return true;
4958 }
4959 return false;
4960}
4961
4962bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4963 const FunctionProtoType *FTP;
4964 const PointerType *PT = QT->getAs<PointerType>();
4965 if (PT) {
4966 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4967 } else {
4968 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4969 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4970 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4971 }
4972 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004973 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4974 E = FTP->param_type_end();
4975 I != E; ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004976 if ((*I)->isObjCQualifiedIdType())
4977 return true;
4978 if ((*I)->isObjCObjectPointerType() &&
4979 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4980 return true;
4981 }
4982
4983 }
4984 return false;
4985}
4986
4987void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4988 const char *&RParen) {
4989 const char *argPtr = strchr(Name, '(');
4990 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4991
4992 LParen = argPtr; // output the start.
4993 argPtr++; // skip past the left paren.
4994 unsigned parenCount = 1;
4995
4996 while (*argPtr && parenCount) {
4997 switch (*argPtr) {
4998 case '(': parenCount++; break;
4999 case ')': parenCount--; break;
5000 default: break;
5001 }
5002 if (parenCount) argPtr++;
5003 }
5004 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5005 RParen = argPtr; // output the end
5006}
5007
5008void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5009 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5010 RewriteBlockPointerFunctionArgs(FD);
5011 return;
5012 }
5013 // Handle Variables and Typedefs.
5014 SourceLocation DeclLoc = ND->getLocation();
5015 QualType DeclT;
5016 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5017 DeclT = VD->getType();
5018 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
5019 DeclT = TDD->getUnderlyingType();
5020 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5021 DeclT = FD->getType();
5022 else
5023 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
5024
5025 const char *startBuf = SM->getCharacterData(DeclLoc);
5026 const char *endBuf = startBuf;
5027 // scan backward (from the decl location) for the end of the previous decl.
5028 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5029 startBuf--;
5030 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
5031 std::string buf;
5032 unsigned OrigLength=0;
5033 // *startBuf != '^' if we are dealing with a pointer to function that
5034 // may take block argument types (which will be handled below).
5035 if (*startBuf == '^') {
5036 // Replace the '^' with '*', computing a negative offset.
5037 buf = '*';
5038 startBuf++;
5039 OrigLength++;
5040 }
5041 while (*startBuf != ')') {
5042 buf += *startBuf;
5043 startBuf++;
5044 OrigLength++;
5045 }
5046 buf += ')';
5047 OrigLength++;
5048
5049 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5050 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
5051 // Replace the '^' with '*' for arguments.
5052 // Replace id<P> with id/*<>*/
5053 DeclLoc = ND->getLocation();
5054 startBuf = SM->getCharacterData(DeclLoc);
5055 const char *argListBegin, *argListEnd;
5056 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5057 while (argListBegin < argListEnd) {
5058 if (*argListBegin == '^')
5059 buf += '*';
5060 else if (*argListBegin == '<') {
5061 buf += "/*";
5062 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005063 OrigLength++;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005064 while (*argListBegin != '>') {
5065 buf += *argListBegin++;
5066 OrigLength++;
5067 }
5068 buf += *argListBegin;
5069 buf += "*/";
5070 }
5071 else
5072 buf += *argListBegin;
5073 argListBegin++;
5074 OrigLength++;
5075 }
5076 buf += ')';
5077 OrigLength++;
5078 }
5079 ReplaceText(Start, OrigLength, buf);
5080
5081 return;
5082}
5083
5084
5085/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5086/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5087/// struct Block_byref_id_object *src) {
5088/// _Block_object_assign (&_dest->object, _src->object,
5089/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5090/// [|BLOCK_FIELD_IS_WEAK]) // object
5091/// _Block_object_assign(&_dest->object, _src->object,
5092/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5093/// [|BLOCK_FIELD_IS_WEAK]) // block
5094/// }
5095/// And:
5096/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5097/// _Block_object_dispose(_src->object,
5098/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5099/// [|BLOCK_FIELD_IS_WEAK]) // object
5100/// _Block_object_dispose(_src->object,
5101/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5102/// [|BLOCK_FIELD_IS_WEAK]) // block
5103/// }
5104
5105std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5106 int flag) {
5107 std::string S;
5108 if (CopyDestroyCache.count(flag))
5109 return S;
5110 CopyDestroyCache.insert(flag);
5111 S = "static void __Block_byref_id_object_copy_";
5112 S += utostr(flag);
5113 S += "(void *dst, void *src) {\n";
5114
5115 // offset into the object pointer is computed as:
5116 // void * + void* + int + int + void* + void *
5117 unsigned IntSize =
5118 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5119 unsigned VoidPtrSize =
5120 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5121
5122 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5123 S += " _Block_object_assign((char*)dst + ";
5124 S += utostr(offset);
5125 S += ", *(void * *) ((char*)src + ";
5126 S += utostr(offset);
5127 S += "), ";
5128 S += utostr(flag);
5129 S += ");\n}\n";
5130
5131 S += "static void __Block_byref_id_object_dispose_";
5132 S += utostr(flag);
5133 S += "(void *src) {\n";
5134 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5135 S += utostr(offset);
5136 S += "), ";
5137 S += utostr(flag);
5138 S += ");\n}\n";
5139 return S;
5140}
5141
5142/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5143/// the declaration into:
5144/// struct __Block_byref_ND {
5145/// void *__isa; // NULL for everything except __weak pointers
5146/// struct __Block_byref_ND *__forwarding;
5147/// int32_t __flags;
5148/// int32_t __size;
5149/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5150/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5151/// typex ND;
5152/// };
5153///
5154/// It then replaces declaration of ND variable with:
5155/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5156/// __size=sizeof(struct __Block_byref_ND),
5157/// ND=initializer-if-any};
5158///
5159///
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005160void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5161 bool lastDecl) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005162 int flag = 0;
5163 int isa = 0;
5164 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5165 if (DeclLoc.isInvalid())
5166 // If type location is missing, it is because of missing type (a warning).
5167 // Use variable's location which is good for this case.
5168 DeclLoc = ND->getLocation();
5169 const char *startBuf = SM->getCharacterData(DeclLoc);
5170 SourceLocation X = ND->getLocEnd();
5171 X = SM->getExpansionLoc(X);
5172 const char *endBuf = SM->getCharacterData(X);
5173 std::string Name(ND->getNameAsString());
5174 std::string ByrefType;
5175 RewriteByRefString(ByrefType, Name, ND, true);
5176 ByrefType += " {\n";
5177 ByrefType += " void *__isa;\n";
5178 RewriteByRefString(ByrefType, Name, ND);
5179 ByrefType += " *__forwarding;\n";
5180 ByrefType += " int __flags;\n";
5181 ByrefType += " int __size;\n";
5182 // Add void *__Block_byref_id_object_copy;
5183 // void *__Block_byref_id_object_dispose; if needed.
5184 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005185 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005186 if (HasCopyAndDispose) {
5187 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5188 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5189 }
5190
5191 QualType T = Ty;
5192 (void)convertBlockPointerToFunctionPointer(T);
5193 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5194
5195 ByrefType += " " + Name + ";\n";
5196 ByrefType += "};\n";
5197 // Insert this type in global scope. It is needed by helper function.
5198 SourceLocation FunLocStart;
5199 if (CurFunctionDef)
Fariborz Jahanianca357d92012-04-19 00:50:01 +00005200 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005201 else {
5202 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5203 FunLocStart = CurMethodDef->getLocStart();
5204 }
5205 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005206
Fariborz Jahanian11671902012-02-07 17:11:38 +00005207 if (Ty.isObjCGCWeak()) {
5208 flag |= BLOCK_FIELD_IS_WEAK;
5209 isa = 1;
5210 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005211 if (HasCopyAndDispose) {
5212 flag = BLOCK_BYREF_CALLER;
5213 QualType Ty = ND->getType();
5214 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5215 if (Ty->isBlockPointerType())
5216 flag |= BLOCK_FIELD_IS_BLOCK;
5217 else
5218 flag |= BLOCK_FIELD_IS_OBJECT;
5219 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5220 if (!HF.empty())
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005221 Preamble += HF;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005222 }
5223
5224 // struct __Block_byref_ND ND =
5225 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5226 // initializer-if-any};
5227 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian5811fd62012-04-11 23:57:12 +00005228 // FIXME. rewriter does not support __block c++ objects which
5229 // require construction.
Fariborz Jahanian16d0d6c2012-04-26 23:20:25 +00005230 if (hasInit)
5231 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5232 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5233 if (CXXDecl && CXXDecl->isDefaultConstructor())
5234 hasInit = false;
5235 }
5236
Fariborz Jahanian11671902012-02-07 17:11:38 +00005237 unsigned flags = 0;
5238 if (HasCopyAndDispose)
5239 flags |= BLOCK_HAS_COPY_DISPOSE;
5240 Name = ND->getNameAsString();
5241 ByrefType.clear();
5242 RewriteByRefString(ByrefType, Name, ND);
5243 std::string ForwardingCastType("(");
5244 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005245 ByrefType += " " + Name + " = {(void*)";
5246 ByrefType += utostr(isa);
5247 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5248 ByrefType += utostr(flags);
5249 ByrefType += ", ";
5250 ByrefType += "sizeof(";
5251 RewriteByRefString(ByrefType, Name, ND);
5252 ByrefType += ")";
5253 if (HasCopyAndDispose) {
5254 ByrefType += ", __Block_byref_id_object_copy_";
5255 ByrefType += utostr(flag);
5256 ByrefType += ", __Block_byref_id_object_dispose_";
5257 ByrefType += utostr(flag);
5258 }
5259
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005260 if (!firstDecl) {
5261 // In multiple __block declarations, and for all but 1st declaration,
5262 // find location of the separating comma. This would be start location
5263 // where new text is to be inserted.
5264 DeclLoc = ND->getLocation();
5265 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5266 const char *commaBuf = startDeclBuf;
5267 while (*commaBuf != ',')
5268 commaBuf--;
5269 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5270 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5271 startBuf = commaBuf;
5272 }
5273
Fariborz Jahanian11671902012-02-07 17:11:38 +00005274 if (!hasInit) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005275 ByrefType += "};\n";
5276 unsigned nameSize = Name.size();
5277 // for block or function pointer declaration. Name is aleady
5278 // part of the declaration.
5279 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5280 nameSize = 1;
5281 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5282 }
5283 else {
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005284 ByrefType += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005285 SourceLocation startLoc;
5286 Expr *E = ND->getInit();
5287 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5288 startLoc = ECE->getLParenLoc();
5289 else
5290 startLoc = E->getLocStart();
5291 startLoc = SM->getExpansionLoc(startLoc);
5292 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005293 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005294
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005295 const char separator = lastDecl ? ';' : ',';
5296 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5297 const char *separatorBuf = strchr(startInitializerBuf, separator);
5298 assert((*separatorBuf == separator) &&
5299 "RewriteByRefVar: can't find ';' or ','");
5300 SourceLocation separatorLoc =
5301 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5302
5303 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00005304 }
5305 return;
5306}
5307
5308void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5309 // Add initializers for any closure decl refs.
5310 GetBlockDeclRefExprs(Exp->getBody());
5311 if (BlockDeclRefs.size()) {
5312 // Unique all "by copy" declarations.
5313 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005314 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005315 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5316 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5317 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5318 }
5319 }
5320 // Unique all "by ref" declarations.
5321 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005322 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005323 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5324 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5325 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5326 }
5327 }
5328 // Find any imported blocks...they will need special attention.
5329 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005330 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005331 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5332 BlockDeclRefs[i]->getType()->isBlockPointerType())
5333 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5334 }
5335}
5336
5337FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5338 IdentifierInfo *ID = &Context->Idents.get(name);
5339 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5340 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5341 SourceLocation(), ID, FType, 0, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005342 false, false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005343}
5344
5345Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00005346 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005347
Fariborz Jahanian11671902012-02-07 17:11:38 +00005348 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005349
Fariborz Jahanian11671902012-02-07 17:11:38 +00005350 Blocks.push_back(Exp);
5351
5352 CollectBlockDeclRefInfo(Exp);
5353
5354 // Add inner imported variables now used in current block.
5355 int countOfInnerDecls = 0;
5356 if (!InnerBlockDeclRefs.empty()) {
5357 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00005358 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian11671902012-02-07 17:11:38 +00005359 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00005360 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005361 // We need to save the copied-in variables in nested
5362 // blocks because it is needed at the end for some of the API generations.
5363 // See SynthesizeBlockLiterals routine.
5364 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5365 BlockDeclRefs.push_back(Exp);
5366 BlockByCopyDeclsPtrSet.insert(VD);
5367 BlockByCopyDecls.push_back(VD);
5368 }
John McCall113bee02012-03-10 09:33:50 +00005369 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005370 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5371 BlockDeclRefs.push_back(Exp);
5372 BlockByRefDeclsPtrSet.insert(VD);
5373 BlockByRefDecls.push_back(VD);
5374 }
5375 }
5376 // Find any imported blocks...they will need special attention.
5377 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005378 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005379 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5380 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5381 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5382 }
5383 InnerDeclRefsCount.push_back(countOfInnerDecls);
5384
5385 std::string FuncName;
5386
5387 if (CurFunctionDef)
5388 FuncName = CurFunctionDef->getNameAsString();
5389 else if (CurMethodDef)
5390 BuildUniqueMethodName(FuncName, CurMethodDef);
5391 else if (GlobalVarDecl)
5392 FuncName = std::string(GlobalVarDecl->getNameAsString());
5393
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005394 bool GlobalBlockExpr =
5395 block->getDeclContext()->getRedeclContext()->isFileContext();
5396
5397 if (GlobalBlockExpr && !GlobalVarDecl) {
5398 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5399 GlobalBlockExpr = false;
5400 }
5401
Fariborz Jahanian11671902012-02-07 17:11:38 +00005402 std::string BlockNumber = utostr(Blocks.size()-1);
5403
Fariborz Jahanian11671902012-02-07 17:11:38 +00005404 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5405
5406 // Get a pointer to the function type so we can cast appropriately.
5407 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5408 QualType FType = Context->getPointerType(BFT);
5409
5410 FunctionDecl *FD;
5411 Expr *NewRep;
5412
Benjamin Kramer60509af2013-09-09 14:48:42 +00005413 // Simulate a constructor call...
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005414 std::string Tag;
5415
5416 if (GlobalBlockExpr)
5417 Tag = "__global_";
5418 else
5419 Tag = "__";
5420 Tag += FuncName + "_block_impl_" + BlockNumber;
5421
Fariborz Jahanian11671902012-02-07 17:11:38 +00005422 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00005423 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005424 SourceLocation());
5425
5426 SmallVector<Expr*, 4> InitExprs;
5427
5428 // Initialize the block function.
5429 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00005430 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5431 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005432 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5433 CK_BitCast, Arg);
5434 InitExprs.push_back(castExpr);
5435
5436 // Initialize the block descriptor.
5437 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5438
5439 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5440 SourceLocation(), SourceLocation(),
5441 &Context->Idents.get(DescData.c_str()),
5442 Context->VoidPtrTy, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005443 SC_Static);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005444 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00005445 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005446 Context->VoidPtrTy,
5447 VK_LValue,
5448 SourceLocation()),
5449 UO_AddrOf,
5450 Context->getPointerType(Context->VoidPtrTy),
5451 VK_RValue, OK_Ordinary,
5452 SourceLocation());
5453 InitExprs.push_back(DescRefExpr);
5454
5455 // Add initializers for any closure decl refs.
5456 if (BlockDeclRefs.size()) {
5457 Expr *Exp;
5458 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005459 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005460 E = BlockByCopyDecls.end(); I != E; ++I) {
5461 if (isObjCType((*I)->getType())) {
5462 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5463 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005464 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5465 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005466 if (HasLocalVariableExternalStorage(*I)) {
5467 QualType QT = (*I)->getType();
5468 QT = Context->getPointerType(QT);
5469 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5470 OK_Ordinary, SourceLocation());
5471 }
5472 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5473 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005474 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5475 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005476 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5477 CK_BitCast, Arg);
5478 } else {
5479 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005480 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5481 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005482 if (HasLocalVariableExternalStorage(*I)) {
5483 QualType QT = (*I)->getType();
5484 QT = Context->getPointerType(QT);
5485 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5486 OK_Ordinary, SourceLocation());
5487 }
5488
5489 }
5490 InitExprs.push_back(Exp);
5491 }
5492 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005493 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005494 E = BlockByRefDecls.end(); I != E; ++I) {
5495 ValueDecl *ND = (*I);
5496 std::string Name(ND->getNameAsString());
5497 std::string RecName;
5498 RewriteByRefString(RecName, Name, ND, true);
5499 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5500 + sizeof("struct"));
5501 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5502 SourceLocation(), SourceLocation(),
5503 II);
5504 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5505 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5506
5507 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005508 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005509 SourceLocation());
5510 bool isNestedCapturedVar = false;
5511 if (block)
Aaron Ballman9371dd22014-03-14 18:34:04 +00005512 for (const auto &CI : block->captures()) {
5513 const VarDecl *variable = CI.getVariable();
5514 if (variable == ND && CI.isNested()) {
5515 assert (CI.isByRef() &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00005516 "SynthBlockInitExpr - captured block variable is not byref");
5517 isNestedCapturedVar = true;
5518 break;
5519 }
5520 }
5521 // captured nested byref variable has its address passed. Do not take
5522 // its address again.
5523 if (!isNestedCapturedVar)
5524 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5525 Context->getPointerType(Exp->getType()),
5526 VK_RValue, OK_Ordinary, SourceLocation());
5527 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5528 InitExprs.push_back(Exp);
5529 }
5530 }
5531 if (ImportedBlockDecls.size()) {
5532 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5533 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5534 unsigned IntSize =
5535 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5536 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5537 Context->IntTy, SourceLocation());
5538 InitExprs.push_back(FlagExp);
5539 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00005540 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005541 FType, VK_LValue, SourceLocation());
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005542
5543 if (GlobalBlockExpr) {
5544 assert (GlobalConstructionExp == 0 &&
5545 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5546 GlobalConstructionExp = NewRep;
5547 NewRep = DRE;
5548 }
5549
Fariborz Jahanian11671902012-02-07 17:11:38 +00005550 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5551 Context->getPointerType(NewRep->getType()),
5552 VK_RValue, OK_Ordinary, SourceLocation());
5553 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5554 NewRep);
5555 BlockDeclRefs.clear();
5556 BlockByRefDecls.clear();
5557 BlockByRefDeclsPtrSet.clear();
5558 BlockByCopyDecls.clear();
5559 BlockByCopyDeclsPtrSet.clear();
5560 ImportedBlockDecls.clear();
5561 return NewRep;
5562}
5563
5564bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5565 if (const ObjCForCollectionStmt * CS =
5566 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5567 return CS->getElement() == DS;
5568 return false;
5569}
5570
5571//===----------------------------------------------------------------------===//
5572// Function Body / Expression rewriting
5573//===----------------------------------------------------------------------===//
5574
5575Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5576 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5577 isa<DoStmt>(S) || isa<ForStmt>(S))
5578 Stmts.push_back(S);
5579 else if (isa<ObjCForCollectionStmt>(S)) {
5580 Stmts.push_back(S);
5581 ObjCBcLabelNo.push_back(++BcLabelCount);
5582 }
5583
5584 // Pseudo-object operations and ivar references need special
5585 // treatment because we're going to recursively rewrite them.
5586 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5587 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5588 return RewritePropertyOrImplicitSetter(PseudoOp);
5589 } else {
5590 return RewritePropertyOrImplicitGetter(PseudoOp);
5591 }
5592 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5593 return RewriteObjCIvarRefExpr(IvarRefExpr);
5594 }
Fariborz Jahanian4254cdb2013-02-08 18:57:50 +00005595 else if (isa<OpaqueValueExpr>(S))
5596 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005597
5598 SourceRange OrigStmtRange = S->getSourceRange();
5599
5600 // Perform a bottom up rewrite of all children.
5601 for (Stmt::child_range CI = S->children(); CI; ++CI)
5602 if (*CI) {
5603 Stmt *childStmt = (*CI);
5604 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5605 if (newStmt) {
5606 *CI = newStmt;
5607 }
5608 }
5609
5610 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00005611 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005612 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5613 InnerContexts.insert(BE->getBlockDecl());
5614 ImportedLocalExternalDecls.clear();
5615 GetInnerBlockDeclRefExprs(BE->getBody(),
5616 InnerBlockDeclRefs, InnerContexts);
5617 // Rewrite the block body in place.
5618 Stmt *SaveCurrentBody = CurrentBody;
5619 CurrentBody = BE->getBody();
5620 PropParentMap = 0;
5621 // block literal on rhs of a property-dot-sytax assignment
5622 // must be replaced by its synthesize ast so getRewrittenText
5623 // works as expected. In this case, what actually ends up on RHS
5624 // is the blockTranscribed which is the helper function for the
5625 // block literal; as in: self.c = ^() {[ace ARR];};
5626 bool saveDisableReplaceStmt = DisableReplaceStmt;
5627 DisableReplaceStmt = false;
5628 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5629 DisableReplaceStmt = saveDisableReplaceStmt;
5630 CurrentBody = SaveCurrentBody;
5631 PropParentMap = 0;
5632 ImportedLocalExternalDecls.clear();
5633 // Now we snarf the rewritten text and stash it away for later use.
5634 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5635 RewrittenBlockExprs[BE] = Str;
5636
5637 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5638
5639 //blockTranscribed->dump();
5640 ReplaceStmt(S, blockTranscribed);
5641 return blockTranscribed;
5642 }
5643 // Handle specific things.
5644 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5645 return RewriteAtEncode(AtEncode);
5646
5647 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5648 return RewriteAtSelector(AtSelector);
5649
5650 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5651 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00005652
5653 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5654 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00005655
Patrick Beard0caa3942012-04-19 00:25:12 +00005656 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5657 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00005658
5659 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5660 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00005661
5662 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5663 dyn_cast<ObjCDictionaryLiteral>(S))
5664 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005665
5666 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5667#if 0
5668 // Before we rewrite it, put the original message expression in a comment.
5669 SourceLocation startLoc = MessExpr->getLocStart();
5670 SourceLocation endLoc = MessExpr->getLocEnd();
5671
5672 const char *startBuf = SM->getCharacterData(startLoc);
5673 const char *endBuf = SM->getCharacterData(endLoc);
5674
5675 std::string messString;
5676 messString += "// ";
5677 messString.append(startBuf, endBuf-startBuf+1);
5678 messString += "\n";
5679
5680 // FIXME: Missing definition of
5681 // InsertText(clang::SourceLocation, char const*, unsigned int).
5682 // InsertText(startLoc, messString.c_str(), messString.size());
5683 // Tried this, but it didn't work either...
5684 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5685#endif
5686 return RewriteMessageExpr(MessExpr);
5687 }
5688
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00005689 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5690 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5691 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5692 }
5693
Fariborz Jahanian11671902012-02-07 17:11:38 +00005694 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5695 return RewriteObjCTryStmt(StmtTry);
5696
5697 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5698 return RewriteObjCSynchronizedStmt(StmtTry);
5699
5700 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5701 return RewriteObjCThrowStmt(StmtThrow);
5702
5703 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5704 return RewriteObjCProtocolExpr(ProtocolExp);
5705
5706 if (ObjCForCollectionStmt *StmtForCollection =
5707 dyn_cast<ObjCForCollectionStmt>(S))
5708 return RewriteObjCForCollectionStmt(StmtForCollection,
5709 OrigStmtRange.getEnd());
5710 if (BreakStmt *StmtBreakStmt =
5711 dyn_cast<BreakStmt>(S))
5712 return RewriteBreakStmt(StmtBreakStmt);
5713 if (ContinueStmt *StmtContinueStmt =
5714 dyn_cast<ContinueStmt>(S))
5715 return RewriteContinueStmt(StmtContinueStmt);
5716
5717 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5718 // and cast exprs.
5719 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5720 // FIXME: What we're doing here is modifying the type-specifier that
5721 // precedes the first Decl. In the future the DeclGroup should have
5722 // a separate type-specifier that we can rewrite.
5723 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5724 // the context of an ObjCForCollectionStmt. For example:
5725 // NSArray *someArray;
5726 // for (id <FooProtocol> index in someArray) ;
5727 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5728 // and it depends on the original text locations/positions.
5729 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5730 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5731
5732 // Blocks rewrite rules.
5733 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5734 DI != DE; ++DI) {
5735 Decl *SD = *DI;
5736 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5737 if (isTopLevelBlockPointerType(ND->getType()))
5738 RewriteBlockPointerDecl(ND);
5739 else if (ND->getType()->isFunctionPointerType())
5740 CheckFunctionPointerDecl(ND->getType(), ND);
5741 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5742 if (VD->hasAttr<BlocksAttr>()) {
5743 static unsigned uniqueByrefDeclCount = 0;
5744 assert(!BlockByRefDeclNo.count(ND) &&
5745 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5746 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005747 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian11671902012-02-07 17:11:38 +00005748 }
5749 else
5750 RewriteTypeOfDecl(VD);
5751 }
5752 }
5753 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5754 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5755 RewriteBlockPointerDecl(TD);
5756 else if (TD->getUnderlyingType()->isFunctionPointerType())
5757 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5758 }
5759 }
5760 }
5761
5762 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5763 RewriteObjCQualifiedInterfaceTypes(CE);
5764
5765 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5766 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5767 assert(!Stmts.empty() && "Statement stack is empty");
5768 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5769 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5770 && "Statement stack mismatch");
5771 Stmts.pop_back();
5772 }
5773 // Handle blocks rewriting.
Fariborz Jahanian11671902012-02-07 17:11:38 +00005774 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5775 ValueDecl *VD = DRE->getDecl();
5776 if (VD->hasAttr<BlocksAttr>())
5777 return RewriteBlockDeclRefExpr(DRE);
5778 if (HasLocalVariableExternalStorage(VD))
5779 return RewriteLocalVariableExternalStorage(DRE);
5780 }
5781
5782 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5783 if (CE->getCallee()->getType()->isBlockPointerType()) {
5784 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5785 ReplaceStmt(S, BlockCall);
5786 return BlockCall;
5787 }
5788 }
5789 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5790 RewriteCastExpr(CE);
5791 }
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00005792 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5793 RewriteImplicitCastObjCExpr(ICE);
5794 }
Fariborz Jahaniancc172282012-04-16 22:14:01 +00005795#if 0
Fariborz Jahanian3a5d5522012-04-13 18:00:54 +00005796
Fariborz Jahanian11671902012-02-07 17:11:38 +00005797 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5798 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5799 ICE->getSubExpr(),
5800 SourceLocation());
5801 // Get the new text.
5802 std::string SStr;
5803 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00005804 Replacement->printPretty(Buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005805 const std::string &Str = Buf.str();
5806
5807 printf("CAST = %s\n", &Str[0]);
5808 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5809 delete S;
5810 return Replacement;
5811 }
5812#endif
5813 // Return this stmt unmodified.
5814 return S;
5815}
5816
5817void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005818 for (auto *FD : RD->fields()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005819 if (isTopLevelBlockPointerType(FD->getType()))
5820 RewriteBlockPointerDecl(FD);
5821 if (FD->getType()->isObjCQualifiedIdType() ||
5822 FD->getType()->isObjCQualifiedInterfaceType())
5823 RewriteObjCQualifiedInterfaceTypes(FD);
5824 }
5825}
5826
5827/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5828/// main file of the input.
5829void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5830 switch (D->getKind()) {
5831 case Decl::Function: {
5832 FunctionDecl *FD = cast<FunctionDecl>(D);
5833 if (FD->isOverloadedOperator())
5834 return;
5835
5836 // Since function prototypes don't have ParmDecl's, we check the function
5837 // prototype. This enables us to rewrite function declarations and
5838 // definitions using the same code.
5839 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5840
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00005841 if (!FD->isThisDeclarationADefinition())
5842 break;
5843
Fariborz Jahanian11671902012-02-07 17:11:38 +00005844 // FIXME: If this should support Obj-C++, support CXXTryStmt
5845 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5846 CurFunctionDef = FD;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005847 CurrentBody = Body;
5848 Body =
5849 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5850 FD->setBody(Body);
5851 CurrentBody = 0;
5852 if (PropParentMap) {
5853 delete PropParentMap;
5854 PropParentMap = 0;
5855 }
5856 // This synthesizes and inserts the block "impl" struct, invoke function,
5857 // and any copy/dispose helper functions.
5858 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005859 RewriteLineDirective(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005860 CurFunctionDef = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005861 }
5862 break;
5863 }
5864 case Decl::ObjCMethod: {
5865 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5866 if (CompoundStmt *Body = MD->getCompoundBody()) {
5867 CurMethodDef = MD;
5868 CurrentBody = Body;
5869 Body =
5870 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5871 MD->setBody(Body);
5872 CurrentBody = 0;
5873 if (PropParentMap) {
5874 delete PropParentMap;
5875 PropParentMap = 0;
5876 }
5877 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005878 RewriteLineDirective(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005879 CurMethodDef = 0;
5880 }
5881 break;
5882 }
5883 case Decl::ObjCImplementation: {
5884 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5885 ClassImplementation.push_back(CI);
5886 break;
5887 }
5888 case Decl::ObjCCategoryImpl: {
5889 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5890 CategoryImplementation.push_back(CI);
5891 break;
5892 }
5893 case Decl::Var: {
5894 VarDecl *VD = cast<VarDecl>(D);
5895 RewriteObjCQualifiedInterfaceTypes(VD);
5896 if (isTopLevelBlockPointerType(VD->getType()))
5897 RewriteBlockPointerDecl(VD);
5898 else if (VD->getType()->isFunctionPointerType()) {
5899 CheckFunctionPointerDecl(VD->getType(), VD);
5900 if (VD->getInit()) {
5901 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5902 RewriteCastExpr(CE);
5903 }
5904 }
5905 } else if (VD->getType()->isRecordType()) {
5906 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5907 if (RD->isCompleteDefinition())
5908 RewriteRecordBody(RD);
5909 }
5910 if (VD->getInit()) {
5911 GlobalVarDecl = VD;
5912 CurrentBody = VD->getInit();
5913 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5914 CurrentBody = 0;
5915 if (PropParentMap) {
5916 delete PropParentMap;
5917 PropParentMap = 0;
5918 }
5919 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5920 GlobalVarDecl = 0;
5921
5922 // This is needed for blocks.
5923 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5924 RewriteCastExpr(CE);
5925 }
5926 }
5927 break;
5928 }
5929 case Decl::TypeAlias:
5930 case Decl::Typedef: {
5931 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5932 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5933 RewriteBlockPointerDecl(TD);
5934 else if (TD->getUnderlyingType()->isFunctionPointerType())
5935 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00005936 else
5937 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005938 }
5939 break;
5940 }
5941 case Decl::CXXRecord:
5942 case Decl::Record: {
5943 RecordDecl *RD = cast<RecordDecl>(D);
5944 if (RD->isCompleteDefinition())
5945 RewriteRecordBody(RD);
5946 break;
5947 }
5948 default:
5949 break;
5950 }
5951 // Nothing yet.
5952}
5953
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005954/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5955/// protocol reference symbols in the for of:
5956/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5957static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5958 ObjCProtocolDecl *PDecl,
5959 std::string &Result) {
5960 // Also output .objc_protorefs$B section and its meta-data.
5961 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanian75f2e3c2012-04-27 21:39:49 +00005962 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005963 Result += "struct _protocol_t *";
5964 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5965 Result += PDecl->getNameAsString();
5966 Result += " = &";
5967 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5968 Result += ";\n";
5969}
5970
Fariborz Jahanian11671902012-02-07 17:11:38 +00005971void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5972 if (Diags.hasErrorOccurred())
5973 return;
5974
5975 RewriteInclude();
5976
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005977 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005978 // translation of function bodies were postponed until all class and
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005979 // their extensions and implementations are seen. This is because, we
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005980 // cannot build grouping structs for bitfields until they are all seen.
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005981 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5982 HandleTopLevelSingleDecl(FDecl);
5983 }
5984
Fariborz Jahanian11671902012-02-07 17:11:38 +00005985 // Here's a great place to add any extra declarations that may be needed.
5986 // Write out meta data for each @protocol(<expr>).
5987 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005988 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00005989 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005990 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
5991 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005992
5993 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00005994
5995 if (ClassImplementation.size() || CategoryImplementation.size())
5996 RewriteImplementations();
5997
Fariborz Jahanian8e1118cbd2012-02-21 23:58:41 +00005998 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
5999 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
6000 // Write struct declaration for the class matching its ivar declarations.
6001 // Note that for modern abi, this is postponed until the end of TU
6002 // because class extensions and the implementation might declare their own
6003 // private ivars.
6004 RewriteInterfaceDecl(CDecl);
6005 }
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006006
Fariborz Jahanian11671902012-02-07 17:11:38 +00006007 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6008 // we are done.
6009 if (const RewriteBuffer *RewriteBuf =
6010 Rewrite.getRewriteBufferFor(MainFileID)) {
6011 //printf("Changed:\n");
6012 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6013 } else {
6014 llvm::errs() << "No changes\n";
6015 }
6016
6017 if (ClassImplementation.size() || CategoryImplementation.size() ||
6018 ProtocolExprDecls.size()) {
6019 // Rewrite Objective-c meta data*
6020 std::string ResultStr;
6021 RewriteMetaDataIntoBuffer(ResultStr);
6022 // Emit metadata.
6023 *OutFile << ResultStr;
6024 }
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006025 // Emit ImageInfo;
6026 {
6027 std::string ResultStr;
6028 WriteImageInfo(ResultStr);
6029 *OutFile << ResultStr;
6030 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006031 OutFile->flush();
6032}
6033
6034void RewriteModernObjC::Initialize(ASTContext &context) {
6035 InitializeCommon(context);
6036
Fariborz Jahanianb52221e2012-03-10 17:45:38 +00006037 Preamble += "#ifndef __OBJC2__\n";
6038 Preamble += "#define __OBJC2__\n";
6039 Preamble += "#endif\n";
6040
Fariborz Jahanian11671902012-02-07 17:11:38 +00006041 // declaring objc_selector outside the parameter list removes a silly
6042 // scope related warning...
6043 if (IsHeader)
6044 Preamble = "#pragma once\n";
6045 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahanian27db0b32012-04-12 23:52:52 +00006046 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
6047 Preamble += "\n\tstruct objc_object *superClass; ";
6048 // Add a constructor for creating temporary objects.
6049 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
6050 Preamble += ": object(o), superClass(s) {} ";
6051 Preamble += "\n};\n";
6052
Fariborz Jahanian11671902012-02-07 17:11:38 +00006053 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006054 // Define all sections using syntax that makes sense.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006055 // These are currently generated.
6056 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006057 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006058 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006059 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6060 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006061 // These are generated but not necessary for functionality.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006062 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006063 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6064 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006065 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006066
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006067 // These need be generated for performance. Currently they are not,
6068 // using API calls instead.
6069 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6070 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6071 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6072
Fariborz Jahanian11671902012-02-07 17:11:38 +00006073 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006074 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6075 Preamble += "typedef struct objc_object Protocol;\n";
6076 Preamble += "#define _REWRITER_typedef_Protocol\n";
6077 Preamble += "#endif\n";
6078 if (LangOpts.MicrosoftExt) {
6079 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6080 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006081 }
6082 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006083 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006084
6085 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6086 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6087 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6088 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6089 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6090
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006091 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006092 Preamble += "(const char *);\n";
6093 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6094 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006095 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006096 Preamble += "(const char *);\n";
Fariborz Jahanian34660592012-03-19 18:11:32 +00006097 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006098 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00006099 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6100 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006101 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00006102 Preamble += "#ifdef _WIN64\n";
6103 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
6104 Preamble += "#else\n";
6105 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
6106 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006107 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6108 Preamble += "struct __objcFastEnumerationState {\n\t";
6109 Preamble += "unsigned long state;\n\t";
6110 Preamble += "void **itemsPtr;\n\t";
6111 Preamble += "unsigned long *mutationsPtr;\n\t";
6112 Preamble += "unsigned long extra[5];\n};\n";
6113 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6114 Preamble += "#define __FASTENUMERATIONSTATE\n";
6115 Preamble += "#endif\n";
6116 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6117 Preamble += "struct __NSConstantStringImpl {\n";
6118 Preamble += " int *isa;\n";
6119 Preamble += " int flags;\n";
6120 Preamble += " char *str;\n";
6121 Preamble += " long length;\n";
6122 Preamble += "};\n";
6123 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6124 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6125 Preamble += "#else\n";
6126 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6127 Preamble += "#endif\n";
6128 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6129 Preamble += "#endif\n";
6130 // Blocks preamble.
6131 Preamble += "#ifndef BLOCK_IMPL\n";
6132 Preamble += "#define BLOCK_IMPL\n";
6133 Preamble += "struct __block_impl {\n";
6134 Preamble += " void *isa;\n";
6135 Preamble += " int Flags;\n";
6136 Preamble += " int Reserved;\n";
6137 Preamble += " void *FuncPtr;\n";
6138 Preamble += "};\n";
6139 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6140 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6141 Preamble += "extern \"C\" __declspec(dllexport) "
6142 "void _Block_object_assign(void *, const void *, const int);\n";
6143 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6144 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6145 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6146 Preamble += "#else\n";
6147 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6148 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6149 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6150 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6151 Preamble += "#endif\n";
6152 Preamble += "#endif\n";
6153 if (LangOpts.MicrosoftExt) {
6154 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6155 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6156 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6157 Preamble += "#define __attribute__(X)\n";
6158 Preamble += "#endif\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006159 Preamble += "#ifndef __weak\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006160 Preamble += "#define __weak\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006161 Preamble += "#endif\n";
6162 Preamble += "#ifndef __block\n";
6163 Preamble += "#define __block\n";
6164 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006165 }
6166 else {
6167 Preamble += "#define __block\n";
6168 Preamble += "#define __weak\n";
6169 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00006170
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006171 // Declarations required for modern objective-c array and dictionary literals.
6172 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006173 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006174 Preamble += " void * *arr;\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006175 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006176 Preamble += "\tva_list marker;\n";
6177 Preamble += "\tva_start(marker, count);\n";
6178 Preamble += "\tarr = new void *[count];\n";
6179 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6180 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6181 Preamble += "\tva_end( marker );\n";
6182 Preamble += " };\n";
Fariborz Jahanian70ef9292012-05-02 23:53:46 +00006183 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006184 Preamble += "\tdelete[] arr;\n";
6185 Preamble += " }\n";
6186 Preamble += "};\n";
6187
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00006188 // Declaration required for implementation of @autoreleasepool statement.
6189 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6190 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6191 Preamble += "struct __AtAutoreleasePool {\n";
6192 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6193 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6194 Preamble += " void * atautoreleasepoolobj;\n";
6195 Preamble += "};\n";
6196
Fariborz Jahanian11671902012-02-07 17:11:38 +00006197 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6198 // as this avoids warning in any 64bit/32bit compilation model.
6199 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6200}
6201
6202/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6203/// ivar offset.
6204void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6205 std::string &Result) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006206 Result += "__OFFSETOFIVAR__(struct ";
6207 Result += ivar->getContainingInterface()->getNameAsString();
6208 if (LangOpts.MicrosoftExt)
6209 Result += "_IMPL";
6210 Result += ", ";
6211 if (ivar->isBitField())
6212 ObjCIvarBitfieldGroupDecl(ivar, Result);
6213 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006214 Result += ivar->getNameAsString();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006215 Result += ")";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006216}
6217
6218/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6219/// struct _prop_t {
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006220/// const char *name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006221/// char *attributes;
6222/// }
6223
6224/// struct _prop_list_t {
6225/// uint32_t entsize; // sizeof(struct _prop_t)
6226/// uint32_t count_of_properties;
6227/// struct _prop_t prop_list[count_of_properties];
6228/// }
6229
6230/// struct _protocol_t;
6231
6232/// struct _protocol_list_t {
6233/// long protocol_count; // Note, this is 32/64 bit
6234/// struct _protocol_t * protocol_list[protocol_count];
6235/// }
6236
6237/// struct _objc_method {
6238/// SEL _cmd;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006239/// const char *method_type;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006240/// char *_imp;
6241/// }
6242
6243/// struct _method_list_t {
6244/// uint32_t entsize; // sizeof(struct _objc_method)
6245/// uint32_t method_count;
6246/// struct _objc_method method_list[method_count];
6247/// }
6248
6249/// struct _protocol_t {
6250/// id isa; // NULL
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006251/// const char *protocol_name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006252/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006253/// const struct method_list_t *instance_methods;
6254/// const struct method_list_t *class_methods;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006255/// const struct method_list_t *optionalInstanceMethods;
6256/// const struct method_list_t *optionalClassMethods;
6257/// const struct _prop_list_t * properties;
6258/// const uint32_t size; // sizeof(struct _protocol_t)
6259/// const uint32_t flags; // = 0
6260/// const char ** extendedMethodTypes;
6261/// }
6262
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006263/// struct _ivar_t {
6264/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006265/// const char *name;
6266/// const char *type;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006267/// uint32_t alignment;
6268/// uint32_t size;
6269/// }
6270
6271/// struct _ivar_list_t {
6272/// uint32 entsize; // sizeof(struct _ivar_t)
6273/// uint32 count;
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006274/// struct _ivar_t list[count];
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006275/// }
6276
6277/// struct _class_ro_t {
Fariborz Jahanian34134812012-03-24 16:53:16 +00006278/// uint32_t flags;
6279/// uint32_t instanceStart;
6280/// uint32_t instanceSize;
6281/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006282/// const uint8_t *ivarLayout;
6283/// const char *name;
6284/// const struct _method_list_t *baseMethods;
6285/// const struct _protocol_list_t *baseProtocols;
6286/// const struct _ivar_list_t *ivars;
6287/// const uint8_t *weakIvarLayout;
6288/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006289/// }
6290
6291/// struct _class_t {
6292/// struct _class_t *isa;
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006293/// struct _class_t *superclass;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006294/// void *cache;
6295/// IMP *vtable;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006296/// struct _class_ro_t *ro;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006297/// }
6298
6299/// struct _category_t {
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006300/// const char *name;
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006301/// struct _class_t *cls;
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006302/// const struct _method_list_t *instance_methods;
6303/// const struct _method_list_t *class_methods;
6304/// const struct _protocol_list_t *protocols;
6305/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006306/// }
6307
6308/// MessageRefTy - LLVM for:
6309/// struct _message_ref_t {
6310/// IMP messenger;
6311/// SEL name;
6312/// };
6313
6314/// SuperMessageRefTy - LLVM for:
6315/// struct _super_message_ref_t {
6316/// SUPER_IMP messenger;
6317/// SEL name;
6318/// };
6319
Fariborz Jahanian45489622012-03-14 18:09:23 +00006320static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006321 static bool meta_data_declared = false;
6322 if (meta_data_declared)
6323 return;
6324
6325 Result += "\nstruct _prop_t {\n";
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006326 Result += "\tconst char *name;\n";
6327 Result += "\tconst char *attributes;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006328 Result += "};\n";
6329
6330 Result += "\nstruct _protocol_t;\n";
6331
Fariborz Jahanian11671902012-02-07 17:11:38 +00006332 Result += "\nstruct _objc_method {\n";
6333 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006334 Result += "\tconst char *method_type;\n";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006335 Result += "\tvoid *_imp;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006336 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006337
6338 Result += "\nstruct _protocol_t {\n";
6339 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006340 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006341 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006342 Result += "\tconst struct method_list_t *instance_methods;\n";
6343 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006344 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6345 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6346 Result += "\tconst struct _prop_list_t * properties;\n";
6347 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6348 Result += "\tconst unsigned int flags; // = 0\n";
6349 Result += "\tconst char ** extendedMethodTypes;\n";
6350 Result += "};\n";
6351
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006352 Result += "\nstruct _ivar_t {\n";
6353 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006354 Result += "\tconst char *name;\n";
6355 Result += "\tconst char *type;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006356 Result += "\tunsigned int alignment;\n";
6357 Result += "\tunsigned int size;\n";
6358 Result += "};\n";
6359
6360 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006361 Result += "\tunsigned int flags;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006362 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006363 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006364 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6365 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian34134812012-03-24 16:53:16 +00006366 Result += "\tunsigned int reserved;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006367 Result += "\tconst unsigned char *ivarLayout;\n";
6368 Result += "\tconst char *name;\n";
6369 Result += "\tconst struct _method_list_t *baseMethods;\n";
6370 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6371 Result += "\tconst struct _ivar_list_t *ivars;\n";
6372 Result += "\tconst unsigned char *weakIvarLayout;\n";
6373 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006374 Result += "};\n";
6375
6376 Result += "\nstruct _class_t {\n";
6377 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006378 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006379 Result += "\tvoid *cache;\n";
6380 Result += "\tvoid *vtable;\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006381 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006382 Result += "};\n";
6383
6384 Result += "\nstruct _category_t {\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006385 Result += "\tconst char *name;\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006386 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006387 Result += "\tconst struct _method_list_t *instance_methods;\n";
6388 Result += "\tconst struct _method_list_t *class_methods;\n";
6389 Result += "\tconst struct _protocol_list_t *protocols;\n";
6390 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006391 Result += "};\n";
6392
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006393 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006394 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006395 meta_data_declared = true;
6396}
6397
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006398static void Write_protocol_list_t_TypeDecl(std::string &Result,
6399 long super_protocol_count) {
6400 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6401 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6402 Result += "\tstruct _protocol_t *super_protocols[";
6403 Result += utostr(super_protocol_count); Result += "];\n";
6404 Result += "}";
6405}
6406
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006407static void Write_method_list_t_TypeDecl(std::string &Result,
6408 unsigned int method_count) {
6409 Result += "struct /*_method_list_t*/"; Result += " {\n";
6410 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6411 Result += "\tunsigned int method_count;\n";
6412 Result += "\tstruct _objc_method method_list[";
6413 Result += utostr(method_count); Result += "];\n";
6414 Result += "}";
6415}
6416
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006417static void Write__prop_list_t_TypeDecl(std::string &Result,
6418 unsigned int property_count) {
6419 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6420 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6421 Result += "\tunsigned int count_of_properties;\n";
6422 Result += "\tstruct _prop_t prop_list[";
6423 Result += utostr(property_count); Result += "];\n";
6424 Result += "}";
6425}
6426
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006427static void Write__ivar_list_t_TypeDecl(std::string &Result,
6428 unsigned int ivar_count) {
6429 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6430 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6431 Result += "\tunsigned int count;\n";
6432 Result += "\tstruct _ivar_t ivar_list[";
6433 Result += utostr(ivar_count); Result += "];\n";
6434 Result += "}";
6435}
6436
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006437static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6438 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6439 StringRef VarName,
6440 StringRef ProtocolName) {
6441 if (SuperProtocols.size() > 0) {
6442 Result += "\nstatic ";
6443 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6444 Result += " "; Result += VarName;
6445 Result += ProtocolName;
6446 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6447 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6448 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6449 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6450 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6451 Result += SuperPD->getNameAsString();
6452 if (i == e-1)
6453 Result += "\n};\n";
6454 else
6455 Result += ",\n";
6456 }
6457 }
6458}
6459
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006460static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6461 ASTContext *Context, std::string &Result,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006462 ArrayRef<ObjCMethodDecl *> Methods,
6463 StringRef VarName,
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006464 StringRef TopLevelDeclName,
6465 bool MethodImpl) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006466 if (Methods.size() > 0) {
6467 Result += "\nstatic ";
6468 Write_method_list_t_TypeDecl(Result, Methods.size());
6469 Result += " "; Result += VarName;
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006470 Result += TopLevelDeclName;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006471 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6472 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6473 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6474 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6475 ObjCMethodDecl *MD = Methods[i];
6476 if (i == 0)
6477 Result += "\t{{(struct objc_selector *)\"";
6478 else
6479 Result += "\t{(struct objc_selector *)\"";
6480 Result += (MD)->getSelector().getAsString(); Result += "\"";
6481 Result += ", ";
6482 std::string MethodTypeString;
6483 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6484 Result += "\""; Result += MethodTypeString; Result += "\"";
6485 Result += ", ";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006486 if (!MethodImpl)
6487 Result += "0";
6488 else {
6489 Result += "(void *)";
6490 Result += RewriteObj.MethodInternalNames[MD];
6491 }
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006492 if (i == e-1)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006493 Result += "}}\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006494 else
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006495 Result += "},\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006496 }
6497 Result += "};\n";
6498 }
6499}
6500
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006501static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006502 ASTContext *Context, std::string &Result,
6503 ArrayRef<ObjCPropertyDecl *> Properties,
6504 const Decl *Container,
6505 StringRef VarName,
6506 StringRef ProtocolName) {
6507 if (Properties.size() > 0) {
6508 Result += "\nstatic ";
6509 Write__prop_list_t_TypeDecl(Result, Properties.size());
6510 Result += " "; Result += VarName;
6511 Result += ProtocolName;
6512 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6513 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6514 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6515 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6516 ObjCPropertyDecl *PropDecl = Properties[i];
6517 if (i == 0)
6518 Result += "\t{{\"";
6519 else
6520 Result += "\t{\"";
6521 Result += PropDecl->getName(); Result += "\",";
6522 std::string PropertyTypeString, QuotePropertyTypeString;
6523 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6524 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6525 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6526 if (i == e-1)
6527 Result += "}}\n";
6528 else
6529 Result += "},\n";
6530 }
6531 Result += "};\n";
6532 }
6533}
6534
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006535// Metadata flags
6536enum MetaDataDlags {
6537 CLS = 0x0,
6538 CLS_META = 0x1,
6539 CLS_ROOT = 0x2,
6540 OBJC2_CLS_HIDDEN = 0x10,
6541 CLS_EXCEPTION = 0x20,
6542
6543 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6544 CLS_HAS_IVAR_RELEASER = 0x40,
6545 /// class was compiled with -fobjc-arr
6546 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6547};
6548
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006549static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6550 unsigned int flags,
6551 const std::string &InstanceStart,
6552 const std::string &InstanceSize,
6553 ArrayRef<ObjCMethodDecl *>baseMethods,
6554 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6555 ArrayRef<ObjCIvarDecl *>ivars,
6556 ArrayRef<ObjCPropertyDecl *>Properties,
6557 StringRef VarName,
6558 StringRef ClassName) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006559 Result += "\nstatic struct _class_ro_t ";
6560 Result += VarName; Result += ClassName;
6561 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6562 Result += "\t";
6563 Result += llvm::utostr(flags); Result += ", ";
6564 Result += InstanceStart; Result += ", ";
6565 Result += InstanceSize; Result += ", \n";
6566 Result += "\t";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006567 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6568 if (Triple.getArch() == llvm::Triple::x86_64)
6569 // uint32_t const reserved; // only when building for 64bit targets
6570 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006571 // const uint8_t * const ivarLayout;
6572 Result += "0, \n\t";
6573 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006574 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006575 if (baseMethods.size() > 0) {
6576 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006577 if (metaclass)
6578 Result += "_OBJC_$_CLASS_METHODS_";
6579 else
6580 Result += "_OBJC_$_INSTANCE_METHODS_";
6581 Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006582 Result += ",\n\t";
6583 }
6584 else
6585 Result += "0, \n\t";
6586
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006587 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006588 Result += "(const struct _objc_protocol_list *)&";
6589 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6590 Result += ",\n\t";
6591 }
6592 else
6593 Result += "0, \n\t";
6594
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006595 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006596 Result += "(const struct _ivar_list_t *)&";
6597 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6598 Result += ",\n\t";
6599 }
6600 else
6601 Result += "0, \n\t";
6602
6603 // weakIvarLayout
6604 Result += "0, \n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006605 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006606 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00006607 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006608 Result += ",\n";
6609 }
6610 else
6611 Result += "0, \n";
6612
6613 Result += "};\n";
6614}
6615
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006616static void Write_class_t(ASTContext *Context, std::string &Result,
6617 StringRef VarName,
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006618 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6619 bool rootClass = (!CDecl->getSuperClass());
6620 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006621
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006622 if (!rootClass) {
6623 // Find the Root class
6624 RootClass = CDecl->getSuperClass();
6625 while (RootClass->getSuperClass()) {
6626 RootClass = RootClass->getSuperClass();
6627 }
6628 }
6629
6630 if (metaclass && rootClass) {
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006631 // Need to handle a case of use of forward declaration.
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006632 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006633 Result += "extern \"C\" ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006634 if (CDecl->getImplementation())
6635 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006636 else
6637 Result += "__declspec(dllimport) ";
6638
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006639 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006640 Result += CDecl->getNameAsString();
6641 Result += ";\n";
6642 }
6643 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006644 if (!rootClass) {
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006645 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006646 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006647 Result += "extern \"C\" ";
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006648 if (SuperClass->getImplementation())
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006649 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006650 else
6651 Result += "__declspec(dllimport) ";
6652
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006653 Result += "struct _class_t ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006654 Result += VarName;
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006655 Result += SuperClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006656 Result += ";\n";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006657
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006658 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006659 Result += "extern \"C\" ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006660 if (RootClass->getImplementation())
6661 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006662 else
6663 Result += "__declspec(dllimport) ";
6664
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006665 Result += "struct _class_t ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006666 Result += VarName;
6667 Result += RootClass->getNameAsString();
6668 Result += ";\n";
6669 }
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006670 }
6671
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006672 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6673 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006674 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6675 Result += "\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006676 if (metaclass) {
6677 if (!rootClass) {
6678 Result += "0, // &"; Result += VarName;
6679 Result += RootClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006680 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006681 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006682 Result += CDecl->getSuperClass()->getNameAsString();
6683 Result += ",\n\t";
6684 }
6685 else {
Fariborz Jahanian35465592012-03-20 21:09:58 +00006686 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006687 Result += CDecl->getNameAsString();
6688 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006689 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006690 Result += ",\n\t";
6691 }
6692 }
6693 else {
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006694 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006695 Result += CDecl->getNameAsString();
6696 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006697 if (!rootClass) {
6698 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006699 Result += CDecl->getSuperClass()->getNameAsString();
6700 Result += ",\n\t";
6701 }
6702 else
6703 Result += "0,\n\t";
6704 }
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006705 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6706 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6707 if (metaclass)
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006708 Result += "&_OBJC_METACLASS_RO_$_";
6709 else
6710 Result += "&_OBJC_CLASS_RO_$_";
6711 Result += CDecl->getNameAsString();
6712 Result += ",\n};\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006713
6714 // Add static function to initialize some of the meta-data fields.
6715 // avoid doing it twice.
6716 if (metaclass)
6717 return;
6718
6719 const ObjCInterfaceDecl *SuperClass =
6720 rootClass ? CDecl : CDecl->getSuperClass();
6721
6722 Result += "static void OBJC_CLASS_SETUP_$_";
6723 Result += CDecl->getNameAsString();
6724 Result += "(void ) {\n";
6725 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6726 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006727 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006728
6729 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian35465592012-03-20 21:09:58 +00006730 Result += ".superclass = ";
6731 if (rootClass)
6732 Result += "&OBJC_CLASS_$_";
6733 else
6734 Result += "&OBJC_METACLASS_$_";
6735
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006736 Result += SuperClass->getNameAsString(); Result += ";\n";
6737
6738 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6739 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6740
6741 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6742 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6743 Result += CDecl->getNameAsString(); Result += ";\n";
6744
6745 if (!rootClass) {
6746 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6747 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6748 Result += SuperClass->getNameAsString(); Result += ";\n";
6749 }
6750
6751 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6752 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6753 Result += "}\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006754}
6755
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006756static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6757 std::string &Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006758 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006759 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006760 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6761 ArrayRef<ObjCMethodDecl *> ClassMethods,
6762 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6763 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006764 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi3eb0edd2012-03-21 03:21:46 +00006765 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006766 // must declare an extern class object in case this class is not implemented
6767 // in this TU.
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006768 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006769 Result += "extern \"C\" ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006770 if (ClassDecl->getImplementation())
6771 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006772 else
6773 Result += "__declspec(dllimport) ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006774
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006775 Result += "struct _class_t ";
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006776 Result += "OBJC_CLASS_$_"; Result += ClassName;
6777 Result += ";\n";
6778
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006779 Result += "\nstatic struct _category_t ";
6780 Result += "_OBJC_$_CATEGORY_";
6781 Result += ClassName; Result += "_$_"; Result += CatName;
6782 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6783 Result += "{\n";
6784 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006785 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006786 Result += ",\n";
6787 if (InstanceMethods.size() > 0) {
6788 Result += "\t(const struct _method_list_t *)&";
6789 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6790 Result += ClassName; Result += "_$_"; Result += CatName;
6791 Result += ",\n";
6792 }
6793 else
6794 Result += "\t0,\n";
6795
6796 if (ClassMethods.size() > 0) {
6797 Result += "\t(const struct _method_list_t *)&";
6798 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6799 Result += ClassName; Result += "_$_"; Result += CatName;
6800 Result += ",\n";
6801 }
6802 else
6803 Result += "\t0,\n";
6804
6805 if (RefedProtocols.size() > 0) {
6806 Result += "\t(const struct _protocol_list_t *)&";
6807 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6808 Result += ClassName; Result += "_$_"; Result += CatName;
6809 Result += ",\n";
6810 }
6811 else
6812 Result += "\t0,\n";
6813
6814 if (ClassProperties.size() > 0) {
6815 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6816 Result += ClassName; Result += "_$_"; Result += CatName;
6817 Result += ",\n";
6818 }
6819 else
6820 Result += "\t0,\n";
6821
6822 Result += "};\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006823
6824 // Add static function to initialize the class pointer in the category structure.
6825 Result += "static void OBJC_CATEGORY_SETUP_$_";
6826 Result += ClassDecl->getNameAsString();
6827 Result += "_$_";
6828 Result += CatName;
6829 Result += "(void ) {\n";
6830 Result += "\t_OBJC_$_CATEGORY_";
6831 Result += ClassDecl->getNameAsString();
6832 Result += "_$_";
6833 Result += CatName;
6834 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6835 Result += ";\n}\n";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006836}
6837
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006838static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6839 ASTContext *Context, std::string &Result,
6840 ArrayRef<ObjCMethodDecl *> Methods,
6841 StringRef VarName,
6842 StringRef ProtocolName) {
6843 if (Methods.size() == 0)
6844 return;
6845
6846 Result += "\nstatic const char *";
6847 Result += VarName; Result += ProtocolName;
6848 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6849 Result += "{\n";
6850 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6851 ObjCMethodDecl *MD = Methods[i];
6852 std::string MethodTypeString, QuoteMethodTypeString;
6853 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6854 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6855 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6856 if (i == e-1)
6857 Result += "\n};\n";
6858 else {
6859 Result += ",\n";
6860 }
6861 }
6862}
6863
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006864static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6865 ASTContext *Context,
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006866 std::string &Result,
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006867 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006868 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006869 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6870 // this is what happens:
6871 /**
6872 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6873 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6874 Class->getVisibility() == HiddenVisibility)
6875 Visibility shoud be: HiddenVisibility;
6876 else
6877 Visibility shoud be: DefaultVisibility;
6878 */
6879
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006880 Result += "\n";
6881 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6882 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006883 if (Context->getLangOpts().MicrosoftExt)
6884 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6885
6886 if (!Context->getLangOpts().MicrosoftExt ||
6887 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanianc9295ec2012-03-10 01:34:42 +00006888 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006889 Result += "extern \"C\" unsigned long int ";
Fariborz Jahanian2677ded2012-03-10 00:53:02 +00006890 else
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006891 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006892 if (Ivars[i]->isBitField())
6893 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6894 else
6895 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006896 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6897 Result += " = ";
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006898 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6899 Result += ";\n";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006900 if (Ivars[i]->isBitField()) {
6901 // skip over rest of the ivar bitfields.
6902 SKIP_BITFIELDS(i , e, Ivars);
6903 }
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006904 }
6905}
6906
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006907static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6908 ASTContext *Context, std::string &Result,
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006909 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006910 StringRef VarName,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006911 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006912 if (OriginalIvars.size() > 0) {
6913 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6914 SmallVector<ObjCIvarDecl *, 8> Ivars;
6915 // strip off all but the first ivar bitfield from each group of ivars.
6916 // Such ivars in the ivar list table will be replaced by their grouping struct
6917 // 'ivar'.
6918 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6919 if (OriginalIvars[i]->isBitField()) {
6920 Ivars.push_back(OriginalIvars[i]);
6921 // skip over rest of the ivar bitfields.
6922 SKIP_BITFIELDS(i , e, OriginalIvars);
6923 }
6924 else
6925 Ivars.push_back(OriginalIvars[i]);
6926 }
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006927
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006928 Result += "\nstatic ";
6929 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6930 Result += " "; Result += VarName;
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006931 Result += CDecl->getNameAsString();
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006932 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6933 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6934 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6935 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6936 ObjCIvarDecl *IvarDecl = Ivars[i];
6937 if (i == 0)
6938 Result += "\t{{";
6939 else
6940 Result += "\t {";
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006941 Result += "(unsigned long int *)&";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006942 if (Ivars[i]->isBitField())
6943 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6944 else
6945 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006946 Result += ", ";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006947
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006948 Result += "\"";
6949 if (Ivars[i]->isBitField())
6950 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6951 else
6952 Result += IvarDecl->getName();
6953 Result += "\", ";
6954
6955 QualType IVQT = IvarDecl->getType();
6956 if (IvarDecl->isBitField())
6957 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6958
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006959 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006960 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006961 IvarDecl);
6962 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6963 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6964
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006965 // FIXME. this alignment represents the host alignment and need be changed to
6966 // represent the target alignment.
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006967 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006968 Align = llvm::Log2_32(Align);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006969 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006970 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00006971 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006972 if (i == e-1)
6973 Result += "}}\n";
6974 else
6975 Result += "},\n";
6976 }
6977 Result += "};\n";
6978 }
6979}
6980
Fariborz Jahanian11671902012-02-07 17:11:38 +00006981/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006982void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6983 std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006984
Fariborz Jahanian11671902012-02-07 17:11:38 +00006985 // Do not synthesize the protocol more than once.
6986 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
6987 return;
Fariborz Jahanian45489622012-03-14 18:09:23 +00006988 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00006989
6990 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
6991 PDecl = Def;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006992 // Must write out all protocol definitions in current qualifier list,
6993 // and in their nested qualifiers before writing out current definition.
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00006994 for (auto *I : PDecl->protocols())
6995 RewriteObjCProtocolMetaData(I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00006996
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006997 // Construct method lists.
6998 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
6999 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007000 for (auto *MD : PDecl->instance_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007001 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7002 OptInstanceMethods.push_back(MD);
7003 } else {
7004 InstanceMethods.push_back(MD);
7005 }
7006 }
7007
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007008 for (auto *MD : PDecl->class_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007009 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7010 OptClassMethods.push_back(MD);
7011 } else {
7012 ClassMethods.push_back(MD);
7013 }
7014 }
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007015 std::vector<ObjCMethodDecl *> AllMethods;
7016 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
7017 AllMethods.push_back(InstanceMethods[i]);
7018 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
7019 AllMethods.push_back(ClassMethods[i]);
7020 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
7021 AllMethods.push_back(OptInstanceMethods[i]);
7022 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
7023 AllMethods.push_back(OptClassMethods[i]);
7024
7025 Write__extendedMethodTypes_initializer(*this, Context, Result,
7026 AllMethods,
7027 "_OBJC_PROTOCOL_METHOD_TYPES_",
7028 PDecl->getNameAsString());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007029 // Protocol's super protocol list
Aaron Ballman0f6e64d2014-03-13 22:58:06 +00007030 SmallVector<ObjCProtocolDecl *, 8> SuperProtocols(PDecl->protocols());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007031 Write_protocol_list_initializer(Context, Result, SuperProtocols,
7032 "_OBJC_PROTOCOL_REFS_",
7033 PDecl->getNameAsString());
7034
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007035 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007036 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007037 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007038
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007039 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007040 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007041 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007042
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007043 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007044 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007045 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007046
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007047 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007048 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007049 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007050
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007051 // Protocol's property metadata.
Aaron Ballmand174edf2014-03-13 19:11:50 +00007052 SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(PDecl->properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007053 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007054 /* Container */0,
7055 "_OBJC_PROTOCOL_PROPERTIES_",
7056 PDecl->getNameAsString());
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007057
Fariborz Jahanian48985802012-02-08 00:50:52 +00007058 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007059 Result += "\n";
7060 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007061 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007062 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007063 Result += PDecl->getNameAsString();
Fariborz Jahanian48985802012-02-08 00:50:52 +00007064 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7065 Result += "\t0,\n"; // id is; is null
7066 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007067 if (SuperProtocols.size() > 0) {
7068 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7069 Result += PDecl->getNameAsString(); Result += ",\n";
7070 }
7071 else
7072 Result += "\t0,\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007073 if (InstanceMethods.size() > 0) {
7074 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7075 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007076 }
7077 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007078 Result += "\t0,\n";
7079
7080 if (ClassMethods.size() > 0) {
7081 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7082 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007083 }
7084 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007085 Result += "\t0,\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007086
Fariborz Jahanian48985802012-02-08 00:50:52 +00007087 if (OptInstanceMethods.size() > 0) {
7088 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7089 Result += PDecl->getNameAsString(); Result += ",\n";
7090 }
7091 else
7092 Result += "\t0,\n";
7093
7094 if (OptClassMethods.size() > 0) {
7095 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7096 Result += PDecl->getNameAsString(); Result += ",\n";
7097 }
7098 else
7099 Result += "\t0,\n";
7100
7101 if (ProtocolProperties.size() > 0) {
7102 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7103 Result += PDecl->getNameAsString(); Result += ",\n";
7104 }
7105 else
7106 Result += "\t0,\n";
7107
7108 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7109 Result += "\t0,\n";
7110
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007111 if (AllMethods.size() > 0) {
7112 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7113 Result += PDecl->getNameAsString();
7114 Result += "\n};\n";
7115 }
7116 else
7117 Result += "\t0\n};\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007118
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007119 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007120 Result += "static ";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007121 Result += "struct _protocol_t *";
7122 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7123 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7124 Result += ";\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007125
Fariborz Jahanian11671902012-02-07 17:11:38 +00007126 // Mark this protocol as having been generated.
7127 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
7128 llvm_unreachable("protocol already synthesized");
7129
7130}
7131
7132void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7133 const ObjCList<ObjCProtocolDecl> &Protocols,
7134 StringRef prefix, StringRef ClassName,
7135 std::string &Result) {
7136 if (Protocols.empty()) return;
7137
7138 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007139 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007140
7141 // Output the top lovel protocol meta-data for the class.
7142 /* struct _objc_protocol_list {
7143 struct _objc_protocol_list *next;
7144 int protocol_count;
7145 struct _objc_protocol *class_protocols[];
7146 }
7147 */
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007148 Result += "\n";
7149 if (LangOpts.MicrosoftExt)
7150 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7151 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007152 Result += "\tstruct _objc_protocol_list *next;\n";
7153 Result += "\tint protocol_count;\n";
7154 Result += "\tstruct _objc_protocol *class_protocols[";
7155 Result += utostr(Protocols.size());
7156 Result += "];\n} _OBJC_";
7157 Result += prefix;
7158 Result += "_PROTOCOLS_";
7159 Result += ClassName;
7160 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7161 "{\n\t0, ";
7162 Result += utostr(Protocols.size());
7163 Result += "\n";
7164
7165 Result += "\t,{&_OBJC_PROTOCOL_";
7166 Result += Protocols[0]->getNameAsString();
7167 Result += " \n";
7168
7169 for (unsigned i = 1; i != Protocols.size(); i++) {
7170 Result += "\t ,&_OBJC_PROTOCOL_";
7171 Result += Protocols[i]->getNameAsString();
7172 Result += "\n";
7173 }
7174 Result += "\t }\n};\n";
7175}
7176
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007177/// hasObjCExceptionAttribute - Return true if this class or any super
7178/// class has the __objc_exception__ attribute.
7179/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7180static bool hasObjCExceptionAttribute(ASTContext &Context,
7181 const ObjCInterfaceDecl *OID) {
7182 if (OID->hasAttr<ObjCExceptionAttr>())
7183 return true;
7184 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7185 return hasObjCExceptionAttribute(Context, Super);
7186 return false;
7187}
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007188
Fariborz Jahanian11671902012-02-07 17:11:38 +00007189void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7190 std::string &Result) {
7191 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7192
7193 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007194 if (CDecl->isImplicitInterfaceDecl())
7195 assert(false &&
7196 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007197
Fariborz Jahanian45489622012-03-14 18:09:23 +00007198 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007199 SmallVector<ObjCIvarDecl *, 8> IVars;
7200
7201 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7202 IVD; IVD = IVD->getNextIvar()) {
7203 // Ignore unnamed bit-fields.
7204 if (!IVD->getDeclName())
7205 continue;
7206 IVars.push_back(IVD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007207 }
7208
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007209 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007210 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007211 CDecl);
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007212
7213 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007214 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007215
7216 // If any of our property implementations have associated getters or
7217 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00007218 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007219 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007220 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007221 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007222 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007223 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007224 if (!PD)
7225 continue;
7226 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007227 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007228 InstanceMethods.push_back(Getter);
7229 if (PD->isReadOnly())
7230 continue;
7231 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007232 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007233 InstanceMethods.push_back(Setter);
7234 }
7235
7236 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7237 "_OBJC_$_INSTANCE_METHODS_",
7238 IDecl->getNameAsString(), true);
7239
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007240 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007241
7242 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7243 "_OBJC_$_CLASS_METHODS_",
7244 IDecl->getNameAsString(), true);
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007245
7246 // Protocols referenced in class declaration?
7247 // Protocol's super protocol list
7248 std::vector<ObjCProtocolDecl *> RefedProtocols;
7249 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7250 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7251 E = Protocols.end();
7252 I != E; ++I) {
7253 RefedProtocols.push_back(*I);
7254 // Must write out all protocol definitions in current qualifier list,
7255 // and in their nested qualifiers before writing out current definition.
7256 RewriteObjCProtocolMetaData(*I, Result);
7257 }
7258
7259 Write_protocol_list_initializer(Context, Result,
7260 RefedProtocols,
7261 "_OBJC_CLASS_PROTOCOLS_$_",
7262 IDecl->getNameAsString());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007263
7264 // Protocol's property metadata.
Aaron Ballmand174edf2014-03-13 19:11:50 +00007265 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007266 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianee1db7a2012-03-22 17:39:35 +00007267 /* Container */IDecl,
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00007268 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007269 CDecl->getNameAsString());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007270
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007271
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007272 // Data for initializing _class_ro_t metaclass meta-data
7273 uint32_t flags = CLS_META;
7274 std::string InstanceSize;
7275 std::string InstanceStart;
7276
7277
7278 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7279 if (classIsHidden)
7280 flags |= OBJC2_CLS_HIDDEN;
7281
7282 if (!CDecl->getSuperClass())
7283 // class is root
7284 flags |= CLS_ROOT;
7285 InstanceSize = "sizeof(struct _class_t)";
7286 InstanceStart = InstanceSize;
7287 Write__class_ro_t_initializer(Context, Result, flags,
7288 InstanceStart, InstanceSize,
7289 ClassMethods,
7290 0,
7291 0,
7292 0,
7293 "_OBJC_METACLASS_RO_$_",
7294 CDecl->getNameAsString());
7295
7296
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007297 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007298 flags = CLS;
7299 if (classIsHidden)
7300 flags |= OBJC2_CLS_HIDDEN;
7301
7302 if (hasObjCExceptionAttribute(*Context, CDecl))
7303 flags |= CLS_EXCEPTION;
7304
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007305 if (!CDecl->getSuperClass())
7306 // class is root
7307 flags |= CLS_ROOT;
7308
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007309 InstanceSize.clear();
7310 InstanceStart.clear();
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007311 if (!ObjCSynthesizedStructs.count(CDecl)) {
7312 InstanceSize = "0";
7313 InstanceStart = "0";
7314 }
7315 else {
7316 InstanceSize = "sizeof(struct ";
7317 InstanceSize += CDecl->getNameAsString();
7318 InstanceSize += "_IMPL)";
7319
7320 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7321 if (IVD) {
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00007322 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007323 }
7324 else
7325 InstanceStart = InstanceSize;
7326 }
7327 Write__class_ro_t_initializer(Context, Result, flags,
7328 InstanceStart, InstanceSize,
7329 InstanceMethods,
7330 RefedProtocols,
7331 IVars,
7332 ClassProperties,
7333 "_OBJC_CLASS_RO_$_",
7334 CDecl->getNameAsString());
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007335
7336 Write_class_t(Context, Result,
7337 "OBJC_METACLASS_$_",
7338 CDecl, /*metaclass*/true);
7339
7340 Write_class_t(Context, Result,
7341 "OBJC_CLASS_$_",
7342 CDecl, /*metaclass*/false);
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007343
7344 if (ImplementationIsNonLazy(IDecl))
7345 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007346
Fariborz Jahanian11671902012-02-07 17:11:38 +00007347}
7348
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007349void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7350 int ClsDefCount = ClassImplementation.size();
7351 if (!ClsDefCount)
7352 return;
7353 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7354 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7355 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7356 for (int i = 0; i < ClsDefCount; i++) {
7357 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7358 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7359 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7360 Result += CDecl->getName(); Result += ",\n";
7361 }
7362 Result += "};\n";
7363}
7364
Fariborz Jahanian11671902012-02-07 17:11:38 +00007365void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7366 int ClsDefCount = ClassImplementation.size();
7367 int CatDefCount = CategoryImplementation.size();
7368
7369 // For each implemented class, write out all its meta data.
7370 for (int i = 0; i < ClsDefCount; i++)
7371 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7372
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007373 RewriteClassSetupInitHook(Result);
7374
Fariborz Jahanian11671902012-02-07 17:11:38 +00007375 // For each implemented category, write out all its meta data.
7376 for (int i = 0; i < CatDefCount; i++)
7377 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7378
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007379 RewriteCategorySetupInitHook(Result);
7380
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007381 if (ClsDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007382 if (LangOpts.MicrosoftExt)
7383 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007384 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7385 Result += llvm::utostr(ClsDefCount); Result += "]";
7386 Result +=
7387 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7388 "regular,no_dead_strip\")))= {\n";
7389 for (int i = 0; i < ClsDefCount; i++) {
7390 Result += "\t&OBJC_CLASS_$_";
7391 Result += ClassImplementation[i]->getNameAsString();
7392 Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007393 }
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007394 Result += "};\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007395
7396 if (!DefinedNonLazyClasses.empty()) {
7397 if (LangOpts.MicrosoftExt)
7398 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7399 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7400 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7401 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7402 Result += ",\n";
7403 }
7404 Result += "};\n";
7405 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007406 }
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007407
7408 if (CatDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007409 if (LangOpts.MicrosoftExt)
7410 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007411 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7412 Result += llvm::utostr(CatDefCount); Result += "]";
7413 Result +=
7414 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7415 "regular,no_dead_strip\")))= {\n";
7416 for (int i = 0; i < CatDefCount; i++) {
7417 Result += "\t&_OBJC_$_CATEGORY_";
7418 Result +=
7419 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7420 Result += "_$_";
7421 Result += CategoryImplementation[i]->getNameAsString();
7422 Result += ",\n";
7423 }
7424 Result += "};\n";
7425 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007426
7427 if (!DefinedNonLazyCategories.empty()) {
7428 if (LangOpts.MicrosoftExt)
7429 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7430 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7431 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7432 Result += "\t&_OBJC_$_CATEGORY_";
7433 Result +=
7434 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7435 Result += "_$_";
7436 Result += DefinedNonLazyCategories[i]->getNameAsString();
7437 Result += ",\n";
7438 }
7439 Result += "};\n";
7440 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007441}
7442
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007443void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7444 if (LangOpts.MicrosoftExt)
7445 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7446
7447 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7448 // version 0, ObjCABI is 2
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007449 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007450}
7451
Fariborz Jahanian11671902012-02-07 17:11:38 +00007452/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7453/// implementation.
7454void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7455 std::string &Result) {
Fariborz Jahanian45489622012-03-14 18:09:23 +00007456 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007457 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7458 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00007459 ObjCCategoryDecl *CDecl
7460 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007461
7462 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007463 FullCategoryName += "_$_";
7464 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007465
7466 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007467 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007468
7469 // If any of our property implementations have associated getters or
7470 // setters, produce metadata for them as well.
Aaron Ballmand85eff42014-03-14 15:02:45 +00007471 for (const auto *Prop : IDecl->property_impls()) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007472 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007473 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007474 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007475 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007476 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007477 if (!PD)
7478 continue;
7479 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7480 InstanceMethods.push_back(Getter);
7481 if (PD->isReadOnly())
7482 continue;
7483 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7484 InstanceMethods.push_back(Setter);
7485 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007486
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007487 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7488 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7489 FullCategoryName, true);
7490
Aaron Ballmane8a7dc92014-03-13 20:11:06 +00007491 SmallVector<ObjCMethodDecl *, 32> ClassMethods(IDecl->class_methods());
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007492
7493 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7494 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7495 FullCategoryName, true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007496
7497 // Protocols referenced in class declaration?
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007498 // Protocol's super protocol list
Aaron Ballman19a41762014-03-14 12:55:57 +00007499 SmallVector<ObjCProtocolDecl *, 8> RefedProtocols(CDecl->protocols());
7500 for (auto *I : CDecl->protocols())
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007501 // Must write out all protocol definitions in current qualifier list,
7502 // and in their nested qualifiers before writing out current definition.
Aaron Ballman19a41762014-03-14 12:55:57 +00007503 RewriteObjCProtocolMetaData(I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007504
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007505 Write_protocol_list_initializer(Context, Result,
7506 RefedProtocols,
7507 "_OBJC_CATEGORY_PROTOCOLS_$_",
7508 FullCategoryName);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007509
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007510 // Protocol's property metadata.
Aaron Ballmand174edf2014-03-13 19:11:50 +00007511 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties());
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007512 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahaniane9863b52012-05-03 23:19:33 +00007513 /* Container */IDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007514 "_OBJC_$_PROP_LIST_",
7515 FullCategoryName);
7516
7517 Write_category_t(*this, Context, Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007518 CDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007519 ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007520 InstanceMethods,
7521 ClassMethods,
7522 RefedProtocols,
7523 ClassProperties);
7524
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007525 // Determine if this category is also "non-lazy".
7526 if (ImplementationIsNonLazy(IDecl))
7527 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007528
7529}
7530
7531void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7532 int CatDefCount = CategoryImplementation.size();
7533 if (!CatDefCount)
7534 return;
7535 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7536 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7537 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7538 for (int i = 0; i < CatDefCount; i++) {
7539 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7540 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7541 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7542 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7543 Result += ClassDecl->getName();
7544 Result += "_$_";
7545 Result += CatDecl->getName();
7546 Result += ",\n";
7547 }
7548 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007549}
7550
7551// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7552/// class methods.
7553template<typename MethodIterator>
7554void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7555 MethodIterator MethodEnd,
7556 bool IsInstanceMethod,
7557 StringRef prefix,
7558 StringRef ClassName,
7559 std::string &Result) {
7560 if (MethodBegin == MethodEnd) return;
7561
7562 if (!objc_impl_method) {
7563 /* struct _objc_method {
7564 SEL _cmd;
7565 char *method_types;
7566 void *_imp;
7567 }
7568 */
7569 Result += "\nstruct _objc_method {\n";
7570 Result += "\tSEL _cmd;\n";
7571 Result += "\tchar *method_types;\n";
7572 Result += "\tvoid *_imp;\n";
7573 Result += "};\n";
7574
7575 objc_impl_method = true;
7576 }
7577
7578 // Build _objc_method_list for class's methods if needed
7579
7580 /* struct {
7581 struct _objc_method_list *next_method;
7582 int method_count;
7583 struct _objc_method method_list[];
7584 }
7585 */
7586 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007587 Result += "\n";
7588 if (LangOpts.MicrosoftExt) {
7589 if (IsInstanceMethod)
7590 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7591 else
7592 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7593 }
7594 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007595 Result += "\tstruct _objc_method_list *next_method;\n";
7596 Result += "\tint method_count;\n";
7597 Result += "\tstruct _objc_method method_list[";
7598 Result += utostr(NumMethods);
7599 Result += "];\n} _OBJC_";
7600 Result += prefix;
7601 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7602 Result += "_METHODS_";
7603 Result += ClassName;
7604 Result += " __attribute__ ((used, section (\"__OBJC, __";
7605 Result += IsInstanceMethod ? "inst" : "cls";
7606 Result += "_meth\")))= ";
7607 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7608
7609 Result += "\t,{{(SEL)\"";
7610 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7611 std::string MethodTypeString;
7612 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7613 Result += "\", \"";
7614 Result += MethodTypeString;
7615 Result += "\", (void *)";
7616 Result += MethodInternalNames[*MethodBegin];
7617 Result += "}\n";
7618 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7619 Result += "\t ,{(SEL)\"";
7620 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7621 std::string MethodTypeString;
7622 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7623 Result += "\", \"";
7624 Result += MethodTypeString;
7625 Result += "\", (void *)";
7626 Result += MethodInternalNames[*MethodBegin];
7627 Result += "}\n";
7628 }
7629 Result += "\t }\n};\n";
7630}
7631
7632Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7633 SourceRange OldRange = IV->getSourceRange();
7634 Expr *BaseExpr = IV->getBase();
7635
7636 // Rewrite the base, but without actually doing replaces.
7637 {
7638 DisableReplaceStmtScope S(*this);
7639 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7640 IV->setBase(BaseExpr);
7641 }
7642
7643 ObjCIvarDecl *D = IV->getDecl();
7644
7645 Expr *Replacement = IV;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007646
Fariborz Jahanian11671902012-02-07 17:11:38 +00007647 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7648 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00007649 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007650 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7651 // lookup which class implements the instance variable.
7652 ObjCInterfaceDecl *clsDeclared = 0;
7653 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7654 clsDeclared);
7655 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7656
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007657 // Build name of symbol holding ivar offset.
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007658 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007659 if (D->isBitField())
7660 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7661 else
7662 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007663
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00007664 ReferencedIvars[clsDeclared].insert(D);
7665
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007666 // cast offset to "char *".
7667 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7668 Context->getPointerType(Context->CharTy),
Fariborz Jahanian11671902012-02-07 17:11:38 +00007669 CK_BitCast,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007670 BaseExpr);
7671 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7672 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007673 Context->UnsignedLongTy, 0, SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00007674 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7675 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007676 SourceLocation());
7677 BinaryOperator *addExpr =
7678 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7679 Context->getPointerType(Context->CharTy),
Lang Hames5de91cc2012-10-02 04:45:10 +00007680 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007681 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007682 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7683 SourceLocation(),
7684 addExpr);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007685 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007686 if (D->isBitField())
7687 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007688
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007689 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007690 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00007691 RD = RD->getDefinition();
7692 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007693 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007694 ObjCContainerDecl *CDecl =
7695 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7696 // ivar in class extensions requires special treatment.
7697 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7698 CDecl = CatDecl->getClassInterface();
7699 std::string RecName = CDecl->getName();
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007700 RecName += "_IMPL";
7701 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7702 SourceLocation(), SourceLocation(),
7703 &Context->Idents.get(RecName.c_str()));
7704 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7705 unsigned UnsignedIntSize =
7706 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7707 Expr *Zero = IntegerLiteral::Create(*Context,
7708 llvm::APInt(UnsignedIntSize, 0),
7709 Context->UnsignedIntTy, SourceLocation());
7710 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7711 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7712 Zero);
7713 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7714 SourceLocation(),
7715 &Context->Idents.get(D->getNameAsString()),
7716 IvarT, 0,
7717 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00007718 ICIS_NoInit);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007719 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7720 FD->getType(), VK_LValue,
7721 OK_Ordinary);
7722 IvarT = Context->getDecltypeType(ME, ME->getType());
7723 }
7724 }
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007725 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007726 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007727
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007728 castExpr = NoTypeInfoCStyleCastExpr(Context,
7729 castT,
7730 CK_BitCast,
7731 PE);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007732
7733
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007734 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007735 VK_LValue, OK_Ordinary,
7736 SourceLocation());
7737 PE = new (Context) ParenExpr(OldRange.getBegin(),
7738 OldRange.getEnd(),
7739 Exp);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007740
7741 if (D->isBitField()) {
7742 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7743 SourceLocation(),
7744 &Context->Idents.get(D->getNameAsString()),
7745 D->getType(), 0,
7746 /*BitWidth=*/D->getBitWidth(),
7747 /*Mutable=*/true,
7748 ICIS_NoInit);
7749 MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(),
7750 FD->getType(), VK_LValue,
7751 OK_Ordinary);
7752 Replacement = ME;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007753
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007754 }
7755 else
7756 Replacement = PE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007757 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007758
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007759 ReplaceStmtWithRange(IV, Replacement, OldRange);
7760 return Replacement;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007761}