blob: 126e563ae6ae763864503f82b2f4c9efddf7ab59 [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.
188 virtual bool HandleTopLevelDecl(DeclGroupRef D) {
189 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 }
Fariborz Jahaniand2940622013-10-07 19:54:22 +0000224
225 virtual void HandleTopLevelDeclInObjCContainer(DeclGroupRef D) {
226 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() {}
246
247 virtual void HandleTranslationUnit(ASTContext &C);
248
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);
417
Fariborz Jahanian11671902012-02-07 17:11:38 +0000418 virtual void Initialize(ASTContext &context);
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);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001168 for (ObjCCategoryDecl::classmeth_iterator
1169 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1170 I != E; ++I)
1171 RewriteMethodDeclaration(*I);
1172
1173 // Lastly, comment out the @end.
1174 ReplaceText(CatDecl->getAtEndRange().getBegin(),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001175 strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001176}
1177
1178void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1179 SourceLocation LocStart = PDecl->getLocStart();
1180 assert(PDecl->isThisDeclarationADefinition());
1181
1182 // FIXME: handle protocol headers that are declared across multiple lines.
1183 ReplaceText(LocStart, 0, "// ");
1184
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001185 for (auto *I : PDecl->instance_methods())
1186 RewriteMethodDeclaration(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001187 for (ObjCProtocolDecl::classmeth_iterator
1188 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1189 I != E; ++I)
1190 RewriteMethodDeclaration(*I);
1191
Aaron Ballmand174edf2014-03-13 19:11:50 +00001192 for (auto *I : PDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001193 RewriteProperty(I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001194
1195 // Lastly, comment out the @end.
1196 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001197 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001198
1199 // Must comment out @optional/@required
1200 const char *startBuf = SM->getCharacterData(LocStart);
1201 const char *endBuf = SM->getCharacterData(LocEnd);
1202 for (const char *p = startBuf; p < endBuf; p++) {
1203 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1204 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1205 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1206
1207 }
1208 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1209 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1210 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1211
1212 }
1213 }
1214}
1215
1216void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1217 SourceLocation LocStart = (*D.begin())->getLocStart();
1218 if (LocStart.isInvalid())
1219 llvm_unreachable("Invalid SourceLocation");
1220 // FIXME: handle forward protocol that are declared across multiple lines.
1221 ReplaceText(LocStart, 0, "// ");
1222}
1223
1224void
Craig Topper5603df42013-07-05 19:34:19 +00001225RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001226 SourceLocation LocStart = DG[0]->getLocStart();
1227 if (LocStart.isInvalid())
1228 llvm_unreachable("Invalid SourceLocation");
1229 // FIXME: handle forward protocol that are declared across multiple lines.
1230 ReplaceText(LocStart, 0, "// ");
1231}
1232
Fariborz Jahanian08ed8922012-04-03 17:35:38 +00001233void
1234RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1235 SourceLocation LocStart = LSD->getExternLoc();
1236 if (LocStart.isInvalid())
1237 llvm_unreachable("Invalid extern SourceLocation");
1238
1239 ReplaceText(LocStart, 0, "// ");
1240 if (!LSD->hasBraces())
1241 return;
1242 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1243 SourceLocation LocRBrace = LSD->getRBraceLoc();
1244 if (LocRBrace.isInvalid())
1245 llvm_unreachable("Invalid rbrace SourceLocation");
1246 ReplaceText(LocRBrace, 0, "// ");
1247}
1248
Fariborz Jahanian11671902012-02-07 17:11:38 +00001249void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1250 const FunctionType *&FPRetType) {
1251 if (T->isObjCQualifiedIdType())
1252 ResultStr += "id";
1253 else if (T->isFunctionPointerType() ||
1254 T->isBlockPointerType()) {
1255 // needs special handling, since pointer-to-functions have special
1256 // syntax (where a decaration models use).
1257 QualType retType = T;
1258 QualType PointeeTy;
1259 if (const PointerType* PT = retType->getAs<PointerType>())
1260 PointeeTy = PT->getPointeeType();
1261 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1262 PointeeTy = BPT->getPointeeType();
1263 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Alp Toker314cc812014-01-25 16:55:45 +00001264 ResultStr +=
1265 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001266 ResultStr += "(*";
1267 }
1268 } else
1269 ResultStr += T.getAsString(Context->getPrintingPolicy());
1270}
1271
1272void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1273 ObjCMethodDecl *OMD,
1274 std::string &ResultStr) {
1275 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1276 const FunctionType *FPRetType = 0;
1277 ResultStr += "\nstatic ";
Alp Toker314cc812014-01-25 16:55:45 +00001278 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001279 ResultStr += " ";
1280
1281 // Unique method name
1282 std::string NameStr;
1283
1284 if (OMD->isInstanceMethod())
1285 NameStr += "_I_";
1286 else
1287 NameStr += "_C_";
1288
1289 NameStr += IDecl->getNameAsString();
1290 NameStr += "_";
1291
1292 if (ObjCCategoryImplDecl *CID =
1293 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1294 NameStr += CID->getNameAsString();
1295 NameStr += "_";
1296 }
1297 // Append selector names, replacing ':' with '_'
1298 {
1299 std::string selString = OMD->getSelector().getAsString();
1300 int len = selString.size();
1301 for (int i = 0; i < len; i++)
1302 if (selString[i] == ':')
1303 selString[i] = '_';
1304 NameStr += selString;
1305 }
1306 // Remember this name for metadata emission
1307 MethodInternalNames[OMD] = NameStr;
1308 ResultStr += NameStr;
1309
1310 // Rewrite arguments
1311 ResultStr += "(";
1312
1313 // invisible arguments
1314 if (OMD->isInstanceMethod()) {
1315 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1316 selfTy = Context->getPointerType(selfTy);
1317 if (!LangOpts.MicrosoftExt) {
1318 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1319 ResultStr += "struct ";
1320 }
1321 // When rewriting for Microsoft, explicitly omit the structure name.
1322 ResultStr += IDecl->getNameAsString();
1323 ResultStr += " *";
1324 }
1325 else
1326 ResultStr += Context->getObjCClassType().getAsString(
1327 Context->getPrintingPolicy());
1328
1329 ResultStr += " self, ";
1330 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1331 ResultStr += " _cmd";
1332
1333 // Method arguments.
Aaron Ballman43b68be2014-03-07 17:50:17 +00001334 for (const auto *PDecl : OMD->params()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001335 ResultStr += ", ";
1336 if (PDecl->getType()->isObjCQualifiedIdType()) {
1337 ResultStr += "id ";
1338 ResultStr += PDecl->getNameAsString();
1339 } else {
1340 std::string Name = PDecl->getNameAsString();
1341 QualType QT = PDecl->getType();
1342 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001343 (void)convertBlockPointerToFunctionPointer(QT);
1344 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001345 ResultStr += Name;
1346 }
1347 }
1348 if (OMD->isVariadic())
1349 ResultStr += ", ...";
1350 ResultStr += ") ";
1351
1352 if (FPRetType) {
1353 ResultStr += ")"; // close the precedence "scope" for "*".
1354
1355 // Now, emit the argument types (if any).
1356 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1357 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001358 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001359 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001360 std::string ParamStr =
1361 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001362 ResultStr += ParamStr;
1363 }
1364 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001365 if (FT->getNumParams())
1366 ResultStr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001367 ResultStr += "...";
1368 }
1369 ResultStr += ")";
1370 } else {
1371 ResultStr += "()";
1372 }
1373 }
1374}
1375void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1376 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1377 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1378
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001379 if (IMD) {
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001380 if (IMD->getIvarRBraceLoc().isValid()) {
1381 ReplaceText(IMD->getLocStart(), 1, "/** ");
1382 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001383 }
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001384 else {
1385 InsertText(IMD->getLocStart(), "// ");
1386 }
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001387 }
1388 else
1389 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001390
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001391 for (auto *OMD : IMD ? IMD->instance_methods() : CID->instance_methods()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001392 std::string ResultStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001393 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1394 SourceLocation LocStart = OMD->getLocStart();
1395 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1396
1397 const char *startBuf = SM->getCharacterData(LocStart);
1398 const char *endBuf = SM->getCharacterData(LocEnd);
1399 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1400 }
1401
1402 for (ObjCCategoryImplDecl::classmeth_iterator
1403 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1404 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1405 I != E; ++I) {
1406 std::string ResultStr;
1407 ObjCMethodDecl *OMD = *I;
1408 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1409 SourceLocation LocStart = OMD->getLocStart();
1410 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1411
1412 const char *startBuf = SM->getCharacterData(LocStart);
1413 const char *endBuf = SM->getCharacterData(LocEnd);
1414 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1415 }
1416 for (ObjCCategoryImplDecl::propimpl_iterator
1417 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1418 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1419 I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001420 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001421 }
1422
1423 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1424}
1425
1426void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian088959a2012-02-11 20:10:52 +00001427 // Do not synthesize more than once.
1428 if (ObjCSynthesizedStructs.count(ClassDecl))
1429 return;
1430 // Make sure super class's are written before current class is written.
1431 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1432 while (SuperClass) {
1433 RewriteInterfaceDecl(SuperClass);
1434 SuperClass = SuperClass->getSuperClass();
1435 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001436 std::string ResultStr;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001437 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001438 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001439 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00001440 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1441
Fariborz Jahanianff513382012-02-15 22:01:47 +00001442 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001443 // Mark this typedef as having been written into its c++ equivalent.
1444 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanianff513382012-02-15 22:01:47 +00001445
Aaron Ballmand174edf2014-03-13 19:11:50 +00001446 for (auto *I : ClassDecl->properties())
Aaron Ballmandc4bea42014-03-13 18:47:37 +00001447 RewriteProperty(I);
Aaron Ballmanf26acce2014-03-13 19:50:17 +00001448 for (auto *I : ClassDecl->instance_methods())
1449 RewriteMethodDeclaration(I);
Fariborz Jahanianff513382012-02-15 22:01:47 +00001450 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian11671902012-02-07 17:11:38 +00001451 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanianff513382012-02-15 22:01:47 +00001452 I != E; ++I)
1453 RewriteMethodDeclaration(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001454
Fariborz Jahanianff513382012-02-15 22:01:47 +00001455 // Lastly, comment out the @end.
1456 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001457 "/* @end */\n");
Fariborz Jahanianff513382012-02-15 22:01:47 +00001458 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001459}
1460
1461Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1462 SourceRange OldRange = PseudoOp->getSourceRange();
1463
1464 // We just magically know some things about the structure of this
1465 // expression.
1466 ObjCMessageExpr *OldMsg =
1467 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1468 PseudoOp->getNumSemanticExprs() - 1));
1469
1470 // Because the rewriter doesn't allow us to rewrite rewritten code,
1471 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001472 Expr *Base;
1473 SmallVector<Expr*, 2> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001474 {
1475 DisableReplaceStmtScope S(*this);
1476
1477 // Rebuild the base expression if we have one.
1478 Base = 0;
1479 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1480 Base = OldMsg->getInstanceReceiver();
1481 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1482 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1483 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001484
1485 unsigned numArgs = OldMsg->getNumArgs();
1486 for (unsigned i = 0; i < numArgs; i++) {
1487 Expr *Arg = OldMsg->getArg(i);
1488 if (isa<OpaqueValueExpr>(Arg))
1489 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1490 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1491 Args.push_back(Arg);
1492 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001493 }
1494
1495 // TODO: avoid this copy.
1496 SmallVector<SourceLocation, 1> SelLocs;
1497 OldMsg->getSelectorLocs(SelLocs);
1498
1499 ObjCMessageExpr *NewMsg = 0;
1500 switch (OldMsg->getReceiverKind()) {
1501 case ObjCMessageExpr::Class:
1502 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1503 OldMsg->getValueKind(),
1504 OldMsg->getLeftLoc(),
1505 OldMsg->getClassReceiverTypeInfo(),
1506 OldMsg->getSelector(),
1507 SelLocs,
1508 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001509 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001510 OldMsg->getRightLoc(),
1511 OldMsg->isImplicit());
1512 break;
1513
1514 case ObjCMessageExpr::Instance:
1515 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1516 OldMsg->getValueKind(),
1517 OldMsg->getLeftLoc(),
1518 Base,
1519 OldMsg->getSelector(),
1520 SelLocs,
1521 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001522 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001523 OldMsg->getRightLoc(),
1524 OldMsg->isImplicit());
1525 break;
1526
1527 case ObjCMessageExpr::SuperClass:
1528 case ObjCMessageExpr::SuperInstance:
1529 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1530 OldMsg->getValueKind(),
1531 OldMsg->getLeftLoc(),
1532 OldMsg->getSuperLoc(),
1533 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1534 OldMsg->getSuperType(),
1535 OldMsg->getSelector(),
1536 SelLocs,
1537 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001538 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001539 OldMsg->getRightLoc(),
1540 OldMsg->isImplicit());
1541 break;
1542 }
1543
1544 Stmt *Replacement = SynthMessageExpr(NewMsg);
1545 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1546 return Replacement;
1547}
1548
1549Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1550 SourceRange OldRange = PseudoOp->getSourceRange();
1551
1552 // We just magically know some things about the structure of this
1553 // expression.
1554 ObjCMessageExpr *OldMsg =
1555 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1556
1557 // Because the rewriter doesn't allow us to rewrite rewritten code,
1558 // we need to suppress rewriting the sub-statements.
1559 Expr *Base = 0;
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001560 SmallVector<Expr*, 1> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001561 {
1562 DisableReplaceStmtScope S(*this);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001563 // Rebuild the base expression if we have one.
1564 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1565 Base = OldMsg->getInstanceReceiver();
1566 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1567 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1568 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001569 unsigned numArgs = OldMsg->getNumArgs();
1570 for (unsigned i = 0; i < numArgs; i++) {
1571 Expr *Arg = OldMsg->getArg(i);
1572 if (isa<OpaqueValueExpr>(Arg))
1573 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1574 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1575 Args.push_back(Arg);
1576 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001577 }
1578
1579 // Intentionally empty.
1580 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001581
1582 ObjCMessageExpr *NewMsg = 0;
1583 switch (OldMsg->getReceiverKind()) {
1584 case ObjCMessageExpr::Class:
1585 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1586 OldMsg->getValueKind(),
1587 OldMsg->getLeftLoc(),
1588 OldMsg->getClassReceiverTypeInfo(),
1589 OldMsg->getSelector(),
1590 SelLocs,
1591 OldMsg->getMethodDecl(),
1592 Args,
1593 OldMsg->getRightLoc(),
1594 OldMsg->isImplicit());
1595 break;
1596
1597 case ObjCMessageExpr::Instance:
1598 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1599 OldMsg->getValueKind(),
1600 OldMsg->getLeftLoc(),
1601 Base,
1602 OldMsg->getSelector(),
1603 SelLocs,
1604 OldMsg->getMethodDecl(),
1605 Args,
1606 OldMsg->getRightLoc(),
1607 OldMsg->isImplicit());
1608 break;
1609
1610 case ObjCMessageExpr::SuperClass:
1611 case ObjCMessageExpr::SuperInstance:
1612 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1613 OldMsg->getValueKind(),
1614 OldMsg->getLeftLoc(),
1615 OldMsg->getSuperLoc(),
1616 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1617 OldMsg->getSuperType(),
1618 OldMsg->getSelector(),
1619 SelLocs,
1620 OldMsg->getMethodDecl(),
1621 Args,
1622 OldMsg->getRightLoc(),
1623 OldMsg->isImplicit());
1624 break;
1625 }
1626
1627 Stmt *Replacement = SynthMessageExpr(NewMsg);
1628 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1629 return Replacement;
1630}
1631
1632/// SynthCountByEnumWithState - To print:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001633/// ((NSUInteger (*)
1634/// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001635/// (void *)objc_msgSend)((id)l_collection,
1636/// sel_registerName(
1637/// "countByEnumeratingWithState:objects:count:"),
1638/// &enumState,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001639/// (id *)__rw_items, (NSUInteger)16)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001640///
1641void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001642 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1643 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001644 buf += "\n\t\t";
1645 buf += "((id)l_collection,\n\t\t";
1646 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1647 buf += "\n\t\t";
1648 buf += "&enumState, "
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001649 "(id *)__rw_items, (_WIN_NSUInteger)16)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001650}
1651
1652/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1653/// statement to exit to its outer synthesized loop.
1654///
1655Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1656 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1657 return S;
1658 // replace break with goto __break_label
1659 std::string buf;
1660
1661 SourceLocation startLoc = S->getLocStart();
1662 buf = "goto __break_label_";
1663 buf += utostr(ObjCBcLabelNo.back());
1664 ReplaceText(startLoc, strlen("break"), buf);
1665
1666 return 0;
1667}
1668
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001669void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1670 SourceLocation Loc,
1671 std::string &LineString) {
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00001672 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001673 LineString += "\n#line ";
1674 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1675 LineString += utostr(PLoc.getLine());
1676 LineString += " \"";
1677 LineString += Lexer::Stringify(PLoc.getFilename());
1678 LineString += "\"\n";
1679 }
1680}
1681
Fariborz Jahanian11671902012-02-07 17:11:38 +00001682/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1683/// statement to continue with its inner synthesized loop.
1684///
1685Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1686 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1687 return S;
1688 // replace continue with goto __continue_label
1689 std::string buf;
1690
1691 SourceLocation startLoc = S->getLocStart();
1692 buf = "goto __continue_label_";
1693 buf += utostr(ObjCBcLabelNo.back());
1694 ReplaceText(startLoc, strlen("continue"), buf);
1695
1696 return 0;
1697}
1698
1699/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1700/// It rewrites:
1701/// for ( type elem in collection) { stmts; }
1702
1703/// Into:
1704/// {
1705/// type elem;
1706/// struct __objcFastEnumerationState enumState = { 0 };
1707/// id __rw_items[16];
1708/// id l_collection = (id)collection;
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001709/// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian11671902012-02-07 17:11:38 +00001710/// objects:__rw_items count:16];
1711/// if (limit) {
1712/// unsigned long startMutations = *enumState.mutationsPtr;
1713/// do {
1714/// unsigned long counter = 0;
1715/// do {
1716/// if (startMutations != *enumState.mutationsPtr)
1717/// objc_enumerationMutation(l_collection);
1718/// elem = (type)enumState.itemsPtr[counter++];
1719/// stmts;
1720/// __continue_label: ;
1721/// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001722/// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1723/// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001724/// elem = nil;
1725/// __break_label: ;
1726/// }
1727/// else
1728/// elem = nil;
1729/// }
1730///
1731Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1732 SourceLocation OrigEnd) {
1733 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1734 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1735 "ObjCForCollectionStmt Statement stack mismatch");
1736 assert(!ObjCBcLabelNo.empty() &&
1737 "ObjCForCollectionStmt - Label No stack empty");
1738
1739 SourceLocation startLoc = S->getLocStart();
1740 const char *startBuf = SM->getCharacterData(startLoc);
1741 StringRef elementName;
1742 std::string elementTypeAsString;
1743 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001744 // line directive first.
1745 SourceLocation ForEachLoc = S->getForLoc();
1746 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1747 buf += "{\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001748 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1749 // type elem;
1750 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1751 QualType ElementType = cast<ValueDecl>(D)->getType();
1752 if (ElementType->isObjCQualifiedIdType() ||
1753 ElementType->isObjCQualifiedInterfaceType())
1754 // Simply use 'id' for all qualified types.
1755 elementTypeAsString = "id";
1756 else
1757 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1758 buf += elementTypeAsString;
1759 buf += " ";
1760 elementName = D->getName();
1761 buf += elementName;
1762 buf += ";\n\t";
1763 }
1764 else {
1765 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1766 elementName = DR->getDecl()->getName();
1767 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1768 if (VD->getType()->isObjCQualifiedIdType() ||
1769 VD->getType()->isObjCQualifiedInterfaceType())
1770 // Simply use 'id' for all qualified types.
1771 elementTypeAsString = "id";
1772 else
1773 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1774 }
1775
1776 // struct __objcFastEnumerationState enumState = { 0 };
1777 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1778 // id __rw_items[16];
1779 buf += "id __rw_items[16];\n\t";
1780 // id l_collection = (id)
1781 buf += "id l_collection = (id)";
1782 // Find start location of 'collection' the hard way!
1783 const char *startCollectionBuf = startBuf;
1784 startCollectionBuf += 3; // skip 'for'
1785 startCollectionBuf = strchr(startCollectionBuf, '(');
1786 startCollectionBuf++; // skip '('
1787 // find 'in' and skip it.
1788 while (*startCollectionBuf != ' ' ||
1789 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1790 (*(startCollectionBuf+3) != ' ' &&
1791 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1792 startCollectionBuf++;
1793 startCollectionBuf += 3;
1794
1795 // Replace: "for (type element in" with string constructed thus far.
1796 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1797 // Replace ')' in for '(' type elem in collection ')' with ';'
1798 SourceLocation rightParenLoc = S->getRParenLoc();
1799 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1800 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1801 buf = ";\n\t";
1802
1803 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1804 // objects:__rw_items count:16];
1805 // which is synthesized into:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001806 // NSUInteger limit =
1807 // ((NSUInteger (*)
1808 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001809 // (void *)objc_msgSend)((id)l_collection,
1810 // sel_registerName(
1811 // "countByEnumeratingWithState:objects:count:"),
1812 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001813 // (id *)__rw_items, (NSUInteger)16);
1814 buf += "_WIN_NSUInteger limit =\n\t\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001815 SynthCountByEnumWithState(buf);
1816 buf += ";\n\t";
1817 /// if (limit) {
1818 /// unsigned long startMutations = *enumState.mutationsPtr;
1819 /// do {
1820 /// unsigned long counter = 0;
1821 /// do {
1822 /// if (startMutations != *enumState.mutationsPtr)
1823 /// objc_enumerationMutation(l_collection);
1824 /// elem = (type)enumState.itemsPtr[counter++];
1825 buf += "if (limit) {\n\t";
1826 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1827 buf += "do {\n\t\t";
1828 buf += "unsigned long counter = 0;\n\t\t";
1829 buf += "do {\n\t\t\t";
1830 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1831 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1832 buf += elementName;
1833 buf += " = (";
1834 buf += elementTypeAsString;
1835 buf += ")enumState.itemsPtr[counter++];";
1836 // Replace ')' in for '(' type elem in collection ')' with all of these.
1837 ReplaceText(lparenLoc, 1, buf);
1838
1839 /// __continue_label: ;
1840 /// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001841 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1842 /// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001843 /// elem = nil;
1844 /// __break_label: ;
1845 /// }
1846 /// else
1847 /// elem = nil;
1848 /// }
1849 ///
1850 buf = ";\n\t";
1851 buf += "__continue_label_";
1852 buf += utostr(ObjCBcLabelNo.back());
1853 buf += ": ;";
1854 buf += "\n\t\t";
1855 buf += "} while (counter < limit);\n\t";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001856 buf += "} while ((limit = ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001857 SynthCountByEnumWithState(buf);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001858 buf += "));\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001859 buf += elementName;
1860 buf += " = ((";
1861 buf += elementTypeAsString;
1862 buf += ")0);\n\t";
1863 buf += "__break_label_";
1864 buf += utostr(ObjCBcLabelNo.back());
1865 buf += ": ;\n\t";
1866 buf += "}\n\t";
1867 buf += "else\n\t\t";
1868 buf += elementName;
1869 buf += " = ((";
1870 buf += elementTypeAsString;
1871 buf += ")0);\n\t";
1872 buf += "}\n";
1873
1874 // Insert all these *after* the statement body.
1875 // FIXME: If this should support Obj-C++, support CXXTryStmt
1876 if (isa<CompoundStmt>(S->getBody())) {
1877 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1878 InsertText(endBodyLoc, buf);
1879 } else {
1880 /* Need to treat single statements specially. For example:
1881 *
1882 * for (A *a in b) if (stuff()) break;
1883 * for (A *a in b) xxxyy;
1884 *
1885 * The following code simply scans ahead to the semi to find the actual end.
1886 */
1887 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1888 const char *semiBuf = strchr(stmtBuf, ';');
1889 assert(semiBuf && "Can't find ';'");
1890 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1891 InsertText(endBodyLoc, buf);
1892 }
1893 Stmts.pop_back();
1894 ObjCBcLabelNo.pop_back();
1895 return 0;
1896}
1897
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001898static void Write_RethrowObject(std::string &buf) {
1899 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1900 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1901 buf += "\tid rethrow;\n";
1902 buf += "\t} _fin_force_rethow(_rethrow);";
1903}
1904
Fariborz Jahanian11671902012-02-07 17:11:38 +00001905/// RewriteObjCSynchronizedStmt -
1906/// This routine rewrites @synchronized(expr) stmt;
1907/// into:
1908/// objc_sync_enter(expr);
1909/// @try stmt @finally { objc_sync_exit(expr); }
1910///
1911Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1912 // Get the start location and compute the semi location.
1913 SourceLocation startLoc = S->getLocStart();
1914 const char *startBuf = SM->getCharacterData(startLoc);
1915
1916 assert((*startBuf == '@') && "bogus @synchronized location");
1917
1918 std::string buf;
Fariborz Jahaniane030a632012-11-07 00:43:05 +00001919 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1920 ConvertSourceLocationToLineDirective(SynchLoc, buf);
Fariborz Jahanianff0c4602013-09-17 17:51:48 +00001921 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001922
Fariborz Jahanian11671902012-02-07 17:11:38 +00001923 const char *lparenBuf = startBuf;
1924 while (*lparenBuf != '(') lparenBuf++;
1925 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001926
1927 buf = "; objc_sync_enter(_sync_obj);\n";
1928 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1929 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1930 buf += "\n\tid sync_exit;";
1931 buf += "\n\t} _sync_exit(_sync_obj);\n";
1932
1933 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1934 // the sync expression is typically a message expression that's already
1935 // been rewritten! (which implies the SourceLocation's are invalid).
1936 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1937 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1938 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1939 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1940
1941 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1942 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1943 assert (*LBraceLocBuf == '{');
1944 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001945
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001946 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay6e177d32012-03-16 22:20:39 +00001947 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1948 "bogus @synchronized block");
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001949
1950 buf = "} catch (id e) {_rethrow = e;}\n";
1951 Write_RethrowObject(buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001952 buf += "}\n";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001953 buf += "}\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001954
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001955 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001956
Fariborz Jahanian11671902012-02-07 17:11:38 +00001957 return 0;
1958}
1959
1960void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1961{
1962 // Perform a bottom up traversal of all children.
1963 for (Stmt::child_range CI = S->children(); CI; ++CI)
1964 if (*CI)
1965 WarnAboutReturnGotoStmts(*CI);
1966
1967 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1968 Diags.Report(Context->getFullLoc(S->getLocStart()),
1969 TryFinallyContainsReturnDiag);
1970 }
1971 return;
1972}
1973
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001974Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1975 SourceLocation startLoc = S->getAtLoc();
1976 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc37a1d62012-05-24 22:59:56 +00001977 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1978 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001979
1980 return 0;
1981}
1982
Fariborz Jahanian11671902012-02-07 17:11:38 +00001983Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001984 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001985 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001986 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001987 SourceLocation TryLocation = S->getAtTryLoc();
1988 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001989
1990 if (finalStmt) {
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001991 if (noCatch)
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001992 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001993 else {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001994 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001995 }
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001996 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001997 // Get the start location and compute the semi location.
1998 SourceLocation startLoc = S->getLocStart();
1999 const char *startBuf = SM->getCharacterData(startLoc);
2000
2001 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00002002 if (finalStmt)
2003 ReplaceText(startLoc, 1, buf);
2004 else
2005 // @try -> try
2006 ReplaceText(startLoc, 1, "");
2007
Fariborz Jahanian11671902012-02-07 17:11:38 +00002008 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
2009 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002010 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00002011
Fariborz Jahanian11671902012-02-07 17:11:38 +00002012 startLoc = Catch->getLocStart();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002013 bool AtRemoved = false;
2014 if (catchDecl) {
2015 QualType t = catchDecl->getType();
2016 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
2017 // Should be a pointer to a class.
2018 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2019 if (IDecl) {
2020 std::string Result;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002021 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
2022
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002023 startBuf = SM->getCharacterData(startLoc);
2024 assert((*startBuf == '@') && "bogus @catch location");
2025 SourceLocation rParenLoc = Catch->getRParenLoc();
2026 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2027
2028 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002029 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002030 Result += " *_"; Result += catchDecl->getNameAsString();
2031 Result += ")";
2032 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2033 // Foo *e = (Foo *)_e;
2034 Result.clear();
2035 Result = "{ ";
2036 Result += IDecl->getNameAsString();
2037 Result += " *"; Result += catchDecl->getNameAsString();
2038 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2039 Result += "_"; Result += catchDecl->getNameAsString();
2040
2041 Result += "; ";
2042 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2043 ReplaceText(lBraceLoc, 1, Result);
2044 AtRemoved = true;
2045 }
2046 }
2047 }
2048 if (!AtRemoved)
2049 // @catch -> catch
2050 ReplaceText(startLoc, 1, "");
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00002051
Fariborz Jahanian11671902012-02-07 17:11:38 +00002052 }
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002053 if (finalStmt) {
2054 buf.clear();
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002055 SourceLocation FinallyLoc = finalStmt->getLocStart();
2056
2057 if (noCatch) {
2058 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2059 buf += "catch (id e) {_rethrow = e;}\n";
2060 }
2061 else {
2062 buf += "}\n";
2063 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2064 buf += "catch (id e) {_rethrow = e;}\n";
2065 }
2066
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002067 SourceLocation startFinalLoc = finalStmt->getLocStart();
2068 ReplaceText(startFinalLoc, 8, buf);
2069 Stmt *body = finalStmt->getFinallyBody();
2070 SourceLocation startFinalBodyLoc = body->getLocStart();
2071 buf.clear();
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00002072 Write_RethrowObject(buf);
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002073 ReplaceText(startFinalBodyLoc, 1, buf);
2074
2075 SourceLocation endFinalBodyLoc = body->getLocEnd();
2076 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahaniane8810762012-03-17 17:46:02 +00002077 // Now check for any return/continue/go statements within the @try.
2078 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002079 }
2080
Fariborz Jahanian11671902012-02-07 17:11:38 +00002081 return 0;
2082}
2083
2084// This can't be done with ReplaceStmt(S, ThrowExpr), since
2085// the throw expression is typically a message expression that's already
2086// been rewritten! (which implies the SourceLocation's are invalid).
2087Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2088 // Get the start location and compute the semi location.
2089 SourceLocation startLoc = S->getLocStart();
2090 const char *startBuf = SM->getCharacterData(startLoc);
2091
2092 assert((*startBuf == '@') && "bogus @throw location");
2093
2094 std::string buf;
2095 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2096 if (S->getThrowExpr())
2097 buf = "objc_exception_throw(";
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002098 else
2099 buf = "throw";
Fariborz Jahanian11671902012-02-07 17:11:38 +00002100
2101 // handle "@ throw" correctly.
2102 const char *wBuf = strchr(startBuf, 'w');
2103 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2104 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2105
Fariborz Jahanianb0fdab22013-02-11 19:30:33 +00002106 SourceLocation endLoc = S->getLocEnd();
2107 const char *endBuf = SM->getCharacterData(endLoc);
2108 const char *semiBuf = strchr(endBuf, ';');
Fariborz Jahanian11671902012-02-07 17:11:38 +00002109 assert((*semiBuf == ';') && "@throw: can't find ';'");
2110 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002111 if (S->getThrowExpr())
2112 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian11671902012-02-07 17:11:38 +00002113 return 0;
2114}
2115
2116Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2117 // Create a new string expression.
Fariborz Jahanian11671902012-02-07 17:11:38 +00002118 std::string StrEncoding;
2119 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Benjamin Kramerfc188422014-02-25 12:26:11 +00002120 Expr *Replacement = getStringLiteral(StrEncoding);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002121 ReplaceStmt(Exp, Replacement);
2122
2123 // Replace this subexpr in the parent.
2124 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2125 return Replacement;
2126}
2127
2128Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2129 if (!SelGetUidFunctionDecl)
2130 SynthSelGetUidFunctionDecl();
2131 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2132 // Create a call to sel_registerName("selName").
2133 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002134 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002135 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2136 &SelExprs[0], SelExprs.size());
2137 ReplaceStmt(Exp, SelExp);
2138 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2139 return SelExp;
2140}
2141
2142CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2143 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2144 SourceLocation EndLoc) {
2145 // Get the type, we will need to reference it in a couple spots.
2146 QualType msgSendType = FD->getType();
2147
2148 // Create a reference to the objc_msgSend() declaration.
2149 DeclRefExpr *DRE =
John McCall113bee02012-03-10 09:33:50 +00002150 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00002151
2152 // Now, we cast the reference to a pointer to the objc_msgSend type.
2153 QualType pToFunc = Context->getPointerType(msgSendType);
2154 ImplicitCastExpr *ICE =
2155 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2156 DRE, 0, VK_RValue);
2157
2158 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2159
2160 CallExpr *Exp =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002161 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian11671902012-02-07 17:11:38 +00002162 FT->getCallResultType(*Context),
2163 VK_RValue, EndLoc);
2164 return Exp;
2165}
2166
2167static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2168 const char *&startRef, const char *&endRef) {
2169 while (startBuf < endBuf) {
2170 if (*startBuf == '<')
2171 startRef = startBuf; // mark the start.
2172 if (*startBuf == '>') {
2173 if (startRef && *startRef == '<') {
2174 endRef = startBuf; // mark the end.
2175 return true;
2176 }
2177 return false;
2178 }
2179 startBuf++;
2180 }
2181 return false;
2182}
2183
2184static void scanToNextArgument(const char *&argRef) {
2185 int angle = 0;
2186 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2187 if (*argRef == '<')
2188 angle++;
2189 else if (*argRef == '>')
2190 angle--;
2191 argRef++;
2192 }
2193 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2194}
2195
2196bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2197 if (T->isObjCQualifiedIdType())
2198 return true;
2199 if (const PointerType *PT = T->getAs<PointerType>()) {
2200 if (PT->getPointeeType()->isObjCQualifiedIdType())
2201 return true;
2202 }
2203 if (T->isObjCObjectPointerType()) {
2204 T = T->getPointeeType();
2205 return T->isObjCQualifiedInterfaceType();
2206 }
2207 if (T->isArrayType()) {
2208 QualType ElemTy = Context->getBaseElementType(T);
2209 return needToScanForQualifiers(ElemTy);
2210 }
2211 return false;
2212}
2213
2214void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2215 QualType Type = E->getType();
2216 if (needToScanForQualifiers(Type)) {
2217 SourceLocation Loc, EndLoc;
2218
2219 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2220 Loc = ECE->getLParenLoc();
2221 EndLoc = ECE->getRParenLoc();
2222 } else {
2223 Loc = E->getLocStart();
2224 EndLoc = E->getLocEnd();
2225 }
2226 // This will defend against trying to rewrite synthesized expressions.
2227 if (Loc.isInvalid() || EndLoc.isInvalid())
2228 return;
2229
2230 const char *startBuf = SM->getCharacterData(Loc);
2231 const char *endBuf = SM->getCharacterData(EndLoc);
2232 const char *startRef = 0, *endRef = 0;
2233 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2234 // Get the locations of the startRef, endRef.
2235 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2236 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2237 // Comment out the protocol references.
2238 InsertText(LessLoc, "/*");
2239 InsertText(GreaterLoc, "*/");
2240 }
2241 }
2242}
2243
2244void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2245 SourceLocation Loc;
2246 QualType Type;
2247 const FunctionProtoType *proto = 0;
2248 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2249 Loc = VD->getLocation();
2250 Type = VD->getType();
2251 }
2252 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2253 Loc = FD->getLocation();
2254 // Check for ObjC 'id' and class types that have been adorned with protocol
2255 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2256 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2257 assert(funcType && "missing function type");
2258 proto = dyn_cast<FunctionProtoType>(funcType);
2259 if (!proto)
2260 return;
Alp Toker314cc812014-01-25 16:55:45 +00002261 Type = proto->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002262 }
2263 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2264 Loc = FD->getLocation();
2265 Type = FD->getType();
2266 }
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00002267 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2268 Loc = TD->getLocation();
2269 Type = TD->getUnderlyingType();
2270 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002271 else
2272 return;
2273
2274 if (needToScanForQualifiers(Type)) {
2275 // Since types are unique, we need to scan the buffer.
2276
2277 const char *endBuf = SM->getCharacterData(Loc);
2278 const char *startBuf = endBuf;
2279 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2280 startBuf--; // scan backward (from the decl location) for return type.
2281 const char *startRef = 0, *endRef = 0;
2282 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2283 // Get the locations of the startRef, endRef.
2284 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2285 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2286 // Comment out the protocol references.
2287 InsertText(LessLoc, "/*");
2288 InsertText(GreaterLoc, "*/");
2289 }
2290 }
2291 if (!proto)
2292 return; // most likely, was a variable
2293 // Now check arguments.
2294 const char *startBuf = SM->getCharacterData(Loc);
2295 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002296 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2297 if (needToScanForQualifiers(proto->getParamType(i))) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002298 // Since types are unique, we need to scan the buffer.
2299
2300 const char *endBuf = startBuf;
2301 // scan forward (from the decl location) for argument types.
2302 scanToNextArgument(endBuf);
2303 const char *startRef = 0, *endRef = 0;
2304 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2305 // Get the locations of the startRef, endRef.
2306 SourceLocation LessLoc =
2307 Loc.getLocWithOffset(startRef-startFuncBuf);
2308 SourceLocation GreaterLoc =
2309 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2310 // Comment out the protocol references.
2311 InsertText(LessLoc, "/*");
2312 InsertText(GreaterLoc, "*/");
2313 }
2314 startBuf = ++endBuf;
2315 }
2316 else {
2317 // If the function name is derived from a macro expansion, then the
2318 // argument buffer will not follow the name. Need to speak with Chris.
2319 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2320 startBuf++; // scan forward (from the decl location) for argument types.
2321 startBuf++;
2322 }
2323 }
2324}
2325
2326void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2327 QualType QT = ND->getType();
2328 const Type* TypePtr = QT->getAs<Type>();
2329 if (!isa<TypeOfExprType>(TypePtr))
2330 return;
2331 while (isa<TypeOfExprType>(TypePtr)) {
2332 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2333 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2334 TypePtr = QT->getAs<Type>();
2335 }
2336 // FIXME. This will not work for multiple declarators; as in:
2337 // __typeof__(a) b,c,d;
2338 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2339 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2340 const char *startBuf = SM->getCharacterData(DeclLoc);
2341 if (ND->getInit()) {
2342 std::string Name(ND->getNameAsString());
2343 TypeAsString += " " + Name + " = ";
2344 Expr *E = ND->getInit();
2345 SourceLocation startLoc;
2346 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2347 startLoc = ECE->getLParenLoc();
2348 else
2349 startLoc = E->getLocStart();
2350 startLoc = SM->getExpansionLoc(startLoc);
2351 const char *endBuf = SM->getCharacterData(startLoc);
2352 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2353 }
2354 else {
2355 SourceLocation X = ND->getLocEnd();
2356 X = SM->getExpansionLoc(X);
2357 const char *endBuf = SM->getCharacterData(X);
2358 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2359 }
2360}
2361
2362// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2363void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2364 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2365 SmallVector<QualType, 16> ArgTys;
2366 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2367 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002368 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002369 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002370 SourceLocation(),
2371 SourceLocation(),
2372 SelGetUidIdent, getFuncType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002373 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002374}
2375
2376void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2377 // declared in <objc/objc.h>
2378 if (FD->getIdentifier() &&
2379 FD->getName() == "sel_registerName") {
2380 SelGetUidFunctionDecl = FD;
2381 return;
2382 }
2383 RewriteObjCQualifiedInterfaceTypes(FD);
2384}
2385
2386void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2387 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2388 const char *argPtr = TypeString.c_str();
2389 if (!strchr(argPtr, '^')) {
2390 Str += TypeString;
2391 return;
2392 }
2393 while (*argPtr) {
2394 Str += (*argPtr == '^' ? '*' : *argPtr);
2395 argPtr++;
2396 }
2397}
2398
2399// FIXME. Consolidate this routine with RewriteBlockPointerType.
2400void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2401 ValueDecl *VD) {
2402 QualType Type = VD->getType();
2403 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2404 const char *argPtr = TypeString.c_str();
2405 int paren = 0;
2406 while (*argPtr) {
2407 switch (*argPtr) {
2408 case '(':
2409 Str += *argPtr;
2410 paren++;
2411 break;
2412 case ')':
2413 Str += *argPtr;
2414 paren--;
2415 break;
2416 case '^':
2417 Str += '*';
2418 if (paren == 1)
2419 Str += VD->getNameAsString();
2420 break;
2421 default:
2422 Str += *argPtr;
2423 break;
2424 }
2425 argPtr++;
2426 }
2427}
2428
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002429void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2430 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2431 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2432 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2433 if (!proto)
2434 return;
Alp Toker314cc812014-01-25 16:55:45 +00002435 QualType Type = proto->getReturnType();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002436 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2437 FdStr += " ";
2438 FdStr += FD->getName();
2439 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002440 unsigned numArgs = proto->getNumParams();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002441 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002442 QualType ArgType = proto->getParamType(i);
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002443 RewriteBlockPointerType(FdStr, ArgType);
2444 if (i+1 < numArgs)
2445 FdStr += ", ";
2446 }
Fariborz Jahaniandf0577d2012-04-19 16:30:28 +00002447 if (FD->isVariadic()) {
2448 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2449 }
2450 else
2451 FdStr += ");\n";
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002452 InsertText(FunLocStart, FdStr);
2453}
2454
Benjamin Kramer60509af2013-09-09 14:48:42 +00002455// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2456void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2457 if (SuperConstructorFunctionDecl)
Fariborz Jahanian11671902012-02-07 17:11:38 +00002458 return;
2459 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2460 SmallVector<QualType, 16> ArgTys;
2461 QualType argT = Context->getObjCIdType();
2462 assert(!argT.isNull() && "Can't find 'id' type");
2463 ArgTys.push_back(argT);
2464 ArgTys.push_back(argT);
2465 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002466 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002467 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002468 SourceLocation(),
2469 SourceLocation(),
2470 msgSendIdent, msgSendType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002471 0, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002472}
2473
2474// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2475void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2476 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2477 SmallVector<QualType, 16> ArgTys;
2478 QualType argT = Context->getObjCIdType();
2479 assert(!argT.isNull() && "Can't find 'id' type");
2480 ArgTys.push_back(argT);
2481 argT = Context->getObjCSelType();
2482 assert(!argT.isNull() && "Can't find 'SEL' type");
2483 ArgTys.push_back(argT);
2484 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002485 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002486 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002487 SourceLocation(),
2488 SourceLocation(),
2489 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002490 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002491}
2492
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002493// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002494void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2495 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002496 SmallVector<QualType, 2> ArgTys;
2497 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002498 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002499 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002500 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002501 SourceLocation(),
2502 SourceLocation(),
2503 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002504 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002505}
2506
2507// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2508void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2509 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2510 SmallVector<QualType, 16> ArgTys;
2511 QualType argT = Context->getObjCIdType();
2512 assert(!argT.isNull() && "Can't find 'id' type");
2513 ArgTys.push_back(argT);
2514 argT = Context->getObjCSelType();
2515 assert(!argT.isNull() && "Can't find 'SEL' type");
2516 ArgTys.push_back(argT);
2517 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002518 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002519 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002520 SourceLocation(),
2521 SourceLocation(),
2522 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002523 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002524}
2525
2526// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002527// id objc_msgSendSuper_stret(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002528void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2529 IdentifierInfo *msgSendIdent =
2530 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002531 SmallVector<QualType, 2> ArgTys;
2532 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002533 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002534 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002535 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2536 SourceLocation(),
2537 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002538 msgSendIdent,
2539 msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002540 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002541}
2542
2543// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2544void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2545 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2546 SmallVector<QualType, 16> ArgTys;
2547 QualType argT = Context->getObjCIdType();
2548 assert(!argT.isNull() && "Can't find 'id' type");
2549 ArgTys.push_back(argT);
2550 argT = Context->getObjCSelType();
2551 assert(!argT.isNull() && "Can't find 'SEL' type");
2552 ArgTys.push_back(argT);
2553 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002554 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002555 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002556 SourceLocation(),
2557 SourceLocation(),
2558 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002559 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002560}
2561
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002562// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002563void RewriteModernObjC::SynthGetClassFunctionDecl() {
2564 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2565 SmallVector<QualType, 16> ArgTys;
2566 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002567 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002568 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002569 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002570 SourceLocation(),
2571 SourceLocation(),
2572 getClassIdent, getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002573 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002574}
2575
2576// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2577void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2578 IdentifierInfo *getSuperClassIdent =
2579 &Context->Idents.get("class_getSuperclass");
2580 SmallVector<QualType, 16> ArgTys;
2581 ArgTys.push_back(Context->getObjCClassType());
2582 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002583 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002584 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2585 SourceLocation(),
2586 SourceLocation(),
2587 getSuperClassIdent,
2588 getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002589 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002590}
2591
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002592// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002593void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2594 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2595 SmallVector<QualType, 16> ArgTys;
2596 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002597 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002598 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002599 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002600 SourceLocation(),
2601 SourceLocation(),
2602 getClassIdent, getClassType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002603 0, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002604}
2605
2606Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2607 QualType strType = getConstantStringStructType();
2608
2609 std::string S = "__NSConstantStringImpl_";
2610
2611 std::string tmpName = InFileName;
2612 unsigned i;
2613 for (i=0; i < tmpName.length(); i++) {
2614 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002615 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002616 if (!isAlphanumeric(c))
Fariborz Jahanian11671902012-02-07 17:11:38 +00002617 tmpName[i] = '_';
2618 }
2619 S += tmpName;
2620 S += "_";
2621 S += utostr(NumObjCStringLiterals++);
2622
2623 Preamble += "static __NSConstantStringImpl " + S;
2624 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2625 Preamble += "0x000007c8,"; // utf8_str
2626 // The pretty printer for StringLiteral handles escape characters properly.
2627 std::string prettyBufS;
2628 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smith235341b2012-08-16 03:56:14 +00002629 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002630 Preamble += prettyBuf.str();
2631 Preamble += ",";
2632 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2633
2634 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2635 SourceLocation(), &Context->Idents.get(S),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002636 strType, 0, SC_Static);
John McCall113bee02012-03-10 09:33:50 +00002637 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00002638 SourceLocation());
2639 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2640 Context->getPointerType(DRE->getType()),
2641 VK_RValue, OK_Ordinary,
2642 SourceLocation());
2643 // cast to NSConstantString *
2644 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2645 CK_CPointerToObjCPointerCast, Unop);
2646 ReplaceStmt(Exp, cast);
2647 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2648 return cast;
2649}
2650
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002651Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2652 unsigned IntSize =
2653 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2654
2655 Expr *FlagExp = IntegerLiteral::Create(*Context,
2656 llvm::APInt(IntSize, Exp->getValue()),
2657 Context->IntTy, Exp->getLocation());
2658 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2659 CK_BitCast, FlagExp);
2660 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2661 cast);
2662 ReplaceStmt(Exp, PE);
2663 return PE;
2664}
2665
Patrick Beard0caa3942012-04-19 00:25:12 +00002666Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002667 // synthesize declaration of helper functions needed in this routine.
2668 if (!SelGetUidFunctionDecl)
2669 SynthSelGetUidFunctionDecl();
2670 // use objc_msgSend() for all.
2671 if (!MsgSendFunctionDecl)
2672 SynthMsgSendFunctionDecl();
2673 if (!GetClassFunctionDecl)
2674 SynthGetClassFunctionDecl();
2675
2676 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2677 SourceLocation StartLoc = Exp->getLocStart();
2678 SourceLocation EndLoc = Exp->getLocEnd();
2679
2680 // Synthesize a call to objc_msgSend().
2681 SmallVector<Expr*, 4> MsgExprs;
2682 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002683
Patrick Beard0caa3942012-04-19 00:25:12 +00002684 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2685 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2686 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002687
Patrick Beard0caa3942012-04-19 00:25:12 +00002688 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002689 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002690 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2691 &ClsExprs[0],
2692 ClsExprs.size(),
2693 StartLoc, EndLoc);
2694 MsgExprs.push_back(Cls);
2695
Patrick Beard0caa3942012-04-19 00:25:12 +00002696 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002697 // it will be the 2nd argument.
2698 SmallVector<Expr*, 4> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002699 SelExprs.push_back(
2700 getStringLiteral(BoxingMethod->getSelector().getAsString()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002701 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2702 &SelExprs[0], SelExprs.size(),
2703 StartLoc, EndLoc);
2704 MsgExprs.push_back(SelExp);
2705
Patrick Beard0caa3942012-04-19 00:25:12 +00002706 // User provided sub-expression is the 3rd, and last, argument.
2707 Expr *subExpr = Exp->getSubExpr();
2708 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002709 QualType type = ICE->getType();
2710 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2711 CastKind CK = CK_BitCast;
2712 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2713 CK = CK_IntegralToBoolean;
Patrick Beard0caa3942012-04-19 00:25:12 +00002714 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002715 }
Patrick Beard0caa3942012-04-19 00:25:12 +00002716 MsgExprs.push_back(subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002717
2718 SmallVector<QualType, 4> ArgTypes;
2719 ArgTypes.push_back(Context->getObjCIdType());
2720 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002721 for (const auto PI : BoxingMethod->parameters())
2722 ArgTypes.push_back(PI->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +00002723
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002724 QualType returnType = Exp->getType();
2725 // Get the type, we will need to reference it in a couple spots.
2726 QualType msgSendType = MsgSendFlavor->getType();
2727
2728 // Create a reference to the objc_msgSend() declaration.
2729 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2730 VK_LValue, SourceLocation());
2731
2732 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beard0caa3942012-04-19 00:25:12 +00002733 Context->getPointerType(Context->VoidTy),
2734 CK_BitCast, DRE);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002735
2736 // Now do the "normal" pointer to function cast.
2737 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002738 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002739 castType = Context->getPointerType(castType);
2740 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2741 cast);
2742
2743 // Don't forget the parens to enforce the proper binding.
2744 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2745
2746 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002747 CallExpr *CE = new (Context)
2748 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002749 ReplaceStmt(Exp, CE);
2750 return CE;
2751}
2752
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002753Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2754 // synthesize declaration of helper functions needed in this routine.
2755 if (!SelGetUidFunctionDecl)
2756 SynthSelGetUidFunctionDecl();
2757 // use objc_msgSend() for all.
2758 if (!MsgSendFunctionDecl)
2759 SynthMsgSendFunctionDecl();
2760 if (!GetClassFunctionDecl)
2761 SynthGetClassFunctionDecl();
2762
2763 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2764 SourceLocation StartLoc = Exp->getLocStart();
2765 SourceLocation EndLoc = Exp->getLocEnd();
2766
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002767 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002768 QualType IntQT = Context->IntTy;
2769 QualType NSArrayFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002770 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002771 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002772 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2773 DeclRefExpr *NSArrayDRE =
2774 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2775 SourceLocation());
2776
2777 SmallVector<Expr*, 16> InitExprs;
2778 unsigned NumElements = Exp->getNumElements();
2779 unsigned UnsignedIntSize =
2780 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2781 Expr *count = IntegerLiteral::Create(*Context,
2782 llvm::APInt(UnsignedIntSize, NumElements),
2783 Context->UnsignedIntTy, SourceLocation());
2784 InitExprs.push_back(count);
2785 for (unsigned i = 0; i < NumElements; i++)
2786 InitExprs.push_back(Exp->getElement(i));
2787 Expr *NSArrayCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002788 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002789 NSArrayFType, VK_LValue, SourceLocation());
2790
2791 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2792 SourceLocation(),
2793 &Context->Idents.get("arr"),
2794 Context->getPointerType(Context->VoidPtrTy), 0,
2795 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002796 ICIS_NoInit);
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002797 MemberExpr *ArrayLiteralME =
2798 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2799 SourceLocation(),
2800 ARRFD->getType(), VK_LValue,
2801 OK_Ordinary);
2802 QualType ConstIdT = Context->getObjCIdType().withConst();
2803 CStyleCastExpr * ArrayLiteralObjects =
2804 NoTypeInfoCStyleCastExpr(Context,
2805 Context->getPointerType(ConstIdT),
2806 CK_BitCast,
2807 ArrayLiteralME);
2808
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002809 // Synthesize a call to objc_msgSend().
2810 SmallVector<Expr*, 32> MsgExprs;
2811 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002812 QualType expType = Exp->getType();
2813
2814 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2815 ObjCInterfaceDecl *Class =
2816 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2817
2818 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002819 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002820 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2821 &ClsExprs[0],
2822 ClsExprs.size(),
2823 StartLoc, EndLoc);
2824 MsgExprs.push_back(Cls);
2825
2826 // Create a call to sel_registerName("arrayWithObjects:count:").
2827 // it will be the 2nd argument.
2828 SmallVector<Expr*, 4> SelExprs;
2829 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002830 SelExprs.push_back(
2831 getStringLiteral(ArrayMethod->getSelector().getAsString()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002832 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2833 &SelExprs[0], SelExprs.size(),
2834 StartLoc, EndLoc);
2835 MsgExprs.push_back(SelExp);
2836
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002837 // (const id [])objects
2838 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002839
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002840 // (NSUInteger)cnt
2841 Expr *cnt = IntegerLiteral::Create(*Context,
2842 llvm::APInt(UnsignedIntSize, NumElements),
2843 Context->UnsignedIntTy, SourceLocation());
2844 MsgExprs.push_back(cnt);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002845
2846
2847 SmallVector<QualType, 4> ArgTypes;
2848 ArgTypes.push_back(Context->getObjCIdType());
2849 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002850 for (const auto *PI : ArrayMethod->params())
2851 ArgTypes.push_back(PI->getType());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002852
2853 QualType returnType = Exp->getType();
2854 // Get the type, we will need to reference it in a couple spots.
2855 QualType msgSendType = MsgSendFlavor->getType();
2856
2857 // Create a reference to the objc_msgSend() declaration.
2858 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2859 VK_LValue, SourceLocation());
2860
2861 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2862 Context->getPointerType(Context->VoidTy),
2863 CK_BitCast, DRE);
2864
2865 // Now do the "normal" pointer to function cast.
2866 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002867 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002868 castType = Context->getPointerType(castType);
2869 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2870 cast);
2871
2872 // Don't forget the parens to enforce the proper binding.
2873 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2874
2875 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002876 CallExpr *CE = new (Context)
2877 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002878 ReplaceStmt(Exp, CE);
2879 return CE;
2880}
2881
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002882Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2883 // synthesize declaration of helper functions needed in this routine.
2884 if (!SelGetUidFunctionDecl)
2885 SynthSelGetUidFunctionDecl();
2886 // use objc_msgSend() for all.
2887 if (!MsgSendFunctionDecl)
2888 SynthMsgSendFunctionDecl();
2889 if (!GetClassFunctionDecl)
2890 SynthGetClassFunctionDecl();
2891
2892 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2893 SourceLocation StartLoc = Exp->getLocStart();
2894 SourceLocation EndLoc = Exp->getLocEnd();
2895
2896 // Build the expression: __NSContainer_literal(int, ...).arr
2897 QualType IntQT = Context->IntTy;
2898 QualType NSDictFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002899 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002900 std::string NSDictFName("__NSContainer_literal");
2901 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2902 DeclRefExpr *NSDictDRE =
2903 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2904 SourceLocation());
2905
2906 SmallVector<Expr*, 16> KeyExprs;
2907 SmallVector<Expr*, 16> ValueExprs;
2908
2909 unsigned NumElements = Exp->getNumElements();
2910 unsigned UnsignedIntSize =
2911 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2912 Expr *count = IntegerLiteral::Create(*Context,
2913 llvm::APInt(UnsignedIntSize, NumElements),
2914 Context->UnsignedIntTy, SourceLocation());
2915 KeyExprs.push_back(count);
2916 ValueExprs.push_back(count);
2917 for (unsigned i = 0; i < NumElements; i++) {
2918 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2919 KeyExprs.push_back(Element.Key);
2920 ValueExprs.push_back(Element.Value);
2921 }
2922
2923 // (const id [])objects
2924 Expr *NSValueCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002925 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002926 NSDictFType, VK_LValue, SourceLocation());
2927
2928 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2929 SourceLocation(),
2930 &Context->Idents.get("arr"),
2931 Context->getPointerType(Context->VoidPtrTy), 0,
2932 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002933 ICIS_NoInit);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002934 MemberExpr *DictLiteralValueME =
2935 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2936 SourceLocation(),
2937 ARRFD->getType(), VK_LValue,
2938 OK_Ordinary);
2939 QualType ConstIdT = Context->getObjCIdType().withConst();
2940 CStyleCastExpr * DictValueObjects =
2941 NoTypeInfoCStyleCastExpr(Context,
2942 Context->getPointerType(ConstIdT),
2943 CK_BitCast,
2944 DictLiteralValueME);
2945 // (const id <NSCopying> [])keys
2946 Expr *NSKeyCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002947 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002948 NSDictFType, VK_LValue, SourceLocation());
2949
2950 MemberExpr *DictLiteralKeyME =
2951 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2952 SourceLocation(),
2953 ARRFD->getType(), VK_LValue,
2954 OK_Ordinary);
2955
2956 CStyleCastExpr * DictKeyObjects =
2957 NoTypeInfoCStyleCastExpr(Context,
2958 Context->getPointerType(ConstIdT),
2959 CK_BitCast,
2960 DictLiteralKeyME);
2961
2962
2963
2964 // Synthesize a call to objc_msgSend().
2965 SmallVector<Expr*, 32> MsgExprs;
2966 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002967 QualType expType = Exp->getType();
2968
2969 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2970 ObjCInterfaceDecl *Class =
2971 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2972
2973 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002974 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002975 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2976 &ClsExprs[0],
2977 ClsExprs.size(),
2978 StartLoc, EndLoc);
2979 MsgExprs.push_back(Cls);
2980
2981 // Create a call to sel_registerName("arrayWithObjects:count:").
2982 // it will be the 2nd argument.
2983 SmallVector<Expr*, 4> SelExprs;
2984 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002985 SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002986 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2987 &SelExprs[0], SelExprs.size(),
2988 StartLoc, EndLoc);
2989 MsgExprs.push_back(SelExp);
2990
2991 // (const id [])objects
2992 MsgExprs.push_back(DictValueObjects);
2993
2994 // (const id <NSCopying> [])keys
2995 MsgExprs.push_back(DictKeyObjects);
2996
2997 // (NSUInteger)cnt
2998 Expr *cnt = IntegerLiteral::Create(*Context,
2999 llvm::APInt(UnsignedIntSize, NumElements),
3000 Context->UnsignedIntTy, SourceLocation());
3001 MsgExprs.push_back(cnt);
3002
3003
3004 SmallVector<QualType, 8> ArgTypes;
3005 ArgTypes.push_back(Context->getObjCIdType());
3006 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00003007 for (const auto *PI : DictMethod->params()) {
3008 QualType T = PI->getType();
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003009 if (const PointerType* PT = T->getAs<PointerType>()) {
3010 QualType PointeeTy = PT->getPointeeType();
3011 convertToUnqualifiedObjCType(PointeeTy);
3012 T = Context->getPointerType(PointeeTy);
3013 }
3014 ArgTypes.push_back(T);
3015 }
3016
3017 QualType returnType = Exp->getType();
3018 // Get the type, we will need to reference it in a couple spots.
3019 QualType msgSendType = MsgSendFlavor->getType();
3020
3021 // Create a reference to the objc_msgSend() declaration.
3022 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3023 VK_LValue, SourceLocation());
3024
3025 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3026 Context->getPointerType(Context->VoidTy),
3027 CK_BitCast, DRE);
3028
3029 // Now do the "normal" pointer to function cast.
3030 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003031 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003032 castType = Context->getPointerType(castType);
3033 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3034 cast);
3035
3036 // Don't forget the parens to enforce the proper binding.
3037 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3038
3039 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003040 CallExpr *CE = new (Context)
3041 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003042 ReplaceStmt(Exp, CE);
3043 return CE;
3044}
3045
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003046// struct __rw_objc_super {
3047// struct objc_object *object; struct objc_object *superClass;
3048// };
Fariborz Jahanian11671902012-02-07 17:11:38 +00003049QualType RewriteModernObjC::getSuperStructType() {
3050 if (!SuperStructDecl) {
3051 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3052 SourceLocation(), SourceLocation(),
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003053 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003054 QualType FieldTypes[2];
3055
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003056 // struct objc_object *object;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003057 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003058 // struct objc_object *superClass;
3059 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003060
3061 // Create fields
3062 for (unsigned i = 0; i < 2; ++i) {
3063 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3064 SourceLocation(),
3065 SourceLocation(), 0,
3066 FieldTypes[i], 0,
3067 /*BitWidth=*/0,
3068 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003069 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003070 }
3071
3072 SuperStructDecl->completeDefinition();
3073 }
3074 return Context->getTagDeclType(SuperStructDecl);
3075}
3076
3077QualType RewriteModernObjC::getConstantStringStructType() {
3078 if (!ConstantStringDecl) {
3079 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3080 SourceLocation(), SourceLocation(),
3081 &Context->Idents.get("__NSConstantStringImpl"));
3082 QualType FieldTypes[4];
3083
3084 // struct objc_object *receiver;
3085 FieldTypes[0] = Context->getObjCIdType();
3086 // int flags;
3087 FieldTypes[1] = Context->IntTy;
3088 // char *str;
3089 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3090 // long length;
3091 FieldTypes[3] = Context->LongTy;
3092
3093 // Create fields
3094 for (unsigned i = 0; i < 4; ++i) {
3095 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3096 ConstantStringDecl,
3097 SourceLocation(),
3098 SourceLocation(), 0,
3099 FieldTypes[i], 0,
3100 /*BitWidth=*/0,
3101 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003102 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003103 }
3104
3105 ConstantStringDecl->completeDefinition();
3106 }
3107 return Context->getTagDeclType(ConstantStringDecl);
3108}
3109
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003110/// getFunctionSourceLocation - returns start location of a function
3111/// definition. Complication arises when function has declared as
3112/// extern "C" or extern "C" {...}
3113static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3114 FunctionDecl *FD) {
3115 if (FD->isExternC() && !FD->isMain()) {
3116 const DeclContext *DC = FD->getDeclContext();
3117 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3118 // if it is extern "C" {...}, return function decl's own location.
3119 if (!LSD->getRBraceLoc().isValid())
3120 return LSD->getExternLoc();
3121 }
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003122 if (FD->getStorageClass() != SC_None)
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003123 R.RewriteBlockLiteralFunctionDecl(FD);
3124 return FD->getTypeSpecStartLoc();
3125}
3126
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003127void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3128
3129 SourceLocation Location = D->getLocation();
3130
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00003131 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian83dadc72012-11-07 18:15:53 +00003132 std::string LineString("\n#line ");
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003133 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3134 LineString += utostr(PLoc.getLine());
3135 LineString += " \"";
NAKAMURA Takumib46a05c2012-11-06 22:45:31 +00003136 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003137 if (isa<ObjCMethodDecl>(D))
3138 LineString += "\"";
3139 else LineString += "\"\n";
3140
3141 Location = D->getLocStart();
3142 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3143 if (FD->isExternC() && !FD->isMain()) {
3144 const DeclContext *DC = FD->getDeclContext();
3145 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3146 // if it is extern "C" {...}, return function decl's own location.
3147 if (!LSD->getRBraceLoc().isValid())
3148 Location = LSD->getExternLoc();
3149 }
3150 }
3151 InsertText(Location, LineString);
3152 }
3153}
3154
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003155/// SynthMsgSendStretCallExpr - This routine translates message expression
3156/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3157/// nil check on receiver must be performed before calling objc_msgSend_stret.
3158/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3159/// msgSendType - function type of objc_msgSend_stret(...)
3160/// returnType - Result type of the method being synthesized.
3161/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3162/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3163/// starting with receiver.
3164/// Method - Method being rewritten.
3165Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003166 QualType returnType,
3167 SmallVectorImpl<QualType> &ArgTypes,
3168 SmallVectorImpl<Expr*> &MsgExprs,
3169 ObjCMethodDecl *Method) {
3170 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003171 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3172 Method ? Method->isVariadic()
3173 : false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003174 castType = Context->getPointerType(castType);
3175
3176 // build type for containing the objc_msgSend_stret object.
3177 static unsigned stretCount=0;
3178 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003179 std::string str =
3180 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003181 str += "namespace {\n";
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003182 str += "struct "; str += name;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003183 str += " {\n\t";
3184 str += name;
3185 str += "(id receiver, SEL sel";
3186 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003187 std::string ArgName = "arg"; ArgName += utostr(i);
3188 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3189 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003190 }
3191 // could be vararg.
3192 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003193 std::string ArgName = "arg"; ArgName += utostr(i);
3194 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3195 Context->getPrintingPolicy());
3196 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003197 }
3198
3199 str += ") {\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003200 str += "\t unsigned size = sizeof(";
3201 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3202
3203 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3204
3205 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3206 str += ")(void *)objc_msgSend)(receiver, sel";
3207 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3208 str += ", arg"; str += utostr(i);
3209 }
3210 // could be vararg.
3211 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3212 str += ", arg"; str += utostr(i);
3213 }
3214 str+= ");\n";
3215
3216 str += "\t else if (receiver == 0)\n";
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003217 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3218 str += "\t else\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003219
3220
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003221 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3222 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3223 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3224 str += ", arg"; str += utostr(i);
3225 }
3226 // could be vararg.
3227 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3228 str += ", arg"; str += utostr(i);
3229 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003230 str += ");\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003231
3232
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003233 str += "\t}\n";
3234 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3235 str += " s;\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003236 str += "};\n};\n\n";
Fariborz Jahanianf1f36c62012-08-21 18:56:50 +00003237 SourceLocation FunLocStart;
3238 if (CurFunctionDef)
3239 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3240 else {
3241 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3242 FunLocStart = CurMethodDef->getLocStart();
3243 }
3244
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003245 InsertText(FunLocStart, str);
3246 ++stretCount;
3247
3248 // AST for __Stretn(receiver, args).s;
3249 IdentifierInfo *ID = &Context->Idents.get(name);
3250 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00003251 SourceLocation(), ID, castType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003252 SC_Extern, false, false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003253 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3254 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003255 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003256 castType, VK_LValue, SourceLocation());
3257
3258 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3259 SourceLocation(),
3260 &Context->Idents.get("s"),
3261 returnType, 0,
3262 /*BitWidth=*/0, /*Mutable=*/true,
3263 ICIS_NoInit);
3264 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3265 FieldD->getType(), VK_LValue,
3266 OK_Ordinary);
3267
3268 return ME;
3269}
3270
Fariborz Jahanian11671902012-02-07 17:11:38 +00003271Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3272 SourceLocation StartLoc,
3273 SourceLocation EndLoc) {
3274 if (!SelGetUidFunctionDecl)
3275 SynthSelGetUidFunctionDecl();
3276 if (!MsgSendFunctionDecl)
3277 SynthMsgSendFunctionDecl();
3278 if (!MsgSendSuperFunctionDecl)
3279 SynthMsgSendSuperFunctionDecl();
3280 if (!MsgSendStretFunctionDecl)
3281 SynthMsgSendStretFunctionDecl();
3282 if (!MsgSendSuperStretFunctionDecl)
3283 SynthMsgSendSuperStretFunctionDecl();
3284 if (!MsgSendFpretFunctionDecl)
3285 SynthMsgSendFpretFunctionDecl();
3286 if (!GetClassFunctionDecl)
3287 SynthGetClassFunctionDecl();
3288 if (!GetSuperClassFunctionDecl)
3289 SynthGetSuperClassFunctionDecl();
3290 if (!GetMetaClassFunctionDecl)
3291 SynthGetMetaClassFunctionDecl();
3292
3293 // default to objc_msgSend().
3294 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3295 // May need to use objc_msgSend_stret() as well.
3296 FunctionDecl *MsgSendStretFlavor = 0;
3297 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003298 QualType resultType = mDecl->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003299 if (resultType->isRecordType())
3300 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3301 else if (resultType->isRealFloatingType())
3302 MsgSendFlavor = MsgSendFpretFunctionDecl;
3303 }
3304
3305 // Synthesize a call to objc_msgSend().
3306 SmallVector<Expr*, 8> MsgExprs;
3307 switch (Exp->getReceiverKind()) {
3308 case ObjCMessageExpr::SuperClass: {
3309 MsgSendFlavor = MsgSendSuperFunctionDecl;
3310 if (MsgSendStretFlavor)
3311 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3312 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3313
3314 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3315
3316 SmallVector<Expr*, 4> InitExprs;
3317
3318 // set the receiver to self, the first argument to all methods.
3319 InitExprs.push_back(
3320 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3321 CK_BitCast,
3322 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003323 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003324 Context->getObjCIdType(),
3325 VK_RValue,
3326 SourceLocation()))
3327 ); // set the 'receiver'.
3328
3329 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3330 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003331 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003332 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003333 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3334 &ClsExprs[0],
3335 ClsExprs.size(),
3336 StartLoc,
3337 EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003338 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003339 ClsExprs.push_back(Cls);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003340 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3341 &ClsExprs[0], ClsExprs.size(),
3342 StartLoc, EndLoc);
3343
3344 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3345 // To turn off a warning, type-cast to 'id'
3346 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3347 NoTypeInfoCStyleCastExpr(Context,
3348 Context->getObjCIdType(),
3349 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003350 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003351 QualType superType = getSuperStructType();
3352 Expr *SuperRep;
3353
3354 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003355 SynthSuperConstructorFunctionDecl();
3356 // Simulate a constructor call...
3357 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003358 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003359 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003360 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003361 superType, VK_LValue,
3362 SourceLocation());
3363 // The code for super is a little tricky to prevent collision with
3364 // the structure definition in the header. The rewriter has it's own
3365 // internal definition (__rw_objc_super) that is uses. This is why
3366 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003367 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003368 //
3369 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3370 Context->getPointerType(SuperRep->getType()),
3371 VK_RValue, OK_Ordinary,
3372 SourceLocation());
3373 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3374 Context->getPointerType(superType),
3375 CK_BitCast, SuperRep);
3376 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003377 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003378 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003379 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003380 SourceLocation());
3381 TypeSourceInfo *superTInfo
3382 = Context->getTrivialTypeSourceInfo(superType);
3383 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3384 superType, VK_LValue,
3385 ILE, false);
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003386 // struct __rw_objc_super *
Fariborz Jahanian11671902012-02-07 17:11:38 +00003387 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3388 Context->getPointerType(SuperRep->getType()),
3389 VK_RValue, OK_Ordinary,
3390 SourceLocation());
3391 }
3392 MsgExprs.push_back(SuperRep);
3393 break;
3394 }
3395
3396 case ObjCMessageExpr::Class: {
3397 SmallVector<Expr*, 8> ClsExprs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003398 ObjCInterfaceDecl *Class
3399 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3400 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00003401 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003402 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3403 &ClsExprs[0],
3404 ClsExprs.size(),
3405 StartLoc, EndLoc);
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003406 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3407 Context->getObjCIdType(),
3408 CK_BitCast, Cls);
3409 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003410 break;
3411 }
3412
3413 case ObjCMessageExpr::SuperInstance:{
3414 MsgSendFlavor = MsgSendSuperFunctionDecl;
3415 if (MsgSendStretFlavor)
3416 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3417 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3418 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3419 SmallVector<Expr*, 4> InitExprs;
3420
3421 InitExprs.push_back(
3422 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3423 CK_BitCast,
3424 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003425 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003426 Context->getObjCIdType(),
3427 VK_RValue, SourceLocation()))
3428 ); // set the 'receiver'.
3429
3430 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3431 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003432 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003433 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003434 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3435 &ClsExprs[0],
3436 ClsExprs.size(),
3437 StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003438 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003439 ClsExprs.push_back(Cls);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003440 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3441 &ClsExprs[0], ClsExprs.size(),
3442 StartLoc, EndLoc);
3443
3444 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3445 // To turn off a warning, type-cast to 'id'
3446 InitExprs.push_back(
3447 // set 'super class', using class_getSuperclass().
3448 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3449 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003450 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003451 QualType superType = getSuperStructType();
3452 Expr *SuperRep;
3453
3454 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003455 SynthSuperConstructorFunctionDecl();
3456 // Simulate a constructor call...
3457 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003458 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003459 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003460 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003461 superType, VK_LValue, SourceLocation());
3462 // The code for super is a little tricky to prevent collision with
3463 // the structure definition in the header. The rewriter has it's own
3464 // internal definition (__rw_objc_super) that is uses. This is why
3465 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003466 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003467 //
3468 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3469 Context->getPointerType(SuperRep->getType()),
3470 VK_RValue, OK_Ordinary,
3471 SourceLocation());
3472 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3473 Context->getPointerType(superType),
3474 CK_BitCast, SuperRep);
3475 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003476 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003477 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003478 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003479 SourceLocation());
3480 TypeSourceInfo *superTInfo
3481 = Context->getTrivialTypeSourceInfo(superType);
3482 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3483 superType, VK_RValue, ILE,
3484 false);
3485 }
3486 MsgExprs.push_back(SuperRep);
3487 break;
3488 }
3489
3490 case ObjCMessageExpr::Instance: {
3491 // Remove all type-casts because it may contain objc-style types; e.g.
3492 // Foo<Proto> *.
3493 Expr *recExpr = Exp->getInstanceReceiver();
3494 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3495 recExpr = CE->getSubExpr();
3496 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3497 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3498 ? CK_BlockPointerToObjCPointerCast
3499 : CK_CPointerToObjCPointerCast;
3500
3501 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3502 CK, recExpr);
3503 MsgExprs.push_back(recExpr);
3504 break;
3505 }
3506 }
3507
3508 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3509 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003510 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003511 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3512 &SelExprs[0], SelExprs.size(),
3513 StartLoc,
3514 EndLoc);
3515 MsgExprs.push_back(SelExp);
3516
3517 // Now push any user supplied arguments.
3518 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3519 Expr *userExpr = Exp->getArg(i);
3520 // Make all implicit casts explicit...ICE comes in handy:-)
3521 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3522 // Reuse the ICE type, it is exactly what the doctor ordered.
3523 QualType type = ICE->getType();
3524 if (needToScanForQualifiers(type))
3525 type = Context->getObjCIdType();
3526 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3527 (void)convertBlockPointerToFunctionPointer(type);
3528 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3529 CastKind CK;
3530 if (SubExpr->getType()->isIntegralType(*Context) &&
3531 type->isBooleanType()) {
3532 CK = CK_IntegralToBoolean;
3533 } else if (type->isObjCObjectPointerType()) {
3534 if (SubExpr->getType()->isBlockPointerType()) {
3535 CK = CK_BlockPointerToObjCPointerCast;
3536 } else if (SubExpr->getType()->isPointerType()) {
3537 CK = CK_CPointerToObjCPointerCast;
3538 } else {
3539 CK = CK_BitCast;
3540 }
3541 } else {
3542 CK = CK_BitCast;
3543 }
3544
3545 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3546 }
3547 // Make id<P...> cast into an 'id' cast.
3548 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3549 if (CE->getType()->isObjCQualifiedIdType()) {
3550 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3551 userExpr = CE->getSubExpr();
3552 CastKind CK;
3553 if (userExpr->getType()->isIntegralType(*Context)) {
3554 CK = CK_IntegralToPointer;
3555 } else if (userExpr->getType()->isBlockPointerType()) {
3556 CK = CK_BlockPointerToObjCPointerCast;
3557 } else if (userExpr->getType()->isPointerType()) {
3558 CK = CK_CPointerToObjCPointerCast;
3559 } else {
3560 CK = CK_BitCast;
3561 }
3562 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3563 CK, userExpr);
3564 }
3565 }
3566 MsgExprs.push_back(userExpr);
3567 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3568 // out the argument in the original expression (since we aren't deleting
3569 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3570 //Exp->setArg(i, 0);
3571 }
3572 // Generate the funky cast.
3573 CastExpr *cast;
3574 SmallVector<QualType, 8> ArgTypes;
3575 QualType returnType;
3576
3577 // Push 'id' and 'SEL', the 2 implicit arguments.
3578 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3579 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3580 else
3581 ArgTypes.push_back(Context->getObjCIdType());
3582 ArgTypes.push_back(Context->getObjCSelType());
3583 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3584 // Push any user argument types.
Aaron Ballman43b68be2014-03-07 17:50:17 +00003585 for (const auto *PI : OMD->params()) {
3586 QualType t = PI->getType()->isObjCQualifiedIdType()
Fariborz Jahanian11671902012-02-07 17:11:38 +00003587 ? Context->getObjCIdType()
Aaron Ballman43b68be2014-03-07 17:50:17 +00003588 : PI->getType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003589 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3590 (void)convertBlockPointerToFunctionPointer(t);
3591 ArgTypes.push_back(t);
3592 }
3593 returnType = Exp->getType();
3594 convertToUnqualifiedObjCType(returnType);
3595 (void)convertBlockPointerToFunctionPointer(returnType);
3596 } else {
3597 returnType = Context->getObjCIdType();
3598 }
3599 // Get the type, we will need to reference it in a couple spots.
3600 QualType msgSendType = MsgSendFlavor->getType();
3601
3602 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00003603 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003604 VK_LValue, SourceLocation());
3605
3606 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3607 // If we don't do this cast, we get the following bizarre warning/note:
3608 // xx.m:13: warning: function called through a non-compatible type
3609 // xx.m:13: note: if this code is reached, the program will abort
3610 cast = NoTypeInfoCStyleCastExpr(Context,
3611 Context->getPointerType(Context->VoidTy),
3612 CK_BitCast, DRE);
3613
3614 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003615 // If we don't have a method decl, force a variadic cast.
3616 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003617 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003618 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003619 castType = Context->getPointerType(castType);
3620 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3621 cast);
3622
3623 // Don't forget the parens to enforce the proper binding.
3624 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3625
3626 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003627 CallExpr *CE = new (Context)
3628 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003629 Stmt *ReplacingStmt = CE;
3630 if (MsgSendStretFlavor) {
3631 // We have the method which returns a struct/union. Must also generate
3632 // call to objc_msgSend_stret and hang both varieties on a conditional
3633 // expression which dictate which one to envoke depending on size of
3634 // method's return type.
3635
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003636 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3637 returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003638 ArgTypes, MsgExprs,
3639 Exp->getMethodDecl());
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003640 ReplacingStmt = STCE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003641 }
3642 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3643 return ReplacingStmt;
3644}
3645
3646Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3647 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3648 Exp->getLocEnd());
3649
3650 // Now do the actual rewrite.
3651 ReplaceStmt(Exp, ReplacingStmt);
3652
3653 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3654 return ReplacingStmt;
3655}
3656
3657// typedef struct objc_object Protocol;
3658QualType RewriteModernObjC::getProtocolType() {
3659 if (!ProtocolTypeDecl) {
3660 TypeSourceInfo *TInfo
3661 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3662 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3663 SourceLocation(), SourceLocation(),
3664 &Context->Idents.get("Protocol"),
3665 TInfo);
3666 }
3667 return Context->getTypeDeclType(ProtocolTypeDecl);
3668}
3669
3670/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3671/// a synthesized/forward data reference (to the protocol's metadata).
3672/// The forward references (and metadata) are generated in
3673/// RewriteModernObjC::HandleTranslationUnit().
3674Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00003675 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3676 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003677 IdentifierInfo *ID = &Context->Idents.get(Name);
3678 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3679 SourceLocation(), ID, getProtocolType(), 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003680 SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00003681 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3682 VK_LValue, SourceLocation());
Fariborz Jahaniand38951a2013-11-22 18:43:41 +00003683 CastExpr *castExpr =
3684 NoTypeInfoCStyleCastExpr(
3685 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003686 ReplaceStmt(Exp, castExpr);
3687 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3688 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3689 return castExpr;
3690
3691}
3692
3693bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3694 const char *endBuf) {
3695 while (startBuf < endBuf) {
3696 if (*startBuf == '#') {
3697 // Skip whitespace.
3698 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3699 ;
3700 if (!strncmp(startBuf, "if", strlen("if")) ||
3701 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3702 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3703 !strncmp(startBuf, "define", strlen("define")) ||
3704 !strncmp(startBuf, "undef", strlen("undef")) ||
3705 !strncmp(startBuf, "else", strlen("else")) ||
3706 !strncmp(startBuf, "elif", strlen("elif")) ||
3707 !strncmp(startBuf, "endif", strlen("endif")) ||
3708 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3709 !strncmp(startBuf, "include", strlen("include")) ||
3710 !strncmp(startBuf, "import", strlen("import")) ||
3711 !strncmp(startBuf, "include_next", strlen("include_next")))
3712 return true;
3713 }
3714 startBuf++;
3715 }
3716 return false;
3717}
3718
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003719/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3720/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003721bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003722 TagDecl *Tag,
3723 bool &IsNamedDefinition) {
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003724 if (!IDecl)
3725 return false;
3726 SourceLocation TagLocation;
3727 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3728 RD = RD->getDefinition();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003729 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003730 return false;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003731 IsNamedDefinition = true;
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003732 TagLocation = RD->getLocation();
3733 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003734 IDecl->getLocation(), TagLocation);
3735 }
3736 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3737 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3738 return false;
3739 IsNamedDefinition = true;
3740 TagLocation = ED->getLocation();
3741 return Context->getSourceManager().isBeforeInTranslationUnit(
3742 IDecl->getLocation(), TagLocation);
3743
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003744 }
3745 return false;
3746}
3747
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003748/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003749/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003750bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3751 std::string &Result) {
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003752 if (isa<TypedefType>(Type)) {
3753 Result += "\t";
3754 return false;
3755 }
3756
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003757 if (Type->isArrayType()) {
3758 QualType ElemTy = Context->getBaseElementType(Type);
3759 return RewriteObjCFieldDeclType(ElemTy, Result);
3760 }
3761 else if (Type->isRecordType()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003762 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3763 if (RD->isCompleteDefinition()) {
3764 if (RD->isStruct())
3765 Result += "\n\tstruct ";
3766 else if (RD->isUnion())
3767 Result += "\n\tunion ";
3768 else
3769 assert(false && "class not allowed as an ivar type");
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003770
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003771 Result += RD->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003772 if (GlobalDefinedTags.count(RD)) {
3773 // struct/union is defined globally, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003774 Result += " ";
3775 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003776 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003777 Result += " {\n";
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003778 for (auto *FD : RD->fields())
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003779 RewriteObjCFieldDecl(FD, Result);
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003780 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003781 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003782 }
3783 }
3784 else if (Type->isEnumeralType()) {
3785 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3786 if (ED->isCompleteDefinition()) {
3787 Result += "\n\tenum ";
3788 Result += ED->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003789 if (GlobalDefinedTags.count(ED)) {
3790 // Enum is globall defined, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003791 Result += " ";
3792 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003793 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003794
3795 Result += " {\n";
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003796 for (const auto *EC : ED->enumerators()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003797 Result += "\t"; Result += EC->getName(); Result += " = ";
3798 llvm::APSInt Val = EC->getInitVal();
3799 Result += Val.toString(10);
3800 Result += ",\n";
3801 }
3802 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003803 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003804 }
3805 }
3806
3807 Result += "\t";
3808 convertObjCTypeToCStyleType(Type);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003809 return false;
3810}
3811
3812
3813/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3814/// It handles elaborated types, as well as enum types in the process.
3815void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3816 std::string &Result) {
3817 QualType Type = fieldDecl->getType();
3818 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003819
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003820 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3821 if (!EleboratedType)
3822 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003823 Result += Name;
3824 if (fieldDecl->isBitField()) {
3825 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3826 }
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003827 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00003828 const ArrayType *AT = Context->getAsArrayType(Type);
3829 do {
3830 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003831 Result += "[";
3832 llvm::APInt Dim = CAT->getSize();
3833 Result += utostr(Dim.getZExtValue());
3834 Result += "]";
3835 }
Eli Friedman07bab732012-12-13 01:43:21 +00003836 AT = Context->getAsArrayType(AT->getElementType());
3837 } while (AT);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003838 }
3839
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003840 Result += ";\n";
3841}
3842
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003843/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3844/// named aggregate types into the input buffer.
3845void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3846 std::string &Result) {
3847 QualType Type = fieldDecl->getType();
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003848 if (isa<TypedefType>(Type))
3849 return;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003850 if (Type->isArrayType())
3851 Type = Context->getBaseElementType(Type);
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003852 ObjCContainerDecl *IDecl =
3853 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003854
3855 TagDecl *TD = 0;
3856 if (Type->isRecordType()) {
3857 TD = Type->getAs<RecordType>()->getDecl();
3858 }
3859 else if (Type->isEnumeralType()) {
3860 TD = Type->getAs<EnumType>()->getDecl();
3861 }
3862
3863 if (TD) {
3864 if (GlobalDefinedTags.count(TD))
3865 return;
3866
3867 bool IsNamedDefinition = false;
3868 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3869 RewriteObjCFieldDeclType(Type, Result);
3870 Result += ";";
3871 }
3872 if (IsNamedDefinition)
3873 GlobalDefinedTags.insert(TD);
3874 }
3875
3876}
3877
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003878unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3879 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3880 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3881 return IvarGroupNumber[IV];
3882 }
3883 unsigned GroupNo = 0;
3884 SmallVector<const ObjCIvarDecl *, 8> IVars;
3885 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3886 IVD; IVD = IVD->getNextIvar())
3887 IVars.push_back(IVD);
3888
3889 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3890 if (IVars[i]->isBitField()) {
3891 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3892 while (i < e && IVars[i]->isBitField())
3893 IvarGroupNumber[IVars[i++]] = GroupNo;
3894 if (i < e)
3895 --i;
3896 }
3897
3898 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3899 return IvarGroupNumber[IV];
3900}
3901
3902QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3903 ObjCIvarDecl *IV,
3904 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3905 std::string StructTagName;
3906 ObjCIvarBitfieldGroupType(IV, StructTagName);
3907 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3908 Context->getTranslationUnitDecl(),
3909 SourceLocation(), SourceLocation(),
3910 &Context->Idents.get(StructTagName));
3911 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3912 ObjCIvarDecl *Ivar = IVars[i];
3913 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3914 &Context->Idents.get(Ivar->getName()),
3915 Ivar->getType(),
3916 0, /*Expr *BW */Ivar->getBitWidth(), false,
3917 ICIS_NoInit));
3918 }
3919 RD->completeDefinition();
3920 return Context->getTagDeclType(RD);
3921}
3922
3923QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3924 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3925 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3926 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3927 if (GroupRecordType.count(tuple))
3928 return GroupRecordType[tuple];
3929
3930 SmallVector<ObjCIvarDecl *, 8> IVars;
3931 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3932 IVD; IVD = IVD->getNextIvar()) {
3933 if (IVD->isBitField())
3934 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3935 else {
3936 if (!IVars.empty()) {
3937 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3938 // Generate the struct type for this group of bitfield ivars.
3939 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3940 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3941 IVars.clear();
3942 }
3943 }
3944 }
3945 if (!IVars.empty()) {
3946 // Do the last one.
3947 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3948 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3949 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3950 }
3951 QualType RetQT = GroupRecordType[tuple];
3952 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3953
3954 return RetQT;
3955}
3956
3957/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3958/// Name would be: classname__GRBF_n where n is the group number for this ivar.
3959void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3960 std::string &Result) {
3961 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3962 Result += CDecl->getName();
3963 Result += "__GRBF_";
3964 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3965 Result += utostr(GroupNo);
3966 return;
3967}
3968
3969/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3970/// Name of the struct would be: classname__T_n where n is the group number for
3971/// this ivar.
3972void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3973 std::string &Result) {
3974 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3975 Result += CDecl->getName();
3976 Result += "__T_";
3977 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3978 Result += utostr(GroupNo);
3979 return;
3980}
3981
3982/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3983/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3984/// this ivar.
3985void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3986 std::string &Result) {
3987 Result += "OBJC_IVAR_$_";
3988 ObjCIvarBitfieldGroupDecl(IV, Result);
3989}
3990
3991#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
3992 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
3993 ++IX; \
3994 if (IX < ENDIX) \
3995 --IX; \
3996}
3997
Fariborz Jahanian11671902012-02-07 17:11:38 +00003998/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3999/// an objective-c class with ivars.
4000void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
4001 std::string &Result) {
4002 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
4003 assert(CDecl->getName() != "" &&
4004 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004005 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004006 SmallVector<ObjCIvarDecl *, 8> IVars;
4007 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00004008 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004009 IVars.push_back(IVD);
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00004010
Fariborz Jahanian11671902012-02-07 17:11:38 +00004011 SourceLocation LocStart = CDecl->getLocStart();
4012 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004013
Fariborz Jahanian11671902012-02-07 17:11:38 +00004014 const char *startBuf = SM->getCharacterData(LocStart);
4015 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004016
Fariborz Jahanian11671902012-02-07 17:11:38 +00004017 // If no ivars and no root or if its root, directly or indirectly,
4018 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004019 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00004020 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
4021 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4022 ReplaceText(LocStart, endBuf-startBuf, Result);
4023 return;
4024 }
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004025
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00004026 // Insert named struct/union definitions inside class to
4027 // outer scope. This follows semantics of locally defined
4028 // struct/unions in objective-c classes.
4029 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4030 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004031
4032 // Insert named structs which are syntheized to group ivar bitfields
4033 // to outer scope as well.
4034 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4035 if (IVars[i]->isBitField()) {
4036 ObjCIvarDecl *IV = IVars[i];
4037 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
4038 RewriteObjCFieldDeclType(QT, Result);
4039 Result += ";";
4040 // skip over ivar bitfields in this group.
4041 SKIP_BITFIELDS(i , e, IVars);
4042 }
4043
Fariborz Jahanian11671902012-02-07 17:11:38 +00004044 Result += "\nstruct ";
4045 Result += CDecl->getNameAsString();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004046 Result += "_IMPL {\n";
4047
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004048 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004049 Result += "\tstruct "; Result += RCDecl->getNameAsString();
4050 Result += "_IMPL "; Result += RCDecl->getNameAsString();
4051 Result += "_IVARS;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004052 }
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00004053
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004054 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
4055 if (IVars[i]->isBitField()) {
4056 ObjCIvarDecl *IV = IVars[i];
4057 Result += "\tstruct ";
4058 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
4059 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
4060 // skip over ivar bitfields in this group.
4061 SKIP_BITFIELDS(i , e, IVars);
4062 }
4063 else
4064 RewriteObjCFieldDecl(IVars[i], Result);
4065 }
Fariborz Jahanian245534d2012-02-12 21:36:23 +00004066
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004067 Result += "};\n";
4068 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4069 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004070 // Mark this struct as having been generated.
4071 if (!ObjCSynthesizedStructs.insert(CDecl))
4072 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004073}
4074
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004075/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4076/// have been referenced in an ivar access expression.
4077void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4078 std::string &Result) {
4079 // write out ivar offset symbols which have been referenced in an ivar
4080 // access expression.
4081 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4082 if (Ivars.empty())
4083 return;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004084
4085 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004086 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
4087 e = Ivars.end(); i != e; i++) {
4088 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004089 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4090 unsigned GroupNo = 0;
4091 if (IvarDecl->isBitField()) {
4092 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4093 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4094 continue;
4095 }
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004096 Result += "\n";
4097 if (LangOpts.MicrosoftExt)
4098 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004099 Result += "extern \"C\" ";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004100 if (LangOpts.MicrosoftExt &&
4101 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004102 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4103 Result += "__declspec(dllimport) ";
4104
Fariborz Jahanian38c59102012-03-27 16:21:30 +00004105 Result += "unsigned long ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004106 if (IvarDecl->isBitField()) {
4107 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4108 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4109 }
4110 else
4111 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00004112 Result += ";";
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004113 }
4114}
4115
Fariborz Jahanian11671902012-02-07 17:11:38 +00004116//===----------------------------------------------------------------------===//
4117// Meta Data Emission
4118//===----------------------------------------------------------------------===//
4119
4120
4121/// RewriteImplementations - This routine rewrites all method implementations
4122/// and emits meta-data.
4123
4124void RewriteModernObjC::RewriteImplementations() {
4125 int ClsDefCount = ClassImplementation.size();
4126 int CatDefCount = CategoryImplementation.size();
4127
4128 // Rewrite implemented methods
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004129 for (int i = 0; i < ClsDefCount; i++) {
4130 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4131 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4132 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00004133 assert(false &&
4134 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004135 RewriteImplementationDecl(OIMP);
4136 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004137
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004138 for (int i = 0; i < CatDefCount; i++) {
4139 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4140 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4141 if (CDecl->isImplicitInterfaceDecl())
4142 assert(false &&
4143 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004144 RewriteImplementationDecl(CIMP);
4145 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004146}
4147
4148void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4149 const std::string &Name,
4150 ValueDecl *VD, bool def) {
4151 assert(BlockByRefDeclNo.count(VD) &&
4152 "RewriteByRefString: ByRef decl missing");
4153 if (def)
4154 ResultStr += "struct ";
4155 ResultStr += "__Block_byref_" + Name +
4156 "_" + utostr(BlockByRefDeclNo[VD]) ;
4157}
4158
4159static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4160 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4161 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4162 return false;
4163}
4164
4165std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4166 StringRef funcName,
4167 std::string Tag) {
4168 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00004169 QualType RT = AFT->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004170 std::string StructRef = "struct " + Tag;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004171 SourceLocation BlockLoc = CE->getExprLoc();
4172 std::string S;
4173 ConvertSourceLocationToLineDirective(BlockLoc, S);
4174
4175 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4176 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004177
4178 BlockDecl *BD = CE->getBlockDecl();
4179
4180 if (isa<FunctionNoProtoType>(AFT)) {
4181 // No user-supplied arguments. Still need to pass in a pointer to the
4182 // block (to reference imported block decl refs).
4183 S += "(" + StructRef + " *__cself)";
4184 } else if (BD->param_empty()) {
4185 S += "(" + StructRef + " *__cself)";
4186 } else {
4187 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4188 assert(FT && "SynthesizeBlockFunc: No function proto");
4189 S += '(';
4190 // first add the implicit argument.
4191 S += StructRef + " *__cself, ";
4192 std::string ParamStr;
4193 for (BlockDecl::param_iterator AI = BD->param_begin(),
4194 E = BD->param_end(); AI != E; ++AI) {
4195 if (AI != BD->param_begin()) S += ", ";
4196 ParamStr = (*AI)->getNameAsString();
4197 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00004198 (void)convertBlockPointerToFunctionPointer(QT);
4199 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004200 S += ParamStr;
4201 }
4202 if (FT->isVariadic()) {
4203 if (!BD->param_empty()) S += ", ";
4204 S += "...";
4205 }
4206 S += ')';
4207 }
4208 S += " {\n";
4209
4210 // Create local declarations to avoid rewriting all closure decl ref exprs.
4211 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00004212 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004213 E = BlockByRefDecls.end(); I != E; ++I) {
4214 S += " ";
4215 std::string Name = (*I)->getNameAsString();
4216 std::string TypeString;
4217 RewriteByRefString(TypeString, Name, (*I));
4218 TypeString += " *";
4219 Name = TypeString + Name;
4220 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4221 }
4222 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004223 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004224 E = BlockByCopyDecls.end(); I != E; ++I) {
4225 S += " ";
4226 // Handle nested closure invocation. For example:
4227 //
4228 // void (^myImportedClosure)(void);
4229 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4230 //
4231 // void (^anotherClosure)(void);
4232 // anotherClosure = ^(void) {
4233 // myImportedClosure(); // import and invoke the closure
4234 // };
4235 //
4236 if (isTopLevelBlockPointerType((*I)->getType())) {
4237 RewriteBlockPointerTypeVariable(S, (*I));
4238 S += " = (";
4239 RewriteBlockPointerType(S, (*I)->getType());
4240 S += ")";
4241 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4242 }
4243 else {
4244 std::string Name = (*I)->getNameAsString();
4245 QualType QT = (*I)->getType();
4246 if (HasLocalVariableExternalStorage(*I))
4247 QT = Context->getPointerType(QT);
4248 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4249 S += Name + " = __cself->" +
4250 (*I)->getNameAsString() + "; // bound by copy\n";
4251 }
4252 }
4253 std::string RewrittenStr = RewrittenBlockExprs[CE];
4254 const char *cstr = RewrittenStr.c_str();
4255 while (*cstr++ != '{') ;
4256 S += cstr;
4257 S += "\n";
4258 return S;
4259}
4260
4261std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4262 StringRef funcName,
4263 std::string Tag) {
4264 std::string StructRef = "struct " + Tag;
4265 std::string S = "static void __";
4266
4267 S += funcName;
4268 S += "_block_copy_" + utostr(i);
4269 S += "(" + StructRef;
4270 S += "*dst, " + StructRef;
4271 S += "*src) {";
4272 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4273 E = ImportedBlockDecls.end(); I != E; ++I) {
4274 ValueDecl *VD = (*I);
4275 S += "_Block_object_assign((void*)&dst->";
4276 S += (*I)->getNameAsString();
4277 S += ", (void*)src->";
4278 S += (*I)->getNameAsString();
4279 if (BlockByRefDeclsPtrSet.count((*I)))
4280 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4281 else if (VD->getType()->isBlockPointerType())
4282 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4283 else
4284 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4285 }
4286 S += "}\n";
4287
4288 S += "\nstatic void __";
4289 S += funcName;
4290 S += "_block_dispose_" + utostr(i);
4291 S += "(" + StructRef;
4292 S += "*src) {";
4293 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4294 E = ImportedBlockDecls.end(); I != E; ++I) {
4295 ValueDecl *VD = (*I);
4296 S += "_Block_object_dispose((void*)src->";
4297 S += (*I)->getNameAsString();
4298 if (BlockByRefDeclsPtrSet.count((*I)))
4299 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4300 else if (VD->getType()->isBlockPointerType())
4301 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4302 else
4303 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4304 }
4305 S += "}\n";
4306 return S;
4307}
4308
4309std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4310 std::string Desc) {
4311 std::string S = "\nstruct " + Tag;
4312 std::string Constructor = " " + Tag;
4313
4314 S += " {\n struct __block_impl impl;\n";
4315 S += " struct " + Desc;
4316 S += "* Desc;\n";
4317
4318 Constructor += "(void *fp, "; // Invoke function pointer.
4319 Constructor += "struct " + Desc; // Descriptor pointer.
4320 Constructor += " *desc";
4321
4322 if (BlockDeclRefs.size()) {
4323 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004324 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004325 E = BlockByCopyDecls.end(); I != E; ++I) {
4326 S += " ";
4327 std::string FieldName = (*I)->getNameAsString();
4328 std::string ArgName = "_" + FieldName;
4329 // Handle nested closure invocation. For example:
4330 //
4331 // void (^myImportedBlock)(void);
4332 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4333 //
4334 // void (^anotherBlock)(void);
4335 // anotherBlock = ^(void) {
4336 // myImportedBlock(); // import and invoke the closure
4337 // };
4338 //
4339 if (isTopLevelBlockPointerType((*I)->getType())) {
4340 S += "struct __block_impl *";
4341 Constructor += ", void *" + ArgName;
4342 } else {
4343 QualType QT = (*I)->getType();
4344 if (HasLocalVariableExternalStorage(*I))
4345 QT = Context->getPointerType(QT);
4346 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4347 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4348 Constructor += ", " + ArgName;
4349 }
4350 S += FieldName + ";\n";
4351 }
4352 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004353 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004354 E = BlockByRefDecls.end(); I != E; ++I) {
4355 S += " ";
4356 std::string FieldName = (*I)->getNameAsString();
4357 std::string ArgName = "_" + FieldName;
4358 {
4359 std::string TypeString;
4360 RewriteByRefString(TypeString, FieldName, (*I));
4361 TypeString += " *";
4362 FieldName = TypeString + FieldName;
4363 ArgName = TypeString + ArgName;
4364 Constructor += ", " + ArgName;
4365 }
4366 S += FieldName + "; // by ref\n";
4367 }
4368 // Finish writing the constructor.
4369 Constructor += ", int flags=0)";
4370 // Initialize all "by copy" arguments.
4371 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00004372 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004373 E = BlockByCopyDecls.end(); I != E; ++I) {
4374 std::string Name = (*I)->getNameAsString();
4375 if (firsTime) {
4376 Constructor += " : ";
4377 firsTime = false;
4378 }
4379 else
4380 Constructor += ", ";
4381 if (isTopLevelBlockPointerType((*I)->getType()))
4382 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4383 else
4384 Constructor += Name + "(_" + Name + ")";
4385 }
4386 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00004387 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004388 E = BlockByRefDecls.end(); I != E; ++I) {
4389 std::string Name = (*I)->getNameAsString();
4390 if (firsTime) {
4391 Constructor += " : ";
4392 firsTime = false;
4393 }
4394 else
4395 Constructor += ", ";
4396 Constructor += Name + "(_" + Name + "->__forwarding)";
4397 }
4398
4399 Constructor += " {\n";
4400 if (GlobalVarDecl)
4401 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4402 else
4403 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4404 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4405
4406 Constructor += " Desc = desc;\n";
4407 } else {
4408 // Finish writing the constructor.
4409 Constructor += ", int flags=0) {\n";
4410 if (GlobalVarDecl)
4411 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4412 else
4413 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4414 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4415 Constructor += " Desc = desc;\n";
4416 }
4417 Constructor += " ";
4418 Constructor += "}\n";
4419 S += Constructor;
4420 S += "};\n";
4421 return S;
4422}
4423
4424std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4425 std::string ImplTag, int i,
4426 StringRef FunName,
4427 unsigned hasCopy) {
4428 std::string S = "\nstatic struct " + DescTag;
4429
Fariborz Jahanian2e7f6382012-05-03 21:44:12 +00004430 S += " {\n size_t reserved;\n";
4431 S += " size_t Block_size;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004432 if (hasCopy) {
4433 S += " void (*copy)(struct ";
4434 S += ImplTag; S += "*, struct ";
4435 S += ImplTag; S += "*);\n";
4436
4437 S += " void (*dispose)(struct ";
4438 S += ImplTag; S += "*);\n";
4439 }
4440 S += "} ";
4441
4442 S += DescTag + "_DATA = { 0, sizeof(struct ";
4443 S += ImplTag + ")";
4444 if (hasCopy) {
4445 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4446 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4447 }
4448 S += "};\n";
4449 return S;
4450}
4451
4452void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4453 StringRef FunName) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004454 bool RewriteSC = (GlobalVarDecl &&
4455 !Blocks.empty() &&
4456 GlobalVarDecl->getStorageClass() == SC_Static &&
4457 GlobalVarDecl->getType().getCVRQualifiers());
4458 if (RewriteSC) {
4459 std::string SC(" void __");
4460 SC += GlobalVarDecl->getNameAsString();
4461 SC += "() {}";
4462 InsertText(FunLocStart, SC);
4463 }
4464
4465 // Insert closures that were part of the function.
4466 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4467 CollectBlockDeclRefInfo(Blocks[i]);
4468 // Need to copy-in the inner copied-in variables not actually used in this
4469 // block.
4470 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00004471 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian11671902012-02-07 17:11:38 +00004472 ValueDecl *VD = Exp->getDecl();
4473 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00004474 if (!VD->hasAttr<BlocksAttr>()) {
4475 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4476 BlockByCopyDeclsPtrSet.insert(VD);
4477 BlockByCopyDecls.push_back(VD);
4478 }
4479 continue;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004480 }
John McCall113bee02012-03-10 09:33:50 +00004481
4482 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004483 BlockByRefDeclsPtrSet.insert(VD);
4484 BlockByRefDecls.push_back(VD);
4485 }
John McCall113bee02012-03-10 09:33:50 +00004486
Fariborz Jahanian11671902012-02-07 17:11:38 +00004487 // imported objects in the inner blocks not used in the outer
4488 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00004489 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00004490 VD->getType()->isBlockPointerType())
4491 ImportedBlockDecls.insert(VD);
4492 }
4493
4494 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4495 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4496
4497 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4498
4499 InsertText(FunLocStart, CI);
4500
4501 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4502
4503 InsertText(FunLocStart, CF);
4504
4505 if (ImportedBlockDecls.size()) {
4506 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4507 InsertText(FunLocStart, HF);
4508 }
4509 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4510 ImportedBlockDecls.size() > 0);
4511 InsertText(FunLocStart, BD);
4512
4513 BlockDeclRefs.clear();
4514 BlockByRefDecls.clear();
4515 BlockByRefDeclsPtrSet.clear();
4516 BlockByCopyDecls.clear();
4517 BlockByCopyDeclsPtrSet.clear();
4518 ImportedBlockDecls.clear();
4519 }
4520 if (RewriteSC) {
4521 // Must insert any 'const/volatile/static here. Since it has been
4522 // removed as result of rewriting of block literals.
4523 std::string SC;
4524 if (GlobalVarDecl->getStorageClass() == SC_Static)
4525 SC = "static ";
4526 if (GlobalVarDecl->getType().isConstQualified())
4527 SC += "const ";
4528 if (GlobalVarDecl->getType().isVolatileQualified())
4529 SC += "volatile ";
4530 if (GlobalVarDecl->getType().isRestrictQualified())
4531 SC += "restrict ";
4532 InsertText(FunLocStart, SC);
4533 }
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004534 if (GlobalConstructionExp) {
4535 // extra fancy dance for global literal expression.
4536
4537 // Always the latest block expression on the block stack.
4538 std::string Tag = "__";
4539 Tag += FunName;
4540 Tag += "_block_impl_";
4541 Tag += utostr(Blocks.size()-1);
4542 std::string globalBuf = "static ";
4543 globalBuf += Tag; globalBuf += " ";
4544 std::string SStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004545
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004546 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00004547 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004548 PrintingPolicy(LangOpts));
4549 globalBuf += constructorExprBuf.str();
4550 globalBuf += ";\n";
4551 InsertText(FunLocStart, globalBuf);
4552 GlobalConstructionExp = 0;
4553 }
4554
Fariborz Jahanian11671902012-02-07 17:11:38 +00004555 Blocks.clear();
4556 InnerDeclRefsCount.clear();
4557 InnerDeclRefs.clear();
4558 RewrittenBlockExprs.clear();
4559}
4560
4561void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahaniane49a42c2012-04-25 17:56:48 +00004562 SourceLocation FunLocStart =
4563 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4564 : FD->getTypeSpecStartLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004565 StringRef FuncName = FD->getName();
4566
4567 SynthesizeBlockLiterals(FunLocStart, FuncName);
4568}
4569
4570static void BuildUniqueMethodName(std::string &Name,
4571 ObjCMethodDecl *MD) {
4572 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4573 Name = IFace->getName();
4574 Name += "__" + MD->getSelector().getAsString();
4575 // Convert colons to underscores.
4576 std::string::size_type loc = 0;
4577 while ((loc = Name.find(":", loc)) != std::string::npos)
4578 Name.replace(loc, 1, "_");
4579}
4580
4581void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4582 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4583 //SourceLocation FunLocStart = MD->getLocStart();
4584 SourceLocation FunLocStart = MD->getLocStart();
4585 std::string FuncName;
4586 BuildUniqueMethodName(FuncName, MD);
4587 SynthesizeBlockLiterals(FunLocStart, FuncName);
4588}
4589
4590void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4591 for (Stmt::child_range CI = S->children(); CI; ++CI)
4592 if (*CI) {
4593 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4594 GetBlockDeclRefExprs(CBE->getBody());
4595 else
4596 GetBlockDeclRefExprs(*CI);
4597 }
4598 // Handle specific things.
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004599 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4600 if (DRE->refersToEnclosingLocal()) {
4601 // FIXME: Handle enums.
4602 if (!isa<FunctionDecl>(DRE->getDecl()))
4603 BlockDeclRefs.push_back(DRE);
4604 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4605 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004606 }
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004607 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004608
4609 return;
4610}
4611
Craig Topper5603df42013-07-05 19:34:19 +00004612void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4613 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004614 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4615 for (Stmt::child_range CI = S->children(); CI; ++CI)
4616 if (*CI) {
4617 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4618 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4619 GetInnerBlockDeclRefExprs(CBE->getBody(),
4620 InnerBlockDeclRefs,
4621 InnerContexts);
4622 }
4623 else
4624 GetInnerBlockDeclRefExprs(*CI,
4625 InnerBlockDeclRefs,
4626 InnerContexts);
4627
4628 }
4629 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00004630 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4631 if (DRE->refersToEnclosingLocal()) {
4632 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4633 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4634 InnerBlockDeclRefs.push_back(DRE);
4635 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4636 if (Var->isFunctionOrMethodVarDecl())
4637 ImportedLocalExternalDecls.insert(Var);
4638 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004639 }
4640
4641 return;
4642}
4643
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004644/// convertObjCTypeToCStyleType - This routine converts such objc types
4645/// as qualified objects, and blocks to their closest c/c++ types that
4646/// it can. It returns true if input type was modified.
4647bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4648 QualType oldT = T;
4649 convertBlockPointerToFunctionPointer(T);
4650 if (T->isFunctionPointerType()) {
4651 QualType PointeeTy;
4652 if (const PointerType* PT = T->getAs<PointerType>()) {
4653 PointeeTy = PT->getPointeeType();
4654 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4655 T = convertFunctionTypeOfBlocks(FT);
4656 T = Context->getPointerType(T);
4657 }
4658 }
4659 }
4660
4661 convertToUnqualifiedObjCType(T);
4662 return T != oldT;
4663}
4664
Fariborz Jahanian11671902012-02-07 17:11:38 +00004665/// convertFunctionTypeOfBlocks - This routine converts a function type
4666/// whose result type may be a block pointer or whose argument type(s)
4667/// might be block pointers to an equivalent function type replacing
4668/// all block pointers to function pointers.
4669QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4670 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4671 // FTP will be null for closures that don't take arguments.
4672 // Generate a funky cast.
4673 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00004674 QualType Res = FT->getReturnType();
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004675 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004676
4677 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004678 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4679 E = FTP->param_type_end();
4680 I && (I != E); ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004681 QualType t = *I;
4682 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004683 if (convertObjCTypeToCStyleType(t))
4684 modified = true;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004685 ArgTypes.push_back(t);
4686 }
4687 }
4688 QualType FuncType;
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004689 if (modified)
Jordan Rose5c382722013-03-08 21:51:21 +00004690 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004691 else FuncType = QualType(FT, 0);
4692 return FuncType;
4693}
4694
4695Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4696 // Navigate to relevant type information.
4697 const BlockPointerType *CPT = 0;
4698
4699 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4700 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004701 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4702 CPT = MExpr->getType()->getAs<BlockPointerType>();
4703 }
4704 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4705 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4706 }
4707 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4708 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4709 else if (const ConditionalOperator *CEXPR =
4710 dyn_cast<ConditionalOperator>(BlockExp)) {
4711 Expr *LHSExp = CEXPR->getLHS();
4712 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4713 Expr *RHSExp = CEXPR->getRHS();
4714 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4715 Expr *CONDExp = CEXPR->getCond();
4716 ConditionalOperator *CondExpr =
4717 new (Context) ConditionalOperator(CONDExp,
4718 SourceLocation(), cast<Expr>(LHSStmt),
4719 SourceLocation(), cast<Expr>(RHSStmt),
4720 Exp->getType(), VK_RValue, OK_Ordinary);
4721 return CondExpr;
4722 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4723 CPT = IRE->getType()->getAs<BlockPointerType>();
4724 } else if (const PseudoObjectExpr *POE
4725 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4726 CPT = POE->getType()->castAs<BlockPointerType>();
4727 } else {
4728 assert(1 && "RewriteBlockClass: Bad type");
4729 }
4730 assert(CPT && "RewriteBlockClass: Bad type");
4731 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4732 assert(FT && "RewriteBlockClass: Bad type");
4733 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4734 // FTP will be null for closures that don't take arguments.
4735
4736 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4737 SourceLocation(), SourceLocation(),
4738 &Context->Idents.get("__block_impl"));
4739 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4740
4741 // Generate a funky cast.
4742 SmallVector<QualType, 8> ArgTypes;
4743
4744 // Push the block argument type.
4745 ArgTypes.push_back(PtrBlock);
4746 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004747 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4748 E = FTP->param_type_end();
4749 I && (I != E); ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004750 QualType t = *I;
4751 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4752 if (!convertBlockPointerToFunctionPointer(t))
4753 convertToUnqualifiedObjCType(t);
4754 ArgTypes.push_back(t);
4755 }
4756 }
4757 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00004758 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004759
4760 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4761
4762 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4763 CK_BitCast,
4764 const_cast<Expr*>(BlockExp));
4765 // Don't forget the parens to enforce the proper binding.
4766 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4767 BlkCast);
4768 //PE->dump();
4769
4770 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4771 SourceLocation(),
4772 &Context->Idents.get("FuncPtr"),
4773 Context->VoidPtrTy, 0,
4774 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004775 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004776 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4777 FD->getType(), VK_LValue,
4778 OK_Ordinary);
4779
4780
4781 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4782 CK_BitCast, ME);
4783 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4784
4785 SmallVector<Expr*, 8> BlkExprs;
4786 // Add the implicit argument.
4787 BlkExprs.push_back(BlkCast);
4788 // Add the user arguments.
4789 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4790 E = Exp->arg_end(); I != E; ++I) {
4791 BlkExprs.push_back(*I);
4792 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004793 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004794 Exp->getType(), VK_RValue,
4795 SourceLocation());
4796 return CE;
4797}
4798
4799// We need to return the rewritten expression to handle cases where the
John McCall113bee02012-03-10 09:33:50 +00004800// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian11671902012-02-07 17:11:38 +00004801// For example:
4802//
4803// int main() {
4804// __block Foo *f;
4805// __block int i;
4806//
4807// void (^myblock)() = ^() {
John McCall113bee02012-03-10 09:33:50 +00004808// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian11671902012-02-07 17:11:38 +00004809// i = 77;
4810// };
4811//}
John McCall113bee02012-03-10 09:33:50 +00004812Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004813 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4814 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00004815 ValueDecl *VD = DeclRefExp->getDecl();
4816 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004817
4818 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4819 SourceLocation(),
4820 &Context->Idents.get("__forwarding"),
4821 Context->VoidPtrTy, 0,
4822 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004823 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004824 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4825 FD, SourceLocation(),
4826 FD->getType(), VK_LValue,
4827 OK_Ordinary);
4828
4829 StringRef Name = VD->getName();
4830 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4831 &Context->Idents.get(Name),
4832 Context->VoidPtrTy, 0,
4833 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004834 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004835 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4836 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4837
4838
4839
4840 // Need parens to enforce precedence.
4841 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4842 DeclRefExp->getExprLoc(),
4843 ME);
4844 ReplaceStmt(DeclRefExp, PE);
4845 return PE;
4846}
4847
4848// Rewrites the imported local variable V with external storage
4849// (static, extern, etc.) as *V
4850//
4851Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4852 ValueDecl *VD = DRE->getDecl();
4853 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4854 if (!ImportedLocalExternalDecls.count(Var))
4855 return DRE;
4856 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4857 VK_LValue, OK_Ordinary,
4858 DRE->getLocation());
4859 // Need parens to enforce precedence.
4860 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4861 Exp);
4862 ReplaceStmt(DRE, PE);
4863 return PE;
4864}
4865
4866void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4867 SourceLocation LocStart = CE->getLParenLoc();
4868 SourceLocation LocEnd = CE->getRParenLoc();
4869
4870 // Need to avoid trying to rewrite synthesized casts.
4871 if (LocStart.isInvalid())
4872 return;
4873 // Need to avoid trying to rewrite casts contained in macros.
4874 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4875 return;
4876
4877 const char *startBuf = SM->getCharacterData(LocStart);
4878 const char *endBuf = SM->getCharacterData(LocEnd);
4879 QualType QT = CE->getType();
4880 const Type* TypePtr = QT->getAs<Type>();
4881 if (isa<TypeOfExprType>(TypePtr)) {
4882 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4883 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4884 std::string TypeAsString = "(";
4885 RewriteBlockPointerType(TypeAsString, QT);
4886 TypeAsString += ")";
4887 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4888 return;
4889 }
4890 // advance the location to startArgList.
4891 const char *argPtr = startBuf;
4892
4893 while (*argPtr++ && (argPtr < endBuf)) {
4894 switch (*argPtr) {
4895 case '^':
4896 // Replace the '^' with '*'.
4897 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4898 ReplaceText(LocStart, 1, "*");
4899 break;
4900 }
4901 }
4902 return;
4903}
4904
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004905void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4906 CastKind CastKind = IC->getCastKind();
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004907 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4908 CastKind != CK_AnyPointerToBlockPointerCast)
4909 return;
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004910
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004911 QualType QT = IC->getType();
4912 (void)convertBlockPointerToFunctionPointer(QT);
4913 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4914 std::string Str = "(";
4915 Str += TypeString;
4916 Str += ")";
4917 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4918
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004919 return;
4920}
4921
Fariborz Jahanian11671902012-02-07 17:11:38 +00004922void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4923 SourceLocation DeclLoc = FD->getLocation();
4924 unsigned parenCount = 0;
4925
4926 // We have 1 or more arguments that have closure pointers.
4927 const char *startBuf = SM->getCharacterData(DeclLoc);
4928 const char *startArgList = strchr(startBuf, '(');
4929
4930 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4931
4932 parenCount++;
4933 // advance the location to startArgList.
4934 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4935 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4936
4937 const char *argPtr = startArgList;
4938
4939 while (*argPtr++ && parenCount) {
4940 switch (*argPtr) {
4941 case '^':
4942 // Replace the '^' with '*'.
4943 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4944 ReplaceText(DeclLoc, 1, "*");
4945 break;
4946 case '(':
4947 parenCount++;
4948 break;
4949 case ')':
4950 parenCount--;
4951 break;
4952 }
4953 }
4954 return;
4955}
4956
4957bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4958 const FunctionProtoType *FTP;
4959 const PointerType *PT = QT->getAs<PointerType>();
4960 if (PT) {
4961 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4962 } else {
4963 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4964 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4965 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4966 }
4967 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004968 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4969 E = FTP->param_type_end();
4970 I != E; ++I)
Fariborz Jahanian11671902012-02-07 17:11:38 +00004971 if (isTopLevelBlockPointerType(*I))
4972 return true;
4973 }
4974 return false;
4975}
4976
4977bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4978 const FunctionProtoType *FTP;
4979 const PointerType *PT = QT->getAs<PointerType>();
4980 if (PT) {
4981 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4982 } else {
4983 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4984 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4985 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4986 }
4987 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004988 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4989 E = FTP->param_type_end();
4990 I != E; ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004991 if ((*I)->isObjCQualifiedIdType())
4992 return true;
4993 if ((*I)->isObjCObjectPointerType() &&
4994 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
4995 return true;
4996 }
4997
4998 }
4999 return false;
5000}
5001
5002void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
5003 const char *&RParen) {
5004 const char *argPtr = strchr(Name, '(');
5005 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
5006
5007 LParen = argPtr; // output the start.
5008 argPtr++; // skip past the left paren.
5009 unsigned parenCount = 1;
5010
5011 while (*argPtr && parenCount) {
5012 switch (*argPtr) {
5013 case '(': parenCount++; break;
5014 case ')': parenCount--; break;
5015 default: break;
5016 }
5017 if (parenCount) argPtr++;
5018 }
5019 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5020 RParen = argPtr; // output the end
5021}
5022
5023void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5024 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5025 RewriteBlockPointerFunctionArgs(FD);
5026 return;
5027 }
5028 // Handle Variables and Typedefs.
5029 SourceLocation DeclLoc = ND->getLocation();
5030 QualType DeclT;
5031 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5032 DeclT = VD->getType();
5033 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
5034 DeclT = TDD->getUnderlyingType();
5035 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5036 DeclT = FD->getType();
5037 else
5038 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
5039
5040 const char *startBuf = SM->getCharacterData(DeclLoc);
5041 const char *endBuf = startBuf;
5042 // scan backward (from the decl location) for the end of the previous decl.
5043 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5044 startBuf--;
5045 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
5046 std::string buf;
5047 unsigned OrigLength=0;
5048 // *startBuf != '^' if we are dealing with a pointer to function that
5049 // may take block argument types (which will be handled below).
5050 if (*startBuf == '^') {
5051 // Replace the '^' with '*', computing a negative offset.
5052 buf = '*';
5053 startBuf++;
5054 OrigLength++;
5055 }
5056 while (*startBuf != ')') {
5057 buf += *startBuf;
5058 startBuf++;
5059 OrigLength++;
5060 }
5061 buf += ')';
5062 OrigLength++;
5063
5064 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5065 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
5066 // Replace the '^' with '*' for arguments.
5067 // Replace id<P> with id/*<>*/
5068 DeclLoc = ND->getLocation();
5069 startBuf = SM->getCharacterData(DeclLoc);
5070 const char *argListBegin, *argListEnd;
5071 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5072 while (argListBegin < argListEnd) {
5073 if (*argListBegin == '^')
5074 buf += '*';
5075 else if (*argListBegin == '<') {
5076 buf += "/*";
5077 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005078 OrigLength++;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005079 while (*argListBegin != '>') {
5080 buf += *argListBegin++;
5081 OrigLength++;
5082 }
5083 buf += *argListBegin;
5084 buf += "*/";
5085 }
5086 else
5087 buf += *argListBegin;
5088 argListBegin++;
5089 OrigLength++;
5090 }
5091 buf += ')';
5092 OrigLength++;
5093 }
5094 ReplaceText(Start, OrigLength, buf);
5095
5096 return;
5097}
5098
5099
5100/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5101/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5102/// struct Block_byref_id_object *src) {
5103/// _Block_object_assign (&_dest->object, _src->object,
5104/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5105/// [|BLOCK_FIELD_IS_WEAK]) // object
5106/// _Block_object_assign(&_dest->object, _src->object,
5107/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5108/// [|BLOCK_FIELD_IS_WEAK]) // block
5109/// }
5110/// And:
5111/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5112/// _Block_object_dispose(_src->object,
5113/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5114/// [|BLOCK_FIELD_IS_WEAK]) // object
5115/// _Block_object_dispose(_src->object,
5116/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5117/// [|BLOCK_FIELD_IS_WEAK]) // block
5118/// }
5119
5120std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5121 int flag) {
5122 std::string S;
5123 if (CopyDestroyCache.count(flag))
5124 return S;
5125 CopyDestroyCache.insert(flag);
5126 S = "static void __Block_byref_id_object_copy_";
5127 S += utostr(flag);
5128 S += "(void *dst, void *src) {\n";
5129
5130 // offset into the object pointer is computed as:
5131 // void * + void* + int + int + void* + void *
5132 unsigned IntSize =
5133 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5134 unsigned VoidPtrSize =
5135 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5136
5137 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5138 S += " _Block_object_assign((char*)dst + ";
5139 S += utostr(offset);
5140 S += ", *(void * *) ((char*)src + ";
5141 S += utostr(offset);
5142 S += "), ";
5143 S += utostr(flag);
5144 S += ");\n}\n";
5145
5146 S += "static void __Block_byref_id_object_dispose_";
5147 S += utostr(flag);
5148 S += "(void *src) {\n";
5149 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5150 S += utostr(offset);
5151 S += "), ";
5152 S += utostr(flag);
5153 S += ");\n}\n";
5154 return S;
5155}
5156
5157/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5158/// the declaration into:
5159/// struct __Block_byref_ND {
5160/// void *__isa; // NULL for everything except __weak pointers
5161/// struct __Block_byref_ND *__forwarding;
5162/// int32_t __flags;
5163/// int32_t __size;
5164/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5165/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5166/// typex ND;
5167/// };
5168///
5169/// It then replaces declaration of ND variable with:
5170/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5171/// __size=sizeof(struct __Block_byref_ND),
5172/// ND=initializer-if-any};
5173///
5174///
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005175void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5176 bool lastDecl) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005177 int flag = 0;
5178 int isa = 0;
5179 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5180 if (DeclLoc.isInvalid())
5181 // If type location is missing, it is because of missing type (a warning).
5182 // Use variable's location which is good for this case.
5183 DeclLoc = ND->getLocation();
5184 const char *startBuf = SM->getCharacterData(DeclLoc);
5185 SourceLocation X = ND->getLocEnd();
5186 X = SM->getExpansionLoc(X);
5187 const char *endBuf = SM->getCharacterData(X);
5188 std::string Name(ND->getNameAsString());
5189 std::string ByrefType;
5190 RewriteByRefString(ByrefType, Name, ND, true);
5191 ByrefType += " {\n";
5192 ByrefType += " void *__isa;\n";
5193 RewriteByRefString(ByrefType, Name, ND);
5194 ByrefType += " *__forwarding;\n";
5195 ByrefType += " int __flags;\n";
5196 ByrefType += " int __size;\n";
5197 // Add void *__Block_byref_id_object_copy;
5198 // void *__Block_byref_id_object_dispose; if needed.
5199 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005200 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005201 if (HasCopyAndDispose) {
5202 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5203 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5204 }
5205
5206 QualType T = Ty;
5207 (void)convertBlockPointerToFunctionPointer(T);
5208 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5209
5210 ByrefType += " " + Name + ";\n";
5211 ByrefType += "};\n";
5212 // Insert this type in global scope. It is needed by helper function.
5213 SourceLocation FunLocStart;
5214 if (CurFunctionDef)
Fariborz Jahanianca357d92012-04-19 00:50:01 +00005215 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005216 else {
5217 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5218 FunLocStart = CurMethodDef->getLocStart();
5219 }
5220 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005221
Fariborz Jahanian11671902012-02-07 17:11:38 +00005222 if (Ty.isObjCGCWeak()) {
5223 flag |= BLOCK_FIELD_IS_WEAK;
5224 isa = 1;
5225 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005226 if (HasCopyAndDispose) {
5227 flag = BLOCK_BYREF_CALLER;
5228 QualType Ty = ND->getType();
5229 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5230 if (Ty->isBlockPointerType())
5231 flag |= BLOCK_FIELD_IS_BLOCK;
5232 else
5233 flag |= BLOCK_FIELD_IS_OBJECT;
5234 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5235 if (!HF.empty())
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005236 Preamble += HF;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005237 }
5238
5239 // struct __Block_byref_ND ND =
5240 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5241 // initializer-if-any};
5242 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian5811fd62012-04-11 23:57:12 +00005243 // FIXME. rewriter does not support __block c++ objects which
5244 // require construction.
Fariborz Jahanian16d0d6c2012-04-26 23:20:25 +00005245 if (hasInit)
5246 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5247 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5248 if (CXXDecl && CXXDecl->isDefaultConstructor())
5249 hasInit = false;
5250 }
5251
Fariborz Jahanian11671902012-02-07 17:11:38 +00005252 unsigned flags = 0;
5253 if (HasCopyAndDispose)
5254 flags |= BLOCK_HAS_COPY_DISPOSE;
5255 Name = ND->getNameAsString();
5256 ByrefType.clear();
5257 RewriteByRefString(ByrefType, Name, ND);
5258 std::string ForwardingCastType("(");
5259 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005260 ByrefType += " " + Name + " = {(void*)";
5261 ByrefType += utostr(isa);
5262 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5263 ByrefType += utostr(flags);
5264 ByrefType += ", ";
5265 ByrefType += "sizeof(";
5266 RewriteByRefString(ByrefType, Name, ND);
5267 ByrefType += ")";
5268 if (HasCopyAndDispose) {
5269 ByrefType += ", __Block_byref_id_object_copy_";
5270 ByrefType += utostr(flag);
5271 ByrefType += ", __Block_byref_id_object_dispose_";
5272 ByrefType += utostr(flag);
5273 }
5274
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005275 if (!firstDecl) {
5276 // In multiple __block declarations, and for all but 1st declaration,
5277 // find location of the separating comma. This would be start location
5278 // where new text is to be inserted.
5279 DeclLoc = ND->getLocation();
5280 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5281 const char *commaBuf = startDeclBuf;
5282 while (*commaBuf != ',')
5283 commaBuf--;
5284 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5285 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5286 startBuf = commaBuf;
5287 }
5288
Fariborz Jahanian11671902012-02-07 17:11:38 +00005289 if (!hasInit) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005290 ByrefType += "};\n";
5291 unsigned nameSize = Name.size();
5292 // for block or function pointer declaration. Name is aleady
5293 // part of the declaration.
5294 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5295 nameSize = 1;
5296 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5297 }
5298 else {
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005299 ByrefType += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005300 SourceLocation startLoc;
5301 Expr *E = ND->getInit();
5302 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5303 startLoc = ECE->getLParenLoc();
5304 else
5305 startLoc = E->getLocStart();
5306 startLoc = SM->getExpansionLoc(startLoc);
5307 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005308 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005309
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005310 const char separator = lastDecl ? ';' : ',';
5311 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5312 const char *separatorBuf = strchr(startInitializerBuf, separator);
5313 assert((*separatorBuf == separator) &&
5314 "RewriteByRefVar: can't find ';' or ','");
5315 SourceLocation separatorLoc =
5316 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5317
5318 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00005319 }
5320 return;
5321}
5322
5323void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5324 // Add initializers for any closure decl refs.
5325 GetBlockDeclRefExprs(Exp->getBody());
5326 if (BlockDeclRefs.size()) {
5327 // Unique all "by copy" declarations.
5328 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005329 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005330 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5331 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5332 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5333 }
5334 }
5335 // Unique all "by ref" declarations.
5336 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005337 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005338 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5339 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5340 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5341 }
5342 }
5343 // Find any imported blocks...they will need special attention.
5344 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005345 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005346 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5347 BlockDeclRefs[i]->getType()->isBlockPointerType())
5348 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5349 }
5350}
5351
5352FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5353 IdentifierInfo *ID = &Context->Idents.get(name);
5354 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5355 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5356 SourceLocation(), ID, FType, 0, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005357 false, false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005358}
5359
5360Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00005361 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005362
Fariborz Jahanian11671902012-02-07 17:11:38 +00005363 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005364
Fariborz Jahanian11671902012-02-07 17:11:38 +00005365 Blocks.push_back(Exp);
5366
5367 CollectBlockDeclRefInfo(Exp);
5368
5369 // Add inner imported variables now used in current block.
5370 int countOfInnerDecls = 0;
5371 if (!InnerBlockDeclRefs.empty()) {
5372 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00005373 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian11671902012-02-07 17:11:38 +00005374 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00005375 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005376 // We need to save the copied-in variables in nested
5377 // blocks because it is needed at the end for some of the API generations.
5378 // See SynthesizeBlockLiterals routine.
5379 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5380 BlockDeclRefs.push_back(Exp);
5381 BlockByCopyDeclsPtrSet.insert(VD);
5382 BlockByCopyDecls.push_back(VD);
5383 }
John McCall113bee02012-03-10 09:33:50 +00005384 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005385 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5386 BlockDeclRefs.push_back(Exp);
5387 BlockByRefDeclsPtrSet.insert(VD);
5388 BlockByRefDecls.push_back(VD);
5389 }
5390 }
5391 // Find any imported blocks...they will need special attention.
5392 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005393 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005394 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5395 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5396 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5397 }
5398 InnerDeclRefsCount.push_back(countOfInnerDecls);
5399
5400 std::string FuncName;
5401
5402 if (CurFunctionDef)
5403 FuncName = CurFunctionDef->getNameAsString();
5404 else if (CurMethodDef)
5405 BuildUniqueMethodName(FuncName, CurMethodDef);
5406 else if (GlobalVarDecl)
5407 FuncName = std::string(GlobalVarDecl->getNameAsString());
5408
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005409 bool GlobalBlockExpr =
5410 block->getDeclContext()->getRedeclContext()->isFileContext();
5411
5412 if (GlobalBlockExpr && !GlobalVarDecl) {
5413 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5414 GlobalBlockExpr = false;
5415 }
5416
Fariborz Jahanian11671902012-02-07 17:11:38 +00005417 std::string BlockNumber = utostr(Blocks.size()-1);
5418
Fariborz Jahanian11671902012-02-07 17:11:38 +00005419 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5420
5421 // Get a pointer to the function type so we can cast appropriately.
5422 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5423 QualType FType = Context->getPointerType(BFT);
5424
5425 FunctionDecl *FD;
5426 Expr *NewRep;
5427
Benjamin Kramer60509af2013-09-09 14:48:42 +00005428 // Simulate a constructor call...
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005429 std::string Tag;
5430
5431 if (GlobalBlockExpr)
5432 Tag = "__global_";
5433 else
5434 Tag = "__";
5435 Tag += FuncName + "_block_impl_" + BlockNumber;
5436
Fariborz Jahanian11671902012-02-07 17:11:38 +00005437 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00005438 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005439 SourceLocation());
5440
5441 SmallVector<Expr*, 4> InitExprs;
5442
5443 // Initialize the block function.
5444 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00005445 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5446 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005447 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5448 CK_BitCast, Arg);
5449 InitExprs.push_back(castExpr);
5450
5451 // Initialize the block descriptor.
5452 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5453
5454 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5455 SourceLocation(), SourceLocation(),
5456 &Context->Idents.get(DescData.c_str()),
5457 Context->VoidPtrTy, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005458 SC_Static);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005459 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00005460 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005461 Context->VoidPtrTy,
5462 VK_LValue,
5463 SourceLocation()),
5464 UO_AddrOf,
5465 Context->getPointerType(Context->VoidPtrTy),
5466 VK_RValue, OK_Ordinary,
5467 SourceLocation());
5468 InitExprs.push_back(DescRefExpr);
5469
5470 // Add initializers for any closure decl refs.
5471 if (BlockDeclRefs.size()) {
5472 Expr *Exp;
5473 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005474 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005475 E = BlockByCopyDecls.end(); I != E; ++I) {
5476 if (isObjCType((*I)->getType())) {
5477 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5478 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005479 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5480 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005481 if (HasLocalVariableExternalStorage(*I)) {
5482 QualType QT = (*I)->getType();
5483 QT = Context->getPointerType(QT);
5484 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5485 OK_Ordinary, SourceLocation());
5486 }
5487 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5488 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005489 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5490 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005491 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5492 CK_BitCast, Arg);
5493 } else {
5494 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005495 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5496 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005497 if (HasLocalVariableExternalStorage(*I)) {
5498 QualType QT = (*I)->getType();
5499 QT = Context->getPointerType(QT);
5500 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5501 OK_Ordinary, SourceLocation());
5502 }
5503
5504 }
5505 InitExprs.push_back(Exp);
5506 }
5507 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005508 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005509 E = BlockByRefDecls.end(); I != E; ++I) {
5510 ValueDecl *ND = (*I);
5511 std::string Name(ND->getNameAsString());
5512 std::string RecName;
5513 RewriteByRefString(RecName, Name, ND, true);
5514 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5515 + sizeof("struct"));
5516 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5517 SourceLocation(), SourceLocation(),
5518 II);
5519 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5520 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5521
5522 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005523 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005524 SourceLocation());
5525 bool isNestedCapturedVar = false;
5526 if (block)
5527 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5528 ce = block->capture_end(); ci != ce; ++ci) {
5529 const VarDecl *variable = ci->getVariable();
5530 if (variable == ND && ci->isNested()) {
5531 assert (ci->isByRef() &&
5532 "SynthBlockInitExpr - captured block variable is not byref");
5533 isNestedCapturedVar = true;
5534 break;
5535 }
5536 }
5537 // captured nested byref variable has its address passed. Do not take
5538 // its address again.
5539 if (!isNestedCapturedVar)
5540 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5541 Context->getPointerType(Exp->getType()),
5542 VK_RValue, OK_Ordinary, SourceLocation());
5543 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5544 InitExprs.push_back(Exp);
5545 }
5546 }
5547 if (ImportedBlockDecls.size()) {
5548 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5549 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5550 unsigned IntSize =
5551 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5552 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5553 Context->IntTy, SourceLocation());
5554 InitExprs.push_back(FlagExp);
5555 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00005556 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005557 FType, VK_LValue, SourceLocation());
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005558
5559 if (GlobalBlockExpr) {
5560 assert (GlobalConstructionExp == 0 &&
5561 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5562 GlobalConstructionExp = NewRep;
5563 NewRep = DRE;
5564 }
5565
Fariborz Jahanian11671902012-02-07 17:11:38 +00005566 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5567 Context->getPointerType(NewRep->getType()),
5568 VK_RValue, OK_Ordinary, SourceLocation());
5569 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5570 NewRep);
5571 BlockDeclRefs.clear();
5572 BlockByRefDecls.clear();
5573 BlockByRefDeclsPtrSet.clear();
5574 BlockByCopyDecls.clear();
5575 BlockByCopyDeclsPtrSet.clear();
5576 ImportedBlockDecls.clear();
5577 return NewRep;
5578}
5579
5580bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5581 if (const ObjCForCollectionStmt * CS =
5582 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5583 return CS->getElement() == DS;
5584 return false;
5585}
5586
5587//===----------------------------------------------------------------------===//
5588// Function Body / Expression rewriting
5589//===----------------------------------------------------------------------===//
5590
5591Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5592 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5593 isa<DoStmt>(S) || isa<ForStmt>(S))
5594 Stmts.push_back(S);
5595 else if (isa<ObjCForCollectionStmt>(S)) {
5596 Stmts.push_back(S);
5597 ObjCBcLabelNo.push_back(++BcLabelCount);
5598 }
5599
5600 // Pseudo-object operations and ivar references need special
5601 // treatment because we're going to recursively rewrite them.
5602 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5603 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5604 return RewritePropertyOrImplicitSetter(PseudoOp);
5605 } else {
5606 return RewritePropertyOrImplicitGetter(PseudoOp);
5607 }
5608 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5609 return RewriteObjCIvarRefExpr(IvarRefExpr);
5610 }
Fariborz Jahanian4254cdb2013-02-08 18:57:50 +00005611 else if (isa<OpaqueValueExpr>(S))
5612 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005613
5614 SourceRange OrigStmtRange = S->getSourceRange();
5615
5616 // Perform a bottom up rewrite of all children.
5617 for (Stmt::child_range CI = S->children(); CI; ++CI)
5618 if (*CI) {
5619 Stmt *childStmt = (*CI);
5620 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5621 if (newStmt) {
5622 *CI = newStmt;
5623 }
5624 }
5625
5626 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00005627 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005628 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5629 InnerContexts.insert(BE->getBlockDecl());
5630 ImportedLocalExternalDecls.clear();
5631 GetInnerBlockDeclRefExprs(BE->getBody(),
5632 InnerBlockDeclRefs, InnerContexts);
5633 // Rewrite the block body in place.
5634 Stmt *SaveCurrentBody = CurrentBody;
5635 CurrentBody = BE->getBody();
5636 PropParentMap = 0;
5637 // block literal on rhs of a property-dot-sytax assignment
5638 // must be replaced by its synthesize ast so getRewrittenText
5639 // works as expected. In this case, what actually ends up on RHS
5640 // is the blockTranscribed which is the helper function for the
5641 // block literal; as in: self.c = ^() {[ace ARR];};
5642 bool saveDisableReplaceStmt = DisableReplaceStmt;
5643 DisableReplaceStmt = false;
5644 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5645 DisableReplaceStmt = saveDisableReplaceStmt;
5646 CurrentBody = SaveCurrentBody;
5647 PropParentMap = 0;
5648 ImportedLocalExternalDecls.clear();
5649 // Now we snarf the rewritten text and stash it away for later use.
5650 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5651 RewrittenBlockExprs[BE] = Str;
5652
5653 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5654
5655 //blockTranscribed->dump();
5656 ReplaceStmt(S, blockTranscribed);
5657 return blockTranscribed;
5658 }
5659 // Handle specific things.
5660 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5661 return RewriteAtEncode(AtEncode);
5662
5663 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5664 return RewriteAtSelector(AtSelector);
5665
5666 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5667 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00005668
5669 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5670 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00005671
Patrick Beard0caa3942012-04-19 00:25:12 +00005672 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5673 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00005674
5675 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5676 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00005677
5678 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5679 dyn_cast<ObjCDictionaryLiteral>(S))
5680 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005681
5682 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5683#if 0
5684 // Before we rewrite it, put the original message expression in a comment.
5685 SourceLocation startLoc = MessExpr->getLocStart();
5686 SourceLocation endLoc = MessExpr->getLocEnd();
5687
5688 const char *startBuf = SM->getCharacterData(startLoc);
5689 const char *endBuf = SM->getCharacterData(endLoc);
5690
5691 std::string messString;
5692 messString += "// ";
5693 messString.append(startBuf, endBuf-startBuf+1);
5694 messString += "\n";
5695
5696 // FIXME: Missing definition of
5697 // InsertText(clang::SourceLocation, char const*, unsigned int).
5698 // InsertText(startLoc, messString.c_str(), messString.size());
5699 // Tried this, but it didn't work either...
5700 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5701#endif
5702 return RewriteMessageExpr(MessExpr);
5703 }
5704
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00005705 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5706 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5707 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5708 }
5709
Fariborz Jahanian11671902012-02-07 17:11:38 +00005710 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5711 return RewriteObjCTryStmt(StmtTry);
5712
5713 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5714 return RewriteObjCSynchronizedStmt(StmtTry);
5715
5716 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5717 return RewriteObjCThrowStmt(StmtThrow);
5718
5719 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5720 return RewriteObjCProtocolExpr(ProtocolExp);
5721
5722 if (ObjCForCollectionStmt *StmtForCollection =
5723 dyn_cast<ObjCForCollectionStmt>(S))
5724 return RewriteObjCForCollectionStmt(StmtForCollection,
5725 OrigStmtRange.getEnd());
5726 if (BreakStmt *StmtBreakStmt =
5727 dyn_cast<BreakStmt>(S))
5728 return RewriteBreakStmt(StmtBreakStmt);
5729 if (ContinueStmt *StmtContinueStmt =
5730 dyn_cast<ContinueStmt>(S))
5731 return RewriteContinueStmt(StmtContinueStmt);
5732
5733 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5734 // and cast exprs.
5735 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5736 // FIXME: What we're doing here is modifying the type-specifier that
5737 // precedes the first Decl. In the future the DeclGroup should have
5738 // a separate type-specifier that we can rewrite.
5739 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5740 // the context of an ObjCForCollectionStmt. For example:
5741 // NSArray *someArray;
5742 // for (id <FooProtocol> index in someArray) ;
5743 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5744 // and it depends on the original text locations/positions.
5745 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5746 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5747
5748 // Blocks rewrite rules.
5749 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5750 DI != DE; ++DI) {
5751 Decl *SD = *DI;
5752 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5753 if (isTopLevelBlockPointerType(ND->getType()))
5754 RewriteBlockPointerDecl(ND);
5755 else if (ND->getType()->isFunctionPointerType())
5756 CheckFunctionPointerDecl(ND->getType(), ND);
5757 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5758 if (VD->hasAttr<BlocksAttr>()) {
5759 static unsigned uniqueByrefDeclCount = 0;
5760 assert(!BlockByRefDeclNo.count(ND) &&
5761 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5762 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005763 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian11671902012-02-07 17:11:38 +00005764 }
5765 else
5766 RewriteTypeOfDecl(VD);
5767 }
5768 }
5769 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5770 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5771 RewriteBlockPointerDecl(TD);
5772 else if (TD->getUnderlyingType()->isFunctionPointerType())
5773 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5774 }
5775 }
5776 }
5777
5778 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5779 RewriteObjCQualifiedInterfaceTypes(CE);
5780
5781 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5782 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5783 assert(!Stmts.empty() && "Statement stack is empty");
5784 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5785 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5786 && "Statement stack mismatch");
5787 Stmts.pop_back();
5788 }
5789 // Handle blocks rewriting.
Fariborz Jahanian11671902012-02-07 17:11:38 +00005790 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5791 ValueDecl *VD = DRE->getDecl();
5792 if (VD->hasAttr<BlocksAttr>())
5793 return RewriteBlockDeclRefExpr(DRE);
5794 if (HasLocalVariableExternalStorage(VD))
5795 return RewriteLocalVariableExternalStorage(DRE);
5796 }
5797
5798 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5799 if (CE->getCallee()->getType()->isBlockPointerType()) {
5800 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5801 ReplaceStmt(S, BlockCall);
5802 return BlockCall;
5803 }
5804 }
5805 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5806 RewriteCastExpr(CE);
5807 }
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00005808 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5809 RewriteImplicitCastObjCExpr(ICE);
5810 }
Fariborz Jahaniancc172282012-04-16 22:14:01 +00005811#if 0
Fariborz Jahanian3a5d5522012-04-13 18:00:54 +00005812
Fariborz Jahanian11671902012-02-07 17:11:38 +00005813 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5814 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5815 ICE->getSubExpr(),
5816 SourceLocation());
5817 // Get the new text.
5818 std::string SStr;
5819 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00005820 Replacement->printPretty(Buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005821 const std::string &Str = Buf.str();
5822
5823 printf("CAST = %s\n", &Str[0]);
5824 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5825 delete S;
5826 return Replacement;
5827 }
5828#endif
5829 // Return this stmt unmodified.
5830 return S;
5831}
5832
5833void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005834 for (auto *FD : RD->fields()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005835 if (isTopLevelBlockPointerType(FD->getType()))
5836 RewriteBlockPointerDecl(FD);
5837 if (FD->getType()->isObjCQualifiedIdType() ||
5838 FD->getType()->isObjCQualifiedInterfaceType())
5839 RewriteObjCQualifiedInterfaceTypes(FD);
5840 }
5841}
5842
5843/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5844/// main file of the input.
5845void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5846 switch (D->getKind()) {
5847 case Decl::Function: {
5848 FunctionDecl *FD = cast<FunctionDecl>(D);
5849 if (FD->isOverloadedOperator())
5850 return;
5851
5852 // Since function prototypes don't have ParmDecl's, we check the function
5853 // prototype. This enables us to rewrite function declarations and
5854 // definitions using the same code.
5855 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5856
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00005857 if (!FD->isThisDeclarationADefinition())
5858 break;
5859
Fariborz Jahanian11671902012-02-07 17:11:38 +00005860 // FIXME: If this should support Obj-C++, support CXXTryStmt
5861 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5862 CurFunctionDef = FD;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005863 CurrentBody = Body;
5864 Body =
5865 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5866 FD->setBody(Body);
5867 CurrentBody = 0;
5868 if (PropParentMap) {
5869 delete PropParentMap;
5870 PropParentMap = 0;
5871 }
5872 // This synthesizes and inserts the block "impl" struct, invoke function,
5873 // and any copy/dispose helper functions.
5874 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005875 RewriteLineDirective(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005876 CurFunctionDef = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005877 }
5878 break;
5879 }
5880 case Decl::ObjCMethod: {
5881 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5882 if (CompoundStmt *Body = MD->getCompoundBody()) {
5883 CurMethodDef = MD;
5884 CurrentBody = Body;
5885 Body =
5886 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5887 MD->setBody(Body);
5888 CurrentBody = 0;
5889 if (PropParentMap) {
5890 delete PropParentMap;
5891 PropParentMap = 0;
5892 }
5893 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005894 RewriteLineDirective(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005895 CurMethodDef = 0;
5896 }
5897 break;
5898 }
5899 case Decl::ObjCImplementation: {
5900 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5901 ClassImplementation.push_back(CI);
5902 break;
5903 }
5904 case Decl::ObjCCategoryImpl: {
5905 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5906 CategoryImplementation.push_back(CI);
5907 break;
5908 }
5909 case Decl::Var: {
5910 VarDecl *VD = cast<VarDecl>(D);
5911 RewriteObjCQualifiedInterfaceTypes(VD);
5912 if (isTopLevelBlockPointerType(VD->getType()))
5913 RewriteBlockPointerDecl(VD);
5914 else if (VD->getType()->isFunctionPointerType()) {
5915 CheckFunctionPointerDecl(VD->getType(), VD);
5916 if (VD->getInit()) {
5917 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5918 RewriteCastExpr(CE);
5919 }
5920 }
5921 } else if (VD->getType()->isRecordType()) {
5922 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5923 if (RD->isCompleteDefinition())
5924 RewriteRecordBody(RD);
5925 }
5926 if (VD->getInit()) {
5927 GlobalVarDecl = VD;
5928 CurrentBody = VD->getInit();
5929 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5930 CurrentBody = 0;
5931 if (PropParentMap) {
5932 delete PropParentMap;
5933 PropParentMap = 0;
5934 }
5935 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5936 GlobalVarDecl = 0;
5937
5938 // This is needed for blocks.
5939 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5940 RewriteCastExpr(CE);
5941 }
5942 }
5943 break;
5944 }
5945 case Decl::TypeAlias:
5946 case Decl::Typedef: {
5947 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5948 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5949 RewriteBlockPointerDecl(TD);
5950 else if (TD->getUnderlyingType()->isFunctionPointerType())
5951 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00005952 else
5953 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005954 }
5955 break;
5956 }
5957 case Decl::CXXRecord:
5958 case Decl::Record: {
5959 RecordDecl *RD = cast<RecordDecl>(D);
5960 if (RD->isCompleteDefinition())
5961 RewriteRecordBody(RD);
5962 break;
5963 }
5964 default:
5965 break;
5966 }
5967 // Nothing yet.
5968}
5969
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005970/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5971/// protocol reference symbols in the for of:
5972/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5973static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5974 ObjCProtocolDecl *PDecl,
5975 std::string &Result) {
5976 // Also output .objc_protorefs$B section and its meta-data.
5977 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanian75f2e3c2012-04-27 21:39:49 +00005978 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005979 Result += "struct _protocol_t *";
5980 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5981 Result += PDecl->getNameAsString();
5982 Result += " = &";
5983 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5984 Result += ";\n";
5985}
5986
Fariborz Jahanian11671902012-02-07 17:11:38 +00005987void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
5988 if (Diags.hasErrorOccurred())
5989 return;
5990
5991 RewriteInclude();
5992
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005993 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005994 // translation of function bodies were postponed until all class and
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005995 // their extensions and implementations are seen. This is because, we
Alp Tokerf6a24ce2013-12-05 16:25:25 +00005996 // cannot build grouping structs for bitfields until they are all seen.
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005997 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
5998 HandleTopLevelSingleDecl(FDecl);
5999 }
6000
Fariborz Jahanian11671902012-02-07 17:11:38 +00006001 // Here's a great place to add any extra declarations that may be needed.
6002 // Write out meta data for each @protocol(<expr>).
6003 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006004 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006005 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006006 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
6007 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006008
6009 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00006010
6011 if (ClassImplementation.size() || CategoryImplementation.size())
6012 RewriteImplementations();
6013
Fariborz Jahanian8e1118cbd2012-02-21 23:58:41 +00006014 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
6015 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
6016 // Write struct declaration for the class matching its ivar declarations.
6017 // Note that for modern abi, this is postponed until the end of TU
6018 // because class extensions and the implementation might declare their own
6019 // private ivars.
6020 RewriteInterfaceDecl(CDecl);
6021 }
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006022
Fariborz Jahanian11671902012-02-07 17:11:38 +00006023 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6024 // we are done.
6025 if (const RewriteBuffer *RewriteBuf =
6026 Rewrite.getRewriteBufferFor(MainFileID)) {
6027 //printf("Changed:\n");
6028 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6029 } else {
6030 llvm::errs() << "No changes\n";
6031 }
6032
6033 if (ClassImplementation.size() || CategoryImplementation.size() ||
6034 ProtocolExprDecls.size()) {
6035 // Rewrite Objective-c meta data*
6036 std::string ResultStr;
6037 RewriteMetaDataIntoBuffer(ResultStr);
6038 // Emit metadata.
6039 *OutFile << ResultStr;
6040 }
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006041 // Emit ImageInfo;
6042 {
6043 std::string ResultStr;
6044 WriteImageInfo(ResultStr);
6045 *OutFile << ResultStr;
6046 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006047 OutFile->flush();
6048}
6049
6050void RewriteModernObjC::Initialize(ASTContext &context) {
6051 InitializeCommon(context);
6052
Fariborz Jahanianb52221e2012-03-10 17:45:38 +00006053 Preamble += "#ifndef __OBJC2__\n";
6054 Preamble += "#define __OBJC2__\n";
6055 Preamble += "#endif\n";
6056
Fariborz Jahanian11671902012-02-07 17:11:38 +00006057 // declaring objc_selector outside the parameter list removes a silly
6058 // scope related warning...
6059 if (IsHeader)
6060 Preamble = "#pragma once\n";
6061 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahanian27db0b32012-04-12 23:52:52 +00006062 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
6063 Preamble += "\n\tstruct objc_object *superClass; ";
6064 // Add a constructor for creating temporary objects.
6065 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
6066 Preamble += ": object(o), superClass(s) {} ";
6067 Preamble += "\n};\n";
6068
Fariborz Jahanian11671902012-02-07 17:11:38 +00006069 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006070 // Define all sections using syntax that makes sense.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006071 // These are currently generated.
6072 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006073 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006074 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006075 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6076 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006077 // These are generated but not necessary for functionality.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006078 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006079 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6080 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006081 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006082
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006083 // These need be generated for performance. Currently they are not,
6084 // using API calls instead.
6085 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6086 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6087 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6088
Fariborz Jahanian11671902012-02-07 17:11:38 +00006089 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006090 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6091 Preamble += "typedef struct objc_object Protocol;\n";
6092 Preamble += "#define _REWRITER_typedef_Protocol\n";
6093 Preamble += "#endif\n";
6094 if (LangOpts.MicrosoftExt) {
6095 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6096 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006097 }
6098 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006099 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006100
6101 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6102 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6103 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6104 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6105 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6106
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006107 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006108 Preamble += "(const char *);\n";
6109 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6110 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006111 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006112 Preamble += "(const char *);\n";
Fariborz Jahanian34660592012-03-19 18:11:32 +00006113 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006114 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00006115 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6116 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006117 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00006118 Preamble += "#ifdef _WIN64\n";
6119 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
6120 Preamble += "#else\n";
6121 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
6122 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006123 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6124 Preamble += "struct __objcFastEnumerationState {\n\t";
6125 Preamble += "unsigned long state;\n\t";
6126 Preamble += "void **itemsPtr;\n\t";
6127 Preamble += "unsigned long *mutationsPtr;\n\t";
6128 Preamble += "unsigned long extra[5];\n};\n";
6129 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6130 Preamble += "#define __FASTENUMERATIONSTATE\n";
6131 Preamble += "#endif\n";
6132 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6133 Preamble += "struct __NSConstantStringImpl {\n";
6134 Preamble += " int *isa;\n";
6135 Preamble += " int flags;\n";
6136 Preamble += " char *str;\n";
6137 Preamble += " long length;\n";
6138 Preamble += "};\n";
6139 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6140 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6141 Preamble += "#else\n";
6142 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6143 Preamble += "#endif\n";
6144 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6145 Preamble += "#endif\n";
6146 // Blocks preamble.
6147 Preamble += "#ifndef BLOCK_IMPL\n";
6148 Preamble += "#define BLOCK_IMPL\n";
6149 Preamble += "struct __block_impl {\n";
6150 Preamble += " void *isa;\n";
6151 Preamble += " int Flags;\n";
6152 Preamble += " int Reserved;\n";
6153 Preamble += " void *FuncPtr;\n";
6154 Preamble += "};\n";
6155 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6156 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6157 Preamble += "extern \"C\" __declspec(dllexport) "
6158 "void _Block_object_assign(void *, const void *, const int);\n";
6159 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6160 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6161 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6162 Preamble += "#else\n";
6163 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6164 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6165 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6166 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6167 Preamble += "#endif\n";
6168 Preamble += "#endif\n";
6169 if (LangOpts.MicrosoftExt) {
6170 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6171 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6172 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6173 Preamble += "#define __attribute__(X)\n";
6174 Preamble += "#endif\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006175 Preamble += "#ifndef __weak\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006176 Preamble += "#define __weak\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006177 Preamble += "#endif\n";
6178 Preamble += "#ifndef __block\n";
6179 Preamble += "#define __block\n";
6180 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006181 }
6182 else {
6183 Preamble += "#define __block\n";
6184 Preamble += "#define __weak\n";
6185 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00006186
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006187 // Declarations required for modern objective-c array and dictionary literals.
6188 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006189 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006190 Preamble += " void * *arr;\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006191 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006192 Preamble += "\tva_list marker;\n";
6193 Preamble += "\tva_start(marker, count);\n";
6194 Preamble += "\tarr = new void *[count];\n";
6195 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6196 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6197 Preamble += "\tva_end( marker );\n";
6198 Preamble += " };\n";
Fariborz Jahanian70ef9292012-05-02 23:53:46 +00006199 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006200 Preamble += "\tdelete[] arr;\n";
6201 Preamble += " }\n";
6202 Preamble += "};\n";
6203
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00006204 // Declaration required for implementation of @autoreleasepool statement.
6205 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6206 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6207 Preamble += "struct __AtAutoreleasePool {\n";
6208 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6209 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6210 Preamble += " void * atautoreleasepoolobj;\n";
6211 Preamble += "};\n";
6212
Fariborz Jahanian11671902012-02-07 17:11:38 +00006213 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6214 // as this avoids warning in any 64bit/32bit compilation model.
6215 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6216}
6217
6218/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6219/// ivar offset.
6220void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6221 std::string &Result) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006222 Result += "__OFFSETOFIVAR__(struct ";
6223 Result += ivar->getContainingInterface()->getNameAsString();
6224 if (LangOpts.MicrosoftExt)
6225 Result += "_IMPL";
6226 Result += ", ";
6227 if (ivar->isBitField())
6228 ObjCIvarBitfieldGroupDecl(ivar, Result);
6229 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006230 Result += ivar->getNameAsString();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006231 Result += ")";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006232}
6233
6234/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6235/// struct _prop_t {
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006236/// const char *name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006237/// char *attributes;
6238/// }
6239
6240/// struct _prop_list_t {
6241/// uint32_t entsize; // sizeof(struct _prop_t)
6242/// uint32_t count_of_properties;
6243/// struct _prop_t prop_list[count_of_properties];
6244/// }
6245
6246/// struct _protocol_t;
6247
6248/// struct _protocol_list_t {
6249/// long protocol_count; // Note, this is 32/64 bit
6250/// struct _protocol_t * protocol_list[protocol_count];
6251/// }
6252
6253/// struct _objc_method {
6254/// SEL _cmd;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006255/// const char *method_type;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006256/// char *_imp;
6257/// }
6258
6259/// struct _method_list_t {
6260/// uint32_t entsize; // sizeof(struct _objc_method)
6261/// uint32_t method_count;
6262/// struct _objc_method method_list[method_count];
6263/// }
6264
6265/// struct _protocol_t {
6266/// id isa; // NULL
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006267/// const char *protocol_name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006268/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006269/// const struct method_list_t *instance_methods;
6270/// const struct method_list_t *class_methods;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006271/// const struct method_list_t *optionalInstanceMethods;
6272/// const struct method_list_t *optionalClassMethods;
6273/// const struct _prop_list_t * properties;
6274/// const uint32_t size; // sizeof(struct _protocol_t)
6275/// const uint32_t flags; // = 0
6276/// const char ** extendedMethodTypes;
6277/// }
6278
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006279/// struct _ivar_t {
6280/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006281/// const char *name;
6282/// const char *type;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006283/// uint32_t alignment;
6284/// uint32_t size;
6285/// }
6286
6287/// struct _ivar_list_t {
6288/// uint32 entsize; // sizeof(struct _ivar_t)
6289/// uint32 count;
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006290/// struct _ivar_t list[count];
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006291/// }
6292
6293/// struct _class_ro_t {
Fariborz Jahanian34134812012-03-24 16:53:16 +00006294/// uint32_t flags;
6295/// uint32_t instanceStart;
6296/// uint32_t instanceSize;
6297/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006298/// const uint8_t *ivarLayout;
6299/// const char *name;
6300/// const struct _method_list_t *baseMethods;
6301/// const struct _protocol_list_t *baseProtocols;
6302/// const struct _ivar_list_t *ivars;
6303/// const uint8_t *weakIvarLayout;
6304/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006305/// }
6306
6307/// struct _class_t {
6308/// struct _class_t *isa;
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006309/// struct _class_t *superclass;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006310/// void *cache;
6311/// IMP *vtable;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006312/// struct _class_ro_t *ro;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006313/// }
6314
6315/// struct _category_t {
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006316/// const char *name;
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006317/// struct _class_t *cls;
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006318/// const struct _method_list_t *instance_methods;
6319/// const struct _method_list_t *class_methods;
6320/// const struct _protocol_list_t *protocols;
6321/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006322/// }
6323
6324/// MessageRefTy - LLVM for:
6325/// struct _message_ref_t {
6326/// IMP messenger;
6327/// SEL name;
6328/// };
6329
6330/// SuperMessageRefTy - LLVM for:
6331/// struct _super_message_ref_t {
6332/// SUPER_IMP messenger;
6333/// SEL name;
6334/// };
6335
Fariborz Jahanian45489622012-03-14 18:09:23 +00006336static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006337 static bool meta_data_declared = false;
6338 if (meta_data_declared)
6339 return;
6340
6341 Result += "\nstruct _prop_t {\n";
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006342 Result += "\tconst char *name;\n";
6343 Result += "\tconst char *attributes;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006344 Result += "};\n";
6345
6346 Result += "\nstruct _protocol_t;\n";
6347
Fariborz Jahanian11671902012-02-07 17:11:38 +00006348 Result += "\nstruct _objc_method {\n";
6349 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006350 Result += "\tconst char *method_type;\n";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006351 Result += "\tvoid *_imp;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006352 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006353
6354 Result += "\nstruct _protocol_t {\n";
6355 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006356 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006357 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006358 Result += "\tconst struct method_list_t *instance_methods;\n";
6359 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006360 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6361 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6362 Result += "\tconst struct _prop_list_t * properties;\n";
6363 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6364 Result += "\tconst unsigned int flags; // = 0\n";
6365 Result += "\tconst char ** extendedMethodTypes;\n";
6366 Result += "};\n";
6367
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006368 Result += "\nstruct _ivar_t {\n";
6369 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006370 Result += "\tconst char *name;\n";
6371 Result += "\tconst char *type;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006372 Result += "\tunsigned int alignment;\n";
6373 Result += "\tunsigned int size;\n";
6374 Result += "};\n";
6375
6376 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006377 Result += "\tunsigned int flags;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006378 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006379 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006380 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6381 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian34134812012-03-24 16:53:16 +00006382 Result += "\tunsigned int reserved;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006383 Result += "\tconst unsigned char *ivarLayout;\n";
6384 Result += "\tconst char *name;\n";
6385 Result += "\tconst struct _method_list_t *baseMethods;\n";
6386 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6387 Result += "\tconst struct _ivar_list_t *ivars;\n";
6388 Result += "\tconst unsigned char *weakIvarLayout;\n";
6389 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006390 Result += "};\n";
6391
6392 Result += "\nstruct _class_t {\n";
6393 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006394 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006395 Result += "\tvoid *cache;\n";
6396 Result += "\tvoid *vtable;\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006397 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006398 Result += "};\n";
6399
6400 Result += "\nstruct _category_t {\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006401 Result += "\tconst char *name;\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006402 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006403 Result += "\tconst struct _method_list_t *instance_methods;\n";
6404 Result += "\tconst struct _method_list_t *class_methods;\n";
6405 Result += "\tconst struct _protocol_list_t *protocols;\n";
6406 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006407 Result += "};\n";
6408
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006409 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006410 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006411 meta_data_declared = true;
6412}
6413
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006414static void Write_protocol_list_t_TypeDecl(std::string &Result,
6415 long super_protocol_count) {
6416 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6417 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6418 Result += "\tstruct _protocol_t *super_protocols[";
6419 Result += utostr(super_protocol_count); Result += "];\n";
6420 Result += "}";
6421}
6422
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006423static void Write_method_list_t_TypeDecl(std::string &Result,
6424 unsigned int method_count) {
6425 Result += "struct /*_method_list_t*/"; Result += " {\n";
6426 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6427 Result += "\tunsigned int method_count;\n";
6428 Result += "\tstruct _objc_method method_list[";
6429 Result += utostr(method_count); Result += "];\n";
6430 Result += "}";
6431}
6432
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006433static void Write__prop_list_t_TypeDecl(std::string &Result,
6434 unsigned int property_count) {
6435 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6436 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6437 Result += "\tunsigned int count_of_properties;\n";
6438 Result += "\tstruct _prop_t prop_list[";
6439 Result += utostr(property_count); Result += "];\n";
6440 Result += "}";
6441}
6442
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006443static void Write__ivar_list_t_TypeDecl(std::string &Result,
6444 unsigned int ivar_count) {
6445 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6446 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6447 Result += "\tunsigned int count;\n";
6448 Result += "\tstruct _ivar_t ivar_list[";
6449 Result += utostr(ivar_count); Result += "];\n";
6450 Result += "}";
6451}
6452
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006453static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6454 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6455 StringRef VarName,
6456 StringRef ProtocolName) {
6457 if (SuperProtocols.size() > 0) {
6458 Result += "\nstatic ";
6459 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6460 Result += " "; Result += VarName;
6461 Result += ProtocolName;
6462 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6463 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6464 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6465 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6466 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6467 Result += SuperPD->getNameAsString();
6468 if (i == e-1)
6469 Result += "\n};\n";
6470 else
6471 Result += ",\n";
6472 }
6473 }
6474}
6475
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006476static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6477 ASTContext *Context, std::string &Result,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006478 ArrayRef<ObjCMethodDecl *> Methods,
6479 StringRef VarName,
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006480 StringRef TopLevelDeclName,
6481 bool MethodImpl) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006482 if (Methods.size() > 0) {
6483 Result += "\nstatic ";
6484 Write_method_list_t_TypeDecl(Result, Methods.size());
6485 Result += " "; Result += VarName;
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006486 Result += TopLevelDeclName;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006487 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6488 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6489 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6490 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6491 ObjCMethodDecl *MD = Methods[i];
6492 if (i == 0)
6493 Result += "\t{{(struct objc_selector *)\"";
6494 else
6495 Result += "\t{(struct objc_selector *)\"";
6496 Result += (MD)->getSelector().getAsString(); Result += "\"";
6497 Result += ", ";
6498 std::string MethodTypeString;
6499 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6500 Result += "\""; Result += MethodTypeString; Result += "\"";
6501 Result += ", ";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006502 if (!MethodImpl)
6503 Result += "0";
6504 else {
6505 Result += "(void *)";
6506 Result += RewriteObj.MethodInternalNames[MD];
6507 }
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006508 if (i == e-1)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006509 Result += "}}\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006510 else
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006511 Result += "},\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006512 }
6513 Result += "};\n";
6514 }
6515}
6516
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006517static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006518 ASTContext *Context, std::string &Result,
6519 ArrayRef<ObjCPropertyDecl *> Properties,
6520 const Decl *Container,
6521 StringRef VarName,
6522 StringRef ProtocolName) {
6523 if (Properties.size() > 0) {
6524 Result += "\nstatic ";
6525 Write__prop_list_t_TypeDecl(Result, Properties.size());
6526 Result += " "; Result += VarName;
6527 Result += ProtocolName;
6528 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6529 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6530 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6531 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6532 ObjCPropertyDecl *PropDecl = Properties[i];
6533 if (i == 0)
6534 Result += "\t{{\"";
6535 else
6536 Result += "\t{\"";
6537 Result += PropDecl->getName(); Result += "\",";
6538 std::string PropertyTypeString, QuotePropertyTypeString;
6539 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6540 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6541 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6542 if (i == e-1)
6543 Result += "}}\n";
6544 else
6545 Result += "},\n";
6546 }
6547 Result += "};\n";
6548 }
6549}
6550
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006551// Metadata flags
6552enum MetaDataDlags {
6553 CLS = 0x0,
6554 CLS_META = 0x1,
6555 CLS_ROOT = 0x2,
6556 OBJC2_CLS_HIDDEN = 0x10,
6557 CLS_EXCEPTION = 0x20,
6558
6559 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6560 CLS_HAS_IVAR_RELEASER = 0x40,
6561 /// class was compiled with -fobjc-arr
6562 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6563};
6564
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006565static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6566 unsigned int flags,
6567 const std::string &InstanceStart,
6568 const std::string &InstanceSize,
6569 ArrayRef<ObjCMethodDecl *>baseMethods,
6570 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6571 ArrayRef<ObjCIvarDecl *>ivars,
6572 ArrayRef<ObjCPropertyDecl *>Properties,
6573 StringRef VarName,
6574 StringRef ClassName) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006575 Result += "\nstatic struct _class_ro_t ";
6576 Result += VarName; Result += ClassName;
6577 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6578 Result += "\t";
6579 Result += llvm::utostr(flags); Result += ", ";
6580 Result += InstanceStart; Result += ", ";
6581 Result += InstanceSize; Result += ", \n";
6582 Result += "\t";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006583 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6584 if (Triple.getArch() == llvm::Triple::x86_64)
6585 // uint32_t const reserved; // only when building for 64bit targets
6586 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006587 // const uint8_t * const ivarLayout;
6588 Result += "0, \n\t";
6589 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006590 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006591 if (baseMethods.size() > 0) {
6592 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006593 if (metaclass)
6594 Result += "_OBJC_$_CLASS_METHODS_";
6595 else
6596 Result += "_OBJC_$_INSTANCE_METHODS_";
6597 Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006598 Result += ",\n\t";
6599 }
6600 else
6601 Result += "0, \n\t";
6602
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006603 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006604 Result += "(const struct _objc_protocol_list *)&";
6605 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6606 Result += ",\n\t";
6607 }
6608 else
6609 Result += "0, \n\t";
6610
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006611 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006612 Result += "(const struct _ivar_list_t *)&";
6613 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6614 Result += ",\n\t";
6615 }
6616 else
6617 Result += "0, \n\t";
6618
6619 // weakIvarLayout
6620 Result += "0, \n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006621 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006622 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00006623 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006624 Result += ",\n";
6625 }
6626 else
6627 Result += "0, \n";
6628
6629 Result += "};\n";
6630}
6631
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006632static void Write_class_t(ASTContext *Context, std::string &Result,
6633 StringRef VarName,
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006634 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6635 bool rootClass = (!CDecl->getSuperClass());
6636 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006637
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006638 if (!rootClass) {
6639 // Find the Root class
6640 RootClass = CDecl->getSuperClass();
6641 while (RootClass->getSuperClass()) {
6642 RootClass = RootClass->getSuperClass();
6643 }
6644 }
6645
6646 if (metaclass && rootClass) {
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006647 // Need to handle a case of use of forward declaration.
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006648 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006649 Result += "extern \"C\" ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006650 if (CDecl->getImplementation())
6651 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006652 else
6653 Result += "__declspec(dllimport) ";
6654
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006655 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006656 Result += CDecl->getNameAsString();
6657 Result += ";\n";
6658 }
6659 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006660 if (!rootClass) {
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006661 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006662 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006663 Result += "extern \"C\" ";
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006664 if (SuperClass->getImplementation())
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006665 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006666 else
6667 Result += "__declspec(dllimport) ";
6668
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006669 Result += "struct _class_t ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006670 Result += VarName;
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006671 Result += SuperClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006672 Result += ";\n";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006673
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006674 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006675 Result += "extern \"C\" ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006676 if (RootClass->getImplementation())
6677 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006678 else
6679 Result += "__declspec(dllimport) ";
6680
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006681 Result += "struct _class_t ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006682 Result += VarName;
6683 Result += RootClass->getNameAsString();
6684 Result += ";\n";
6685 }
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006686 }
6687
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006688 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6689 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006690 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6691 Result += "\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006692 if (metaclass) {
6693 if (!rootClass) {
6694 Result += "0, // &"; Result += VarName;
6695 Result += RootClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006696 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006697 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006698 Result += CDecl->getSuperClass()->getNameAsString();
6699 Result += ",\n\t";
6700 }
6701 else {
Fariborz Jahanian35465592012-03-20 21:09:58 +00006702 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006703 Result += CDecl->getNameAsString();
6704 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006705 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006706 Result += ",\n\t";
6707 }
6708 }
6709 else {
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006710 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006711 Result += CDecl->getNameAsString();
6712 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006713 if (!rootClass) {
6714 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006715 Result += CDecl->getSuperClass()->getNameAsString();
6716 Result += ",\n\t";
6717 }
6718 else
6719 Result += "0,\n\t";
6720 }
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006721 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6722 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6723 if (metaclass)
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006724 Result += "&_OBJC_METACLASS_RO_$_";
6725 else
6726 Result += "&_OBJC_CLASS_RO_$_";
6727 Result += CDecl->getNameAsString();
6728 Result += ",\n};\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006729
6730 // Add static function to initialize some of the meta-data fields.
6731 // avoid doing it twice.
6732 if (metaclass)
6733 return;
6734
6735 const ObjCInterfaceDecl *SuperClass =
6736 rootClass ? CDecl : CDecl->getSuperClass();
6737
6738 Result += "static void OBJC_CLASS_SETUP_$_";
6739 Result += CDecl->getNameAsString();
6740 Result += "(void ) {\n";
6741 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6742 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006743 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006744
6745 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian35465592012-03-20 21:09:58 +00006746 Result += ".superclass = ";
6747 if (rootClass)
6748 Result += "&OBJC_CLASS_$_";
6749 else
6750 Result += "&OBJC_METACLASS_$_";
6751
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006752 Result += SuperClass->getNameAsString(); Result += ";\n";
6753
6754 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6755 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6756
6757 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6758 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6759 Result += CDecl->getNameAsString(); Result += ";\n";
6760
6761 if (!rootClass) {
6762 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6763 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6764 Result += SuperClass->getNameAsString(); Result += ";\n";
6765 }
6766
6767 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6768 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6769 Result += "}\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006770}
6771
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006772static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6773 std::string &Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006774 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006775 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006776 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6777 ArrayRef<ObjCMethodDecl *> ClassMethods,
6778 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6779 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006780 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi3eb0edd2012-03-21 03:21:46 +00006781 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006782 // must declare an extern class object in case this class is not implemented
6783 // in this TU.
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006784 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006785 Result += "extern \"C\" ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006786 if (ClassDecl->getImplementation())
6787 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006788 else
6789 Result += "__declspec(dllimport) ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006790
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006791 Result += "struct _class_t ";
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006792 Result += "OBJC_CLASS_$_"; Result += ClassName;
6793 Result += ";\n";
6794
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006795 Result += "\nstatic struct _category_t ";
6796 Result += "_OBJC_$_CATEGORY_";
6797 Result += ClassName; Result += "_$_"; Result += CatName;
6798 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6799 Result += "{\n";
6800 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006801 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006802 Result += ",\n";
6803 if (InstanceMethods.size() > 0) {
6804 Result += "\t(const struct _method_list_t *)&";
6805 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6806 Result += ClassName; Result += "_$_"; Result += CatName;
6807 Result += ",\n";
6808 }
6809 else
6810 Result += "\t0,\n";
6811
6812 if (ClassMethods.size() > 0) {
6813 Result += "\t(const struct _method_list_t *)&";
6814 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6815 Result += ClassName; Result += "_$_"; Result += CatName;
6816 Result += ",\n";
6817 }
6818 else
6819 Result += "\t0,\n";
6820
6821 if (RefedProtocols.size() > 0) {
6822 Result += "\t(const struct _protocol_list_t *)&";
6823 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6824 Result += ClassName; Result += "_$_"; Result += CatName;
6825 Result += ",\n";
6826 }
6827 else
6828 Result += "\t0,\n";
6829
6830 if (ClassProperties.size() > 0) {
6831 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6832 Result += ClassName; Result += "_$_"; Result += CatName;
6833 Result += ",\n";
6834 }
6835 else
6836 Result += "\t0,\n";
6837
6838 Result += "};\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006839
6840 // Add static function to initialize the class pointer in the category structure.
6841 Result += "static void OBJC_CATEGORY_SETUP_$_";
6842 Result += ClassDecl->getNameAsString();
6843 Result += "_$_";
6844 Result += CatName;
6845 Result += "(void ) {\n";
6846 Result += "\t_OBJC_$_CATEGORY_";
6847 Result += ClassDecl->getNameAsString();
6848 Result += "_$_";
6849 Result += CatName;
6850 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6851 Result += ";\n}\n";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006852}
6853
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006854static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6855 ASTContext *Context, std::string &Result,
6856 ArrayRef<ObjCMethodDecl *> Methods,
6857 StringRef VarName,
6858 StringRef ProtocolName) {
6859 if (Methods.size() == 0)
6860 return;
6861
6862 Result += "\nstatic const char *";
6863 Result += VarName; Result += ProtocolName;
6864 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6865 Result += "{\n";
6866 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6867 ObjCMethodDecl *MD = Methods[i];
6868 std::string MethodTypeString, QuoteMethodTypeString;
6869 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6870 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6871 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6872 if (i == e-1)
6873 Result += "\n};\n";
6874 else {
6875 Result += ",\n";
6876 }
6877 }
6878}
6879
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006880static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6881 ASTContext *Context,
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006882 std::string &Result,
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006883 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006884 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006885 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6886 // this is what happens:
6887 /**
6888 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6889 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6890 Class->getVisibility() == HiddenVisibility)
6891 Visibility shoud be: HiddenVisibility;
6892 else
6893 Visibility shoud be: DefaultVisibility;
6894 */
6895
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006896 Result += "\n";
6897 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6898 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006899 if (Context->getLangOpts().MicrosoftExt)
6900 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6901
6902 if (!Context->getLangOpts().MicrosoftExt ||
6903 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanianc9295ec2012-03-10 01:34:42 +00006904 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006905 Result += "extern \"C\" unsigned long int ";
Fariborz Jahanian2677ded2012-03-10 00:53:02 +00006906 else
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006907 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006908 if (Ivars[i]->isBitField())
6909 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6910 else
6911 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006912 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6913 Result += " = ";
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006914 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6915 Result += ";\n";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006916 if (Ivars[i]->isBitField()) {
6917 // skip over rest of the ivar bitfields.
6918 SKIP_BITFIELDS(i , e, Ivars);
6919 }
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006920 }
6921}
6922
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006923static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6924 ASTContext *Context, std::string &Result,
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006925 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006926 StringRef VarName,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006927 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006928 if (OriginalIvars.size() > 0) {
6929 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6930 SmallVector<ObjCIvarDecl *, 8> Ivars;
6931 // strip off all but the first ivar bitfield from each group of ivars.
6932 // Such ivars in the ivar list table will be replaced by their grouping struct
6933 // 'ivar'.
6934 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6935 if (OriginalIvars[i]->isBitField()) {
6936 Ivars.push_back(OriginalIvars[i]);
6937 // skip over rest of the ivar bitfields.
6938 SKIP_BITFIELDS(i , e, OriginalIvars);
6939 }
6940 else
6941 Ivars.push_back(OriginalIvars[i]);
6942 }
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006943
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006944 Result += "\nstatic ";
6945 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6946 Result += " "; Result += VarName;
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006947 Result += CDecl->getNameAsString();
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006948 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6949 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6950 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6951 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6952 ObjCIvarDecl *IvarDecl = Ivars[i];
6953 if (i == 0)
6954 Result += "\t{{";
6955 else
6956 Result += "\t {";
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006957 Result += "(unsigned long int *)&";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006958 if (Ivars[i]->isBitField())
6959 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6960 else
6961 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006962 Result += ", ";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006963
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006964 Result += "\"";
6965 if (Ivars[i]->isBitField())
6966 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6967 else
6968 Result += IvarDecl->getName();
6969 Result += "\", ";
6970
6971 QualType IVQT = IvarDecl->getType();
6972 if (IvarDecl->isBitField())
6973 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6974
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006975 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006976 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006977 IvarDecl);
6978 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6979 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6980
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006981 // FIXME. this alignment represents the host alignment and need be changed to
6982 // represent the target alignment.
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006983 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006984 Align = llvm::Log2_32(Align);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006985 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006986 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00006987 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006988 if (i == e-1)
6989 Result += "}}\n";
6990 else
6991 Result += "},\n";
6992 }
6993 Result += "};\n";
6994 }
6995}
6996
Fariborz Jahanian11671902012-02-07 17:11:38 +00006997/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006998void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
6999 std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00007000
Fariborz Jahanian11671902012-02-07 17:11:38 +00007001 // Do not synthesize the protocol more than once.
7002 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
7003 return;
Fariborz Jahanian45489622012-03-14 18:09:23 +00007004 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007005
7006 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
7007 PDecl = Def;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007008 // Must write out all protocol definitions in current qualifier list,
7009 // and in their nested qualifiers before writing out current definition.
7010 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7011 E = PDecl->protocol_end(); I != E; ++I)
7012 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007013
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007014 // Construct method lists.
7015 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
7016 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007017 for (auto *MD : PDecl->instance_methods()) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007018 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7019 OptInstanceMethods.push_back(MD);
7020 } else {
7021 InstanceMethods.push_back(MD);
7022 }
7023 }
7024
7025 for (ObjCProtocolDecl::classmeth_iterator
7026 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
7027 I != E; ++I) {
7028 ObjCMethodDecl *MD = *I;
7029 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7030 OptClassMethods.push_back(MD);
7031 } else {
7032 ClassMethods.push_back(MD);
7033 }
7034 }
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007035 std::vector<ObjCMethodDecl *> AllMethods;
7036 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
7037 AllMethods.push_back(InstanceMethods[i]);
7038 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
7039 AllMethods.push_back(ClassMethods[i]);
7040 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
7041 AllMethods.push_back(OptInstanceMethods[i]);
7042 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
7043 AllMethods.push_back(OptClassMethods[i]);
7044
7045 Write__extendedMethodTypes_initializer(*this, Context, Result,
7046 AllMethods,
7047 "_OBJC_PROTOCOL_METHOD_TYPES_",
7048 PDecl->getNameAsString());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007049 // Protocol's super protocol list
7050 std::vector<ObjCProtocolDecl *> SuperProtocols;
7051 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7052 E = PDecl->protocol_end(); I != E; ++I)
7053 SuperProtocols.push_back(*I);
7054
7055 Write_protocol_list_initializer(Context, Result, SuperProtocols,
7056 "_OBJC_PROTOCOL_REFS_",
7057 PDecl->getNameAsString());
7058
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007059 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007060 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007061 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007062
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007063 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007064 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007065 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007066
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007067 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007068 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007069 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007070
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007071 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007072 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007073 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007074
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007075 // Protocol's property metadata.
Aaron Ballmand174edf2014-03-13 19:11:50 +00007076 SmallVector<ObjCPropertyDecl *, 8> ProtocolProperties(PDecl->properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007077 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007078 /* Container */0,
7079 "_OBJC_PROTOCOL_PROPERTIES_",
7080 PDecl->getNameAsString());
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007081
Fariborz Jahanian48985802012-02-08 00:50:52 +00007082 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007083 Result += "\n";
7084 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007085 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007086 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007087 Result += PDecl->getNameAsString();
Fariborz Jahanian48985802012-02-08 00:50:52 +00007088 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7089 Result += "\t0,\n"; // id is; is null
7090 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007091 if (SuperProtocols.size() > 0) {
7092 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7093 Result += PDecl->getNameAsString(); Result += ",\n";
7094 }
7095 else
7096 Result += "\t0,\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007097 if (InstanceMethods.size() > 0) {
7098 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7099 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007100 }
7101 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007102 Result += "\t0,\n";
7103
7104 if (ClassMethods.size() > 0) {
7105 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7106 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007107 }
7108 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007109 Result += "\t0,\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007110
Fariborz Jahanian48985802012-02-08 00:50:52 +00007111 if (OptInstanceMethods.size() > 0) {
7112 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7113 Result += PDecl->getNameAsString(); Result += ",\n";
7114 }
7115 else
7116 Result += "\t0,\n";
7117
7118 if (OptClassMethods.size() > 0) {
7119 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7120 Result += PDecl->getNameAsString(); Result += ",\n";
7121 }
7122 else
7123 Result += "\t0,\n";
7124
7125 if (ProtocolProperties.size() > 0) {
7126 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7127 Result += PDecl->getNameAsString(); Result += ",\n";
7128 }
7129 else
7130 Result += "\t0,\n";
7131
7132 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7133 Result += "\t0,\n";
7134
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007135 if (AllMethods.size() > 0) {
7136 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7137 Result += PDecl->getNameAsString();
7138 Result += "\n};\n";
7139 }
7140 else
7141 Result += "\t0\n};\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007142
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007143 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007144 Result += "static ";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007145 Result += "struct _protocol_t *";
7146 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7147 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7148 Result += ";\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007149
Fariborz Jahanian11671902012-02-07 17:11:38 +00007150 // Mark this protocol as having been generated.
7151 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
7152 llvm_unreachable("protocol already synthesized");
7153
7154}
7155
7156void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7157 const ObjCList<ObjCProtocolDecl> &Protocols,
7158 StringRef prefix, StringRef ClassName,
7159 std::string &Result) {
7160 if (Protocols.empty()) return;
7161
7162 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007163 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007164
7165 // Output the top lovel protocol meta-data for the class.
7166 /* struct _objc_protocol_list {
7167 struct _objc_protocol_list *next;
7168 int protocol_count;
7169 struct _objc_protocol *class_protocols[];
7170 }
7171 */
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007172 Result += "\n";
7173 if (LangOpts.MicrosoftExt)
7174 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7175 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007176 Result += "\tstruct _objc_protocol_list *next;\n";
7177 Result += "\tint protocol_count;\n";
7178 Result += "\tstruct _objc_protocol *class_protocols[";
7179 Result += utostr(Protocols.size());
7180 Result += "];\n} _OBJC_";
7181 Result += prefix;
7182 Result += "_PROTOCOLS_";
7183 Result += ClassName;
7184 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7185 "{\n\t0, ";
7186 Result += utostr(Protocols.size());
7187 Result += "\n";
7188
7189 Result += "\t,{&_OBJC_PROTOCOL_";
7190 Result += Protocols[0]->getNameAsString();
7191 Result += " \n";
7192
7193 for (unsigned i = 1; i != Protocols.size(); i++) {
7194 Result += "\t ,&_OBJC_PROTOCOL_";
7195 Result += Protocols[i]->getNameAsString();
7196 Result += "\n";
7197 }
7198 Result += "\t }\n};\n";
7199}
7200
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007201/// hasObjCExceptionAttribute - Return true if this class or any super
7202/// class has the __objc_exception__ attribute.
7203/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7204static bool hasObjCExceptionAttribute(ASTContext &Context,
7205 const ObjCInterfaceDecl *OID) {
7206 if (OID->hasAttr<ObjCExceptionAttr>())
7207 return true;
7208 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7209 return hasObjCExceptionAttribute(Context, Super);
7210 return false;
7211}
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007212
Fariborz Jahanian11671902012-02-07 17:11:38 +00007213void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7214 std::string &Result) {
7215 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7216
7217 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007218 if (CDecl->isImplicitInterfaceDecl())
7219 assert(false &&
7220 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007221
Fariborz Jahanian45489622012-03-14 18:09:23 +00007222 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007223 SmallVector<ObjCIvarDecl *, 8> IVars;
7224
7225 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7226 IVD; IVD = IVD->getNextIvar()) {
7227 // Ignore unnamed bit-fields.
7228 if (!IVD->getDeclName())
7229 continue;
7230 IVars.push_back(IVD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007231 }
7232
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007233 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007234 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007235 CDecl);
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007236
7237 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007238 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007239
7240 // If any of our property implementations have associated getters or
7241 // setters, produce metadata for them as well.
7242 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7243 PropEnd = IDecl->propimpl_end();
7244 Prop != PropEnd; ++Prop) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007245 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007246 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007247 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007248 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007249 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007250 if (!PD)
7251 continue;
7252 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007253 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007254 InstanceMethods.push_back(Getter);
7255 if (PD->isReadOnly())
7256 continue;
7257 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007258 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007259 InstanceMethods.push_back(Setter);
7260 }
7261
7262 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7263 "_OBJC_$_INSTANCE_METHODS_",
7264 IDecl->getNameAsString(), true);
7265
7266 SmallVector<ObjCMethodDecl *, 32>
7267 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7268
7269 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7270 "_OBJC_$_CLASS_METHODS_",
7271 IDecl->getNameAsString(), true);
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007272
7273 // Protocols referenced in class declaration?
7274 // Protocol's super protocol list
7275 std::vector<ObjCProtocolDecl *> RefedProtocols;
7276 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7277 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7278 E = Protocols.end();
7279 I != E; ++I) {
7280 RefedProtocols.push_back(*I);
7281 // Must write out all protocol definitions in current qualifier list,
7282 // and in their nested qualifiers before writing out current definition.
7283 RewriteObjCProtocolMetaData(*I, Result);
7284 }
7285
7286 Write_protocol_list_initializer(Context, Result,
7287 RefedProtocols,
7288 "_OBJC_CLASS_PROTOCOLS_$_",
7289 IDecl->getNameAsString());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007290
7291 // Protocol's property metadata.
Aaron Ballmand174edf2014-03-13 19:11:50 +00007292 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007293 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianee1db7a2012-03-22 17:39:35 +00007294 /* Container */IDecl,
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00007295 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007296 CDecl->getNameAsString());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007297
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007298
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007299 // Data for initializing _class_ro_t metaclass meta-data
7300 uint32_t flags = CLS_META;
7301 std::string InstanceSize;
7302 std::string InstanceStart;
7303
7304
7305 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7306 if (classIsHidden)
7307 flags |= OBJC2_CLS_HIDDEN;
7308
7309 if (!CDecl->getSuperClass())
7310 // class is root
7311 flags |= CLS_ROOT;
7312 InstanceSize = "sizeof(struct _class_t)";
7313 InstanceStart = InstanceSize;
7314 Write__class_ro_t_initializer(Context, Result, flags,
7315 InstanceStart, InstanceSize,
7316 ClassMethods,
7317 0,
7318 0,
7319 0,
7320 "_OBJC_METACLASS_RO_$_",
7321 CDecl->getNameAsString());
7322
7323
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007324 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007325 flags = CLS;
7326 if (classIsHidden)
7327 flags |= OBJC2_CLS_HIDDEN;
7328
7329 if (hasObjCExceptionAttribute(*Context, CDecl))
7330 flags |= CLS_EXCEPTION;
7331
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007332 if (!CDecl->getSuperClass())
7333 // class is root
7334 flags |= CLS_ROOT;
7335
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007336 InstanceSize.clear();
7337 InstanceStart.clear();
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007338 if (!ObjCSynthesizedStructs.count(CDecl)) {
7339 InstanceSize = "0";
7340 InstanceStart = "0";
7341 }
7342 else {
7343 InstanceSize = "sizeof(struct ";
7344 InstanceSize += CDecl->getNameAsString();
7345 InstanceSize += "_IMPL)";
7346
7347 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7348 if (IVD) {
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00007349 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007350 }
7351 else
7352 InstanceStart = InstanceSize;
7353 }
7354 Write__class_ro_t_initializer(Context, Result, flags,
7355 InstanceStart, InstanceSize,
7356 InstanceMethods,
7357 RefedProtocols,
7358 IVars,
7359 ClassProperties,
7360 "_OBJC_CLASS_RO_$_",
7361 CDecl->getNameAsString());
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007362
7363 Write_class_t(Context, Result,
7364 "OBJC_METACLASS_$_",
7365 CDecl, /*metaclass*/true);
7366
7367 Write_class_t(Context, Result,
7368 "OBJC_CLASS_$_",
7369 CDecl, /*metaclass*/false);
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007370
7371 if (ImplementationIsNonLazy(IDecl))
7372 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007373
Fariborz Jahanian11671902012-02-07 17:11:38 +00007374}
7375
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007376void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7377 int ClsDefCount = ClassImplementation.size();
7378 if (!ClsDefCount)
7379 return;
7380 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7381 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7382 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7383 for (int i = 0; i < ClsDefCount; i++) {
7384 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7385 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7386 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7387 Result += CDecl->getName(); Result += ",\n";
7388 }
7389 Result += "};\n";
7390}
7391
Fariborz Jahanian11671902012-02-07 17:11:38 +00007392void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7393 int ClsDefCount = ClassImplementation.size();
7394 int CatDefCount = CategoryImplementation.size();
7395
7396 // For each implemented class, write out all its meta data.
7397 for (int i = 0; i < ClsDefCount; i++)
7398 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7399
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007400 RewriteClassSetupInitHook(Result);
7401
Fariborz Jahanian11671902012-02-07 17:11:38 +00007402 // For each implemented category, write out all its meta data.
7403 for (int i = 0; i < CatDefCount; i++)
7404 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7405
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007406 RewriteCategorySetupInitHook(Result);
7407
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007408 if (ClsDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007409 if (LangOpts.MicrosoftExt)
7410 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007411 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7412 Result += llvm::utostr(ClsDefCount); Result += "]";
7413 Result +=
7414 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7415 "regular,no_dead_strip\")))= {\n";
7416 for (int i = 0; i < ClsDefCount; i++) {
7417 Result += "\t&OBJC_CLASS_$_";
7418 Result += ClassImplementation[i]->getNameAsString();
7419 Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007420 }
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007421 Result += "};\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007422
7423 if (!DefinedNonLazyClasses.empty()) {
7424 if (LangOpts.MicrosoftExt)
7425 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7426 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7427 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7428 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7429 Result += ",\n";
7430 }
7431 Result += "};\n";
7432 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007433 }
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007434
7435 if (CatDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007436 if (LangOpts.MicrosoftExt)
7437 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007438 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7439 Result += llvm::utostr(CatDefCount); Result += "]";
7440 Result +=
7441 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7442 "regular,no_dead_strip\")))= {\n";
7443 for (int i = 0; i < CatDefCount; i++) {
7444 Result += "\t&_OBJC_$_CATEGORY_";
7445 Result +=
7446 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7447 Result += "_$_";
7448 Result += CategoryImplementation[i]->getNameAsString();
7449 Result += ",\n";
7450 }
7451 Result += "};\n";
7452 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007453
7454 if (!DefinedNonLazyCategories.empty()) {
7455 if (LangOpts.MicrosoftExt)
7456 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7457 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7458 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7459 Result += "\t&_OBJC_$_CATEGORY_";
7460 Result +=
7461 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7462 Result += "_$_";
7463 Result += DefinedNonLazyCategories[i]->getNameAsString();
7464 Result += ",\n";
7465 }
7466 Result += "};\n";
7467 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007468}
7469
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007470void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7471 if (LangOpts.MicrosoftExt)
7472 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7473
7474 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7475 // version 0, ObjCABI is 2
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007476 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007477}
7478
Fariborz Jahanian11671902012-02-07 17:11:38 +00007479/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7480/// implementation.
7481void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7482 std::string &Result) {
Fariborz Jahanian45489622012-03-14 18:09:23 +00007483 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007484 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7485 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00007486 ObjCCategoryDecl *CDecl
7487 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007488
7489 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007490 FullCategoryName += "_$_";
7491 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007492
7493 // Build _objc_method_list for class's instance methods if needed
Aaron Ballmanf26acce2014-03-13 19:50:17 +00007494 SmallVector<ObjCMethodDecl *, 32> InstanceMethods(IDecl->instance_methods());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007495
7496 // If any of our property implementations have associated getters or
7497 // setters, produce metadata for them as well.
7498 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7499 PropEnd = IDecl->propimpl_end();
7500 Prop != PropEnd; ++Prop) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007501 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007502 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007503 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007504 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007505 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007506 if (!PD)
7507 continue;
7508 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7509 InstanceMethods.push_back(Getter);
7510 if (PD->isReadOnly())
7511 continue;
7512 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7513 InstanceMethods.push_back(Setter);
7514 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007515
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007516 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7517 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7518 FullCategoryName, true);
7519
7520 SmallVector<ObjCMethodDecl *, 32>
7521 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7522
7523 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7524 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7525 FullCategoryName, true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007526
7527 // Protocols referenced in class declaration?
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007528 // Protocol's super protocol list
7529 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidise7f3ef32012-03-13 01:09:41 +00007530 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7531 E = CDecl->protocol_end();
7532
7533 I != E; ++I) {
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007534 RefedProtocols.push_back(*I);
7535 // Must write out all protocol definitions in current qualifier list,
7536 // and in their nested qualifiers before writing out current definition.
7537 RewriteObjCProtocolMetaData(*I, Result);
7538 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007539
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007540 Write_protocol_list_initializer(Context, Result,
7541 RefedProtocols,
7542 "_OBJC_CATEGORY_PROTOCOLS_$_",
7543 FullCategoryName);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007544
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007545 // Protocol's property metadata.
Aaron Ballmand174edf2014-03-13 19:11:50 +00007546 SmallVector<ObjCPropertyDecl *, 8> ClassProperties(CDecl->properties());
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007547 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahaniane9863b52012-05-03 23:19:33 +00007548 /* Container */IDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007549 "_OBJC_$_PROP_LIST_",
7550 FullCategoryName);
7551
7552 Write_category_t(*this, Context, Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007553 CDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007554 ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007555 InstanceMethods,
7556 ClassMethods,
7557 RefedProtocols,
7558 ClassProperties);
7559
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007560 // Determine if this category is also "non-lazy".
7561 if (ImplementationIsNonLazy(IDecl))
7562 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007563
7564}
7565
7566void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7567 int CatDefCount = CategoryImplementation.size();
7568 if (!CatDefCount)
7569 return;
7570 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7571 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7572 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7573 for (int i = 0; i < CatDefCount; i++) {
7574 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7575 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7576 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7577 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7578 Result += ClassDecl->getName();
7579 Result += "_$_";
7580 Result += CatDecl->getName();
7581 Result += ",\n";
7582 }
7583 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007584}
7585
7586// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7587/// class methods.
7588template<typename MethodIterator>
7589void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7590 MethodIterator MethodEnd,
7591 bool IsInstanceMethod,
7592 StringRef prefix,
7593 StringRef ClassName,
7594 std::string &Result) {
7595 if (MethodBegin == MethodEnd) return;
7596
7597 if (!objc_impl_method) {
7598 /* struct _objc_method {
7599 SEL _cmd;
7600 char *method_types;
7601 void *_imp;
7602 }
7603 */
7604 Result += "\nstruct _objc_method {\n";
7605 Result += "\tSEL _cmd;\n";
7606 Result += "\tchar *method_types;\n";
7607 Result += "\tvoid *_imp;\n";
7608 Result += "};\n";
7609
7610 objc_impl_method = true;
7611 }
7612
7613 // Build _objc_method_list for class's methods if needed
7614
7615 /* struct {
7616 struct _objc_method_list *next_method;
7617 int method_count;
7618 struct _objc_method method_list[];
7619 }
7620 */
7621 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007622 Result += "\n";
7623 if (LangOpts.MicrosoftExt) {
7624 if (IsInstanceMethod)
7625 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7626 else
7627 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7628 }
7629 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007630 Result += "\tstruct _objc_method_list *next_method;\n";
7631 Result += "\tint method_count;\n";
7632 Result += "\tstruct _objc_method method_list[";
7633 Result += utostr(NumMethods);
7634 Result += "];\n} _OBJC_";
7635 Result += prefix;
7636 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7637 Result += "_METHODS_";
7638 Result += ClassName;
7639 Result += " __attribute__ ((used, section (\"__OBJC, __";
7640 Result += IsInstanceMethod ? "inst" : "cls";
7641 Result += "_meth\")))= ";
7642 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7643
7644 Result += "\t,{{(SEL)\"";
7645 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7646 std::string MethodTypeString;
7647 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7648 Result += "\", \"";
7649 Result += MethodTypeString;
7650 Result += "\", (void *)";
7651 Result += MethodInternalNames[*MethodBegin];
7652 Result += "}\n";
7653 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7654 Result += "\t ,{(SEL)\"";
7655 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7656 std::string MethodTypeString;
7657 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7658 Result += "\", \"";
7659 Result += MethodTypeString;
7660 Result += "\", (void *)";
7661 Result += MethodInternalNames[*MethodBegin];
7662 Result += "}\n";
7663 }
7664 Result += "\t }\n};\n";
7665}
7666
7667Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7668 SourceRange OldRange = IV->getSourceRange();
7669 Expr *BaseExpr = IV->getBase();
7670
7671 // Rewrite the base, but without actually doing replaces.
7672 {
7673 DisableReplaceStmtScope S(*this);
7674 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7675 IV->setBase(BaseExpr);
7676 }
7677
7678 ObjCIvarDecl *D = IV->getDecl();
7679
7680 Expr *Replacement = IV;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007681
Fariborz Jahanian11671902012-02-07 17:11:38 +00007682 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7683 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00007684 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007685 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7686 // lookup which class implements the instance variable.
7687 ObjCInterfaceDecl *clsDeclared = 0;
7688 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7689 clsDeclared);
7690 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7691
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007692 // Build name of symbol holding ivar offset.
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007693 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007694 if (D->isBitField())
7695 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7696 else
7697 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007698
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00007699 ReferencedIvars[clsDeclared].insert(D);
7700
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007701 // cast offset to "char *".
7702 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7703 Context->getPointerType(Context->CharTy),
Fariborz Jahanian11671902012-02-07 17:11:38 +00007704 CK_BitCast,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007705 BaseExpr);
7706 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7707 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007708 Context->UnsignedLongTy, 0, SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00007709 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7710 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007711 SourceLocation());
7712 BinaryOperator *addExpr =
7713 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7714 Context->getPointerType(Context->CharTy),
Lang Hames5de91cc2012-10-02 04:45:10 +00007715 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007716 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007717 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7718 SourceLocation(),
7719 addExpr);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007720 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007721 if (D->isBitField())
7722 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007723
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007724 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007725 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00007726 RD = RD->getDefinition();
7727 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007728 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007729 ObjCContainerDecl *CDecl =
7730 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7731 // ivar in class extensions requires special treatment.
7732 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7733 CDecl = CatDecl->getClassInterface();
7734 std::string RecName = CDecl->getName();
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007735 RecName += "_IMPL";
7736 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7737 SourceLocation(), SourceLocation(),
7738 &Context->Idents.get(RecName.c_str()));
7739 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7740 unsigned UnsignedIntSize =
7741 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7742 Expr *Zero = IntegerLiteral::Create(*Context,
7743 llvm::APInt(UnsignedIntSize, 0),
7744 Context->UnsignedIntTy, SourceLocation());
7745 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7746 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7747 Zero);
7748 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7749 SourceLocation(),
7750 &Context->Idents.get(D->getNameAsString()),
7751 IvarT, 0,
7752 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00007753 ICIS_NoInit);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007754 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7755 FD->getType(), VK_LValue,
7756 OK_Ordinary);
7757 IvarT = Context->getDecltypeType(ME, ME->getType());
7758 }
7759 }
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007760 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007761 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007762
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007763 castExpr = NoTypeInfoCStyleCastExpr(Context,
7764 castT,
7765 CK_BitCast,
7766 PE);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007767
7768
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007769 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007770 VK_LValue, OK_Ordinary,
7771 SourceLocation());
7772 PE = new (Context) ParenExpr(OldRange.getBegin(),
7773 OldRange.getEnd(),
7774 Exp);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007775
7776 if (D->isBitField()) {
7777 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7778 SourceLocation(),
7779 &Context->Idents.get(D->getNameAsString()),
7780 D->getType(), 0,
7781 /*BitWidth=*/D->getBitWidth(),
7782 /*Mutable=*/true,
7783 ICIS_NoInit);
7784 MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(),
7785 FD->getType(), VK_LValue,
7786 OK_Ordinary);
7787 Replacement = ME;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007788
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007789 }
7790 else
7791 Replacement = PE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007792 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007793
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007794 ReplaceStmtWithRange(IV, Replacement, OldRange);
7795 return Replacement;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007796}