blob: d14b78ce2e676daa6a32664ffc776fa3576bb11f [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"
27#include "llvm/ADT/OwningPtr.h"
28#include "llvm/ADT/SmallPtrSet.h"
29#include "llvm/ADT/StringExtras.h"
Fariborz Jahanian11671902012-02-07 17:11:38 +000030#include "llvm/Support/MemoryBuffer.h"
31#include "llvm/Support/raw_ostream.h"
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
Fariborz Jahanian11671902012-02-07 17:11:38 +00001163 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1164 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001165 RewriteProperty(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001166
1167 for (ObjCCategoryDecl::instmeth_iterator
1168 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1169 I != E; ++I)
1170 RewriteMethodDeclaration(*I);
1171 for (ObjCCategoryDecl::classmeth_iterator
1172 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1173 I != E; ++I)
1174 RewriteMethodDeclaration(*I);
1175
1176 // Lastly, comment out the @end.
1177 ReplaceText(CatDecl->getAtEndRange().getBegin(),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001178 strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001179}
1180
1181void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1182 SourceLocation LocStart = PDecl->getLocStart();
1183 assert(PDecl->isThisDeclarationADefinition());
1184
1185 // FIXME: handle protocol headers that are declared across multiple lines.
1186 ReplaceText(LocStart, 0, "// ");
1187
1188 for (ObjCProtocolDecl::instmeth_iterator
1189 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1190 I != E; ++I)
1191 RewriteMethodDeclaration(*I);
1192 for (ObjCProtocolDecl::classmeth_iterator
1193 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1194 I != E; ++I)
1195 RewriteMethodDeclaration(*I);
1196
1197 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1198 E = PDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001199 RewriteProperty(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001200
1201 // Lastly, comment out the @end.
1202 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001203 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001204
1205 // Must comment out @optional/@required
1206 const char *startBuf = SM->getCharacterData(LocStart);
1207 const char *endBuf = SM->getCharacterData(LocEnd);
1208 for (const char *p = startBuf; p < endBuf; p++) {
1209 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1210 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1211 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1212
1213 }
1214 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1215 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1216 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1217
1218 }
1219 }
1220}
1221
1222void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1223 SourceLocation LocStart = (*D.begin())->getLocStart();
1224 if (LocStart.isInvalid())
1225 llvm_unreachable("Invalid SourceLocation");
1226 // FIXME: handle forward protocol that are declared across multiple lines.
1227 ReplaceText(LocStart, 0, "// ");
1228}
1229
1230void
Craig Topper5603df42013-07-05 19:34:19 +00001231RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001232 SourceLocation LocStart = DG[0]->getLocStart();
1233 if (LocStart.isInvalid())
1234 llvm_unreachable("Invalid SourceLocation");
1235 // FIXME: handle forward protocol that are declared across multiple lines.
1236 ReplaceText(LocStart, 0, "// ");
1237}
1238
Fariborz Jahanian08ed8922012-04-03 17:35:38 +00001239void
1240RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1241 SourceLocation LocStart = LSD->getExternLoc();
1242 if (LocStart.isInvalid())
1243 llvm_unreachable("Invalid extern SourceLocation");
1244
1245 ReplaceText(LocStart, 0, "// ");
1246 if (!LSD->hasBraces())
1247 return;
1248 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1249 SourceLocation LocRBrace = LSD->getRBraceLoc();
1250 if (LocRBrace.isInvalid())
1251 llvm_unreachable("Invalid rbrace SourceLocation");
1252 ReplaceText(LocRBrace, 0, "// ");
1253}
1254
Fariborz Jahanian11671902012-02-07 17:11:38 +00001255void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1256 const FunctionType *&FPRetType) {
1257 if (T->isObjCQualifiedIdType())
1258 ResultStr += "id";
1259 else if (T->isFunctionPointerType() ||
1260 T->isBlockPointerType()) {
1261 // needs special handling, since pointer-to-functions have special
1262 // syntax (where a decaration models use).
1263 QualType retType = T;
1264 QualType PointeeTy;
1265 if (const PointerType* PT = retType->getAs<PointerType>())
1266 PointeeTy = PT->getPointeeType();
1267 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1268 PointeeTy = BPT->getPointeeType();
1269 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
Alp Toker314cc812014-01-25 16:55:45 +00001270 ResultStr +=
1271 FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001272 ResultStr += "(*";
1273 }
1274 } else
1275 ResultStr += T.getAsString(Context->getPrintingPolicy());
1276}
1277
1278void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1279 ObjCMethodDecl *OMD,
1280 std::string &ResultStr) {
1281 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1282 const FunctionType *FPRetType = 0;
1283 ResultStr += "\nstatic ";
Alp Toker314cc812014-01-25 16:55:45 +00001284 RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001285 ResultStr += " ";
1286
1287 // Unique method name
1288 std::string NameStr;
1289
1290 if (OMD->isInstanceMethod())
1291 NameStr += "_I_";
1292 else
1293 NameStr += "_C_";
1294
1295 NameStr += IDecl->getNameAsString();
1296 NameStr += "_";
1297
1298 if (ObjCCategoryImplDecl *CID =
1299 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1300 NameStr += CID->getNameAsString();
1301 NameStr += "_";
1302 }
1303 // Append selector names, replacing ':' with '_'
1304 {
1305 std::string selString = OMD->getSelector().getAsString();
1306 int len = selString.size();
1307 for (int i = 0; i < len; i++)
1308 if (selString[i] == ':')
1309 selString[i] = '_';
1310 NameStr += selString;
1311 }
1312 // Remember this name for metadata emission
1313 MethodInternalNames[OMD] = NameStr;
1314 ResultStr += NameStr;
1315
1316 // Rewrite arguments
1317 ResultStr += "(";
1318
1319 // invisible arguments
1320 if (OMD->isInstanceMethod()) {
1321 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1322 selfTy = Context->getPointerType(selfTy);
1323 if (!LangOpts.MicrosoftExt) {
1324 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1325 ResultStr += "struct ";
1326 }
1327 // When rewriting for Microsoft, explicitly omit the structure name.
1328 ResultStr += IDecl->getNameAsString();
1329 ResultStr += " *";
1330 }
1331 else
1332 ResultStr += Context->getObjCClassType().getAsString(
1333 Context->getPrintingPolicy());
1334
1335 ResultStr += " self, ";
1336 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1337 ResultStr += " _cmd";
1338
1339 // Method arguments.
Aaron Ballman43b68be2014-03-07 17:50:17 +00001340 for (const auto *PDecl : OMD->params()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001341 ResultStr += ", ";
1342 if (PDecl->getType()->isObjCQualifiedIdType()) {
1343 ResultStr += "id ";
1344 ResultStr += PDecl->getNameAsString();
1345 } else {
1346 std::string Name = PDecl->getNameAsString();
1347 QualType QT = PDecl->getType();
1348 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00001349 (void)convertBlockPointerToFunctionPointer(QT);
1350 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001351 ResultStr += Name;
1352 }
1353 }
1354 if (OMD->isVariadic())
1355 ResultStr += ", ...";
1356 ResultStr += ") ";
1357
1358 if (FPRetType) {
1359 ResultStr += ")"; // close the precedence "scope" for "*".
1360
1361 // Now, emit the argument types (if any).
1362 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1363 ResultStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00001364 for (unsigned i = 0, e = FT->getNumParams(); i != e; ++i) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001365 if (i) ResultStr += ", ";
Alp Toker9cacbab2014-01-20 20:26:09 +00001366 std::string ParamStr =
1367 FT->getParamType(i).getAsString(Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00001368 ResultStr += ParamStr;
1369 }
1370 if (FT->isVariadic()) {
Alp Toker9cacbab2014-01-20 20:26:09 +00001371 if (FT->getNumParams())
1372 ResultStr += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001373 ResultStr += "...";
1374 }
1375 ResultStr += ")";
1376 } else {
1377 ResultStr += "()";
1378 }
1379 }
1380}
1381void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1382 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1383 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1384
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001385 if (IMD) {
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001386 if (IMD->getIvarRBraceLoc().isValid()) {
1387 ReplaceText(IMD->getLocStart(), 1, "/** ");
1388 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001389 }
Fariborz Jahanian144b7222012-05-01 17:46:45 +00001390 else {
1391 InsertText(IMD->getLocStart(), "// ");
1392 }
Fariborz Jahanian2b383d212012-02-19 19:00:05 +00001393 }
1394 else
1395 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian11671902012-02-07 17:11:38 +00001396
1397 for (ObjCCategoryImplDecl::instmeth_iterator
1398 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1399 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1400 I != E; ++I) {
1401 std::string ResultStr;
1402 ObjCMethodDecl *OMD = *I;
1403 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1404 SourceLocation LocStart = OMD->getLocStart();
1405 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1406
1407 const char *startBuf = SM->getCharacterData(LocStart);
1408 const char *endBuf = SM->getCharacterData(LocEnd);
1409 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1410 }
1411
1412 for (ObjCCategoryImplDecl::classmeth_iterator
1413 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1414 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1415 I != E; ++I) {
1416 std::string ResultStr;
1417 ObjCMethodDecl *OMD = *I;
1418 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1419 SourceLocation LocStart = OMD->getLocStart();
1420 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1421
1422 const char *startBuf = SM->getCharacterData(LocStart);
1423 const char *endBuf = SM->getCharacterData(LocEnd);
1424 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1425 }
1426 for (ObjCCategoryImplDecl::propimpl_iterator
1427 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1428 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1429 I != E; ++I) {
David Blaikie40ed2972012-06-06 20:45:41 +00001430 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001431 }
1432
1433 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1434}
1435
1436void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian088959a2012-02-11 20:10:52 +00001437 // Do not synthesize more than once.
1438 if (ObjCSynthesizedStructs.count(ClassDecl))
1439 return;
1440 // Make sure super class's are written before current class is written.
1441 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1442 while (SuperClass) {
1443 RewriteInterfaceDecl(SuperClass);
1444 SuperClass = SuperClass->getSuperClass();
1445 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001446 std::string ResultStr;
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001447 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00001448 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00001449 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00001450 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1451
Fariborz Jahanianff513382012-02-15 22:01:47 +00001452 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00001453 // Mark this typedef as having been written into its c++ equivalent.
1454 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanianff513382012-02-15 22:01:47 +00001455
1456 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00001457 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00001458 RewriteProperty(*I);
Fariborz Jahanianff513382012-02-15 22:01:47 +00001459 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian11671902012-02-07 17:11:38 +00001460 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanianff513382012-02-15 22:01:47 +00001461 I != E; ++I)
1462 RewriteMethodDeclaration(*I);
1463 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian11671902012-02-07 17:11:38 +00001464 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanianff513382012-02-15 22:01:47 +00001465 I != E; ++I)
1466 RewriteMethodDeclaration(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001467
Fariborz Jahanianff513382012-02-15 22:01:47 +00001468 // Lastly, comment out the @end.
1469 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00001470 "/* @end */\n");
Fariborz Jahanianff513382012-02-15 22:01:47 +00001471 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001472}
1473
1474Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1475 SourceRange OldRange = PseudoOp->getSourceRange();
1476
1477 // We just magically know some things about the structure of this
1478 // expression.
1479 ObjCMessageExpr *OldMsg =
1480 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1481 PseudoOp->getNumSemanticExprs() - 1));
1482
1483 // Because the rewriter doesn't allow us to rewrite rewritten code,
1484 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001485 Expr *Base;
1486 SmallVector<Expr*, 2> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001487 {
1488 DisableReplaceStmtScope S(*this);
1489
1490 // Rebuild the base expression if we have one.
1491 Base = 0;
1492 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1493 Base = OldMsg->getInstanceReceiver();
1494 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1495 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1496 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001497
1498 unsigned numArgs = OldMsg->getNumArgs();
1499 for (unsigned i = 0; i < numArgs; i++) {
1500 Expr *Arg = OldMsg->getArg(i);
1501 if (isa<OpaqueValueExpr>(Arg))
1502 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1503 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1504 Args.push_back(Arg);
1505 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001506 }
1507
1508 // TODO: avoid this copy.
1509 SmallVector<SourceLocation, 1> SelLocs;
1510 OldMsg->getSelectorLocs(SelLocs);
1511
1512 ObjCMessageExpr *NewMsg = 0;
1513 switch (OldMsg->getReceiverKind()) {
1514 case ObjCMessageExpr::Class:
1515 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1516 OldMsg->getValueKind(),
1517 OldMsg->getLeftLoc(),
1518 OldMsg->getClassReceiverTypeInfo(),
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::Instance:
1528 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1529 OldMsg->getValueKind(),
1530 OldMsg->getLeftLoc(),
1531 Base,
1532 OldMsg->getSelector(),
1533 SelLocs,
1534 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001535 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001536 OldMsg->getRightLoc(),
1537 OldMsg->isImplicit());
1538 break;
1539
1540 case ObjCMessageExpr::SuperClass:
1541 case ObjCMessageExpr::SuperInstance:
1542 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1543 OldMsg->getValueKind(),
1544 OldMsg->getLeftLoc(),
1545 OldMsg->getSuperLoc(),
1546 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1547 OldMsg->getSuperType(),
1548 OldMsg->getSelector(),
1549 SelLocs,
1550 OldMsg->getMethodDecl(),
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001551 Args,
Fariborz Jahanian11671902012-02-07 17:11:38 +00001552 OldMsg->getRightLoc(),
1553 OldMsg->isImplicit());
1554 break;
1555 }
1556
1557 Stmt *Replacement = SynthMessageExpr(NewMsg);
1558 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1559 return Replacement;
1560}
1561
1562Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1563 SourceRange OldRange = PseudoOp->getSourceRange();
1564
1565 // We just magically know some things about the structure of this
1566 // expression.
1567 ObjCMessageExpr *OldMsg =
1568 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1569
1570 // Because the rewriter doesn't allow us to rewrite rewritten code,
1571 // we need to suppress rewriting the sub-statements.
1572 Expr *Base = 0;
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001573 SmallVector<Expr*, 1> Args;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001574 {
1575 DisableReplaceStmtScope S(*this);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001576 // Rebuild the base expression if we have one.
1577 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1578 Base = OldMsg->getInstanceReceiver();
1579 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1580 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1581 }
Fariborz Jahanian31176b12012-04-10 22:06:54 +00001582 unsigned numArgs = OldMsg->getNumArgs();
1583 for (unsigned i = 0; i < numArgs; i++) {
1584 Expr *Arg = OldMsg->getArg(i);
1585 if (isa<OpaqueValueExpr>(Arg))
1586 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1587 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1588 Args.push_back(Arg);
1589 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00001590 }
1591
1592 // Intentionally empty.
1593 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00001594
1595 ObjCMessageExpr *NewMsg = 0;
1596 switch (OldMsg->getReceiverKind()) {
1597 case ObjCMessageExpr::Class:
1598 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1599 OldMsg->getValueKind(),
1600 OldMsg->getLeftLoc(),
1601 OldMsg->getClassReceiverTypeInfo(),
1602 OldMsg->getSelector(),
1603 SelLocs,
1604 OldMsg->getMethodDecl(),
1605 Args,
1606 OldMsg->getRightLoc(),
1607 OldMsg->isImplicit());
1608 break;
1609
1610 case ObjCMessageExpr::Instance:
1611 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1612 OldMsg->getValueKind(),
1613 OldMsg->getLeftLoc(),
1614 Base,
1615 OldMsg->getSelector(),
1616 SelLocs,
1617 OldMsg->getMethodDecl(),
1618 Args,
1619 OldMsg->getRightLoc(),
1620 OldMsg->isImplicit());
1621 break;
1622
1623 case ObjCMessageExpr::SuperClass:
1624 case ObjCMessageExpr::SuperInstance:
1625 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1626 OldMsg->getValueKind(),
1627 OldMsg->getLeftLoc(),
1628 OldMsg->getSuperLoc(),
1629 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1630 OldMsg->getSuperType(),
1631 OldMsg->getSelector(),
1632 SelLocs,
1633 OldMsg->getMethodDecl(),
1634 Args,
1635 OldMsg->getRightLoc(),
1636 OldMsg->isImplicit());
1637 break;
1638 }
1639
1640 Stmt *Replacement = SynthMessageExpr(NewMsg);
1641 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1642 return Replacement;
1643}
1644
1645/// SynthCountByEnumWithState - To print:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001646/// ((NSUInteger (*)
1647/// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001648/// (void *)objc_msgSend)((id)l_collection,
1649/// sel_registerName(
1650/// "countByEnumeratingWithState:objects:count:"),
1651/// &enumState,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001652/// (id *)__rw_items, (NSUInteger)16)
Fariborz Jahanian11671902012-02-07 17:11:38 +00001653///
1654void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001655 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1656 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001657 buf += "\n\t\t";
1658 buf += "((id)l_collection,\n\t\t";
1659 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1660 buf += "\n\t\t";
1661 buf += "&enumState, "
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001662 "(id *)__rw_items, (_WIN_NSUInteger)16)";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001663}
1664
1665/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1666/// statement to exit to its outer synthesized loop.
1667///
1668Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1669 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1670 return S;
1671 // replace break with goto __break_label
1672 std::string buf;
1673
1674 SourceLocation startLoc = S->getLocStart();
1675 buf = "goto __break_label_";
1676 buf += utostr(ObjCBcLabelNo.back());
1677 ReplaceText(startLoc, strlen("break"), buf);
1678
1679 return 0;
1680}
1681
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001682void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1683 SourceLocation Loc,
1684 std::string &LineString) {
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00001685 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001686 LineString += "\n#line ";
1687 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1688 LineString += utostr(PLoc.getLine());
1689 LineString += " \"";
1690 LineString += Lexer::Stringify(PLoc.getFilename());
1691 LineString += "\"\n";
1692 }
1693}
1694
Fariborz Jahanian11671902012-02-07 17:11:38 +00001695/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1696/// statement to continue with its inner synthesized loop.
1697///
1698Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1699 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1700 return S;
1701 // replace continue with goto __continue_label
1702 std::string buf;
1703
1704 SourceLocation startLoc = S->getLocStart();
1705 buf = "goto __continue_label_";
1706 buf += utostr(ObjCBcLabelNo.back());
1707 ReplaceText(startLoc, strlen("continue"), buf);
1708
1709 return 0;
1710}
1711
1712/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1713/// It rewrites:
1714/// for ( type elem in collection) { stmts; }
1715
1716/// Into:
1717/// {
1718/// type elem;
1719/// struct __objcFastEnumerationState enumState = { 0 };
1720/// id __rw_items[16];
1721/// id l_collection = (id)collection;
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001722/// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian11671902012-02-07 17:11:38 +00001723/// objects:__rw_items count:16];
1724/// if (limit) {
1725/// unsigned long startMutations = *enumState.mutationsPtr;
1726/// do {
1727/// unsigned long counter = 0;
1728/// do {
1729/// if (startMutations != *enumState.mutationsPtr)
1730/// objc_enumerationMutation(l_collection);
1731/// elem = (type)enumState.itemsPtr[counter++];
1732/// stmts;
1733/// __continue_label: ;
1734/// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001735/// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1736/// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001737/// elem = nil;
1738/// __break_label: ;
1739/// }
1740/// else
1741/// elem = nil;
1742/// }
1743///
1744Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1745 SourceLocation OrigEnd) {
1746 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1747 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1748 "ObjCForCollectionStmt Statement stack mismatch");
1749 assert(!ObjCBcLabelNo.empty() &&
1750 "ObjCForCollectionStmt - Label No stack empty");
1751
1752 SourceLocation startLoc = S->getLocStart();
1753 const char *startBuf = SM->getCharacterData(startLoc);
1754 StringRef elementName;
1755 std::string elementTypeAsString;
1756 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00001757 // line directive first.
1758 SourceLocation ForEachLoc = S->getForLoc();
1759 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1760 buf += "{\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001761 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1762 // type elem;
1763 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1764 QualType ElementType = cast<ValueDecl>(D)->getType();
1765 if (ElementType->isObjCQualifiedIdType() ||
1766 ElementType->isObjCQualifiedInterfaceType())
1767 // Simply use 'id' for all qualified types.
1768 elementTypeAsString = "id";
1769 else
1770 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1771 buf += elementTypeAsString;
1772 buf += " ";
1773 elementName = D->getName();
1774 buf += elementName;
1775 buf += ";\n\t";
1776 }
1777 else {
1778 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1779 elementName = DR->getDecl()->getName();
1780 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1781 if (VD->getType()->isObjCQualifiedIdType() ||
1782 VD->getType()->isObjCQualifiedInterfaceType())
1783 // Simply use 'id' for all qualified types.
1784 elementTypeAsString = "id";
1785 else
1786 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1787 }
1788
1789 // struct __objcFastEnumerationState enumState = { 0 };
1790 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1791 // id __rw_items[16];
1792 buf += "id __rw_items[16];\n\t";
1793 // id l_collection = (id)
1794 buf += "id l_collection = (id)";
1795 // Find start location of 'collection' the hard way!
1796 const char *startCollectionBuf = startBuf;
1797 startCollectionBuf += 3; // skip 'for'
1798 startCollectionBuf = strchr(startCollectionBuf, '(');
1799 startCollectionBuf++; // skip '('
1800 // find 'in' and skip it.
1801 while (*startCollectionBuf != ' ' ||
1802 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1803 (*(startCollectionBuf+3) != ' ' &&
1804 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1805 startCollectionBuf++;
1806 startCollectionBuf += 3;
1807
1808 // Replace: "for (type element in" with string constructed thus far.
1809 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1810 // Replace ')' in for '(' type elem in collection ')' with ';'
1811 SourceLocation rightParenLoc = S->getRParenLoc();
1812 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1813 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1814 buf = ";\n\t";
1815
1816 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1817 // objects:__rw_items count:16];
1818 // which is synthesized into:
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001819 // NSUInteger limit =
1820 // ((NSUInteger (*)
1821 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian11671902012-02-07 17:11:38 +00001822 // (void *)objc_msgSend)((id)l_collection,
1823 // sel_registerName(
1824 // "countByEnumeratingWithState:objects:count:"),
1825 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001826 // (id *)__rw_items, (NSUInteger)16);
1827 buf += "_WIN_NSUInteger limit =\n\t\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001828 SynthCountByEnumWithState(buf);
1829 buf += ";\n\t";
1830 /// if (limit) {
1831 /// unsigned long startMutations = *enumState.mutationsPtr;
1832 /// do {
1833 /// unsigned long counter = 0;
1834 /// do {
1835 /// if (startMutations != *enumState.mutationsPtr)
1836 /// objc_enumerationMutation(l_collection);
1837 /// elem = (type)enumState.itemsPtr[counter++];
1838 buf += "if (limit) {\n\t";
1839 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1840 buf += "do {\n\t\t";
1841 buf += "unsigned long counter = 0;\n\t\t";
1842 buf += "do {\n\t\t\t";
1843 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1844 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1845 buf += elementName;
1846 buf += " = (";
1847 buf += elementTypeAsString;
1848 buf += ")enumState.itemsPtr[counter++];";
1849 // Replace ')' in for '(' type elem in collection ')' with all of these.
1850 ReplaceText(lparenLoc, 1, buf);
1851
1852 /// __continue_label: ;
1853 /// } while (counter < limit);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001854 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1855 /// objects:__rw_items count:16]));
Fariborz Jahanian11671902012-02-07 17:11:38 +00001856 /// elem = nil;
1857 /// __break_label: ;
1858 /// }
1859 /// else
1860 /// elem = nil;
1861 /// }
1862 ///
1863 buf = ";\n\t";
1864 buf += "__continue_label_";
1865 buf += utostr(ObjCBcLabelNo.back());
1866 buf += ": ;";
1867 buf += "\n\t\t";
1868 buf += "} while (counter < limit);\n\t";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001869 buf += "} while ((limit = ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001870 SynthCountByEnumWithState(buf);
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00001871 buf += "));\n\t";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001872 buf += elementName;
1873 buf += " = ((";
1874 buf += elementTypeAsString;
1875 buf += ")0);\n\t";
1876 buf += "__break_label_";
1877 buf += utostr(ObjCBcLabelNo.back());
1878 buf += ": ;\n\t";
1879 buf += "}\n\t";
1880 buf += "else\n\t\t";
1881 buf += elementName;
1882 buf += " = ((";
1883 buf += elementTypeAsString;
1884 buf += ")0);\n\t";
1885 buf += "}\n";
1886
1887 // Insert all these *after* the statement body.
1888 // FIXME: If this should support Obj-C++, support CXXTryStmt
1889 if (isa<CompoundStmt>(S->getBody())) {
1890 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1891 InsertText(endBodyLoc, buf);
1892 } else {
1893 /* Need to treat single statements specially. For example:
1894 *
1895 * for (A *a in b) if (stuff()) break;
1896 * for (A *a in b) xxxyy;
1897 *
1898 * The following code simply scans ahead to the semi to find the actual end.
1899 */
1900 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1901 const char *semiBuf = strchr(stmtBuf, ';');
1902 assert(semiBuf && "Can't find ';'");
1903 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1904 InsertText(endBodyLoc, buf);
1905 }
1906 Stmts.pop_back();
1907 ObjCBcLabelNo.pop_back();
1908 return 0;
1909}
1910
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001911static void Write_RethrowObject(std::string &buf) {
1912 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1913 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1914 buf += "\tid rethrow;\n";
1915 buf += "\t} _fin_force_rethow(_rethrow);";
1916}
1917
Fariborz Jahanian11671902012-02-07 17:11:38 +00001918/// RewriteObjCSynchronizedStmt -
1919/// This routine rewrites @synchronized(expr) stmt;
1920/// into:
1921/// objc_sync_enter(expr);
1922/// @try stmt @finally { objc_sync_exit(expr); }
1923///
1924Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1925 // Get the start location and compute the semi location.
1926 SourceLocation startLoc = S->getLocStart();
1927 const char *startBuf = SM->getCharacterData(startLoc);
1928
1929 assert((*startBuf == '@') && "bogus @synchronized location");
1930
1931 std::string buf;
Fariborz Jahaniane030a632012-11-07 00:43:05 +00001932 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1933 ConvertSourceLocationToLineDirective(SynchLoc, buf);
Fariborz Jahanianff0c4602013-09-17 17:51:48 +00001934 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001935
Fariborz Jahanian11671902012-02-07 17:11:38 +00001936 const char *lparenBuf = startBuf;
1937 while (*lparenBuf != '(') lparenBuf++;
1938 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahaniane8810762012-03-17 17:46:02 +00001939
1940 buf = "; objc_sync_enter(_sync_obj);\n";
1941 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1942 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1943 buf += "\n\tid sync_exit;";
1944 buf += "\n\t} _sync_exit(_sync_obj);\n";
1945
1946 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1947 // the sync expression is typically a message expression that's already
1948 // been rewritten! (which implies the SourceLocation's are invalid).
1949 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1950 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1951 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1952 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1953
1954 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1955 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1956 assert (*LBraceLocBuf == '{');
1957 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001958
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001959 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay6e177d32012-03-16 22:20:39 +00001960 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1961 "bogus @synchronized block");
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001962
1963 buf = "} catch (id e) {_rethrow = e;}\n";
1964 Write_RethrowObject(buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001965 buf += "}\n";
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00001966 buf += "}\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00001967
Fariborz Jahanian1d24a0252012-03-16 21:43:45 +00001968 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00001969
Fariborz Jahanian11671902012-02-07 17:11:38 +00001970 return 0;
1971}
1972
1973void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1974{
1975 // Perform a bottom up traversal of all children.
1976 for (Stmt::child_range CI = S->children(); CI; ++CI)
1977 if (*CI)
1978 WarnAboutReturnGotoStmts(*CI);
1979
1980 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1981 Diags.Report(Context->getFullLoc(S->getLocStart()),
1982 TryFinallyContainsReturnDiag);
1983 }
1984 return;
1985}
1986
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001987Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1988 SourceLocation startLoc = S->getAtLoc();
1989 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc37a1d62012-05-24 22:59:56 +00001990 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1991 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00001992
1993 return 0;
1994}
1995
Fariborz Jahanian11671902012-02-07 17:11:38 +00001996Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001997 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanianb960db42012-03-15 23:50:33 +00001998 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00001999 std::string buf;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002000 SourceLocation TryLocation = S->getAtTryLoc();
2001 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00002002
2003 if (finalStmt) {
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002004 if (noCatch)
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002005 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002006 else {
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002007 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002008 }
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00002009 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002010 // Get the start location and compute the semi location.
2011 SourceLocation startLoc = S->getLocStart();
2012 const char *startBuf = SM->getCharacterData(startLoc);
2013
2014 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanian3b71b172012-03-15 22:42:15 +00002015 if (finalStmt)
2016 ReplaceText(startLoc, 1, buf);
2017 else
2018 // @try -> try
2019 ReplaceText(startLoc, 1, "");
2020
Fariborz Jahanian11671902012-02-07 17:11:38 +00002021 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
2022 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002023 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00002024
Fariborz Jahanian11671902012-02-07 17:11:38 +00002025 startLoc = Catch->getLocStart();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002026 bool AtRemoved = false;
2027 if (catchDecl) {
2028 QualType t = catchDecl->getType();
2029 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
2030 // Should be a pointer to a class.
2031 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2032 if (IDecl) {
2033 std::string Result;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002034 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
2035
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002036 startBuf = SM->getCharacterData(startLoc);
2037 assert((*startBuf == '@') && "bogus @catch location");
2038 SourceLocation rParenLoc = Catch->getRParenLoc();
2039 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2040
2041 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002042 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanianf232bb42012-03-15 20:11:10 +00002043 Result += " *_"; Result += catchDecl->getNameAsString();
2044 Result += ")";
2045 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2046 // Foo *e = (Foo *)_e;
2047 Result.clear();
2048 Result = "{ ";
2049 Result += IDecl->getNameAsString();
2050 Result += " *"; Result += catchDecl->getNameAsString();
2051 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2052 Result += "_"; Result += catchDecl->getNameAsString();
2053
2054 Result += "; ";
2055 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2056 ReplaceText(lBraceLoc, 1, Result);
2057 AtRemoved = true;
2058 }
2059 }
2060 }
2061 if (!AtRemoved)
2062 // @catch -> catch
2063 ReplaceText(startLoc, 1, "");
Fariborz Jahanian2cc29af2012-03-12 23:58:28 +00002064
Fariborz Jahanian11671902012-02-07 17:11:38 +00002065 }
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002066 if (finalStmt) {
2067 buf.clear();
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00002068 SourceLocation FinallyLoc = finalStmt->getLocStart();
2069
2070 if (noCatch) {
2071 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2072 buf += "catch (id e) {_rethrow = e;}\n";
2073 }
2074 else {
2075 buf += "}\n";
2076 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2077 buf += "catch (id e) {_rethrow = e;}\n";
2078 }
2079
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002080 SourceLocation startFinalLoc = finalStmt->getLocStart();
2081 ReplaceText(startFinalLoc, 8, buf);
2082 Stmt *body = finalStmt->getFinallyBody();
2083 SourceLocation startFinalBodyLoc = body->getLocStart();
2084 buf.clear();
Fariborz Jahanianfe6268e2012-03-16 21:33:16 +00002085 Write_RethrowObject(buf);
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002086 ReplaceText(startFinalBodyLoc, 1, buf);
2087
2088 SourceLocation endFinalBodyLoc = body->getLocEnd();
2089 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahaniane8810762012-03-17 17:46:02 +00002090 // Now check for any return/continue/go statements within the @try.
2091 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanianb960db42012-03-15 23:50:33 +00002092 }
2093
Fariborz Jahanian11671902012-02-07 17:11:38 +00002094 return 0;
2095}
2096
2097// This can't be done with ReplaceStmt(S, ThrowExpr), since
2098// the throw expression is typically a message expression that's already
2099// been rewritten! (which implies the SourceLocation's are invalid).
2100Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2101 // Get the start location and compute the semi location.
2102 SourceLocation startLoc = S->getLocStart();
2103 const char *startBuf = SM->getCharacterData(startLoc);
2104
2105 assert((*startBuf == '@') && "bogus @throw location");
2106
2107 std::string buf;
2108 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2109 if (S->getThrowExpr())
2110 buf = "objc_exception_throw(";
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002111 else
2112 buf = "throw";
Fariborz Jahanian11671902012-02-07 17:11:38 +00002113
2114 // handle "@ throw" correctly.
2115 const char *wBuf = strchr(startBuf, 'w');
2116 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2117 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2118
Fariborz Jahanianb0fdab22013-02-11 19:30:33 +00002119 SourceLocation endLoc = S->getLocEnd();
2120 const char *endBuf = SM->getCharacterData(endLoc);
2121 const char *semiBuf = strchr(endBuf, ';');
Fariborz Jahanian11671902012-02-07 17:11:38 +00002122 assert((*semiBuf == ';') && "@throw: can't find ';'");
2123 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian52fe6a02012-03-16 16:52:06 +00002124 if (S->getThrowExpr())
2125 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian11671902012-02-07 17:11:38 +00002126 return 0;
2127}
2128
2129Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2130 // Create a new string expression.
Fariborz Jahanian11671902012-02-07 17:11:38 +00002131 std::string StrEncoding;
2132 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
Benjamin Kramerfc188422014-02-25 12:26:11 +00002133 Expr *Replacement = getStringLiteral(StrEncoding);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002134 ReplaceStmt(Exp, Replacement);
2135
2136 // Replace this subexpr in the parent.
2137 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2138 return Replacement;
2139}
2140
2141Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2142 if (!SelGetUidFunctionDecl)
2143 SynthSelGetUidFunctionDecl();
2144 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2145 // Create a call to sel_registerName("selName").
2146 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002147 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002148 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2149 &SelExprs[0], SelExprs.size());
2150 ReplaceStmt(Exp, SelExp);
2151 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2152 return SelExp;
2153}
2154
2155CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2156 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2157 SourceLocation EndLoc) {
2158 // Get the type, we will need to reference it in a couple spots.
2159 QualType msgSendType = FD->getType();
2160
2161 // Create a reference to the objc_msgSend() declaration.
2162 DeclRefExpr *DRE =
John McCall113bee02012-03-10 09:33:50 +00002163 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00002164
2165 // Now, we cast the reference to a pointer to the objc_msgSend type.
2166 QualType pToFunc = Context->getPointerType(msgSendType);
2167 ImplicitCastExpr *ICE =
2168 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2169 DRE, 0, VK_RValue);
2170
2171 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2172
2173 CallExpr *Exp =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002174 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian11671902012-02-07 17:11:38 +00002175 FT->getCallResultType(*Context),
2176 VK_RValue, EndLoc);
2177 return Exp;
2178}
2179
2180static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2181 const char *&startRef, const char *&endRef) {
2182 while (startBuf < endBuf) {
2183 if (*startBuf == '<')
2184 startRef = startBuf; // mark the start.
2185 if (*startBuf == '>') {
2186 if (startRef && *startRef == '<') {
2187 endRef = startBuf; // mark the end.
2188 return true;
2189 }
2190 return false;
2191 }
2192 startBuf++;
2193 }
2194 return false;
2195}
2196
2197static void scanToNextArgument(const char *&argRef) {
2198 int angle = 0;
2199 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2200 if (*argRef == '<')
2201 angle++;
2202 else if (*argRef == '>')
2203 angle--;
2204 argRef++;
2205 }
2206 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2207}
2208
2209bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2210 if (T->isObjCQualifiedIdType())
2211 return true;
2212 if (const PointerType *PT = T->getAs<PointerType>()) {
2213 if (PT->getPointeeType()->isObjCQualifiedIdType())
2214 return true;
2215 }
2216 if (T->isObjCObjectPointerType()) {
2217 T = T->getPointeeType();
2218 return T->isObjCQualifiedInterfaceType();
2219 }
2220 if (T->isArrayType()) {
2221 QualType ElemTy = Context->getBaseElementType(T);
2222 return needToScanForQualifiers(ElemTy);
2223 }
2224 return false;
2225}
2226
2227void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2228 QualType Type = E->getType();
2229 if (needToScanForQualifiers(Type)) {
2230 SourceLocation Loc, EndLoc;
2231
2232 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2233 Loc = ECE->getLParenLoc();
2234 EndLoc = ECE->getRParenLoc();
2235 } else {
2236 Loc = E->getLocStart();
2237 EndLoc = E->getLocEnd();
2238 }
2239 // This will defend against trying to rewrite synthesized expressions.
2240 if (Loc.isInvalid() || EndLoc.isInvalid())
2241 return;
2242
2243 const char *startBuf = SM->getCharacterData(Loc);
2244 const char *endBuf = SM->getCharacterData(EndLoc);
2245 const char *startRef = 0, *endRef = 0;
2246 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2247 // Get the locations of the startRef, endRef.
2248 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2249 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2250 // Comment out the protocol references.
2251 InsertText(LessLoc, "/*");
2252 InsertText(GreaterLoc, "*/");
2253 }
2254 }
2255}
2256
2257void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2258 SourceLocation Loc;
2259 QualType Type;
2260 const FunctionProtoType *proto = 0;
2261 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2262 Loc = VD->getLocation();
2263 Type = VD->getType();
2264 }
2265 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2266 Loc = FD->getLocation();
2267 // Check for ObjC 'id' and class types that have been adorned with protocol
2268 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2269 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2270 assert(funcType && "missing function type");
2271 proto = dyn_cast<FunctionProtoType>(funcType);
2272 if (!proto)
2273 return;
Alp Toker314cc812014-01-25 16:55:45 +00002274 Type = proto->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00002275 }
2276 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2277 Loc = FD->getLocation();
2278 Type = FD->getType();
2279 }
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00002280 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2281 Loc = TD->getLocation();
2282 Type = TD->getUnderlyingType();
2283 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00002284 else
2285 return;
2286
2287 if (needToScanForQualifiers(Type)) {
2288 // Since types are unique, we need to scan the buffer.
2289
2290 const char *endBuf = SM->getCharacterData(Loc);
2291 const char *startBuf = endBuf;
2292 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2293 startBuf--; // scan backward (from the decl location) for return type.
2294 const char *startRef = 0, *endRef = 0;
2295 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2296 // Get the locations of the startRef, endRef.
2297 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2298 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2299 // Comment out the protocol references.
2300 InsertText(LessLoc, "/*");
2301 InsertText(GreaterLoc, "*/");
2302 }
2303 }
2304 if (!proto)
2305 return; // most likely, was a variable
2306 // Now check arguments.
2307 const char *startBuf = SM->getCharacterData(Loc);
2308 const char *startFuncBuf = startBuf;
Alp Toker9cacbab2014-01-20 20:26:09 +00002309 for (unsigned i = 0; i < proto->getNumParams(); i++) {
2310 if (needToScanForQualifiers(proto->getParamType(i))) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00002311 // Since types are unique, we need to scan the buffer.
2312
2313 const char *endBuf = startBuf;
2314 // scan forward (from the decl location) for argument types.
2315 scanToNextArgument(endBuf);
2316 const char *startRef = 0, *endRef = 0;
2317 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2318 // Get the locations of the startRef, endRef.
2319 SourceLocation LessLoc =
2320 Loc.getLocWithOffset(startRef-startFuncBuf);
2321 SourceLocation GreaterLoc =
2322 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2323 // Comment out the protocol references.
2324 InsertText(LessLoc, "/*");
2325 InsertText(GreaterLoc, "*/");
2326 }
2327 startBuf = ++endBuf;
2328 }
2329 else {
2330 // If the function name is derived from a macro expansion, then the
2331 // argument buffer will not follow the name. Need to speak with Chris.
2332 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2333 startBuf++; // scan forward (from the decl location) for argument types.
2334 startBuf++;
2335 }
2336 }
2337}
2338
2339void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2340 QualType QT = ND->getType();
2341 const Type* TypePtr = QT->getAs<Type>();
2342 if (!isa<TypeOfExprType>(TypePtr))
2343 return;
2344 while (isa<TypeOfExprType>(TypePtr)) {
2345 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2346 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2347 TypePtr = QT->getAs<Type>();
2348 }
2349 // FIXME. This will not work for multiple declarators; as in:
2350 // __typeof__(a) b,c,d;
2351 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2352 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2353 const char *startBuf = SM->getCharacterData(DeclLoc);
2354 if (ND->getInit()) {
2355 std::string Name(ND->getNameAsString());
2356 TypeAsString += " " + Name + " = ";
2357 Expr *E = ND->getInit();
2358 SourceLocation startLoc;
2359 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2360 startLoc = ECE->getLParenLoc();
2361 else
2362 startLoc = E->getLocStart();
2363 startLoc = SM->getExpansionLoc(startLoc);
2364 const char *endBuf = SM->getCharacterData(startLoc);
2365 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2366 }
2367 else {
2368 SourceLocation X = ND->getLocEnd();
2369 X = SM->getExpansionLoc(X);
2370 const char *endBuf = SM->getCharacterData(X);
2371 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2372 }
2373}
2374
2375// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2376void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2377 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2378 SmallVector<QualType, 16> ArgTys;
2379 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2380 QualType getFuncType =
Jordan Rose5c382722013-03-08 21:51:21 +00002381 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002382 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002383 SourceLocation(),
2384 SourceLocation(),
2385 SelGetUidIdent, getFuncType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002386 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002387}
2388
2389void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2390 // declared in <objc/objc.h>
2391 if (FD->getIdentifier() &&
2392 FD->getName() == "sel_registerName") {
2393 SelGetUidFunctionDecl = FD;
2394 return;
2395 }
2396 RewriteObjCQualifiedInterfaceTypes(FD);
2397}
2398
2399void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2400 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2401 const char *argPtr = TypeString.c_str();
2402 if (!strchr(argPtr, '^')) {
2403 Str += TypeString;
2404 return;
2405 }
2406 while (*argPtr) {
2407 Str += (*argPtr == '^' ? '*' : *argPtr);
2408 argPtr++;
2409 }
2410}
2411
2412// FIXME. Consolidate this routine with RewriteBlockPointerType.
2413void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2414 ValueDecl *VD) {
2415 QualType Type = VD->getType();
2416 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2417 const char *argPtr = TypeString.c_str();
2418 int paren = 0;
2419 while (*argPtr) {
2420 switch (*argPtr) {
2421 case '(':
2422 Str += *argPtr;
2423 paren++;
2424 break;
2425 case ')':
2426 Str += *argPtr;
2427 paren--;
2428 break;
2429 case '^':
2430 Str += '*';
2431 if (paren == 1)
2432 Str += VD->getNameAsString();
2433 break;
2434 default:
2435 Str += *argPtr;
2436 break;
2437 }
2438 argPtr++;
2439 }
2440}
2441
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002442void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2443 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2444 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2445 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2446 if (!proto)
2447 return;
Alp Toker314cc812014-01-25 16:55:45 +00002448 QualType Type = proto->getReturnType();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002449 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2450 FdStr += " ";
2451 FdStr += FD->getName();
2452 FdStr += "(";
Alp Toker9cacbab2014-01-20 20:26:09 +00002453 unsigned numArgs = proto->getNumParams();
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002454 for (unsigned i = 0; i < numArgs; i++) {
Alp Toker9cacbab2014-01-20 20:26:09 +00002455 QualType ArgType = proto->getParamType(i);
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002456 RewriteBlockPointerType(FdStr, ArgType);
2457 if (i+1 < numArgs)
2458 FdStr += ", ";
2459 }
Fariborz Jahaniandf0577d2012-04-19 16:30:28 +00002460 if (FD->isVariadic()) {
2461 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2462 }
2463 else
2464 FdStr += ");\n";
Fariborz Jahanianca357d92012-04-19 00:50:01 +00002465 InsertText(FunLocStart, FdStr);
2466}
2467
Benjamin Kramer60509af2013-09-09 14:48:42 +00002468// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2469void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2470 if (SuperConstructorFunctionDecl)
Fariborz Jahanian11671902012-02-07 17:11:38 +00002471 return;
2472 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2473 SmallVector<QualType, 16> ArgTys;
2474 QualType argT = Context->getObjCIdType();
2475 assert(!argT.isNull() && "Can't find 'id' type");
2476 ArgTys.push_back(argT);
2477 ArgTys.push_back(argT);
2478 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002479 ArgTys);
Benjamin Kramer60509af2013-09-09 14:48:42 +00002480 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002481 SourceLocation(),
2482 SourceLocation(),
2483 msgSendIdent, msgSendType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002484 0, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002485}
2486
2487// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2488void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2489 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2490 SmallVector<QualType, 16> ArgTys;
2491 QualType argT = Context->getObjCIdType();
2492 assert(!argT.isNull() && "Can't find 'id' type");
2493 ArgTys.push_back(argT);
2494 argT = Context->getObjCSelType();
2495 assert(!argT.isNull() && "Can't find 'SEL' type");
2496 ArgTys.push_back(argT);
2497 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002498 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002499 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002500 SourceLocation(),
2501 SourceLocation(),
2502 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002503 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002504}
2505
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002506// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002507void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2508 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002509 SmallVector<QualType, 2> ArgTys;
2510 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002511 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002512 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002513 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002514 SourceLocation(),
2515 SourceLocation(),
2516 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002517 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002518}
2519
2520// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2521void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2522 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2523 SmallVector<QualType, 16> ArgTys;
2524 QualType argT = Context->getObjCIdType();
2525 assert(!argT.isNull() && "Can't find 'id' type");
2526 ArgTys.push_back(argT);
2527 argT = Context->getObjCSelType();
2528 assert(!argT.isNull() && "Can't find 'SEL' type");
2529 ArgTys.push_back(argT);
2530 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002531 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002532 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002533 SourceLocation(),
2534 SourceLocation(),
2535 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002536 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002537}
2538
2539// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002540// id objc_msgSendSuper_stret(void);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002541void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2542 IdentifierInfo *msgSendIdent =
2543 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00002544 SmallVector<QualType, 2> ArgTys;
2545 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002546 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002547 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002548 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2549 SourceLocation(),
2550 SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00002551 msgSendIdent,
2552 msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002553 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002554}
2555
2556// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2557void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2558 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2559 SmallVector<QualType, 16> ArgTys;
2560 QualType argT = Context->getObjCIdType();
2561 assert(!argT.isNull() && "Can't find 'id' type");
2562 ArgTys.push_back(argT);
2563 argT = Context->getObjCSelType();
2564 assert(!argT.isNull() && "Can't find 'SEL' type");
2565 ArgTys.push_back(argT);
2566 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rose5c382722013-03-08 21:51:21 +00002567 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002568 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002569 SourceLocation(),
2570 SourceLocation(),
2571 msgSendIdent, msgSendType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002572 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002573}
2574
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002575// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002576void RewriteModernObjC::SynthGetClassFunctionDecl() {
2577 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2578 SmallVector<QualType, 16> ArgTys;
2579 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002580 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002581 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002582 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002583 SourceLocation(),
2584 SourceLocation(),
2585 getClassIdent, getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002586 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002587}
2588
2589// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2590void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2591 IdentifierInfo *getSuperClassIdent =
2592 &Context->Idents.get("class_getSuperclass");
2593 SmallVector<QualType, 16> ArgTys;
2594 ArgTys.push_back(Context->getObjCClassType());
2595 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002596 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002597 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2598 SourceLocation(),
2599 SourceLocation(),
2600 getSuperClassIdent,
2601 getClassType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002602 SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002603}
2604
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002605// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002606void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2607 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2608 SmallVector<QualType, 16> ArgTys;
2609 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00002610 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rose5c382722013-03-08 21:51:21 +00002611 ArgTys);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002612 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosierac00fbc2013-01-04 22:40:33 +00002613 SourceLocation(),
2614 SourceLocation(),
2615 getClassIdent, getClassType,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002616 0, SC_Extern);
Fariborz Jahanian11671902012-02-07 17:11:38 +00002617}
2618
2619Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2620 QualType strType = getConstantStringStructType();
2621
2622 std::string S = "__NSConstantStringImpl_";
2623
2624 std::string tmpName = InFileName;
2625 unsigned i;
2626 for (i=0; i < tmpName.length(); i++) {
2627 char c = tmpName.at(i);
Alp Tokerd4733632013-12-05 04:47:09 +00002628 // replace any non-alphanumeric characters with '_'.
Jordan Rosea7d03842013-02-08 22:30:41 +00002629 if (!isAlphanumeric(c))
Fariborz Jahanian11671902012-02-07 17:11:38 +00002630 tmpName[i] = '_';
2631 }
2632 S += tmpName;
2633 S += "_";
2634 S += utostr(NumObjCStringLiterals++);
2635
2636 Preamble += "static __NSConstantStringImpl " + S;
2637 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2638 Preamble += "0x000007c8,"; // utf8_str
2639 // The pretty printer for StringLiteral handles escape characters properly.
2640 std::string prettyBufS;
2641 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smith235341b2012-08-16 03:56:14 +00002642 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian11671902012-02-07 17:11:38 +00002643 Preamble += prettyBuf.str();
2644 Preamble += ",";
2645 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2646
2647 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2648 SourceLocation(), &Context->Idents.get(S),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00002649 strType, 0, SC_Static);
John McCall113bee02012-03-10 09:33:50 +00002650 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00002651 SourceLocation());
2652 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2653 Context->getPointerType(DRE->getType()),
2654 VK_RValue, OK_Ordinary,
2655 SourceLocation());
2656 // cast to NSConstantString *
2657 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2658 CK_CPointerToObjCPointerCast, Unop);
2659 ReplaceStmt(Exp, cast);
2660 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2661 return cast;
2662}
2663
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00002664Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2665 unsigned IntSize =
2666 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2667
2668 Expr *FlagExp = IntegerLiteral::Create(*Context,
2669 llvm::APInt(IntSize, Exp->getValue()),
2670 Context->IntTy, Exp->getLocation());
2671 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2672 CK_BitCast, FlagExp);
2673 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2674 cast);
2675 ReplaceStmt(Exp, PE);
2676 return PE;
2677}
2678
Patrick Beard0caa3942012-04-19 00:25:12 +00002679Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002680 // synthesize declaration of helper functions needed in this routine.
2681 if (!SelGetUidFunctionDecl)
2682 SynthSelGetUidFunctionDecl();
2683 // use objc_msgSend() for all.
2684 if (!MsgSendFunctionDecl)
2685 SynthMsgSendFunctionDecl();
2686 if (!GetClassFunctionDecl)
2687 SynthGetClassFunctionDecl();
2688
2689 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2690 SourceLocation StartLoc = Exp->getLocStart();
2691 SourceLocation EndLoc = Exp->getLocEnd();
2692
2693 // Synthesize a call to objc_msgSend().
2694 SmallVector<Expr*, 4> MsgExprs;
2695 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002696
Patrick Beard0caa3942012-04-19 00:25:12 +00002697 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2698 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2699 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002700
Patrick Beard0caa3942012-04-19 00:25:12 +00002701 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002702 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002703 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2704 &ClsExprs[0],
2705 ClsExprs.size(),
2706 StartLoc, EndLoc);
2707 MsgExprs.push_back(Cls);
2708
Patrick Beard0caa3942012-04-19 00:25:12 +00002709 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002710 // it will be the 2nd argument.
2711 SmallVector<Expr*, 4> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00002712 SelExprs.push_back(
2713 getStringLiteral(BoxingMethod->getSelector().getAsString()));
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002714 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2715 &SelExprs[0], SelExprs.size(),
2716 StartLoc, EndLoc);
2717 MsgExprs.push_back(SelExp);
2718
Patrick Beard0caa3942012-04-19 00:25:12 +00002719 // User provided sub-expression is the 3rd, and last, argument.
2720 Expr *subExpr = Exp->getSubExpr();
2721 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002722 QualType type = ICE->getType();
2723 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2724 CastKind CK = CK_BitCast;
2725 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2726 CK = CK_IntegralToBoolean;
Patrick Beard0caa3942012-04-19 00:25:12 +00002727 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002728 }
Patrick Beard0caa3942012-04-19 00:25:12 +00002729 MsgExprs.push_back(subExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002730
2731 SmallVector<QualType, 4> ArgTypes;
2732 ArgTypes.push_back(Context->getObjCIdType());
2733 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002734 for (const auto PI : BoxingMethod->parameters())
2735 ArgTypes.push_back(PI->getType());
Patrick Beard0caa3942012-04-19 00:25:12 +00002736
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002737 QualType returnType = Exp->getType();
2738 // Get the type, we will need to reference it in a couple spots.
2739 QualType msgSendType = MsgSendFlavor->getType();
2740
2741 // Create a reference to the objc_msgSend() declaration.
2742 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2743 VK_LValue, SourceLocation());
2744
2745 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beard0caa3942012-04-19 00:25:12 +00002746 Context->getPointerType(Context->VoidTy),
2747 CK_BitCast, DRE);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002748
2749 // Now do the "normal" pointer to function cast.
2750 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002751 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002752 castType = Context->getPointerType(castType);
2753 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2754 cast);
2755
2756 // Don't forget the parens to enforce the proper binding.
2757 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2758
2759 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002760 CallExpr *CE = new (Context)
2761 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00002762 ReplaceStmt(Exp, CE);
2763 return CE;
2764}
2765
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002766Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2767 // synthesize declaration of helper functions needed in this routine.
2768 if (!SelGetUidFunctionDecl)
2769 SynthSelGetUidFunctionDecl();
2770 // use objc_msgSend() for all.
2771 if (!MsgSendFunctionDecl)
2772 SynthMsgSendFunctionDecl();
2773 if (!GetClassFunctionDecl)
2774 SynthGetClassFunctionDecl();
2775
2776 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2777 SourceLocation StartLoc = Exp->getLocStart();
2778 SourceLocation EndLoc = Exp->getLocEnd();
2779
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002780 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002781 QualType IntQT = Context->IntTy;
2782 QualType NSArrayFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002783 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002784 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002785 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2786 DeclRefExpr *NSArrayDRE =
2787 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2788 SourceLocation());
2789
2790 SmallVector<Expr*, 16> InitExprs;
2791 unsigned NumElements = Exp->getNumElements();
2792 unsigned UnsignedIntSize =
2793 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2794 Expr *count = IntegerLiteral::Create(*Context,
2795 llvm::APInt(UnsignedIntSize, NumElements),
2796 Context->UnsignedIntTy, SourceLocation());
2797 InitExprs.push_back(count);
2798 for (unsigned i = 0; i < NumElements; i++)
2799 InitExprs.push_back(Exp->getElement(i));
2800 Expr *NSArrayCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002801 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002802 NSArrayFType, VK_LValue, SourceLocation());
2803
2804 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2805 SourceLocation(),
2806 &Context->Idents.get("arr"),
2807 Context->getPointerType(Context->VoidPtrTy), 0,
2808 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002809 ICIS_NoInit);
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002810 MemberExpr *ArrayLiteralME =
2811 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2812 SourceLocation(),
2813 ARRFD->getType(), VK_LValue,
2814 OK_Ordinary);
2815 QualType ConstIdT = Context->getObjCIdType().withConst();
2816 CStyleCastExpr * ArrayLiteralObjects =
2817 NoTypeInfoCStyleCastExpr(Context,
2818 Context->getPointerType(ConstIdT),
2819 CK_BitCast,
2820 ArrayLiteralME);
2821
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002822 // Synthesize a call to objc_msgSend().
2823 SmallVector<Expr*, 32> MsgExprs;
2824 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002825 QualType expType = Exp->getType();
2826
2827 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2828 ObjCInterfaceDecl *Class =
2829 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2830
2831 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002832 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002833 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2834 &ClsExprs[0],
2835 ClsExprs.size(),
2836 StartLoc, EndLoc);
2837 MsgExprs.push_back(Cls);
2838
2839 // Create a call to sel_registerName("arrayWithObjects:count:").
2840 // it will be the 2nd argument.
2841 SmallVector<Expr*, 4> SelExprs;
2842 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002843 SelExprs.push_back(
2844 getStringLiteral(ArrayMethod->getSelector().getAsString()));
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002845 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2846 &SelExprs[0], SelExprs.size(),
2847 StartLoc, EndLoc);
2848 MsgExprs.push_back(SelExp);
2849
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002850 // (const id [])objects
2851 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002852
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00002853 // (NSUInteger)cnt
2854 Expr *cnt = IntegerLiteral::Create(*Context,
2855 llvm::APInt(UnsignedIntSize, NumElements),
2856 Context->UnsignedIntTy, SourceLocation());
2857 MsgExprs.push_back(cnt);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002858
2859
2860 SmallVector<QualType, 4> ArgTypes;
2861 ArgTypes.push_back(Context->getObjCIdType());
2862 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00002863 for (const auto *PI : ArrayMethod->params())
2864 ArgTypes.push_back(PI->getType());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002865
2866 QualType returnType = Exp->getType();
2867 // Get the type, we will need to reference it in a couple spots.
2868 QualType msgSendType = MsgSendFlavor->getType();
2869
2870 // Create a reference to the objc_msgSend() declaration.
2871 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2872 VK_LValue, SourceLocation());
2873
2874 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2875 Context->getPointerType(Context->VoidTy),
2876 CK_BitCast, DRE);
2877
2878 // Now do the "normal" pointer to function cast.
2879 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00002880 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002881 castType = Context->getPointerType(castType);
2882 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2883 cast);
2884
2885 // Don't forget the parens to enforce the proper binding.
2886 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2887
2888 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00002889 CallExpr *CE = new (Context)
2890 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00002891 ReplaceStmt(Exp, CE);
2892 return CE;
2893}
2894
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002895Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2896 // synthesize declaration of helper functions needed in this routine.
2897 if (!SelGetUidFunctionDecl)
2898 SynthSelGetUidFunctionDecl();
2899 // use objc_msgSend() for all.
2900 if (!MsgSendFunctionDecl)
2901 SynthMsgSendFunctionDecl();
2902 if (!GetClassFunctionDecl)
2903 SynthGetClassFunctionDecl();
2904
2905 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2906 SourceLocation StartLoc = Exp->getLocStart();
2907 SourceLocation EndLoc = Exp->getLocEnd();
2908
2909 // Build the expression: __NSContainer_literal(int, ...).arr
2910 QualType IntQT = Context->IntTy;
2911 QualType NSDictFType =
Jordan Rose5c382722013-03-08 21:51:21 +00002912 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002913 std::string NSDictFName("__NSContainer_literal");
2914 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2915 DeclRefExpr *NSDictDRE =
2916 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2917 SourceLocation());
2918
2919 SmallVector<Expr*, 16> KeyExprs;
2920 SmallVector<Expr*, 16> ValueExprs;
2921
2922 unsigned NumElements = Exp->getNumElements();
2923 unsigned UnsignedIntSize =
2924 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2925 Expr *count = IntegerLiteral::Create(*Context,
2926 llvm::APInt(UnsignedIntSize, NumElements),
2927 Context->UnsignedIntTy, SourceLocation());
2928 KeyExprs.push_back(count);
2929 ValueExprs.push_back(count);
2930 for (unsigned i = 0; i < NumElements; i++) {
2931 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2932 KeyExprs.push_back(Element.Key);
2933 ValueExprs.push_back(Element.Value);
2934 }
2935
2936 // (const id [])objects
2937 Expr *NSValueCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002938 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002939 NSDictFType, VK_LValue, SourceLocation());
2940
2941 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2942 SourceLocation(),
2943 &Context->Idents.get("arr"),
2944 Context->getPointerType(Context->VoidPtrTy), 0,
2945 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00002946 ICIS_NoInit);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002947 MemberExpr *DictLiteralValueME =
2948 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2949 SourceLocation(),
2950 ARRFD->getType(), VK_LValue,
2951 OK_Ordinary);
2952 QualType ConstIdT = Context->getObjCIdType().withConst();
2953 CStyleCastExpr * DictValueObjects =
2954 NoTypeInfoCStyleCastExpr(Context,
2955 Context->getPointerType(ConstIdT),
2956 CK_BitCast,
2957 DictLiteralValueME);
2958 // (const id <NSCopying> [])keys
2959 Expr *NSKeyCallExpr =
Benjamin Kramerc215e762012-08-24 11:54:20 +00002960 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002961 NSDictFType, VK_LValue, SourceLocation());
2962
2963 MemberExpr *DictLiteralKeyME =
2964 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2965 SourceLocation(),
2966 ARRFD->getType(), VK_LValue,
2967 OK_Ordinary);
2968
2969 CStyleCastExpr * DictKeyObjects =
2970 NoTypeInfoCStyleCastExpr(Context,
2971 Context->getPointerType(ConstIdT),
2972 CK_BitCast,
2973 DictLiteralKeyME);
2974
2975
2976
2977 // Synthesize a call to objc_msgSend().
2978 SmallVector<Expr*, 32> MsgExprs;
2979 SmallVector<Expr*, 4> ClsExprs;
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002980 QualType expType = Exp->getType();
2981
2982 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2983 ObjCInterfaceDecl *Class =
2984 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2985
2986 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002987 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002988 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2989 &ClsExprs[0],
2990 ClsExprs.size(),
2991 StartLoc, EndLoc);
2992 MsgExprs.push_back(Cls);
2993
2994 // Create a call to sel_registerName("arrayWithObjects:count:").
2995 // it will be the 2nd argument.
2996 SmallVector<Expr*, 4> SelExprs;
2997 ObjCMethodDecl *DictMethod = Exp->getDictWithObjectsMethod();
Benjamin Kramerfc188422014-02-25 12:26:11 +00002998 SelExprs.push_back(getStringLiteral(DictMethod->getSelector().getAsString()));
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00002999 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3000 &SelExprs[0], SelExprs.size(),
3001 StartLoc, EndLoc);
3002 MsgExprs.push_back(SelExp);
3003
3004 // (const id [])objects
3005 MsgExprs.push_back(DictValueObjects);
3006
3007 // (const id <NSCopying> [])keys
3008 MsgExprs.push_back(DictKeyObjects);
3009
3010 // (NSUInteger)cnt
3011 Expr *cnt = IntegerLiteral::Create(*Context,
3012 llvm::APInt(UnsignedIntSize, NumElements),
3013 Context->UnsignedIntTy, SourceLocation());
3014 MsgExprs.push_back(cnt);
3015
3016
3017 SmallVector<QualType, 8> ArgTypes;
3018 ArgTypes.push_back(Context->getObjCIdType());
3019 ArgTypes.push_back(Context->getObjCSelType());
Aaron Ballman43b68be2014-03-07 17:50:17 +00003020 for (const auto *PI : DictMethod->params()) {
3021 QualType T = PI->getType();
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003022 if (const PointerType* PT = T->getAs<PointerType>()) {
3023 QualType PointeeTy = PT->getPointeeType();
3024 convertToUnqualifiedObjCType(PointeeTy);
3025 T = Context->getPointerType(PointeeTy);
3026 }
3027 ArgTypes.push_back(T);
3028 }
3029
3030 QualType returnType = Exp->getType();
3031 // Get the type, we will need to reference it in a couple spots.
3032 QualType msgSendType = MsgSendFlavor->getType();
3033
3034 // Create a reference to the objc_msgSend() declaration.
3035 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3036 VK_LValue, SourceLocation());
3037
3038 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3039 Context->getPointerType(Context->VoidTy),
3040 CK_BitCast, DRE);
3041
3042 // Now do the "normal" pointer to function cast.
3043 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003044 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003045 castType = Context->getPointerType(castType);
3046 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3047 cast);
3048
3049 // Don't forget the parens to enforce the proper binding.
3050 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3051
3052 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003053 CallExpr *CE = new (Context)
3054 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00003055 ReplaceStmt(Exp, CE);
3056 return CE;
3057}
3058
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003059// struct __rw_objc_super {
3060// struct objc_object *object; struct objc_object *superClass;
3061// };
Fariborz Jahanian11671902012-02-07 17:11:38 +00003062QualType RewriteModernObjC::getSuperStructType() {
3063 if (!SuperStructDecl) {
3064 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3065 SourceLocation(), SourceLocation(),
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003066 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003067 QualType FieldTypes[2];
3068
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003069 // struct objc_object *object;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003070 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003071 // struct objc_object *superClass;
3072 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003073
3074 // Create fields
3075 for (unsigned i = 0; i < 2; ++i) {
3076 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3077 SourceLocation(),
3078 SourceLocation(), 0,
3079 FieldTypes[i], 0,
3080 /*BitWidth=*/0,
3081 /*Mutable=*/false,
Richard Smith2b013182012-06-10 03:12:00 +00003082 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003083 }
3084
3085 SuperStructDecl->completeDefinition();
3086 }
3087 return Context->getTagDeclType(SuperStructDecl);
3088}
3089
3090QualType RewriteModernObjC::getConstantStringStructType() {
3091 if (!ConstantStringDecl) {
3092 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3093 SourceLocation(), SourceLocation(),
3094 &Context->Idents.get("__NSConstantStringImpl"));
3095 QualType FieldTypes[4];
3096
3097 // struct objc_object *receiver;
3098 FieldTypes[0] = Context->getObjCIdType();
3099 // int flags;
3100 FieldTypes[1] = Context->IntTy;
3101 // char *str;
3102 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3103 // long length;
3104 FieldTypes[3] = Context->LongTy;
3105
3106 // Create fields
3107 for (unsigned i = 0; i < 4; ++i) {
3108 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3109 ConstantStringDecl,
3110 SourceLocation(),
3111 SourceLocation(), 0,
3112 FieldTypes[i], 0,
3113 /*BitWidth=*/0,
3114 /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00003115 ICIS_NoInit));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003116 }
3117
3118 ConstantStringDecl->completeDefinition();
3119 }
3120 return Context->getTagDeclType(ConstantStringDecl);
3121}
3122
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003123/// getFunctionSourceLocation - returns start location of a function
3124/// definition. Complication arises when function has declared as
3125/// extern "C" or extern "C" {...}
3126static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3127 FunctionDecl *FD) {
3128 if (FD->isExternC() && !FD->isMain()) {
3129 const DeclContext *DC = FD->getDeclContext();
3130 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3131 // if it is extern "C" {...}, return function decl's own location.
3132 if (!LSD->getRBraceLoc().isValid())
3133 return LSD->getExternLoc();
3134 }
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003135 if (FD->getStorageClass() != SC_None)
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003136 R.RewriteBlockLiteralFunctionDecl(FD);
3137 return FD->getTypeSpecStartLoc();
3138}
3139
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003140void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3141
3142 SourceLocation Location = D->getLocation();
3143
Fariborz Jahaniane4c7e852013-02-08 00:27:34 +00003144 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian83dadc72012-11-07 18:15:53 +00003145 std::string LineString("\n#line ");
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003146 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3147 LineString += utostr(PLoc.getLine());
3148 LineString += " \"";
NAKAMURA Takumib46a05c2012-11-06 22:45:31 +00003149 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00003150 if (isa<ObjCMethodDecl>(D))
3151 LineString += "\"";
3152 else LineString += "\"\n";
3153
3154 Location = D->getLocStart();
3155 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3156 if (FD->isExternC() && !FD->isMain()) {
3157 const DeclContext *DC = FD->getDeclContext();
3158 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3159 // if it is extern "C" {...}, return function decl's own location.
3160 if (!LSD->getRBraceLoc().isValid())
3161 Location = LSD->getExternLoc();
3162 }
3163 }
3164 InsertText(Location, LineString);
3165 }
3166}
3167
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003168/// SynthMsgSendStretCallExpr - This routine translates message expression
3169/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3170/// nil check on receiver must be performed before calling objc_msgSend_stret.
3171/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3172/// msgSendType - function type of objc_msgSend_stret(...)
3173/// returnType - Result type of the method being synthesized.
3174/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3175/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3176/// starting with receiver.
3177/// Method - Method being rewritten.
3178Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003179 QualType returnType,
3180 SmallVectorImpl<QualType> &ArgTypes,
3181 SmallVectorImpl<Expr*> &MsgExprs,
3182 ObjCMethodDecl *Method) {
3183 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003184 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3185 Method ? Method->isVariadic()
3186 : false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003187 castType = Context->getPointerType(castType);
3188
3189 // build type for containing the objc_msgSend_stret object.
3190 static unsigned stretCount=0;
3191 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003192 std::string str =
3193 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003194 str += "namespace {\n";
Fariborz Jahanian1a112522012-07-25 21:48:36 +00003195 str += "struct "; str += name;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003196 str += " {\n\t";
3197 str += name;
3198 str += "(id receiver, SEL sel";
3199 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003200 std::string ArgName = "arg"; ArgName += utostr(i);
3201 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3202 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003203 }
3204 // could be vararg.
3205 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian2794ad52012-06-29 19:55:46 +00003206 std::string ArgName = "arg"; ArgName += utostr(i);
3207 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3208 Context->getPrintingPolicy());
3209 str += ", "; str += ArgName;
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003210 }
3211
3212 str += ") {\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003213 str += "\t unsigned size = sizeof(";
3214 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3215
3216 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3217
3218 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3219 str += ")(void *)objc_msgSend)(receiver, sel";
3220 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3221 str += ", arg"; str += utostr(i);
3222 }
3223 // could be vararg.
3224 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3225 str += ", arg"; str += utostr(i);
3226 }
3227 str+= ");\n";
3228
3229 str += "\t else if (receiver == 0)\n";
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003230 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3231 str += "\t else\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003232
3233
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003234 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3235 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3236 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3237 str += ", arg"; str += utostr(i);
3238 }
3239 // could be vararg.
3240 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3241 str += ", arg"; str += utostr(i);
3242 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003243 str += ");\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003244
3245
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003246 str += "\t}\n";
3247 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3248 str += " s;\n";
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003249 str += "};\n};\n\n";
Fariborz Jahanianf1f36c62012-08-21 18:56:50 +00003250 SourceLocation FunLocStart;
3251 if (CurFunctionDef)
3252 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3253 else {
3254 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3255 FunLocStart = CurMethodDef->getLocStart();
3256 }
3257
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003258 InsertText(FunLocStart, str);
3259 ++stretCount;
3260
3261 // AST for __Stretn(receiver, args).s;
3262 IdentifierInfo *ID = &Context->Idents.get(name);
3263 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Chad Rosierac00fbc2013-01-04 22:40:33 +00003264 SourceLocation(), ID, castType, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003265 SC_Extern, false, false);
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003266 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3267 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003268 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003269 castType, VK_LValue, SourceLocation());
3270
3271 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3272 SourceLocation(),
3273 &Context->Idents.get("s"),
3274 returnType, 0,
3275 /*BitWidth=*/0, /*Mutable=*/true,
3276 ICIS_NoInit);
3277 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3278 FieldD->getType(), VK_LValue,
3279 OK_Ordinary);
3280
3281 return ME;
3282}
3283
Fariborz Jahanian11671902012-02-07 17:11:38 +00003284Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3285 SourceLocation StartLoc,
3286 SourceLocation EndLoc) {
3287 if (!SelGetUidFunctionDecl)
3288 SynthSelGetUidFunctionDecl();
3289 if (!MsgSendFunctionDecl)
3290 SynthMsgSendFunctionDecl();
3291 if (!MsgSendSuperFunctionDecl)
3292 SynthMsgSendSuperFunctionDecl();
3293 if (!MsgSendStretFunctionDecl)
3294 SynthMsgSendStretFunctionDecl();
3295 if (!MsgSendSuperStretFunctionDecl)
3296 SynthMsgSendSuperStretFunctionDecl();
3297 if (!MsgSendFpretFunctionDecl)
3298 SynthMsgSendFpretFunctionDecl();
3299 if (!GetClassFunctionDecl)
3300 SynthGetClassFunctionDecl();
3301 if (!GetSuperClassFunctionDecl)
3302 SynthGetSuperClassFunctionDecl();
3303 if (!GetMetaClassFunctionDecl)
3304 SynthGetMetaClassFunctionDecl();
3305
3306 // default to objc_msgSend().
3307 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3308 // May need to use objc_msgSend_stret() as well.
3309 FunctionDecl *MsgSendStretFlavor = 0;
3310 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
Alp Toker314cc812014-01-25 16:55:45 +00003311 QualType resultType = mDecl->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003312 if (resultType->isRecordType())
3313 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3314 else if (resultType->isRealFloatingType())
3315 MsgSendFlavor = MsgSendFpretFunctionDecl;
3316 }
3317
3318 // Synthesize a call to objc_msgSend().
3319 SmallVector<Expr*, 8> MsgExprs;
3320 switch (Exp->getReceiverKind()) {
3321 case ObjCMessageExpr::SuperClass: {
3322 MsgSendFlavor = MsgSendSuperFunctionDecl;
3323 if (MsgSendStretFlavor)
3324 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3325 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3326
3327 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3328
3329 SmallVector<Expr*, 4> InitExprs;
3330
3331 // set the receiver to self, the first argument to all methods.
3332 InitExprs.push_back(
3333 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3334 CK_BitCast,
3335 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003336 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003337 Context->getObjCIdType(),
3338 VK_RValue,
3339 SourceLocation()))
3340 ); // set the 'receiver'.
3341
3342 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3343 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003344 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003345 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003346 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3347 &ClsExprs[0],
3348 ClsExprs.size(),
3349 StartLoc,
3350 EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003351 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003352 ClsExprs.push_back(Cls);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003353 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3354 &ClsExprs[0], ClsExprs.size(),
3355 StartLoc, EndLoc);
3356
3357 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3358 // To turn off a warning, type-cast to 'id'
3359 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3360 NoTypeInfoCStyleCastExpr(Context,
3361 Context->getObjCIdType(),
3362 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003363 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003364 QualType superType = getSuperStructType();
3365 Expr *SuperRep;
3366
3367 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003368 SynthSuperConstructorFunctionDecl();
3369 // Simulate a constructor call...
3370 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003371 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003372 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003373 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003374 superType, VK_LValue,
3375 SourceLocation());
3376 // The code for super is a little tricky to prevent collision with
3377 // the structure definition in the header. The rewriter has it's own
3378 // internal definition (__rw_objc_super) that is uses. This is why
3379 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003380 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003381 //
3382 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3383 Context->getPointerType(SuperRep->getType()),
3384 VK_RValue, OK_Ordinary,
3385 SourceLocation());
3386 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3387 Context->getPointerType(superType),
3388 CK_BitCast, SuperRep);
3389 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003390 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003391 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003392 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003393 SourceLocation());
3394 TypeSourceInfo *superTInfo
3395 = Context->getTrivialTypeSourceInfo(superType);
3396 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3397 superType, VK_LValue,
3398 ILE, false);
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003399 // struct __rw_objc_super *
Fariborz Jahanian11671902012-02-07 17:11:38 +00003400 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3401 Context->getPointerType(SuperRep->getType()),
3402 VK_RValue, OK_Ordinary,
3403 SourceLocation());
3404 }
3405 MsgExprs.push_back(SuperRep);
3406 break;
3407 }
3408
3409 case ObjCMessageExpr::Class: {
3410 SmallVector<Expr*, 8> ClsExprs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003411 ObjCInterfaceDecl *Class
3412 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3413 IdentifierInfo *clsName = Class->getIdentifier();
Benjamin Kramerfc188422014-02-25 12:26:11 +00003414 ClsExprs.push_back(getStringLiteral(clsName->getName()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003415 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3416 &ClsExprs[0],
3417 ClsExprs.size(),
3418 StartLoc, EndLoc);
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003419 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3420 Context->getObjCIdType(),
3421 CK_BitCast, Cls);
3422 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003423 break;
3424 }
3425
3426 case ObjCMessageExpr::SuperInstance:{
3427 MsgSendFlavor = MsgSendSuperFunctionDecl;
3428 if (MsgSendStretFlavor)
3429 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3430 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3431 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3432 SmallVector<Expr*, 4> InitExprs;
3433
3434 InitExprs.push_back(
3435 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3436 CK_BitCast,
3437 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCall113bee02012-03-10 09:33:50 +00003438 false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003439 Context->getObjCIdType(),
3440 VK_RValue, SourceLocation()))
3441 ); // set the 'receiver'.
3442
3443 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3444 SmallVector<Expr*, 8> ClsExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003445 ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003446 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian11671902012-02-07 17:11:38 +00003447 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3448 &ClsExprs[0],
3449 ClsExprs.size(),
3450 StartLoc, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003451 ClsExprs.clear();
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00003452 ClsExprs.push_back(Cls);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003453 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3454 &ClsExprs[0], ClsExprs.size(),
3455 StartLoc, EndLoc);
3456
3457 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3458 // To turn off a warning, type-cast to 'id'
3459 InitExprs.push_back(
3460 // set 'super class', using class_getSuperclass().
3461 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3462 CK_BitCast, Cls));
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003463 // struct __rw_objc_super
Fariborz Jahanian11671902012-02-07 17:11:38 +00003464 QualType superType = getSuperStructType();
3465 Expr *SuperRep;
3466
3467 if (LangOpts.MicrosoftExt) {
Benjamin Kramer60509af2013-09-09 14:48:42 +00003468 SynthSuperConstructorFunctionDecl();
3469 // Simulate a constructor call...
3470 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCall113bee02012-03-10 09:33:50 +00003471 false, superType, VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003472 SourceLocation());
Benjamin Kramerc215e762012-08-24 11:54:20 +00003473 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003474 superType, VK_LValue, SourceLocation());
3475 // The code for super is a little tricky to prevent collision with
3476 // the structure definition in the header. The rewriter has it's own
3477 // internal definition (__rw_objc_super) that is uses. This is why
3478 // we need the cast below. For example:
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003479 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian11671902012-02-07 17:11:38 +00003480 //
3481 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3482 Context->getPointerType(SuperRep->getType()),
3483 VK_RValue, OK_Ordinary,
3484 SourceLocation());
3485 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3486 Context->getPointerType(superType),
3487 CK_BitCast, SuperRep);
3488 } else {
Fariborz Jahanian4af0e9e2012-04-13 16:20:05 +00003489 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian11671902012-02-07 17:11:38 +00003490 InitListExpr *ILE =
Benjamin Kramerc215e762012-08-24 11:54:20 +00003491 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003492 SourceLocation());
3493 TypeSourceInfo *superTInfo
3494 = Context->getTrivialTypeSourceInfo(superType);
3495 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3496 superType, VK_RValue, ILE,
3497 false);
3498 }
3499 MsgExprs.push_back(SuperRep);
3500 break;
3501 }
3502
3503 case ObjCMessageExpr::Instance: {
3504 // Remove all type-casts because it may contain objc-style types; e.g.
3505 // Foo<Proto> *.
3506 Expr *recExpr = Exp->getInstanceReceiver();
3507 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3508 recExpr = CE->getSubExpr();
3509 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3510 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3511 ? CK_BlockPointerToObjCPointerCast
3512 : CK_CPointerToObjCPointerCast;
3513
3514 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3515 CK, recExpr);
3516 MsgExprs.push_back(recExpr);
3517 break;
3518 }
3519 }
3520
3521 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3522 SmallVector<Expr*, 8> SelExprs;
Benjamin Kramerfc188422014-02-25 12:26:11 +00003523 SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
Fariborz Jahanian11671902012-02-07 17:11:38 +00003524 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3525 &SelExprs[0], SelExprs.size(),
3526 StartLoc,
3527 EndLoc);
3528 MsgExprs.push_back(SelExp);
3529
3530 // Now push any user supplied arguments.
3531 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3532 Expr *userExpr = Exp->getArg(i);
3533 // Make all implicit casts explicit...ICE comes in handy:-)
3534 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3535 // Reuse the ICE type, it is exactly what the doctor ordered.
3536 QualType type = ICE->getType();
3537 if (needToScanForQualifiers(type))
3538 type = Context->getObjCIdType();
3539 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3540 (void)convertBlockPointerToFunctionPointer(type);
3541 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3542 CastKind CK;
3543 if (SubExpr->getType()->isIntegralType(*Context) &&
3544 type->isBooleanType()) {
3545 CK = CK_IntegralToBoolean;
3546 } else if (type->isObjCObjectPointerType()) {
3547 if (SubExpr->getType()->isBlockPointerType()) {
3548 CK = CK_BlockPointerToObjCPointerCast;
3549 } else if (SubExpr->getType()->isPointerType()) {
3550 CK = CK_CPointerToObjCPointerCast;
3551 } else {
3552 CK = CK_BitCast;
3553 }
3554 } else {
3555 CK = CK_BitCast;
3556 }
3557
3558 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3559 }
3560 // Make id<P...> cast into an 'id' cast.
3561 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3562 if (CE->getType()->isObjCQualifiedIdType()) {
3563 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3564 userExpr = CE->getSubExpr();
3565 CastKind CK;
3566 if (userExpr->getType()->isIntegralType(*Context)) {
3567 CK = CK_IntegralToPointer;
3568 } else if (userExpr->getType()->isBlockPointerType()) {
3569 CK = CK_BlockPointerToObjCPointerCast;
3570 } else if (userExpr->getType()->isPointerType()) {
3571 CK = CK_CPointerToObjCPointerCast;
3572 } else {
3573 CK = CK_BitCast;
3574 }
3575 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3576 CK, userExpr);
3577 }
3578 }
3579 MsgExprs.push_back(userExpr);
3580 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3581 // out the argument in the original expression (since we aren't deleting
3582 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3583 //Exp->setArg(i, 0);
3584 }
3585 // Generate the funky cast.
3586 CastExpr *cast;
3587 SmallVector<QualType, 8> ArgTypes;
3588 QualType returnType;
3589
3590 // Push 'id' and 'SEL', the 2 implicit arguments.
3591 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3592 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3593 else
3594 ArgTypes.push_back(Context->getObjCIdType());
3595 ArgTypes.push_back(Context->getObjCSelType());
3596 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3597 // Push any user argument types.
Aaron Ballman43b68be2014-03-07 17:50:17 +00003598 for (const auto *PI : OMD->params()) {
3599 QualType t = PI->getType()->isObjCQualifiedIdType()
Fariborz Jahanian11671902012-02-07 17:11:38 +00003600 ? Context->getObjCIdType()
Aaron Ballman43b68be2014-03-07 17:50:17 +00003601 : PI->getType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003602 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3603 (void)convertBlockPointerToFunctionPointer(t);
3604 ArgTypes.push_back(t);
3605 }
3606 returnType = Exp->getType();
3607 convertToUnqualifiedObjCType(returnType);
3608 (void)convertBlockPointerToFunctionPointer(returnType);
3609 } else {
3610 returnType = Context->getObjCIdType();
3611 }
3612 // Get the type, we will need to reference it in a couple spots.
3613 QualType msgSendType = MsgSendFlavor->getType();
3614
3615 // Create a reference to the objc_msgSend() declaration.
John McCall113bee02012-03-10 09:33:50 +00003616 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian11671902012-02-07 17:11:38 +00003617 VK_LValue, SourceLocation());
3618
3619 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3620 // If we don't do this cast, we get the following bizarre warning/note:
3621 // xx.m:13: warning: function called through a non-compatible type
3622 // xx.m:13: note: if this code is reached, the program will abort
3623 cast = NoTypeInfoCStyleCastExpr(Context,
3624 Context->getPointerType(Context->VoidTy),
3625 CK_BitCast, DRE);
3626
3627 // Now do the "normal" pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00003628 // If we don't have a method decl, force a variadic cast.
3629 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003630 QualType castType =
Jordan Rose5c382722013-03-08 21:51:21 +00003631 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003632 castType = Context->getPointerType(castType);
3633 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3634 cast);
3635
3636 // Don't forget the parens to enforce the proper binding.
3637 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3638
3639 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Alp Toker314cc812014-01-25 16:55:45 +00003640 CallExpr *CE = new (Context)
3641 CallExpr(*Context, PE, MsgExprs, FT->getReturnType(), VK_RValue, EndLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003642 Stmt *ReplacingStmt = CE;
3643 if (MsgSendStretFlavor) {
3644 // We have the method which returns a struct/union. Must also generate
3645 // call to objc_msgSend_stret and hang both varieties on a conditional
3646 // expression which dictate which one to envoke depending on size of
3647 // method's return type.
3648
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003649 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3650 returnType,
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00003651 ArgTypes, MsgExprs,
3652 Exp->getMethodDecl());
Fariborz Jahanianb1a21242013-09-09 19:59:59 +00003653 ReplacingStmt = STCE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00003654 }
3655 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3656 return ReplacingStmt;
3657}
3658
3659Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3660 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3661 Exp->getLocEnd());
3662
3663 // Now do the actual rewrite.
3664 ReplaceStmt(Exp, ReplacingStmt);
3665
3666 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3667 return ReplacingStmt;
3668}
3669
3670// typedef struct objc_object Protocol;
3671QualType RewriteModernObjC::getProtocolType() {
3672 if (!ProtocolTypeDecl) {
3673 TypeSourceInfo *TInfo
3674 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3675 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3676 SourceLocation(), SourceLocation(),
3677 &Context->Idents.get("Protocol"),
3678 TInfo);
3679 }
3680 return Context->getTypeDeclType(ProtocolTypeDecl);
3681}
3682
3683/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3684/// a synthesized/forward data reference (to the protocol's metadata).
3685/// The forward references (and metadata) are generated in
3686/// RewriteModernObjC::HandleTranslationUnit().
3687Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00003688 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3689 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00003690 IdentifierInfo *ID = &Context->Idents.get(Name);
3691 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3692 SourceLocation(), ID, getProtocolType(), 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00003693 SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00003694 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3695 VK_LValue, SourceLocation());
Fariborz Jahaniand38951a2013-11-22 18:43:41 +00003696 CastExpr *castExpr =
3697 NoTypeInfoCStyleCastExpr(
3698 Context, Context->getPointerType(DRE->getType()), CK_BitCast, DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00003699 ReplaceStmt(Exp, castExpr);
3700 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3701 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3702 return castExpr;
3703
3704}
3705
3706bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3707 const char *endBuf) {
3708 while (startBuf < endBuf) {
3709 if (*startBuf == '#') {
3710 // Skip whitespace.
3711 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3712 ;
3713 if (!strncmp(startBuf, "if", strlen("if")) ||
3714 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3715 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3716 !strncmp(startBuf, "define", strlen("define")) ||
3717 !strncmp(startBuf, "undef", strlen("undef")) ||
3718 !strncmp(startBuf, "else", strlen("else")) ||
3719 !strncmp(startBuf, "elif", strlen("elif")) ||
3720 !strncmp(startBuf, "endif", strlen("endif")) ||
3721 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3722 !strncmp(startBuf, "include", strlen("include")) ||
3723 !strncmp(startBuf, "import", strlen("import")) ||
3724 !strncmp(startBuf, "include_next", strlen("include_next")))
3725 return true;
3726 }
3727 startBuf++;
3728 }
3729 return false;
3730}
3731
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003732/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3733/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003734bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003735 TagDecl *Tag,
3736 bool &IsNamedDefinition) {
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003737 if (!IDecl)
3738 return false;
3739 SourceLocation TagLocation;
3740 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3741 RD = RD->getDefinition();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003742 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003743 return false;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003744 IsNamedDefinition = true;
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003745 TagLocation = RD->getLocation();
3746 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003747 IDecl->getLocation(), TagLocation);
3748 }
3749 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3750 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3751 return false;
3752 IsNamedDefinition = true;
3753 TagLocation = ED->getLocation();
3754 return Context->getSourceManager().isBeforeInTranslationUnit(
3755 IDecl->getLocation(), TagLocation);
3756
Fariborz Jahanian5979c312012-04-30 19:46:53 +00003757 }
3758 return false;
3759}
3760
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003761/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003762/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003763bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3764 std::string &Result) {
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003765 if (isa<TypedefType>(Type)) {
3766 Result += "\t";
3767 return false;
3768 }
3769
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003770 if (Type->isArrayType()) {
3771 QualType ElemTy = Context->getBaseElementType(Type);
3772 return RewriteObjCFieldDeclType(ElemTy, Result);
3773 }
3774 else if (Type->isRecordType()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003775 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3776 if (RD->isCompleteDefinition()) {
3777 if (RD->isStruct())
3778 Result += "\n\tstruct ";
3779 else if (RD->isUnion())
3780 Result += "\n\tunion ";
3781 else
3782 assert(false && "class not allowed as an ivar type");
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003783
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003784 Result += RD->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003785 if (GlobalDefinedTags.count(RD)) {
3786 // struct/union is defined globally, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003787 Result += " ";
3788 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003789 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003790 Result += " {\n";
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00003791 for (auto *FD : RD->fields())
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003792 RewriteObjCFieldDecl(FD, Result);
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003793 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003794 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003795 }
3796 }
3797 else if (Type->isEnumeralType()) {
3798 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3799 if (ED->isCompleteDefinition()) {
3800 Result += "\n\tenum ";
3801 Result += ED->getName();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003802 if (GlobalDefinedTags.count(ED)) {
3803 // Enum is globall defined, use it.
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003804 Result += " ";
3805 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003806 }
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003807
3808 Result += " {\n";
Aaron Ballman23a6dcb2014-03-08 18:45:14 +00003809 for (const auto *EC : ED->enumerators()) {
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003810 Result += "\t"; Result += EC->getName(); Result += " = ";
3811 llvm::APSInt Val = EC->getInitVal();
3812 Result += Val.toString(10);
3813 Result += ",\n";
3814 }
3815 Result += "\t} ";
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003816 return true;
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003817 }
3818 }
3819
3820 Result += "\t";
3821 convertObjCTypeToCStyleType(Type);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003822 return false;
3823}
3824
3825
3826/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3827/// It handles elaborated types, as well as enum types in the process.
3828void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3829 std::string &Result) {
3830 QualType Type = fieldDecl->getType();
3831 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003832
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003833 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3834 if (!EleboratedType)
3835 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003836 Result += Name;
3837 if (fieldDecl->isBitField()) {
3838 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3839 }
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003840 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman07bab732012-12-13 01:43:21 +00003841 const ArrayType *AT = Context->getAsArrayType(Type);
3842 do {
3843 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003844 Result += "[";
3845 llvm::APInt Dim = CAT->getSize();
3846 Result += utostr(Dim.getZExtValue());
3847 Result += "]";
3848 }
Eli Friedman07bab732012-12-13 01:43:21 +00003849 AT = Context->getAsArrayType(AT->getElementType());
3850 } while (AT);
Fariborz Jahanianc2e2ad62012-03-09 23:46:23 +00003851 }
3852
Fariborz Jahanian265a4212012-02-28 22:45:07 +00003853 Result += ";\n";
3854}
3855
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003856/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3857/// named aggregate types into the input buffer.
3858void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3859 std::string &Result) {
3860 QualType Type = fieldDecl->getType();
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00003861 if (isa<TypedefType>(Type))
3862 return;
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003863 if (Type->isArrayType())
3864 Type = Context->getBaseElementType(Type);
Fariborz Jahanian144b7222012-05-01 17:46:45 +00003865 ObjCContainerDecl *IDecl =
3866 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00003867
3868 TagDecl *TD = 0;
3869 if (Type->isRecordType()) {
3870 TD = Type->getAs<RecordType>()->getDecl();
3871 }
3872 else if (Type->isEnumeralType()) {
3873 TD = Type->getAs<EnumType>()->getDecl();
3874 }
3875
3876 if (TD) {
3877 if (GlobalDefinedTags.count(TD))
3878 return;
3879
3880 bool IsNamedDefinition = false;
3881 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3882 RewriteObjCFieldDeclType(Type, Result);
3883 Result += ";";
3884 }
3885 if (IsNamedDefinition)
3886 GlobalDefinedTags.insert(TD);
3887 }
3888
3889}
3890
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00003891unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3892 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3893 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3894 return IvarGroupNumber[IV];
3895 }
3896 unsigned GroupNo = 0;
3897 SmallVector<const ObjCIvarDecl *, 8> IVars;
3898 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3899 IVD; IVD = IVD->getNextIvar())
3900 IVars.push_back(IVD);
3901
3902 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3903 if (IVars[i]->isBitField()) {
3904 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3905 while (i < e && IVars[i]->isBitField())
3906 IvarGroupNumber[IVars[i++]] = GroupNo;
3907 if (i < e)
3908 --i;
3909 }
3910
3911 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3912 return IvarGroupNumber[IV];
3913}
3914
3915QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3916 ObjCIvarDecl *IV,
3917 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3918 std::string StructTagName;
3919 ObjCIvarBitfieldGroupType(IV, StructTagName);
3920 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3921 Context->getTranslationUnitDecl(),
3922 SourceLocation(), SourceLocation(),
3923 &Context->Idents.get(StructTagName));
3924 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3925 ObjCIvarDecl *Ivar = IVars[i];
3926 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3927 &Context->Idents.get(Ivar->getName()),
3928 Ivar->getType(),
3929 0, /*Expr *BW */Ivar->getBitWidth(), false,
3930 ICIS_NoInit));
3931 }
3932 RD->completeDefinition();
3933 return Context->getTagDeclType(RD);
3934}
3935
3936QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3937 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3938 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3939 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3940 if (GroupRecordType.count(tuple))
3941 return GroupRecordType[tuple];
3942
3943 SmallVector<ObjCIvarDecl *, 8> IVars;
3944 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3945 IVD; IVD = IVD->getNextIvar()) {
3946 if (IVD->isBitField())
3947 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3948 else {
3949 if (!IVars.empty()) {
3950 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3951 // Generate the struct type for this group of bitfield ivars.
3952 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3953 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3954 IVars.clear();
3955 }
3956 }
3957 }
3958 if (!IVars.empty()) {
3959 // Do the last one.
3960 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3961 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3962 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3963 }
3964 QualType RetQT = GroupRecordType[tuple];
3965 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3966
3967 return RetQT;
3968}
3969
3970/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
3971/// Name would be: classname__GRBF_n where n is the group number for this ivar.
3972void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
3973 std::string &Result) {
3974 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3975 Result += CDecl->getName();
3976 Result += "__GRBF_";
3977 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3978 Result += utostr(GroupNo);
3979 return;
3980}
3981
3982/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
3983/// Name of the struct would be: classname__T_n where n is the group number for
3984/// this ivar.
3985void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
3986 std::string &Result) {
3987 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3988 Result += CDecl->getName();
3989 Result += "__T_";
3990 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3991 Result += utostr(GroupNo);
3992 return;
3993}
3994
3995/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
3996/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
3997/// this ivar.
3998void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
3999 std::string &Result) {
4000 Result += "OBJC_IVAR_$_";
4001 ObjCIvarBitfieldGroupDecl(IV, Result);
4002}
4003
4004#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
4005 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
4006 ++IX; \
4007 if (IX < ENDIX) \
4008 --IX; \
4009}
4010
Fariborz Jahanian11671902012-02-07 17:11:38 +00004011/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
4012/// an objective-c class with ivars.
4013void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
4014 std::string &Result) {
4015 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
4016 assert(CDecl->getName() != "" &&
4017 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004018 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004019 SmallVector<ObjCIvarDecl *, 8> IVars;
4020 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00004021 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004022 IVars.push_back(IVD);
Fariborz Jahaniand7a32612012-03-06 17:16:27 +00004023
Fariborz Jahanian11671902012-02-07 17:11:38 +00004024 SourceLocation LocStart = CDecl->getLocStart();
4025 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004026
Fariborz Jahanian11671902012-02-07 17:11:38 +00004027 const char *startBuf = SM->getCharacterData(LocStart);
4028 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004029
Fariborz Jahanian11671902012-02-07 17:11:38 +00004030 // If no ivars and no root or if its root, directly or indirectly,
4031 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004032 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian11671902012-02-07 17:11:38 +00004033 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
4034 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4035 ReplaceText(LocStart, endBuf-startBuf, Result);
4036 return;
4037 }
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004038
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00004039 // Insert named struct/union definitions inside class to
4040 // outer scope. This follows semantics of locally defined
4041 // struct/unions in objective-c classes.
4042 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4043 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004044
4045 // Insert named structs which are syntheized to group ivar bitfields
4046 // to outer scope as well.
4047 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4048 if (IVars[i]->isBitField()) {
4049 ObjCIvarDecl *IV = IVars[i];
4050 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
4051 RewriteObjCFieldDeclType(QT, Result);
4052 Result += ";";
4053 // skip over ivar bitfields in this group.
4054 SKIP_BITFIELDS(i , e, IVars);
4055 }
4056
Fariborz Jahanian11671902012-02-07 17:11:38 +00004057 Result += "\nstruct ";
4058 Result += CDecl->getNameAsString();
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004059 Result += "_IMPL {\n";
4060
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004061 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004062 Result += "\tstruct "; Result += RCDecl->getNameAsString();
4063 Result += "_IMPL "; Result += RCDecl->getNameAsString();
4064 Result += "_IVARS;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004065 }
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00004066
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004067 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
4068 if (IVars[i]->isBitField()) {
4069 ObjCIvarDecl *IV = IVars[i];
4070 Result += "\tstruct ";
4071 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
4072 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
4073 // skip over ivar bitfields in this group.
4074 SKIP_BITFIELDS(i , e, IVars);
4075 }
4076 else
4077 RewriteObjCFieldDecl(IVars[i], Result);
4078 }
Fariborz Jahanian245534d2012-02-12 21:36:23 +00004079
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00004080 Result += "};\n";
4081 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4082 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00004083 // Mark this struct as having been generated.
4084 if (!ObjCSynthesizedStructs.insert(CDecl))
4085 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian11671902012-02-07 17:11:38 +00004086}
4087
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004088/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4089/// have been referenced in an ivar access expression.
4090void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4091 std::string &Result) {
4092 // write out ivar offset symbols which have been referenced in an ivar
4093 // access expression.
4094 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4095 if (Ivars.empty())
4096 return;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004097
4098 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004099 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
4100 e = Ivars.end(); i != e; i++) {
4101 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004102 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4103 unsigned GroupNo = 0;
4104 if (IvarDecl->isBitField()) {
4105 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4106 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4107 continue;
4108 }
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004109 Result += "\n";
4110 if (LangOpts.MicrosoftExt)
4111 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004112 Result += "extern \"C\" ";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00004113 if (LangOpts.MicrosoftExt &&
4114 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00004115 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4116 Result += "__declspec(dllimport) ";
4117
Fariborz Jahanian38c59102012-03-27 16:21:30 +00004118 Result += "unsigned long ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00004119 if (IvarDecl->isBitField()) {
4120 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4121 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4122 }
4123 else
4124 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00004125 Result += ";";
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00004126 }
4127}
4128
Fariborz Jahanian11671902012-02-07 17:11:38 +00004129//===----------------------------------------------------------------------===//
4130// Meta Data Emission
4131//===----------------------------------------------------------------------===//
4132
4133
4134/// RewriteImplementations - This routine rewrites all method implementations
4135/// and emits meta-data.
4136
4137void RewriteModernObjC::RewriteImplementations() {
4138 int ClsDefCount = ClassImplementation.size();
4139 int CatDefCount = CategoryImplementation.size();
4140
4141 // Rewrite implemented methods
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004142 for (int i = 0; i < ClsDefCount; i++) {
4143 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4144 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4145 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniand268b0c2012-02-17 22:20:12 +00004146 assert(false &&
4147 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00004148 RewriteImplementationDecl(OIMP);
4149 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004150
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004151 for (int i = 0; i < CatDefCount; i++) {
4152 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4153 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4154 if (CDecl->isImplicitInterfaceDecl())
4155 assert(false &&
4156 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00004157 RewriteImplementationDecl(CIMP);
4158 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004159}
4160
4161void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4162 const std::string &Name,
4163 ValueDecl *VD, bool def) {
4164 assert(BlockByRefDeclNo.count(VD) &&
4165 "RewriteByRefString: ByRef decl missing");
4166 if (def)
4167 ResultStr += "struct ";
4168 ResultStr += "__Block_byref_" + Name +
4169 "_" + utostr(BlockByRefDeclNo[VD]) ;
4170}
4171
4172static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4173 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4174 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4175 return false;
4176}
4177
4178std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4179 StringRef funcName,
4180 std::string Tag) {
4181 const FunctionType *AFT = CE->getFunctionType();
Alp Toker314cc812014-01-25 16:55:45 +00004182 QualType RT = AFT->getReturnType();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004183 std::string StructRef = "struct " + Tag;
Fariborz Jahanianb6933bc2012-11-06 23:25:49 +00004184 SourceLocation BlockLoc = CE->getExprLoc();
4185 std::string S;
4186 ConvertSourceLocationToLineDirective(BlockLoc, S);
4187
4188 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4189 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004190
4191 BlockDecl *BD = CE->getBlockDecl();
4192
4193 if (isa<FunctionNoProtoType>(AFT)) {
4194 // No user-supplied arguments. Still need to pass in a pointer to the
4195 // block (to reference imported block decl refs).
4196 S += "(" + StructRef + " *__cself)";
4197 } else if (BD->param_empty()) {
4198 S += "(" + StructRef + " *__cself)";
4199 } else {
4200 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4201 assert(FT && "SynthesizeBlockFunc: No function proto");
4202 S += '(';
4203 // first add the implicit argument.
4204 S += StructRef + " *__cself, ";
4205 std::string ParamStr;
4206 for (BlockDecl::param_iterator AI = BD->param_begin(),
4207 E = BD->param_end(); AI != E; ++AI) {
4208 if (AI != BD->param_begin()) S += ", ";
4209 ParamStr = (*AI)->getNameAsString();
4210 QualType QT = (*AI)->getType();
Fariborz Jahanian835cabe2012-03-27 16:42:20 +00004211 (void)convertBlockPointerToFunctionPointer(QT);
4212 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian11671902012-02-07 17:11:38 +00004213 S += ParamStr;
4214 }
4215 if (FT->isVariadic()) {
4216 if (!BD->param_empty()) S += ", ";
4217 S += "...";
4218 }
4219 S += ')';
4220 }
4221 S += " {\n";
4222
4223 // Create local declarations to avoid rewriting all closure decl ref exprs.
4224 // First, emit a declaration for all "by ref" decls.
Craig Topper2341c0d2013-07-04 03:08:24 +00004225 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004226 E = BlockByRefDecls.end(); I != E; ++I) {
4227 S += " ";
4228 std::string Name = (*I)->getNameAsString();
4229 std::string TypeString;
4230 RewriteByRefString(TypeString, Name, (*I));
4231 TypeString += " *";
4232 Name = TypeString + Name;
4233 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4234 }
4235 // Next, emit a declaration for all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004236 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004237 E = BlockByCopyDecls.end(); I != E; ++I) {
4238 S += " ";
4239 // Handle nested closure invocation. For example:
4240 //
4241 // void (^myImportedClosure)(void);
4242 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4243 //
4244 // void (^anotherClosure)(void);
4245 // anotherClosure = ^(void) {
4246 // myImportedClosure(); // import and invoke the closure
4247 // };
4248 //
4249 if (isTopLevelBlockPointerType((*I)->getType())) {
4250 RewriteBlockPointerTypeVariable(S, (*I));
4251 S += " = (";
4252 RewriteBlockPointerType(S, (*I)->getType());
4253 S += ")";
4254 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4255 }
4256 else {
4257 std::string Name = (*I)->getNameAsString();
4258 QualType QT = (*I)->getType();
4259 if (HasLocalVariableExternalStorage(*I))
4260 QT = Context->getPointerType(QT);
4261 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4262 S += Name + " = __cself->" +
4263 (*I)->getNameAsString() + "; // bound by copy\n";
4264 }
4265 }
4266 std::string RewrittenStr = RewrittenBlockExprs[CE];
4267 const char *cstr = RewrittenStr.c_str();
4268 while (*cstr++ != '{') ;
4269 S += cstr;
4270 S += "\n";
4271 return S;
4272}
4273
4274std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4275 StringRef funcName,
4276 std::string Tag) {
4277 std::string StructRef = "struct " + Tag;
4278 std::string S = "static void __";
4279
4280 S += funcName;
4281 S += "_block_copy_" + utostr(i);
4282 S += "(" + StructRef;
4283 S += "*dst, " + StructRef;
4284 S += "*src) {";
4285 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4286 E = ImportedBlockDecls.end(); I != E; ++I) {
4287 ValueDecl *VD = (*I);
4288 S += "_Block_object_assign((void*)&dst->";
4289 S += (*I)->getNameAsString();
4290 S += ", (void*)src->";
4291 S += (*I)->getNameAsString();
4292 if (BlockByRefDeclsPtrSet.count((*I)))
4293 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4294 else if (VD->getType()->isBlockPointerType())
4295 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4296 else
4297 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4298 }
4299 S += "}\n";
4300
4301 S += "\nstatic void __";
4302 S += funcName;
4303 S += "_block_dispose_" + utostr(i);
4304 S += "(" + StructRef;
4305 S += "*src) {";
4306 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4307 E = ImportedBlockDecls.end(); I != E; ++I) {
4308 ValueDecl *VD = (*I);
4309 S += "_Block_object_dispose((void*)src->";
4310 S += (*I)->getNameAsString();
4311 if (BlockByRefDeclsPtrSet.count((*I)))
4312 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4313 else if (VD->getType()->isBlockPointerType())
4314 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4315 else
4316 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4317 }
4318 S += "}\n";
4319 return S;
4320}
4321
4322std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4323 std::string Desc) {
4324 std::string S = "\nstruct " + Tag;
4325 std::string Constructor = " " + Tag;
4326
4327 S += " {\n struct __block_impl impl;\n";
4328 S += " struct " + Desc;
4329 S += "* Desc;\n";
4330
4331 Constructor += "(void *fp, "; // Invoke function pointer.
4332 Constructor += "struct " + Desc; // Descriptor pointer.
4333 Constructor += " *desc";
4334
4335 if (BlockDeclRefs.size()) {
4336 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004337 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004338 E = BlockByCopyDecls.end(); I != E; ++I) {
4339 S += " ";
4340 std::string FieldName = (*I)->getNameAsString();
4341 std::string ArgName = "_" + FieldName;
4342 // Handle nested closure invocation. For example:
4343 //
4344 // void (^myImportedBlock)(void);
4345 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4346 //
4347 // void (^anotherBlock)(void);
4348 // anotherBlock = ^(void) {
4349 // myImportedBlock(); // import and invoke the closure
4350 // };
4351 //
4352 if (isTopLevelBlockPointerType((*I)->getType())) {
4353 S += "struct __block_impl *";
4354 Constructor += ", void *" + ArgName;
4355 } else {
4356 QualType QT = (*I)->getType();
4357 if (HasLocalVariableExternalStorage(*I))
4358 QT = Context->getPointerType(QT);
4359 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4360 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4361 Constructor += ", " + ArgName;
4362 }
4363 S += FieldName + ";\n";
4364 }
4365 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00004366 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004367 E = BlockByRefDecls.end(); I != E; ++I) {
4368 S += " ";
4369 std::string FieldName = (*I)->getNameAsString();
4370 std::string ArgName = "_" + FieldName;
4371 {
4372 std::string TypeString;
4373 RewriteByRefString(TypeString, FieldName, (*I));
4374 TypeString += " *";
4375 FieldName = TypeString + FieldName;
4376 ArgName = TypeString + ArgName;
4377 Constructor += ", " + ArgName;
4378 }
4379 S += FieldName + "; // by ref\n";
4380 }
4381 // Finish writing the constructor.
4382 Constructor += ", int flags=0)";
4383 // Initialize all "by copy" arguments.
4384 bool firsTime = true;
Craig Topper2341c0d2013-07-04 03:08:24 +00004385 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004386 E = BlockByCopyDecls.end(); I != E; ++I) {
4387 std::string Name = (*I)->getNameAsString();
4388 if (firsTime) {
4389 Constructor += " : ";
4390 firsTime = false;
4391 }
4392 else
4393 Constructor += ", ";
4394 if (isTopLevelBlockPointerType((*I)->getType()))
4395 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4396 else
4397 Constructor += Name + "(_" + Name + ")";
4398 }
4399 // Initialize all "by ref" arguments.
Craig Topper2341c0d2013-07-04 03:08:24 +00004400 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00004401 E = BlockByRefDecls.end(); I != E; ++I) {
4402 std::string Name = (*I)->getNameAsString();
4403 if (firsTime) {
4404 Constructor += " : ";
4405 firsTime = false;
4406 }
4407 else
4408 Constructor += ", ";
4409 Constructor += Name + "(_" + Name + "->__forwarding)";
4410 }
4411
4412 Constructor += " {\n";
4413 if (GlobalVarDecl)
4414 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4415 else
4416 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4417 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4418
4419 Constructor += " Desc = desc;\n";
4420 } else {
4421 // Finish writing the constructor.
4422 Constructor += ", int flags=0) {\n";
4423 if (GlobalVarDecl)
4424 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4425 else
4426 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4427 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4428 Constructor += " Desc = desc;\n";
4429 }
4430 Constructor += " ";
4431 Constructor += "}\n";
4432 S += Constructor;
4433 S += "};\n";
4434 return S;
4435}
4436
4437std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4438 std::string ImplTag, int i,
4439 StringRef FunName,
4440 unsigned hasCopy) {
4441 std::string S = "\nstatic struct " + DescTag;
4442
Fariborz Jahanian2e7f6382012-05-03 21:44:12 +00004443 S += " {\n size_t reserved;\n";
4444 S += " size_t Block_size;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00004445 if (hasCopy) {
4446 S += " void (*copy)(struct ";
4447 S += ImplTag; S += "*, struct ";
4448 S += ImplTag; S += "*);\n";
4449
4450 S += " void (*dispose)(struct ";
4451 S += ImplTag; S += "*);\n";
4452 }
4453 S += "} ";
4454
4455 S += DescTag + "_DATA = { 0, sizeof(struct ";
4456 S += ImplTag + ")";
4457 if (hasCopy) {
4458 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4459 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4460 }
4461 S += "};\n";
4462 return S;
4463}
4464
4465void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4466 StringRef FunName) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004467 bool RewriteSC = (GlobalVarDecl &&
4468 !Blocks.empty() &&
4469 GlobalVarDecl->getStorageClass() == SC_Static &&
4470 GlobalVarDecl->getType().getCVRQualifiers());
4471 if (RewriteSC) {
4472 std::string SC(" void __");
4473 SC += GlobalVarDecl->getNameAsString();
4474 SC += "() {}";
4475 InsertText(FunLocStart, SC);
4476 }
4477
4478 // Insert closures that were part of the function.
4479 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4480 CollectBlockDeclRefInfo(Blocks[i]);
4481 // Need to copy-in the inner copied-in variables not actually used in this
4482 // block.
4483 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCall113bee02012-03-10 09:33:50 +00004484 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian11671902012-02-07 17:11:38 +00004485 ValueDecl *VD = Exp->getDecl();
4486 BlockDeclRefs.push_back(Exp);
John McCall113bee02012-03-10 09:33:50 +00004487 if (!VD->hasAttr<BlocksAttr>()) {
4488 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4489 BlockByCopyDeclsPtrSet.insert(VD);
4490 BlockByCopyDecls.push_back(VD);
4491 }
4492 continue;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004493 }
John McCall113bee02012-03-10 09:33:50 +00004494
4495 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004496 BlockByRefDeclsPtrSet.insert(VD);
4497 BlockByRefDecls.push_back(VD);
4498 }
John McCall113bee02012-03-10 09:33:50 +00004499
Fariborz Jahanian11671902012-02-07 17:11:38 +00004500 // imported objects in the inner blocks not used in the outer
4501 // blocks must be copied/disposed in the outer block as well.
John McCall113bee02012-03-10 09:33:50 +00004502 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00004503 VD->getType()->isBlockPointerType())
4504 ImportedBlockDecls.insert(VD);
4505 }
4506
4507 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4508 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4509
4510 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4511
4512 InsertText(FunLocStart, CI);
4513
4514 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4515
4516 InsertText(FunLocStart, CF);
4517
4518 if (ImportedBlockDecls.size()) {
4519 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4520 InsertText(FunLocStart, HF);
4521 }
4522 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4523 ImportedBlockDecls.size() > 0);
4524 InsertText(FunLocStart, BD);
4525
4526 BlockDeclRefs.clear();
4527 BlockByRefDecls.clear();
4528 BlockByRefDeclsPtrSet.clear();
4529 BlockByCopyDecls.clear();
4530 BlockByCopyDeclsPtrSet.clear();
4531 ImportedBlockDecls.clear();
4532 }
4533 if (RewriteSC) {
4534 // Must insert any 'const/volatile/static here. Since it has been
4535 // removed as result of rewriting of block literals.
4536 std::string SC;
4537 if (GlobalVarDecl->getStorageClass() == SC_Static)
4538 SC = "static ";
4539 if (GlobalVarDecl->getType().isConstQualified())
4540 SC += "const ";
4541 if (GlobalVarDecl->getType().isVolatileQualified())
4542 SC += "volatile ";
4543 if (GlobalVarDecl->getType().isRestrictQualified())
4544 SC += "restrict ";
4545 InsertText(FunLocStart, SC);
4546 }
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004547 if (GlobalConstructionExp) {
4548 // extra fancy dance for global literal expression.
4549
4550 // Always the latest block expression on the block stack.
4551 std::string Tag = "__";
4552 Tag += FunName;
4553 Tag += "_block_impl_";
4554 Tag += utostr(Blocks.size()-1);
4555 std::string globalBuf = "static ";
4556 globalBuf += Tag; globalBuf += " ";
4557 std::string SStr;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004558
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004559 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00004560 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniane0050702012-03-23 00:00:49 +00004561 PrintingPolicy(LangOpts));
4562 globalBuf += constructorExprBuf.str();
4563 globalBuf += ";\n";
4564 InsertText(FunLocStart, globalBuf);
4565 GlobalConstructionExp = 0;
4566 }
4567
Fariborz Jahanian11671902012-02-07 17:11:38 +00004568 Blocks.clear();
4569 InnerDeclRefsCount.clear();
4570 InnerDeclRefs.clear();
4571 RewrittenBlockExprs.clear();
4572}
4573
4574void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahaniane49a42c2012-04-25 17:56:48 +00004575 SourceLocation FunLocStart =
4576 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4577 : FD->getTypeSpecStartLoc();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004578 StringRef FuncName = FD->getName();
4579
4580 SynthesizeBlockLiterals(FunLocStart, FuncName);
4581}
4582
4583static void BuildUniqueMethodName(std::string &Name,
4584 ObjCMethodDecl *MD) {
4585 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4586 Name = IFace->getName();
4587 Name += "__" + MD->getSelector().getAsString();
4588 // Convert colons to underscores.
4589 std::string::size_type loc = 0;
4590 while ((loc = Name.find(":", loc)) != std::string::npos)
4591 Name.replace(loc, 1, "_");
4592}
4593
4594void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4595 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4596 //SourceLocation FunLocStart = MD->getLocStart();
4597 SourceLocation FunLocStart = MD->getLocStart();
4598 std::string FuncName;
4599 BuildUniqueMethodName(FuncName, MD);
4600 SynthesizeBlockLiterals(FunLocStart, FuncName);
4601}
4602
4603void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4604 for (Stmt::child_range CI = S->children(); CI; ++CI)
4605 if (*CI) {
4606 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4607 GetBlockDeclRefExprs(CBE->getBody());
4608 else
4609 GetBlockDeclRefExprs(*CI);
4610 }
4611 // Handle specific things.
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004612 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4613 if (DRE->refersToEnclosingLocal()) {
4614 // FIXME: Handle enums.
4615 if (!isa<FunctionDecl>(DRE->getDecl()))
4616 BlockDeclRefs.push_back(DRE);
4617 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4618 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004619 }
Fariborz Jahanian35f6e122012-04-16 23:00:57 +00004620 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004621
4622 return;
4623}
4624
Craig Topper5603df42013-07-05 19:34:19 +00004625void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4626 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004627 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4628 for (Stmt::child_range CI = S->children(); CI; ++CI)
4629 if (*CI) {
4630 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4631 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4632 GetInnerBlockDeclRefExprs(CBE->getBody(),
4633 InnerBlockDeclRefs,
4634 InnerContexts);
4635 }
4636 else
4637 GetInnerBlockDeclRefExprs(*CI,
4638 InnerBlockDeclRefs,
4639 InnerContexts);
4640
4641 }
4642 // Handle specific things.
John McCall113bee02012-03-10 09:33:50 +00004643 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4644 if (DRE->refersToEnclosingLocal()) {
4645 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4646 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4647 InnerBlockDeclRefs.push_back(DRE);
4648 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4649 if (Var->isFunctionOrMethodVarDecl())
4650 ImportedLocalExternalDecls.insert(Var);
4651 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00004652 }
4653
4654 return;
4655}
4656
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004657/// convertObjCTypeToCStyleType - This routine converts such objc types
4658/// as qualified objects, and blocks to their closest c/c++ types that
4659/// it can. It returns true if input type was modified.
4660bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4661 QualType oldT = T;
4662 convertBlockPointerToFunctionPointer(T);
4663 if (T->isFunctionPointerType()) {
4664 QualType PointeeTy;
4665 if (const PointerType* PT = T->getAs<PointerType>()) {
4666 PointeeTy = PT->getPointeeType();
4667 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4668 T = convertFunctionTypeOfBlocks(FT);
4669 T = Context->getPointerType(T);
4670 }
4671 }
4672 }
4673
4674 convertToUnqualifiedObjCType(T);
4675 return T != oldT;
4676}
4677
Fariborz Jahanian11671902012-02-07 17:11:38 +00004678/// convertFunctionTypeOfBlocks - This routine converts a function type
4679/// whose result type may be a block pointer or whose argument type(s)
4680/// might be block pointers to an equivalent function type replacing
4681/// all block pointers to function pointers.
4682QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4683 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4684 // FTP will be null for closures that don't take arguments.
4685 // Generate a funky cast.
4686 SmallVector<QualType, 8> ArgTypes;
Alp Toker314cc812014-01-25 16:55:45 +00004687 QualType Res = FT->getReturnType();
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004688 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004689
4690 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004691 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4692 E = FTP->param_type_end();
4693 I && (I != E); ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004694 QualType t = *I;
4695 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004696 if (convertObjCTypeToCStyleType(t))
4697 modified = true;
Fariborz Jahanian11671902012-02-07 17:11:38 +00004698 ArgTypes.push_back(t);
4699 }
4700 }
4701 QualType FuncType;
Fariborz Jahanianc3cdc412012-02-13 18:57:49 +00004702 if (modified)
Jordan Rose5c382722013-03-08 21:51:21 +00004703 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004704 else FuncType = QualType(FT, 0);
4705 return FuncType;
4706}
4707
4708Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4709 // Navigate to relevant type information.
4710 const BlockPointerType *CPT = 0;
4711
4712 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4713 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004714 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4715 CPT = MExpr->getType()->getAs<BlockPointerType>();
4716 }
4717 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4718 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4719 }
4720 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4721 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4722 else if (const ConditionalOperator *CEXPR =
4723 dyn_cast<ConditionalOperator>(BlockExp)) {
4724 Expr *LHSExp = CEXPR->getLHS();
4725 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4726 Expr *RHSExp = CEXPR->getRHS();
4727 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4728 Expr *CONDExp = CEXPR->getCond();
4729 ConditionalOperator *CondExpr =
4730 new (Context) ConditionalOperator(CONDExp,
4731 SourceLocation(), cast<Expr>(LHSStmt),
4732 SourceLocation(), cast<Expr>(RHSStmt),
4733 Exp->getType(), VK_RValue, OK_Ordinary);
4734 return CondExpr;
4735 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4736 CPT = IRE->getType()->getAs<BlockPointerType>();
4737 } else if (const PseudoObjectExpr *POE
4738 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4739 CPT = POE->getType()->castAs<BlockPointerType>();
4740 } else {
4741 assert(1 && "RewriteBlockClass: Bad type");
4742 }
4743 assert(CPT && "RewriteBlockClass: Bad type");
4744 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4745 assert(FT && "RewriteBlockClass: Bad type");
4746 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4747 // FTP will be null for closures that don't take arguments.
4748
4749 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4750 SourceLocation(), SourceLocation(),
4751 &Context->Idents.get("__block_impl"));
4752 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4753
4754 // Generate a funky cast.
4755 SmallVector<QualType, 8> ArgTypes;
4756
4757 // Push the block argument type.
4758 ArgTypes.push_back(PtrBlock);
4759 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004760 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4761 E = FTP->param_type_end();
4762 I && (I != E); ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004763 QualType t = *I;
4764 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4765 if (!convertBlockPointerToFunctionPointer(t))
4766 convertToUnqualifiedObjCType(t);
4767 ArgTypes.push_back(t);
4768 }
4769 }
4770 // Now do the pointer to function cast.
Jordan Rose5c382722013-03-08 21:51:21 +00004771 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004772
4773 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4774
4775 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4776 CK_BitCast,
4777 const_cast<Expr*>(BlockExp));
4778 // Don't forget the parens to enforce the proper binding.
4779 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4780 BlkCast);
4781 //PE->dump();
4782
4783 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4784 SourceLocation(),
4785 &Context->Idents.get("FuncPtr"),
4786 Context->VoidPtrTy, 0,
4787 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004788 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004789 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4790 FD->getType(), VK_LValue,
4791 OK_Ordinary);
4792
4793
4794 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4795 CK_BitCast, ME);
4796 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4797
4798 SmallVector<Expr*, 8> BlkExprs;
4799 // Add the implicit argument.
4800 BlkExprs.push_back(BlkCast);
4801 // Add the user arguments.
4802 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4803 E = Exp->arg_end(); I != E; ++I) {
4804 BlkExprs.push_back(*I);
4805 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00004806 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00004807 Exp->getType(), VK_RValue,
4808 SourceLocation());
4809 return CE;
4810}
4811
4812// We need to return the rewritten expression to handle cases where the
John McCall113bee02012-03-10 09:33:50 +00004813// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian11671902012-02-07 17:11:38 +00004814// For example:
4815//
4816// int main() {
4817// __block Foo *f;
4818// __block int i;
4819//
4820// void (^myblock)() = ^() {
John McCall113bee02012-03-10 09:33:50 +00004821// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian11671902012-02-07 17:11:38 +00004822// i = 77;
4823// };
4824//}
John McCall113bee02012-03-10 09:33:50 +00004825Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00004826 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4827 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCall113bee02012-03-10 09:33:50 +00004828 ValueDecl *VD = DeclRefExp->getDecl();
4829 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian11671902012-02-07 17:11:38 +00004830
4831 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4832 SourceLocation(),
4833 &Context->Idents.get("__forwarding"),
4834 Context->VoidPtrTy, 0,
4835 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004836 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004837 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4838 FD, SourceLocation(),
4839 FD->getType(), VK_LValue,
4840 OK_Ordinary);
4841
4842 StringRef Name = VD->getName();
4843 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4844 &Context->Idents.get(Name),
4845 Context->VoidPtrTy, 0,
4846 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00004847 ICIS_NoInit);
Fariborz Jahanian11671902012-02-07 17:11:38 +00004848 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4849 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4850
4851
4852
4853 // Need parens to enforce precedence.
4854 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4855 DeclRefExp->getExprLoc(),
4856 ME);
4857 ReplaceStmt(DeclRefExp, PE);
4858 return PE;
4859}
4860
4861// Rewrites the imported local variable V with external storage
4862// (static, extern, etc.) as *V
4863//
4864Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4865 ValueDecl *VD = DRE->getDecl();
4866 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4867 if (!ImportedLocalExternalDecls.count(Var))
4868 return DRE;
4869 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4870 VK_LValue, OK_Ordinary,
4871 DRE->getLocation());
4872 // Need parens to enforce precedence.
4873 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4874 Exp);
4875 ReplaceStmt(DRE, PE);
4876 return PE;
4877}
4878
4879void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4880 SourceLocation LocStart = CE->getLParenLoc();
4881 SourceLocation LocEnd = CE->getRParenLoc();
4882
4883 // Need to avoid trying to rewrite synthesized casts.
4884 if (LocStart.isInvalid())
4885 return;
4886 // Need to avoid trying to rewrite casts contained in macros.
4887 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4888 return;
4889
4890 const char *startBuf = SM->getCharacterData(LocStart);
4891 const char *endBuf = SM->getCharacterData(LocEnd);
4892 QualType QT = CE->getType();
4893 const Type* TypePtr = QT->getAs<Type>();
4894 if (isa<TypeOfExprType>(TypePtr)) {
4895 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4896 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4897 std::string TypeAsString = "(";
4898 RewriteBlockPointerType(TypeAsString, QT);
4899 TypeAsString += ")";
4900 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4901 return;
4902 }
4903 // advance the location to startArgList.
4904 const char *argPtr = startBuf;
4905
4906 while (*argPtr++ && (argPtr < endBuf)) {
4907 switch (*argPtr) {
4908 case '^':
4909 // Replace the '^' with '*'.
4910 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4911 ReplaceText(LocStart, 1, "*");
4912 break;
4913 }
4914 }
4915 return;
4916}
4917
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004918void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4919 CastKind CastKind = IC->getCastKind();
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004920 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4921 CastKind != CK_AnyPointerToBlockPointerCast)
4922 return;
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004923
Fariborz Jahaniancc172282012-04-16 22:14:01 +00004924 QualType QT = IC->getType();
4925 (void)convertBlockPointerToFunctionPointer(QT);
4926 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4927 std::string Str = "(";
4928 Str += TypeString;
4929 Str += ")";
4930 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4931
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00004932 return;
4933}
4934
Fariborz Jahanian11671902012-02-07 17:11:38 +00004935void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4936 SourceLocation DeclLoc = FD->getLocation();
4937 unsigned parenCount = 0;
4938
4939 // We have 1 or more arguments that have closure pointers.
4940 const char *startBuf = SM->getCharacterData(DeclLoc);
4941 const char *startArgList = strchr(startBuf, '(');
4942
4943 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4944
4945 parenCount++;
4946 // advance the location to startArgList.
4947 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4948 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4949
4950 const char *argPtr = startArgList;
4951
4952 while (*argPtr++ && parenCount) {
4953 switch (*argPtr) {
4954 case '^':
4955 // Replace the '^' with '*'.
4956 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4957 ReplaceText(DeclLoc, 1, "*");
4958 break;
4959 case '(':
4960 parenCount++;
4961 break;
4962 case ')':
4963 parenCount--;
4964 break;
4965 }
4966 }
4967 return;
4968}
4969
4970bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4971 const FunctionProtoType *FTP;
4972 const PointerType *PT = QT->getAs<PointerType>();
4973 if (PT) {
4974 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4975 } else {
4976 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4977 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4978 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4979 }
4980 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00004981 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
4982 E = FTP->param_type_end();
4983 I != E; ++I)
Fariborz Jahanian11671902012-02-07 17:11:38 +00004984 if (isTopLevelBlockPointerType(*I))
4985 return true;
4986 }
4987 return false;
4988}
4989
4990bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
4991 const FunctionProtoType *FTP;
4992 const PointerType *PT = QT->getAs<PointerType>();
4993 if (PT) {
4994 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
4995 } else {
4996 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
4997 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
4998 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
4999 }
5000 if (FTP) {
Alp Toker9cacbab2014-01-20 20:26:09 +00005001 for (FunctionProtoType::param_type_iterator I = FTP->param_type_begin(),
5002 E = FTP->param_type_end();
5003 I != E; ++I) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005004 if ((*I)->isObjCQualifiedIdType())
5005 return true;
5006 if ((*I)->isObjCObjectPointerType() &&
5007 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
5008 return true;
5009 }
5010
5011 }
5012 return false;
5013}
5014
5015void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
5016 const char *&RParen) {
5017 const char *argPtr = strchr(Name, '(');
5018 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
5019
5020 LParen = argPtr; // output the start.
5021 argPtr++; // skip past the left paren.
5022 unsigned parenCount = 1;
5023
5024 while (*argPtr && parenCount) {
5025 switch (*argPtr) {
5026 case '(': parenCount++; break;
5027 case ')': parenCount--; break;
5028 default: break;
5029 }
5030 if (parenCount) argPtr++;
5031 }
5032 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5033 RParen = argPtr; // output the end
5034}
5035
5036void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5037 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5038 RewriteBlockPointerFunctionArgs(FD);
5039 return;
5040 }
5041 // Handle Variables and Typedefs.
5042 SourceLocation DeclLoc = ND->getLocation();
5043 QualType DeclT;
5044 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5045 DeclT = VD->getType();
5046 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
5047 DeclT = TDD->getUnderlyingType();
5048 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5049 DeclT = FD->getType();
5050 else
5051 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
5052
5053 const char *startBuf = SM->getCharacterData(DeclLoc);
5054 const char *endBuf = startBuf;
5055 // scan backward (from the decl location) for the end of the previous decl.
5056 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5057 startBuf--;
5058 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
5059 std::string buf;
5060 unsigned OrigLength=0;
5061 // *startBuf != '^' if we are dealing with a pointer to function that
5062 // may take block argument types (which will be handled below).
5063 if (*startBuf == '^') {
5064 // Replace the '^' with '*', computing a negative offset.
5065 buf = '*';
5066 startBuf++;
5067 OrigLength++;
5068 }
5069 while (*startBuf != ')') {
5070 buf += *startBuf;
5071 startBuf++;
5072 OrigLength++;
5073 }
5074 buf += ')';
5075 OrigLength++;
5076
5077 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5078 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
5079 // Replace the '^' with '*' for arguments.
5080 // Replace id<P> with id/*<>*/
5081 DeclLoc = ND->getLocation();
5082 startBuf = SM->getCharacterData(DeclLoc);
5083 const char *argListBegin, *argListEnd;
5084 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5085 while (argListBegin < argListEnd) {
5086 if (*argListBegin == '^')
5087 buf += '*';
5088 else if (*argListBegin == '<') {
5089 buf += "/*";
5090 buf += *argListBegin++;
Dmitri Gribenko76bb5cabfa2012-09-10 21:20:09 +00005091 OrigLength++;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005092 while (*argListBegin != '>') {
5093 buf += *argListBegin++;
5094 OrigLength++;
5095 }
5096 buf += *argListBegin;
5097 buf += "*/";
5098 }
5099 else
5100 buf += *argListBegin;
5101 argListBegin++;
5102 OrigLength++;
5103 }
5104 buf += ')';
5105 OrigLength++;
5106 }
5107 ReplaceText(Start, OrigLength, buf);
5108
5109 return;
5110}
5111
5112
5113/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5114/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5115/// struct Block_byref_id_object *src) {
5116/// _Block_object_assign (&_dest->object, _src->object,
5117/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5118/// [|BLOCK_FIELD_IS_WEAK]) // object
5119/// _Block_object_assign(&_dest->object, _src->object,
5120/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5121/// [|BLOCK_FIELD_IS_WEAK]) // block
5122/// }
5123/// And:
5124/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5125/// _Block_object_dispose(_src->object,
5126/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5127/// [|BLOCK_FIELD_IS_WEAK]) // object
5128/// _Block_object_dispose(_src->object,
5129/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5130/// [|BLOCK_FIELD_IS_WEAK]) // block
5131/// }
5132
5133std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5134 int flag) {
5135 std::string S;
5136 if (CopyDestroyCache.count(flag))
5137 return S;
5138 CopyDestroyCache.insert(flag);
5139 S = "static void __Block_byref_id_object_copy_";
5140 S += utostr(flag);
5141 S += "(void *dst, void *src) {\n";
5142
5143 // offset into the object pointer is computed as:
5144 // void * + void* + int + int + void* + void *
5145 unsigned IntSize =
5146 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5147 unsigned VoidPtrSize =
5148 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5149
5150 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5151 S += " _Block_object_assign((char*)dst + ";
5152 S += utostr(offset);
5153 S += ", *(void * *) ((char*)src + ";
5154 S += utostr(offset);
5155 S += "), ";
5156 S += utostr(flag);
5157 S += ");\n}\n";
5158
5159 S += "static void __Block_byref_id_object_dispose_";
5160 S += utostr(flag);
5161 S += "(void *src) {\n";
5162 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5163 S += utostr(offset);
5164 S += "), ";
5165 S += utostr(flag);
5166 S += ");\n}\n";
5167 return S;
5168}
5169
5170/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5171/// the declaration into:
5172/// struct __Block_byref_ND {
5173/// void *__isa; // NULL for everything except __weak pointers
5174/// struct __Block_byref_ND *__forwarding;
5175/// int32_t __flags;
5176/// int32_t __size;
5177/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5178/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5179/// typex ND;
5180/// };
5181///
5182/// It then replaces declaration of ND variable with:
5183/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5184/// __size=sizeof(struct __Block_byref_ND),
5185/// ND=initializer-if-any};
5186///
5187///
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005188void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5189 bool lastDecl) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005190 int flag = 0;
5191 int isa = 0;
5192 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5193 if (DeclLoc.isInvalid())
5194 // If type location is missing, it is because of missing type (a warning).
5195 // Use variable's location which is good for this case.
5196 DeclLoc = ND->getLocation();
5197 const char *startBuf = SM->getCharacterData(DeclLoc);
5198 SourceLocation X = ND->getLocEnd();
5199 X = SM->getExpansionLoc(X);
5200 const char *endBuf = SM->getCharacterData(X);
5201 std::string Name(ND->getNameAsString());
5202 std::string ByrefType;
5203 RewriteByRefString(ByrefType, Name, ND, true);
5204 ByrefType += " {\n";
5205 ByrefType += " void *__isa;\n";
5206 RewriteByRefString(ByrefType, Name, ND);
5207 ByrefType += " *__forwarding;\n";
5208 ByrefType += " int __flags;\n";
5209 ByrefType += " int __size;\n";
5210 // Add void *__Block_byref_id_object_copy;
5211 // void *__Block_byref_id_object_dispose; if needed.
5212 QualType Ty = ND->getType();
Fariborz Jahanian998f0a32012-11-28 23:12:17 +00005213 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005214 if (HasCopyAndDispose) {
5215 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5216 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5217 }
5218
5219 QualType T = Ty;
5220 (void)convertBlockPointerToFunctionPointer(T);
5221 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5222
5223 ByrefType += " " + Name + ";\n";
5224 ByrefType += "};\n";
5225 // Insert this type in global scope. It is needed by helper function.
5226 SourceLocation FunLocStart;
5227 if (CurFunctionDef)
Fariborz Jahanianca357d92012-04-19 00:50:01 +00005228 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005229 else {
5230 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5231 FunLocStart = CurMethodDef->getLocStart();
5232 }
5233 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005234
Fariborz Jahanian11671902012-02-07 17:11:38 +00005235 if (Ty.isObjCGCWeak()) {
5236 flag |= BLOCK_FIELD_IS_WEAK;
5237 isa = 1;
5238 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00005239 if (HasCopyAndDispose) {
5240 flag = BLOCK_BYREF_CALLER;
5241 QualType Ty = ND->getType();
5242 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5243 if (Ty->isBlockPointerType())
5244 flag |= BLOCK_FIELD_IS_BLOCK;
5245 else
5246 flag |= BLOCK_FIELD_IS_OBJECT;
5247 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5248 if (!HF.empty())
Fariborz Jahaniane4996132013-02-07 22:50:40 +00005249 Preamble += HF;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005250 }
5251
5252 // struct __Block_byref_ND ND =
5253 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5254 // initializer-if-any};
5255 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian5811fd62012-04-11 23:57:12 +00005256 // FIXME. rewriter does not support __block c++ objects which
5257 // require construction.
Fariborz Jahanian16d0d6c2012-04-26 23:20:25 +00005258 if (hasInit)
5259 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5260 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5261 if (CXXDecl && CXXDecl->isDefaultConstructor())
5262 hasInit = false;
5263 }
5264
Fariborz Jahanian11671902012-02-07 17:11:38 +00005265 unsigned flags = 0;
5266 if (HasCopyAndDispose)
5267 flags |= BLOCK_HAS_COPY_DISPOSE;
5268 Name = ND->getNameAsString();
5269 ByrefType.clear();
5270 RewriteByRefString(ByrefType, Name, ND);
5271 std::string ForwardingCastType("(");
5272 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005273 ByrefType += " " + Name + " = {(void*)";
5274 ByrefType += utostr(isa);
5275 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5276 ByrefType += utostr(flags);
5277 ByrefType += ", ";
5278 ByrefType += "sizeof(";
5279 RewriteByRefString(ByrefType, Name, ND);
5280 ByrefType += ")";
5281 if (HasCopyAndDispose) {
5282 ByrefType += ", __Block_byref_id_object_copy_";
5283 ByrefType += utostr(flag);
5284 ByrefType += ", __Block_byref_id_object_dispose_";
5285 ByrefType += utostr(flag);
5286 }
5287
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005288 if (!firstDecl) {
5289 // In multiple __block declarations, and for all but 1st declaration,
5290 // find location of the separating comma. This would be start location
5291 // where new text is to be inserted.
5292 DeclLoc = ND->getLocation();
5293 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5294 const char *commaBuf = startDeclBuf;
5295 while (*commaBuf != ',')
5296 commaBuf--;
5297 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5298 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5299 startBuf = commaBuf;
5300 }
5301
Fariborz Jahanian11671902012-02-07 17:11:38 +00005302 if (!hasInit) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005303 ByrefType += "};\n";
5304 unsigned nameSize = Name.size();
5305 // for block or function pointer declaration. Name is aleady
5306 // part of the declaration.
5307 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5308 nameSize = 1;
5309 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5310 }
5311 else {
Fariborz Jahanian3fd9bbd2012-04-24 16:45:27 +00005312 ByrefType += ", ";
Fariborz Jahanian11671902012-02-07 17:11:38 +00005313 SourceLocation startLoc;
5314 Expr *E = ND->getInit();
5315 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5316 startLoc = ECE->getLParenLoc();
5317 else
5318 startLoc = E->getLocStart();
5319 startLoc = SM->getExpansionLoc(startLoc);
5320 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005321 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005322
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005323 const char separator = lastDecl ? ';' : ',';
5324 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5325 const char *separatorBuf = strchr(startInitializerBuf, separator);
5326 assert((*separatorBuf == separator) &&
5327 "RewriteByRefVar: can't find ';' or ','");
5328 SourceLocation separatorLoc =
5329 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5330
5331 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian11671902012-02-07 17:11:38 +00005332 }
5333 return;
5334}
5335
5336void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5337 // Add initializers for any closure decl refs.
5338 GetBlockDeclRefExprs(Exp->getBody());
5339 if (BlockDeclRefs.size()) {
5340 // Unique all "by copy" declarations.
5341 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005342 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005343 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5344 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5345 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5346 }
5347 }
5348 // Unique all "by ref" declarations.
5349 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005350 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005351 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5352 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5353 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5354 }
5355 }
5356 // Find any imported blocks...they will need special attention.
5357 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005358 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005359 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5360 BlockDeclRefs[i]->getType()->isBlockPointerType())
5361 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5362 }
5363}
5364
5365FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5366 IdentifierInfo *ID = &Context->Idents.get(name);
5367 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5368 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5369 SourceLocation(), ID, FType, 0, SC_Extern,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005370 false, false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005371}
5372
5373Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper5603df42013-07-05 19:34:19 +00005374 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005375
Fariborz Jahanian11671902012-02-07 17:11:38 +00005376 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahanianbdf975e2012-03-22 19:54:39 +00005377
Fariborz Jahanian11671902012-02-07 17:11:38 +00005378 Blocks.push_back(Exp);
5379
5380 CollectBlockDeclRefInfo(Exp);
5381
5382 // Add inner imported variables now used in current block.
5383 int countOfInnerDecls = 0;
5384 if (!InnerBlockDeclRefs.empty()) {
5385 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCall113bee02012-03-10 09:33:50 +00005386 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian11671902012-02-07 17:11:38 +00005387 ValueDecl *VD = Exp->getDecl();
John McCall113bee02012-03-10 09:33:50 +00005388 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005389 // We need to save the copied-in variables in nested
5390 // blocks because it is needed at the end for some of the API generations.
5391 // See SynthesizeBlockLiterals routine.
5392 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5393 BlockDeclRefs.push_back(Exp);
5394 BlockByCopyDeclsPtrSet.insert(VD);
5395 BlockByCopyDecls.push_back(VD);
5396 }
John McCall113bee02012-03-10 09:33:50 +00005397 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005398 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5399 BlockDeclRefs.push_back(Exp);
5400 BlockByRefDeclsPtrSet.insert(VD);
5401 BlockByRefDecls.push_back(VD);
5402 }
5403 }
5404 // Find any imported blocks...they will need special attention.
5405 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCall113bee02012-03-10 09:33:50 +00005406 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian11671902012-02-07 17:11:38 +00005407 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5408 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5409 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5410 }
5411 InnerDeclRefsCount.push_back(countOfInnerDecls);
5412
5413 std::string FuncName;
5414
5415 if (CurFunctionDef)
5416 FuncName = CurFunctionDef->getNameAsString();
5417 else if (CurMethodDef)
5418 BuildUniqueMethodName(FuncName, CurMethodDef);
5419 else if (GlobalVarDecl)
5420 FuncName = std::string(GlobalVarDecl->getNameAsString());
5421
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005422 bool GlobalBlockExpr =
5423 block->getDeclContext()->getRedeclContext()->isFileContext();
5424
5425 if (GlobalBlockExpr && !GlobalVarDecl) {
5426 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5427 GlobalBlockExpr = false;
5428 }
5429
Fariborz Jahanian11671902012-02-07 17:11:38 +00005430 std::string BlockNumber = utostr(Blocks.size()-1);
5431
Fariborz Jahanian11671902012-02-07 17:11:38 +00005432 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5433
5434 // Get a pointer to the function type so we can cast appropriately.
5435 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5436 QualType FType = Context->getPointerType(BFT);
5437
5438 FunctionDecl *FD;
5439 Expr *NewRep;
5440
Benjamin Kramer60509af2013-09-09 14:48:42 +00005441 // Simulate a constructor call...
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005442 std::string Tag;
5443
5444 if (GlobalBlockExpr)
5445 Tag = "__global_";
5446 else
5447 Tag = "__";
5448 Tag += FuncName + "_block_impl_" + BlockNumber;
5449
Fariborz Jahanian11671902012-02-07 17:11:38 +00005450 FD = SynthBlockInitFunctionDecl(Tag);
John McCall113bee02012-03-10 09:33:50 +00005451 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005452 SourceLocation());
5453
5454 SmallVector<Expr*, 4> InitExprs;
5455
5456 // Initialize the block function.
5457 FD = SynthBlockInitFunctionDecl(Func);
John McCall113bee02012-03-10 09:33:50 +00005458 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5459 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005460 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5461 CK_BitCast, Arg);
5462 InitExprs.push_back(castExpr);
5463
5464 // Initialize the block descriptor.
5465 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5466
5467 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5468 SourceLocation(), SourceLocation(),
5469 &Context->Idents.get(DescData.c_str()),
5470 Context->VoidPtrTy, 0,
Rafael Espindola6ae7e502013-04-03 19:27:57 +00005471 SC_Static);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005472 UnaryOperator *DescRefExpr =
John McCall113bee02012-03-10 09:33:50 +00005473 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005474 Context->VoidPtrTy,
5475 VK_LValue,
5476 SourceLocation()),
5477 UO_AddrOf,
5478 Context->getPointerType(Context->VoidPtrTy),
5479 VK_RValue, OK_Ordinary,
5480 SourceLocation());
5481 InitExprs.push_back(DescRefExpr);
5482
5483 // Add initializers for any closure decl refs.
5484 if (BlockDeclRefs.size()) {
5485 Expr *Exp;
5486 // Output all "by copy" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005487 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005488 E = BlockByCopyDecls.end(); I != E; ++I) {
5489 if (isObjCType((*I)->getType())) {
5490 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5491 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005492 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5493 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005494 if (HasLocalVariableExternalStorage(*I)) {
5495 QualType QT = (*I)->getType();
5496 QT = Context->getPointerType(QT);
5497 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5498 OK_Ordinary, SourceLocation());
5499 }
5500 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5501 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005502 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5503 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005504 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5505 CK_BitCast, Arg);
5506 } else {
5507 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005508 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5509 VK_LValue, SourceLocation());
Fariborz Jahanian11671902012-02-07 17:11:38 +00005510 if (HasLocalVariableExternalStorage(*I)) {
5511 QualType QT = (*I)->getType();
5512 QT = Context->getPointerType(QT);
5513 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5514 OK_Ordinary, SourceLocation());
5515 }
5516
5517 }
5518 InitExprs.push_back(Exp);
5519 }
5520 // Output all "by ref" declarations.
Craig Topper2341c0d2013-07-04 03:08:24 +00005521 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian11671902012-02-07 17:11:38 +00005522 E = BlockByRefDecls.end(); I != E; ++I) {
5523 ValueDecl *ND = (*I);
5524 std::string Name(ND->getNameAsString());
5525 std::string RecName;
5526 RewriteByRefString(RecName, Name, ND, true);
5527 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5528 + sizeof("struct"));
5529 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5530 SourceLocation(), SourceLocation(),
5531 II);
5532 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5533 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5534
5535 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCall113bee02012-03-10 09:33:50 +00005536 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005537 SourceLocation());
5538 bool isNestedCapturedVar = false;
5539 if (block)
5540 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5541 ce = block->capture_end(); ci != ce; ++ci) {
5542 const VarDecl *variable = ci->getVariable();
5543 if (variable == ND && ci->isNested()) {
5544 assert (ci->isByRef() &&
5545 "SynthBlockInitExpr - captured block variable is not byref");
5546 isNestedCapturedVar = true;
5547 break;
5548 }
5549 }
5550 // captured nested byref variable has its address passed. Do not take
5551 // its address again.
5552 if (!isNestedCapturedVar)
5553 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5554 Context->getPointerType(Exp->getType()),
5555 VK_RValue, OK_Ordinary, SourceLocation());
5556 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5557 InitExprs.push_back(Exp);
5558 }
5559 }
5560 if (ImportedBlockDecls.size()) {
5561 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5562 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5563 unsigned IntSize =
5564 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5565 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5566 Context->IntTy, SourceLocation());
5567 InitExprs.push_back(FlagExp);
5568 }
Benjamin Kramerc215e762012-08-24 11:54:20 +00005569 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian11671902012-02-07 17:11:38 +00005570 FType, VK_LValue, SourceLocation());
Fariborz Jahaniane0050702012-03-23 00:00:49 +00005571
5572 if (GlobalBlockExpr) {
5573 assert (GlobalConstructionExp == 0 &&
5574 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5575 GlobalConstructionExp = NewRep;
5576 NewRep = DRE;
5577 }
5578
Fariborz Jahanian11671902012-02-07 17:11:38 +00005579 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5580 Context->getPointerType(NewRep->getType()),
5581 VK_RValue, OK_Ordinary, SourceLocation());
5582 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5583 NewRep);
5584 BlockDeclRefs.clear();
5585 BlockByRefDecls.clear();
5586 BlockByRefDeclsPtrSet.clear();
5587 BlockByCopyDecls.clear();
5588 BlockByCopyDeclsPtrSet.clear();
5589 ImportedBlockDecls.clear();
5590 return NewRep;
5591}
5592
5593bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5594 if (const ObjCForCollectionStmt * CS =
5595 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5596 return CS->getElement() == DS;
5597 return false;
5598}
5599
5600//===----------------------------------------------------------------------===//
5601// Function Body / Expression rewriting
5602//===----------------------------------------------------------------------===//
5603
5604Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5605 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5606 isa<DoStmt>(S) || isa<ForStmt>(S))
5607 Stmts.push_back(S);
5608 else if (isa<ObjCForCollectionStmt>(S)) {
5609 Stmts.push_back(S);
5610 ObjCBcLabelNo.push_back(++BcLabelCount);
5611 }
5612
5613 // Pseudo-object operations and ivar references need special
5614 // treatment because we're going to recursively rewrite them.
5615 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5616 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5617 return RewritePropertyOrImplicitSetter(PseudoOp);
5618 } else {
5619 return RewritePropertyOrImplicitGetter(PseudoOp);
5620 }
5621 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5622 return RewriteObjCIvarRefExpr(IvarRefExpr);
5623 }
Fariborz Jahanian4254cdb2013-02-08 18:57:50 +00005624 else if (isa<OpaqueValueExpr>(S))
5625 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian11671902012-02-07 17:11:38 +00005626
5627 SourceRange OrigStmtRange = S->getSourceRange();
5628
5629 // Perform a bottom up rewrite of all children.
5630 for (Stmt::child_range CI = S->children(); CI; ++CI)
5631 if (*CI) {
5632 Stmt *childStmt = (*CI);
5633 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5634 if (newStmt) {
5635 *CI = newStmt;
5636 }
5637 }
5638
5639 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCall113bee02012-03-10 09:33:50 +00005640 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005641 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5642 InnerContexts.insert(BE->getBlockDecl());
5643 ImportedLocalExternalDecls.clear();
5644 GetInnerBlockDeclRefExprs(BE->getBody(),
5645 InnerBlockDeclRefs, InnerContexts);
5646 // Rewrite the block body in place.
5647 Stmt *SaveCurrentBody = CurrentBody;
5648 CurrentBody = BE->getBody();
5649 PropParentMap = 0;
5650 // block literal on rhs of a property-dot-sytax assignment
5651 // must be replaced by its synthesize ast so getRewrittenText
5652 // works as expected. In this case, what actually ends up on RHS
5653 // is the blockTranscribed which is the helper function for the
5654 // block literal; as in: self.c = ^() {[ace ARR];};
5655 bool saveDisableReplaceStmt = DisableReplaceStmt;
5656 DisableReplaceStmt = false;
5657 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5658 DisableReplaceStmt = saveDisableReplaceStmt;
5659 CurrentBody = SaveCurrentBody;
5660 PropParentMap = 0;
5661 ImportedLocalExternalDecls.clear();
5662 // Now we snarf the rewritten text and stash it away for later use.
5663 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5664 RewrittenBlockExprs[BE] = Str;
5665
5666 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5667
5668 //blockTranscribed->dump();
5669 ReplaceStmt(S, blockTranscribed);
5670 return blockTranscribed;
5671 }
5672 // Handle specific things.
5673 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5674 return RewriteAtEncode(AtEncode);
5675
5676 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5677 return RewriteAtSelector(AtSelector);
5678
5679 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5680 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian307b7ad2012-03-27 20:17:30 +00005681
5682 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5683 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian9c967fe2012-03-30 16:49:36 +00005684
Patrick Beard0caa3942012-04-19 00:25:12 +00005685 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5686 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian991a08d2012-03-30 23:35:47 +00005687
5688 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5689 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00005690
5691 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5692 dyn_cast<ObjCDictionaryLiteral>(S))
5693 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005694
5695 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5696#if 0
5697 // Before we rewrite it, put the original message expression in a comment.
5698 SourceLocation startLoc = MessExpr->getLocStart();
5699 SourceLocation endLoc = MessExpr->getLocEnd();
5700
5701 const char *startBuf = SM->getCharacterData(startLoc);
5702 const char *endBuf = SM->getCharacterData(endLoc);
5703
5704 std::string messString;
5705 messString += "// ";
5706 messString.append(startBuf, endBuf-startBuf+1);
5707 messString += "\n";
5708
5709 // FIXME: Missing definition of
5710 // InsertText(clang::SourceLocation, char const*, unsigned int).
5711 // InsertText(startLoc, messString.c_str(), messString.size());
5712 // Tried this, but it didn't work either...
5713 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5714#endif
5715 return RewriteMessageExpr(MessExpr);
5716 }
5717
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00005718 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5719 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5720 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5721 }
5722
Fariborz Jahanian11671902012-02-07 17:11:38 +00005723 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5724 return RewriteObjCTryStmt(StmtTry);
5725
5726 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5727 return RewriteObjCSynchronizedStmt(StmtTry);
5728
5729 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5730 return RewriteObjCThrowStmt(StmtThrow);
5731
5732 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5733 return RewriteObjCProtocolExpr(ProtocolExp);
5734
5735 if (ObjCForCollectionStmt *StmtForCollection =
5736 dyn_cast<ObjCForCollectionStmt>(S))
5737 return RewriteObjCForCollectionStmt(StmtForCollection,
5738 OrigStmtRange.getEnd());
5739 if (BreakStmt *StmtBreakStmt =
5740 dyn_cast<BreakStmt>(S))
5741 return RewriteBreakStmt(StmtBreakStmt);
5742 if (ContinueStmt *StmtContinueStmt =
5743 dyn_cast<ContinueStmt>(S))
5744 return RewriteContinueStmt(StmtContinueStmt);
5745
5746 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5747 // and cast exprs.
5748 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5749 // FIXME: What we're doing here is modifying the type-specifier that
5750 // precedes the first Decl. In the future the DeclGroup should have
5751 // a separate type-specifier that we can rewrite.
5752 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5753 // the context of an ObjCForCollectionStmt. For example:
5754 // NSArray *someArray;
5755 // for (id <FooProtocol> index in someArray) ;
5756 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5757 // and it depends on the original text locations/positions.
5758 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5759 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5760
5761 // Blocks rewrite rules.
5762 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5763 DI != DE; ++DI) {
5764 Decl *SD = *DI;
5765 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5766 if (isTopLevelBlockPointerType(ND->getType()))
5767 RewriteBlockPointerDecl(ND);
5768 else if (ND->getType()->isFunctionPointerType())
5769 CheckFunctionPointerDecl(ND->getType(), ND);
5770 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5771 if (VD->hasAttr<BlocksAttr>()) {
5772 static unsigned uniqueByrefDeclCount = 0;
5773 assert(!BlockByRefDeclNo.count(ND) &&
5774 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5775 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian847713a2012-04-24 19:38:45 +00005776 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian11671902012-02-07 17:11:38 +00005777 }
5778 else
5779 RewriteTypeOfDecl(VD);
5780 }
5781 }
5782 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5783 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5784 RewriteBlockPointerDecl(TD);
5785 else if (TD->getUnderlyingType()->isFunctionPointerType())
5786 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5787 }
5788 }
5789 }
5790
5791 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5792 RewriteObjCQualifiedInterfaceTypes(CE);
5793
5794 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5795 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5796 assert(!Stmts.empty() && "Statement stack is empty");
5797 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5798 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5799 && "Statement stack mismatch");
5800 Stmts.pop_back();
5801 }
5802 // Handle blocks rewriting.
Fariborz Jahanian11671902012-02-07 17:11:38 +00005803 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5804 ValueDecl *VD = DRE->getDecl();
5805 if (VD->hasAttr<BlocksAttr>())
5806 return RewriteBlockDeclRefExpr(DRE);
5807 if (HasLocalVariableExternalStorage(VD))
5808 return RewriteLocalVariableExternalStorage(DRE);
5809 }
5810
5811 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5812 if (CE->getCallee()->getType()->isBlockPointerType()) {
5813 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5814 ReplaceStmt(S, BlockCall);
5815 return BlockCall;
5816 }
5817 }
5818 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5819 RewriteCastExpr(CE);
5820 }
Fariborz Jahanian2c00acd2012-04-10 00:08:18 +00005821 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5822 RewriteImplicitCastObjCExpr(ICE);
5823 }
Fariborz Jahaniancc172282012-04-16 22:14:01 +00005824#if 0
Fariborz Jahanian3a5d5522012-04-13 18:00:54 +00005825
Fariborz Jahanian11671902012-02-07 17:11:38 +00005826 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5827 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5828 ICE->getSubExpr(),
5829 SourceLocation());
5830 // Get the new text.
5831 std::string SStr;
5832 llvm::raw_string_ostream Buf(SStr);
Richard Smith235341b2012-08-16 03:56:14 +00005833 Replacement->printPretty(Buf);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005834 const std::string &Str = Buf.str();
5835
5836 printf("CAST = %s\n", &Str[0]);
5837 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5838 delete S;
5839 return Replacement;
5840 }
5841#endif
5842 // Return this stmt unmodified.
5843 return S;
5844}
5845
5846void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
Aaron Ballmane8a8bae2014-03-08 20:12:42 +00005847 for (auto *FD : RD->fields()) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00005848 if (isTopLevelBlockPointerType(FD->getType()))
5849 RewriteBlockPointerDecl(FD);
5850 if (FD->getType()->isObjCQualifiedIdType() ||
5851 FD->getType()->isObjCQualifiedInterfaceType())
5852 RewriteObjCQualifiedInterfaceTypes(FD);
5853 }
5854}
5855
5856/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5857/// main file of the input.
5858void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5859 switch (D->getKind()) {
5860 case Decl::Function: {
5861 FunctionDecl *FD = cast<FunctionDecl>(D);
5862 if (FD->isOverloadedOperator())
5863 return;
5864
5865 // Since function prototypes don't have ParmDecl's, we check the function
5866 // prototype. This enables us to rewrite function declarations and
5867 // definitions using the same code.
5868 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5869
Argyrios Kyrtzidis75627ad2012-02-12 04:48:45 +00005870 if (!FD->isThisDeclarationADefinition())
5871 break;
5872
Fariborz Jahanian11671902012-02-07 17:11:38 +00005873 // FIXME: If this should support Obj-C++, support CXXTryStmt
5874 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5875 CurFunctionDef = FD;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005876 CurrentBody = Body;
5877 Body =
5878 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5879 FD->setBody(Body);
5880 CurrentBody = 0;
5881 if (PropParentMap) {
5882 delete PropParentMap;
5883 PropParentMap = 0;
5884 }
5885 // This synthesizes and inserts the block "impl" struct, invoke function,
5886 // and any copy/dispose helper functions.
5887 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005888 RewriteLineDirective(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005889 CurFunctionDef = 0;
Fariborz Jahanian11671902012-02-07 17:11:38 +00005890 }
5891 break;
5892 }
5893 case Decl::ObjCMethod: {
5894 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5895 if (CompoundStmt *Body = MD->getCompoundBody()) {
5896 CurMethodDef = MD;
5897 CurrentBody = Body;
5898 Body =
5899 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5900 MD->setBody(Body);
5901 CurrentBody = 0;
5902 if (PropParentMap) {
5903 delete PropParentMap;
5904 PropParentMap = 0;
5905 }
5906 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanianaa4a2422012-11-06 17:30:23 +00005907 RewriteLineDirective(D);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005908 CurMethodDef = 0;
5909 }
5910 break;
5911 }
5912 case Decl::ObjCImplementation: {
5913 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5914 ClassImplementation.push_back(CI);
5915 break;
5916 }
5917 case Decl::ObjCCategoryImpl: {
5918 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5919 CategoryImplementation.push_back(CI);
5920 break;
5921 }
5922 case Decl::Var: {
5923 VarDecl *VD = cast<VarDecl>(D);
5924 RewriteObjCQualifiedInterfaceTypes(VD);
5925 if (isTopLevelBlockPointerType(VD->getType()))
5926 RewriteBlockPointerDecl(VD);
5927 else if (VD->getType()->isFunctionPointerType()) {
5928 CheckFunctionPointerDecl(VD->getType(), VD);
5929 if (VD->getInit()) {
5930 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5931 RewriteCastExpr(CE);
5932 }
5933 }
5934 } else if (VD->getType()->isRecordType()) {
5935 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5936 if (RD->isCompleteDefinition())
5937 RewriteRecordBody(RD);
5938 }
5939 if (VD->getInit()) {
5940 GlobalVarDecl = VD;
5941 CurrentBody = VD->getInit();
5942 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5943 CurrentBody = 0;
5944 if (PropParentMap) {
5945 delete PropParentMap;
5946 PropParentMap = 0;
5947 }
5948 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5949 GlobalVarDecl = 0;
5950
5951 // This is needed for blocks.
5952 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5953 RewriteCastExpr(CE);
5954 }
5955 }
5956 break;
5957 }
5958 case Decl::TypeAlias:
5959 case Decl::Typedef: {
5960 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5961 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5962 RewriteBlockPointerDecl(TD);
5963 else if (TD->getUnderlyingType()->isFunctionPointerType())
5964 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanian3a65ce32013-04-03 19:11:21 +00005965 else
5966 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00005967 }
5968 break;
5969 }
5970 case Decl::CXXRecord:
5971 case Decl::Record: {
5972 RecordDecl *RD = cast<RecordDecl>(D);
5973 if (RD->isCompleteDefinition())
5974 RewriteRecordBody(RD);
5975 break;
5976 }
5977 default:
5978 break;
5979 }
5980 // Nothing yet.
5981}
5982
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005983/// Write_ProtocolExprReferencedMetadata - This routine writer out the
5984/// protocol reference symbols in the for of:
5985/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
5986static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
5987 ObjCProtocolDecl *PDecl,
5988 std::string &Result) {
5989 // Also output .objc_protorefs$B section and its meta-data.
5990 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanian75f2e3c2012-04-27 21:39:49 +00005991 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00005992 Result += "struct _protocol_t *";
5993 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
5994 Result += PDecl->getNameAsString();
5995 Result += " = &";
5996 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
5997 Result += ";\n";
5998}
5999
Fariborz Jahanian11671902012-02-07 17:11:38 +00006000void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
6001 if (Diags.hasErrorOccurred())
6002 return;
6003
6004 RewriteInclude();
6005
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006006 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
Alp Tokerf6a24ce2013-12-05 16:25:25 +00006007 // translation of function bodies were postponed until all class and
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006008 // their extensions and implementations are seen. This is because, we
Alp Tokerf6a24ce2013-12-05 16:25:25 +00006009 // cannot build grouping structs for bitfields until they are all seen.
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006010 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
6011 HandleTopLevelSingleDecl(FDecl);
6012 }
6013
Fariborz Jahanian11671902012-02-07 17:11:38 +00006014 // Here's a great place to add any extra declarations that may be needed.
6015 // Write out meta data for each @protocol(<expr>).
6016 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006017 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006018 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006019 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
6020 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006021
6022 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00006023
6024 if (ClassImplementation.size() || CategoryImplementation.size())
6025 RewriteImplementations();
6026
Fariborz Jahanian8e1118cbd2012-02-21 23:58:41 +00006027 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
6028 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
6029 // Write struct declaration for the class matching its ivar declarations.
6030 // Note that for modern abi, this is postponed until the end of TU
6031 // because class extensions and the implementation might declare their own
6032 // private ivars.
6033 RewriteInterfaceDecl(CDecl);
6034 }
Fariborz Jahaniane4996132013-02-07 22:50:40 +00006035
Fariborz Jahanian11671902012-02-07 17:11:38 +00006036 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6037 // we are done.
6038 if (const RewriteBuffer *RewriteBuf =
6039 Rewrite.getRewriteBufferFor(MainFileID)) {
6040 //printf("Changed:\n");
6041 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6042 } else {
6043 llvm::errs() << "No changes\n";
6044 }
6045
6046 if (ClassImplementation.size() || CategoryImplementation.size() ||
6047 ProtocolExprDecls.size()) {
6048 // Rewrite Objective-c meta data*
6049 std::string ResultStr;
6050 RewriteMetaDataIntoBuffer(ResultStr);
6051 // Emit metadata.
6052 *OutFile << ResultStr;
6053 }
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006054 // Emit ImageInfo;
6055 {
6056 std::string ResultStr;
6057 WriteImageInfo(ResultStr);
6058 *OutFile << ResultStr;
6059 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006060 OutFile->flush();
6061}
6062
6063void RewriteModernObjC::Initialize(ASTContext &context) {
6064 InitializeCommon(context);
6065
Fariborz Jahanianb52221e2012-03-10 17:45:38 +00006066 Preamble += "#ifndef __OBJC2__\n";
6067 Preamble += "#define __OBJC2__\n";
6068 Preamble += "#endif\n";
6069
Fariborz Jahanian11671902012-02-07 17:11:38 +00006070 // declaring objc_selector outside the parameter list removes a silly
6071 // scope related warning...
6072 if (IsHeader)
6073 Preamble = "#pragma once\n";
6074 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahanian27db0b32012-04-12 23:52:52 +00006075 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
6076 Preamble += "\n\tstruct objc_object *superClass; ";
6077 // Add a constructor for creating temporary objects.
6078 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
6079 Preamble += ": object(o), superClass(s) {} ";
6080 Preamble += "\n};\n";
6081
Fariborz Jahanian11671902012-02-07 17:11:38 +00006082 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006083 // Define all sections using syntax that makes sense.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006084 // These are currently generated.
6085 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006086 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006087 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006088 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6089 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006090 // These are generated but not necessary for functionality.
Fariborz Jahanianddddca32012-03-14 21:44:09 +00006091 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00006092 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6093 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006094 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006095
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00006096 // These need be generated for performance. Currently they are not,
6097 // using API calls instead.
6098 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6099 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6100 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6101
Fariborz Jahanian11671902012-02-07 17:11:38 +00006102 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00006103 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6104 Preamble += "typedef struct objc_object Protocol;\n";
6105 Preamble += "#define _REWRITER_typedef_Protocol\n";
6106 Preamble += "#endif\n";
6107 if (LangOpts.MicrosoftExt) {
6108 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6109 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006110 }
6111 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006112 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian167384d2012-03-21 23:41:04 +00006113
6114 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6115 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6116 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6117 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6118 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6119
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006120 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006121 Preamble += "(const char *);\n";
6122 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6123 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian9c0c0502012-05-08 20:55:55 +00006124 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006125 Preamble += "(const char *);\n";
Fariborz Jahanian34660592012-03-19 18:11:32 +00006126 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006127 // @synchronized hooks.
Aaron Ballman9c004462012-09-06 16:44:16 +00006128 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6129 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006130 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahanian6c0af642013-09-05 17:17:32 +00006131 Preamble += "#ifdef _WIN64\n";
6132 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
6133 Preamble += "#else\n";
6134 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
6135 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006136 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6137 Preamble += "struct __objcFastEnumerationState {\n\t";
6138 Preamble += "unsigned long state;\n\t";
6139 Preamble += "void **itemsPtr;\n\t";
6140 Preamble += "unsigned long *mutationsPtr;\n\t";
6141 Preamble += "unsigned long extra[5];\n};\n";
6142 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6143 Preamble += "#define __FASTENUMERATIONSTATE\n";
6144 Preamble += "#endif\n";
6145 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6146 Preamble += "struct __NSConstantStringImpl {\n";
6147 Preamble += " int *isa;\n";
6148 Preamble += " int flags;\n";
6149 Preamble += " char *str;\n";
6150 Preamble += " long length;\n";
6151 Preamble += "};\n";
6152 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6153 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6154 Preamble += "#else\n";
6155 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6156 Preamble += "#endif\n";
6157 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6158 Preamble += "#endif\n";
6159 // Blocks preamble.
6160 Preamble += "#ifndef BLOCK_IMPL\n";
6161 Preamble += "#define BLOCK_IMPL\n";
6162 Preamble += "struct __block_impl {\n";
6163 Preamble += " void *isa;\n";
6164 Preamble += " int Flags;\n";
6165 Preamble += " int Reserved;\n";
6166 Preamble += " void *FuncPtr;\n";
6167 Preamble += "};\n";
6168 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6169 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6170 Preamble += "extern \"C\" __declspec(dllexport) "
6171 "void _Block_object_assign(void *, const void *, const int);\n";
6172 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6173 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6174 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6175 Preamble += "#else\n";
6176 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6177 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6178 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6179 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6180 Preamble += "#endif\n";
6181 Preamble += "#endif\n";
6182 if (LangOpts.MicrosoftExt) {
6183 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6184 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6185 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6186 Preamble += "#define __attribute__(X)\n";
6187 Preamble += "#endif\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006188 Preamble += "#ifndef __weak\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006189 Preamble += "#define __weak\n";
Fariborz Jahaniane1240fe2012-04-12 16:33:31 +00006190 Preamble += "#endif\n";
6191 Preamble += "#ifndef __block\n";
6192 Preamble += "#define __block\n";
6193 Preamble += "#endif\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006194 }
6195 else {
6196 Preamble += "#define __block\n";
6197 Preamble += "#define __weak\n";
6198 }
Fariborz Jahanian4a031bd2012-06-29 18:27:08 +00006199
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006200 // Declarations required for modern objective-c array and dictionary literals.
6201 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006202 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006203 Preamble += " void * *arr;\n";
Fariborz Jahanian4460e0f2012-04-06 22:29:36 +00006204 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006205 Preamble += "\tva_list marker;\n";
6206 Preamble += "\tva_start(marker, count);\n";
6207 Preamble += "\tarr = new void *[count];\n";
6208 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6209 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6210 Preamble += "\tva_end( marker );\n";
6211 Preamble += " };\n";
Fariborz Jahanian70ef9292012-05-02 23:53:46 +00006212 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahaniane110fe42012-04-06 19:47:36 +00006213 Preamble += "\tdelete[] arr;\n";
6214 Preamble += " }\n";
6215 Preamble += "};\n";
6216
Fariborz Jahanian9b43c3f2012-05-23 23:47:20 +00006217 // Declaration required for implementation of @autoreleasepool statement.
6218 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6219 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6220 Preamble += "struct __AtAutoreleasePool {\n";
6221 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6222 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6223 Preamble += " void * atautoreleasepoolobj;\n";
6224 Preamble += "};\n";
6225
Fariborz Jahanian11671902012-02-07 17:11:38 +00006226 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6227 // as this avoids warning in any 64bit/32bit compilation model.
6228 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6229}
6230
6231/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6232/// ivar offset.
6233void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6234 std::string &Result) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006235 Result += "__OFFSETOFIVAR__(struct ";
6236 Result += ivar->getContainingInterface()->getNameAsString();
6237 if (LangOpts.MicrosoftExt)
6238 Result += "_IMPL";
6239 Result += ", ";
6240 if (ivar->isBitField())
6241 ObjCIvarBitfieldGroupDecl(ivar, Result);
6242 else
Fariborz Jahanian11671902012-02-07 17:11:38 +00006243 Result += ivar->getNameAsString();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006244 Result += ")";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006245}
6246
6247/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6248/// struct _prop_t {
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006249/// const char *name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006250/// char *attributes;
6251/// }
6252
6253/// struct _prop_list_t {
6254/// uint32_t entsize; // sizeof(struct _prop_t)
6255/// uint32_t count_of_properties;
6256/// struct _prop_t prop_list[count_of_properties];
6257/// }
6258
6259/// struct _protocol_t;
6260
6261/// struct _protocol_list_t {
6262/// long protocol_count; // Note, this is 32/64 bit
6263/// struct _protocol_t * protocol_list[protocol_count];
6264/// }
6265
6266/// struct _objc_method {
6267/// SEL _cmd;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006268/// const char *method_type;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006269/// char *_imp;
6270/// }
6271
6272/// struct _method_list_t {
6273/// uint32_t entsize; // sizeof(struct _objc_method)
6274/// uint32_t method_count;
6275/// struct _objc_method method_list[method_count];
6276/// }
6277
6278/// struct _protocol_t {
6279/// id isa; // NULL
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006280/// const char *protocol_name;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006281/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006282/// const struct method_list_t *instance_methods;
6283/// const struct method_list_t *class_methods;
Fariborz Jahanian11671902012-02-07 17:11:38 +00006284/// const struct method_list_t *optionalInstanceMethods;
6285/// const struct method_list_t *optionalClassMethods;
6286/// const struct _prop_list_t * properties;
6287/// const uint32_t size; // sizeof(struct _protocol_t)
6288/// const uint32_t flags; // = 0
6289/// const char ** extendedMethodTypes;
6290/// }
6291
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006292/// struct _ivar_t {
6293/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006294/// const char *name;
6295/// const char *type;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006296/// uint32_t alignment;
6297/// uint32_t size;
6298/// }
6299
6300/// struct _ivar_list_t {
6301/// uint32 entsize; // sizeof(struct _ivar_t)
6302/// uint32 count;
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006303/// struct _ivar_t list[count];
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006304/// }
6305
6306/// struct _class_ro_t {
Fariborz Jahanian34134812012-03-24 16:53:16 +00006307/// uint32_t flags;
6308/// uint32_t instanceStart;
6309/// uint32_t instanceSize;
6310/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006311/// const uint8_t *ivarLayout;
6312/// const char *name;
6313/// const struct _method_list_t *baseMethods;
6314/// const struct _protocol_list_t *baseProtocols;
6315/// const struct _ivar_list_t *ivars;
6316/// const uint8_t *weakIvarLayout;
6317/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006318/// }
6319
6320/// struct _class_t {
6321/// struct _class_t *isa;
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006322/// struct _class_t *superclass;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006323/// void *cache;
6324/// IMP *vtable;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006325/// struct _class_ro_t *ro;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006326/// }
6327
6328/// struct _category_t {
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006329/// const char *name;
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006330/// struct _class_t *cls;
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006331/// const struct _method_list_t *instance_methods;
6332/// const struct _method_list_t *class_methods;
6333/// const struct _protocol_list_t *protocols;
6334/// const struct _prop_list_t *properties;
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006335/// }
6336
6337/// MessageRefTy - LLVM for:
6338/// struct _message_ref_t {
6339/// IMP messenger;
6340/// SEL name;
6341/// };
6342
6343/// SuperMessageRefTy - LLVM for:
6344/// struct _super_message_ref_t {
6345/// SUPER_IMP messenger;
6346/// SEL name;
6347/// };
6348
Fariborz Jahanian45489622012-03-14 18:09:23 +00006349static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00006350 static bool meta_data_declared = false;
6351 if (meta_data_declared)
6352 return;
6353
6354 Result += "\nstruct _prop_t {\n";
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006355 Result += "\tconst char *name;\n";
6356 Result += "\tconst char *attributes;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006357 Result += "};\n";
6358
6359 Result += "\nstruct _protocol_t;\n";
6360
Fariborz Jahanian11671902012-02-07 17:11:38 +00006361 Result += "\nstruct _objc_method {\n";
6362 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006363 Result += "\tconst char *method_type;\n";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006364 Result += "\tvoid *_imp;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006365 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006366
6367 Result += "\nstruct _protocol_t {\n";
6368 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006369 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006370 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006371 Result += "\tconst struct method_list_t *instance_methods;\n";
6372 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006373 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6374 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6375 Result += "\tconst struct _prop_list_t * properties;\n";
6376 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6377 Result += "\tconst unsigned int flags; // = 0\n";
6378 Result += "\tconst char ** extendedMethodTypes;\n";
6379 Result += "};\n";
6380
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006381 Result += "\nstruct _ivar_t {\n";
6382 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006383 Result += "\tconst char *name;\n";
6384 Result += "\tconst char *type;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006385 Result += "\tunsigned int alignment;\n";
6386 Result += "\tunsigned int size;\n";
6387 Result += "};\n";
6388
6389 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006390 Result += "\tunsigned int flags;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006391 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian34134812012-03-24 16:53:16 +00006392 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006393 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6394 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian34134812012-03-24 16:53:16 +00006395 Result += "\tunsigned int reserved;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006396 Result += "\tconst unsigned char *ivarLayout;\n";
6397 Result += "\tconst char *name;\n";
6398 Result += "\tconst struct _method_list_t *baseMethods;\n";
6399 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6400 Result += "\tconst struct _ivar_list_t *ivars;\n";
6401 Result += "\tconst unsigned char *weakIvarLayout;\n";
6402 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006403 Result += "};\n";
6404
6405 Result += "\nstruct _class_t {\n";
6406 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanian6e60c132012-03-20 17:34:50 +00006407 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006408 Result += "\tvoid *cache;\n";
6409 Result += "\tvoid *vtable;\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006410 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006411 Result += "};\n";
6412
6413 Result += "\nstruct _category_t {\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006414 Result += "\tconst char *name;\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006415 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanianeb4eb5c2012-03-21 16:23:16 +00006416 Result += "\tconst struct _method_list_t *instance_methods;\n";
6417 Result += "\tconst struct _method_list_t *class_methods;\n";
6418 Result += "\tconst struct _protocol_list_t *protocols;\n";
6419 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian591b7de2012-02-10 00:04:22 +00006420 Result += "};\n";
6421
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006422 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006423 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00006424 meta_data_declared = true;
6425}
6426
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006427static void Write_protocol_list_t_TypeDecl(std::string &Result,
6428 long super_protocol_count) {
6429 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6430 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6431 Result += "\tstruct _protocol_t *super_protocols[";
6432 Result += utostr(super_protocol_count); Result += "];\n";
6433 Result += "}";
6434}
6435
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006436static void Write_method_list_t_TypeDecl(std::string &Result,
6437 unsigned int method_count) {
6438 Result += "struct /*_method_list_t*/"; Result += " {\n";
6439 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6440 Result += "\tunsigned int method_count;\n";
6441 Result += "\tstruct _objc_method method_list[";
6442 Result += utostr(method_count); Result += "];\n";
6443 Result += "}";
6444}
6445
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006446static void Write__prop_list_t_TypeDecl(std::string &Result,
6447 unsigned int property_count) {
6448 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6449 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6450 Result += "\tunsigned int count_of_properties;\n";
6451 Result += "\tstruct _prop_t prop_list[";
6452 Result += utostr(property_count); Result += "];\n";
6453 Result += "}";
6454}
6455
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006456static void Write__ivar_list_t_TypeDecl(std::string &Result,
6457 unsigned int ivar_count) {
6458 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6459 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6460 Result += "\tunsigned int count;\n";
6461 Result += "\tstruct _ivar_t ivar_list[";
6462 Result += utostr(ivar_count); Result += "];\n";
6463 Result += "}";
6464}
6465
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00006466static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6467 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6468 StringRef VarName,
6469 StringRef ProtocolName) {
6470 if (SuperProtocols.size() > 0) {
6471 Result += "\nstatic ";
6472 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6473 Result += " "; Result += VarName;
6474 Result += ProtocolName;
6475 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6476 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6477 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6478 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6479 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6480 Result += SuperPD->getNameAsString();
6481 if (i == e-1)
6482 Result += "\n};\n";
6483 else
6484 Result += ",\n";
6485 }
6486 }
6487}
6488
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006489static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6490 ASTContext *Context, std::string &Result,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006491 ArrayRef<ObjCMethodDecl *> Methods,
6492 StringRef VarName,
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006493 StringRef TopLevelDeclName,
6494 bool MethodImpl) {
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006495 if (Methods.size() > 0) {
6496 Result += "\nstatic ";
6497 Write_method_list_t_TypeDecl(Result, Methods.size());
6498 Result += " "; Result += VarName;
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006499 Result += TopLevelDeclName;
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006500 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6501 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6502 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6503 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6504 ObjCMethodDecl *MD = Methods[i];
6505 if (i == 0)
6506 Result += "\t{{(struct objc_selector *)\"";
6507 else
6508 Result += "\t{(struct objc_selector *)\"";
6509 Result += (MD)->getSelector().getAsString(); Result += "\"";
6510 Result += ", ";
6511 std::string MethodTypeString;
6512 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6513 Result += "\""; Result += MethodTypeString; Result += "\"";
6514 Result += ", ";
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006515 if (!MethodImpl)
6516 Result += "0";
6517 else {
6518 Result += "(void *)";
6519 Result += RewriteObj.MethodInternalNames[MD];
6520 }
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006521 if (i == e-1)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006522 Result += "}}\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006523 else
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00006524 Result += "},\n";
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00006525 }
6526 Result += "};\n";
6527 }
6528}
6529
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006530static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00006531 ASTContext *Context, std::string &Result,
6532 ArrayRef<ObjCPropertyDecl *> Properties,
6533 const Decl *Container,
6534 StringRef VarName,
6535 StringRef ProtocolName) {
6536 if (Properties.size() > 0) {
6537 Result += "\nstatic ";
6538 Write__prop_list_t_TypeDecl(Result, Properties.size());
6539 Result += " "; Result += VarName;
6540 Result += ProtocolName;
6541 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6542 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6543 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6544 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6545 ObjCPropertyDecl *PropDecl = Properties[i];
6546 if (i == 0)
6547 Result += "\t{{\"";
6548 else
6549 Result += "\t{\"";
6550 Result += PropDecl->getName(); Result += "\",";
6551 std::string PropertyTypeString, QuotePropertyTypeString;
6552 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6553 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6554 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6555 if (i == e-1)
6556 Result += "}}\n";
6557 else
6558 Result += "},\n";
6559 }
6560 Result += "};\n";
6561 }
6562}
6563
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006564// Metadata flags
6565enum MetaDataDlags {
6566 CLS = 0x0,
6567 CLS_META = 0x1,
6568 CLS_ROOT = 0x2,
6569 OBJC2_CLS_HIDDEN = 0x10,
6570 CLS_EXCEPTION = 0x20,
6571
6572 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6573 CLS_HAS_IVAR_RELEASER = 0x40,
6574 /// class was compiled with -fobjc-arr
6575 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6576};
6577
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006578static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6579 unsigned int flags,
6580 const std::string &InstanceStart,
6581 const std::string &InstanceSize,
6582 ArrayRef<ObjCMethodDecl *>baseMethods,
6583 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6584 ArrayRef<ObjCIvarDecl *>ivars,
6585 ArrayRef<ObjCPropertyDecl *>Properties,
6586 StringRef VarName,
6587 StringRef ClassName) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006588 Result += "\nstatic struct _class_ro_t ";
6589 Result += VarName; Result += ClassName;
6590 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6591 Result += "\t";
6592 Result += llvm::utostr(flags); Result += ", ";
6593 Result += InstanceStart; Result += ", ";
6594 Result += InstanceSize; Result += ", \n";
6595 Result += "\t";
Fariborz Jahanian45489622012-03-14 18:09:23 +00006596 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6597 if (Triple.getArch() == llvm::Triple::x86_64)
6598 // uint32_t const reserved; // only when building for 64bit targets
6599 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006600 // const uint8_t * const ivarLayout;
6601 Result += "0, \n\t";
6602 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006603 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006604 if (baseMethods.size() > 0) {
6605 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006606 if (metaclass)
6607 Result += "_OBJC_$_CLASS_METHODS_";
6608 else
6609 Result += "_OBJC_$_INSTANCE_METHODS_";
6610 Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006611 Result += ",\n\t";
6612 }
6613 else
6614 Result += "0, \n\t";
6615
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006616 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006617 Result += "(const struct _objc_protocol_list *)&";
6618 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6619 Result += ",\n\t";
6620 }
6621 else
6622 Result += "0, \n\t";
6623
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006624 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006625 Result += "(const struct _ivar_list_t *)&";
6626 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6627 Result += ",\n\t";
6628 }
6629 else
6630 Result += "0, \n\t";
6631
6632 // weakIvarLayout
6633 Result += "0, \n\t";
Fariborz Jahanian0a256882012-02-16 18:54:09 +00006634 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006635 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00006636 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00006637 Result += ",\n";
6638 }
6639 else
6640 Result += "0, \n";
6641
6642 Result += "};\n";
6643}
6644
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006645static void Write_class_t(ASTContext *Context, std::string &Result,
6646 StringRef VarName,
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006647 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6648 bool rootClass = (!CDecl->getSuperClass());
6649 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006650
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006651 if (!rootClass) {
6652 // Find the Root class
6653 RootClass = CDecl->getSuperClass();
6654 while (RootClass->getSuperClass()) {
6655 RootClass = RootClass->getSuperClass();
6656 }
6657 }
6658
6659 if (metaclass && rootClass) {
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006660 // Need to handle a case of use of forward declaration.
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006661 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006662 Result += "extern \"C\" ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006663 if (CDecl->getImplementation())
6664 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006665 else
6666 Result += "__declspec(dllimport) ";
6667
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006668 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006669 Result += CDecl->getNameAsString();
6670 Result += ";\n";
6671 }
6672 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006673 if (!rootClass) {
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006674 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006675 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006676 Result += "extern \"C\" ";
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006677 if (SuperClass->getImplementation())
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006678 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006679 else
6680 Result += "__declspec(dllimport) ";
6681
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006682 Result += "struct _class_t ";
Fariborz Jahanianfca65102012-03-10 18:25:06 +00006683 Result += VarName;
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006684 Result += SuperClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006685 Result += ";\n";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006686
Fariborz Jahanian064b5382012-03-29 19:04:10 +00006687 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006688 Result += "extern \"C\" ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006689 if (RootClass->getImplementation())
6690 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006691 else
6692 Result += "__declspec(dllimport) ";
6693
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006694 Result += "struct _class_t ";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006695 Result += VarName;
6696 Result += RootClass->getNameAsString();
6697 Result += ";\n";
6698 }
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006699 }
6700
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006701 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6702 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006703 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6704 Result += "\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006705 if (metaclass) {
6706 if (!rootClass) {
6707 Result += "0, // &"; Result += VarName;
6708 Result += RootClass->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006709 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006710 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006711 Result += CDecl->getSuperClass()->getNameAsString();
6712 Result += ",\n\t";
6713 }
6714 else {
Fariborz Jahanian35465592012-03-20 21:09:58 +00006715 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006716 Result += CDecl->getNameAsString();
6717 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006718 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006719 Result += ",\n\t";
6720 }
6721 }
6722 else {
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006723 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006724 Result += CDecl->getNameAsString();
6725 Result += ",\n\t";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006726 if (!rootClass) {
6727 Result += "0, // &"; Result += VarName;
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006728 Result += CDecl->getSuperClass()->getNameAsString();
6729 Result += ",\n\t";
6730 }
6731 else
6732 Result += "0,\n\t";
6733 }
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006734 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6735 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6736 if (metaclass)
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006737 Result += "&_OBJC_METACLASS_RO_$_";
6738 else
6739 Result += "&_OBJC_CLASS_RO_$_";
6740 Result += CDecl->getNameAsString();
6741 Result += ",\n};\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006742
6743 // Add static function to initialize some of the meta-data fields.
6744 // avoid doing it twice.
6745 if (metaclass)
6746 return;
6747
6748 const ObjCInterfaceDecl *SuperClass =
6749 rootClass ? CDecl : CDecl->getSuperClass();
6750
6751 Result += "static void OBJC_CLASS_SETUP_$_";
6752 Result += CDecl->getNameAsString();
6753 Result += "(void ) {\n";
6754 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6755 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian35465592012-03-20 21:09:58 +00006756 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006757
6758 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian35465592012-03-20 21:09:58 +00006759 Result += ".superclass = ";
6760 if (rootClass)
6761 Result += "&OBJC_CLASS_$_";
6762 else
6763 Result += "&OBJC_METACLASS_$_";
6764
Fariborz Jahanian40ca00d2012-03-20 19:54:33 +00006765 Result += SuperClass->getNameAsString(); Result += ";\n";
6766
6767 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6768 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6769
6770 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6771 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6772 Result += CDecl->getNameAsString(); Result += ";\n";
6773
6774 if (!rootClass) {
6775 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6776 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6777 Result += SuperClass->getNameAsString(); Result += ";\n";
6778 }
6779
6780 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6781 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6782 Result += "}\n";
Fariborz Jahanian638252f2012-02-16 21:37:05 +00006783}
6784
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006785static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6786 std::string &Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006787 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006788 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006789 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6790 ArrayRef<ObjCMethodDecl *> ClassMethods,
6791 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6792 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00006793 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi3eb0edd2012-03-21 03:21:46 +00006794 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006795 // must declare an extern class object in case this class is not implemented
6796 // in this TU.
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006797 Result += "\n";
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006798 Result += "extern \"C\" ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006799 if (ClassDecl->getImplementation())
6800 Result += "__declspec(dllexport) ";
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006801 else
6802 Result += "__declspec(dllimport) ";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00006803
Fariborz Jahanian38c59102012-03-27 16:21:30 +00006804 Result += "struct _class_t ";
Fariborz Jahanian320c88a2012-02-17 20:33:00 +00006805 Result += "OBJC_CLASS_$_"; Result += ClassName;
6806 Result += ";\n";
6807
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006808 Result += "\nstatic struct _category_t ";
6809 Result += "_OBJC_$_CATEGORY_";
6810 Result += ClassName; Result += "_$_"; Result += CatName;
6811 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6812 Result += "{\n";
6813 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006814 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006815 Result += ",\n";
6816 if (InstanceMethods.size() > 0) {
6817 Result += "\t(const struct _method_list_t *)&";
6818 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6819 Result += ClassName; Result += "_$_"; Result += CatName;
6820 Result += ",\n";
6821 }
6822 else
6823 Result += "\t0,\n";
6824
6825 if (ClassMethods.size() > 0) {
6826 Result += "\t(const struct _method_list_t *)&";
6827 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6828 Result += ClassName; Result += "_$_"; Result += CatName;
6829 Result += ",\n";
6830 }
6831 else
6832 Result += "\t0,\n";
6833
6834 if (RefedProtocols.size() > 0) {
6835 Result += "\t(const struct _protocol_list_t *)&";
6836 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6837 Result += ClassName; Result += "_$_"; Result += CatName;
6838 Result += ",\n";
6839 }
6840 else
6841 Result += "\t0,\n";
6842
6843 if (ClassProperties.size() > 0) {
6844 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6845 Result += ClassName; Result += "_$_"; Result += CatName;
6846 Result += ",\n";
6847 }
6848 else
6849 Result += "\t0,\n";
6850
6851 Result += "};\n";
Fariborz Jahaniancd79a492012-03-20 21:41:28 +00006852
6853 // Add static function to initialize the class pointer in the category structure.
6854 Result += "static void OBJC_CATEGORY_SETUP_$_";
6855 Result += ClassDecl->getNameAsString();
6856 Result += "_$_";
6857 Result += CatName;
6858 Result += "(void ) {\n";
6859 Result += "\t_OBJC_$_CATEGORY_";
6860 Result += ClassDecl->getNameAsString();
6861 Result += "_$_";
6862 Result += CatName;
6863 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6864 Result += ";\n}\n";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00006865}
6866
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00006867static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6868 ASTContext *Context, std::string &Result,
6869 ArrayRef<ObjCMethodDecl *> Methods,
6870 StringRef VarName,
6871 StringRef ProtocolName) {
6872 if (Methods.size() == 0)
6873 return;
6874
6875 Result += "\nstatic const char *";
6876 Result += VarName; Result += ProtocolName;
6877 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6878 Result += "{\n";
6879 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6880 ObjCMethodDecl *MD = Methods[i];
6881 std::string MethodTypeString, QuoteMethodTypeString;
6882 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6883 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6884 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6885 if (i == e-1)
6886 Result += "\n};\n";
6887 else {
6888 Result += ",\n";
6889 }
6890 }
6891}
6892
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006893static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6894 ASTContext *Context,
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006895 std::string &Result,
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006896 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006897 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006898 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6899 // this is what happens:
6900 /**
6901 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6902 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6903 Class->getVisibility() == HiddenVisibility)
6904 Visibility shoud be: HiddenVisibility;
6905 else
6906 Visibility shoud be: DefaultVisibility;
6907 */
6908
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006909 Result += "\n";
6910 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6911 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahaniane47bf2b2012-03-12 16:46:58 +00006912 if (Context->getLangOpts().MicrosoftExt)
6913 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6914
6915 if (!Context->getLangOpts().MicrosoftExt ||
6916 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanianc9295ec2012-03-10 01:34:42 +00006917 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006918 Result += "extern \"C\" unsigned long int ";
Fariborz Jahanian2677ded2012-03-10 00:53:02 +00006919 else
Fariborz Jahanianf35e0202012-03-29 17:51:09 +00006920 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006921 if (Ivars[i]->isBitField())
6922 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6923 else
6924 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006925 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6926 Result += " = ";
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00006927 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6928 Result += ";\n";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006929 if (Ivars[i]->isBitField()) {
6930 // skip over rest of the ivar bitfields.
6931 SKIP_BITFIELDS(i , e, Ivars);
6932 }
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006933 }
6934}
6935
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006936static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6937 ASTContext *Context, std::string &Result,
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006938 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006939 StringRef VarName,
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006940 ObjCInterfaceDecl *CDecl) {
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006941 if (OriginalIvars.size() > 0) {
6942 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6943 SmallVector<ObjCIvarDecl *, 8> Ivars;
6944 // strip off all but the first ivar bitfield from each group of ivars.
6945 // Such ivars in the ivar list table will be replaced by their grouping struct
6946 // 'ivar'.
6947 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6948 if (OriginalIvars[i]->isBitField()) {
6949 Ivars.push_back(OriginalIvars[i]);
6950 // skip over rest of the ivar bitfields.
6951 SKIP_BITFIELDS(i , e, OriginalIvars);
6952 }
6953 else
6954 Ivars.push_back(OriginalIvars[i]);
6955 }
Fariborz Jahanian1c1da172012-02-13 21:34:45 +00006956
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006957 Result += "\nstatic ";
6958 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6959 Result += " "; Result += VarName;
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006960 Result += CDecl->getNameAsString();
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006961 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6962 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6963 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6964 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6965 ObjCIvarDecl *IvarDecl = Ivars[i];
6966 if (i == 0)
6967 Result += "\t{{";
6968 else
6969 Result += "\t {";
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00006970 Result += "(unsigned long int *)&";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006971 if (Ivars[i]->isBitField())
6972 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6973 else
6974 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian75e71b92012-02-13 20:59:02 +00006975 Result += ", ";
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006976
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006977 Result += "\"";
6978 if (Ivars[i]->isBitField())
6979 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
6980 else
6981 Result += IvarDecl->getName();
6982 Result += "\", ";
6983
6984 QualType IVQT = IvarDecl->getType();
6985 if (IvarDecl->isBitField())
6986 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
6987
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006988 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006989 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006990 IvarDecl);
6991 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
6992 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
6993
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006994 // FIXME. this alignment represents the host alignment and need be changed to
6995 // represent the target alignment.
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006996 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian088959a2012-02-11 20:10:52 +00006997 Align = llvm::Log2_32(Align);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00006998 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00006999 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniancb1d9f32012-02-10 23:18:24 +00007000 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007001 if (i == e-1)
7002 Result += "}}\n";
7003 else
7004 Result += "},\n";
7005 }
7006 Result += "};\n";
7007 }
7008}
7009
Fariborz Jahanian11671902012-02-07 17:11:38 +00007010/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007011void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
7012 std::string &Result) {
Fariborz Jahanian11671902012-02-07 17:11:38 +00007013
Fariborz Jahanian11671902012-02-07 17:11:38 +00007014 // Do not synthesize the protocol more than once.
7015 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
7016 return;
Fariborz Jahanian45489622012-03-14 18:09:23 +00007017 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007018
7019 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
7020 PDecl = Def;
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007021 // Must write out all protocol definitions in current qualifier list,
7022 // and in their nested qualifiers before writing out current definition.
7023 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7024 E = PDecl->protocol_end(); I != E; ++I)
7025 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007026
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007027 // Construct method lists.
7028 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
7029 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
7030 for (ObjCProtocolDecl::instmeth_iterator
7031 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
7032 I != E; ++I) {
7033 ObjCMethodDecl *MD = *I;
7034 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7035 OptInstanceMethods.push_back(MD);
7036 } else {
7037 InstanceMethods.push_back(MD);
7038 }
7039 }
7040
7041 for (ObjCProtocolDecl::classmeth_iterator
7042 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
7043 I != E; ++I) {
7044 ObjCMethodDecl *MD = *I;
7045 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7046 OptClassMethods.push_back(MD);
7047 } else {
7048 ClassMethods.push_back(MD);
7049 }
7050 }
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007051 std::vector<ObjCMethodDecl *> AllMethods;
7052 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
7053 AllMethods.push_back(InstanceMethods[i]);
7054 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
7055 AllMethods.push_back(ClassMethods[i]);
7056 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
7057 AllMethods.push_back(OptInstanceMethods[i]);
7058 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
7059 AllMethods.push_back(OptClassMethods[i]);
7060
7061 Write__extendedMethodTypes_initializer(*this, Context, Result,
7062 AllMethods,
7063 "_OBJC_PROTOCOL_METHOD_TYPES_",
7064 PDecl->getNameAsString());
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007065 // Protocol's super protocol list
7066 std::vector<ObjCProtocolDecl *> SuperProtocols;
7067 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7068 E = PDecl->protocol_end(); I != E; ++I)
7069 SuperProtocols.push_back(*I);
7070
7071 Write_protocol_list_initializer(Context, Result, SuperProtocols,
7072 "_OBJC_PROTOCOL_REFS_",
7073 PDecl->getNameAsString());
7074
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007075 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007076 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007077 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007078
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007079 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007080 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007081 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007082
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007083 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007084 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007085 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007086
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007087 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007088 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007089 PDecl->getNameAsString(), false);
Fariborz Jahanian4aaf8b12012-02-07 20:15:08 +00007090
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007091 // Protocol's property metadata.
7092 std::vector<ObjCPropertyDecl *> ProtocolProperties;
7093 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
7094 E = PDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00007095 ProtocolProperties.push_back(*I);
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007096
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007097 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007098 /* Container */0,
7099 "_OBJC_PROTOCOL_PROPERTIES_",
7100 PDecl->getNameAsString());
Fariborz Jahanian67f7c552012-02-07 23:31:52 +00007101
Fariborz Jahanian48985802012-02-08 00:50:52 +00007102 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007103 Result += "\n";
7104 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007105 Result += "static ";
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007106 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007107 Result += PDecl->getNameAsString();
Fariborz Jahanian48985802012-02-08 00:50:52 +00007108 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7109 Result += "\t0,\n"; // id is; is null
7110 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007111 if (SuperProtocols.size() > 0) {
7112 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7113 Result += PDecl->getNameAsString(); Result += ",\n";
7114 }
7115 else
7116 Result += "\t0,\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007117 if (InstanceMethods.size() > 0) {
7118 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7119 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007120 }
7121 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007122 Result += "\t0,\n";
7123
7124 if (ClassMethods.size() > 0) {
7125 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7126 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007127 }
7128 else
Fariborz Jahanian48985802012-02-08 00:50:52 +00007129 Result += "\t0,\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007130
Fariborz Jahanian48985802012-02-08 00:50:52 +00007131 if (OptInstanceMethods.size() > 0) {
7132 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7133 Result += PDecl->getNameAsString(); Result += ",\n";
7134 }
7135 else
7136 Result += "\t0,\n";
7137
7138 if (OptClassMethods.size() > 0) {
7139 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7140 Result += PDecl->getNameAsString(); Result += ",\n";
7141 }
7142 else
7143 Result += "\t0,\n";
7144
7145 if (ProtocolProperties.size() > 0) {
7146 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7147 Result += PDecl->getNameAsString(); Result += ",\n";
7148 }
7149 else
7150 Result += "\t0,\n";
7151
7152 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7153 Result += "\t0,\n";
7154
Fariborz Jahaniana8395a62012-02-08 22:23:26 +00007155 if (AllMethods.size() > 0) {
7156 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7157 Result += PDecl->getNameAsString();
7158 Result += "\n};\n";
7159 }
7160 else
7161 Result += "\t0\n};\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007162
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007163 if (LangOpts.MicrosoftExt)
Fariborz Jahanian1b085422012-04-14 17:13:08 +00007164 Result += "static ";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007165 Result += "struct _protocol_t *";
7166 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7167 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7168 Result += ";\n";
Fariborz Jahanian48985802012-02-08 00:50:52 +00007169
Fariborz Jahanian11671902012-02-07 17:11:38 +00007170 // Mark this protocol as having been generated.
7171 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
7172 llvm_unreachable("protocol already synthesized");
7173
7174}
7175
7176void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7177 const ObjCList<ObjCProtocolDecl> &Protocols,
7178 StringRef prefix, StringRef ClassName,
7179 std::string &Result) {
7180 if (Protocols.empty()) return;
7181
7182 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahaniane18961b2012-02-08 19:53:58 +00007183 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007184
7185 // Output the top lovel protocol meta-data for the class.
7186 /* struct _objc_protocol_list {
7187 struct _objc_protocol_list *next;
7188 int protocol_count;
7189 struct _objc_protocol *class_protocols[];
7190 }
7191 */
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007192 Result += "\n";
7193 if (LangOpts.MicrosoftExt)
7194 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7195 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007196 Result += "\tstruct _objc_protocol_list *next;\n";
7197 Result += "\tint protocol_count;\n";
7198 Result += "\tstruct _objc_protocol *class_protocols[";
7199 Result += utostr(Protocols.size());
7200 Result += "];\n} _OBJC_";
7201 Result += prefix;
7202 Result += "_PROTOCOLS_";
7203 Result += ClassName;
7204 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7205 "{\n\t0, ";
7206 Result += utostr(Protocols.size());
7207 Result += "\n";
7208
7209 Result += "\t,{&_OBJC_PROTOCOL_";
7210 Result += Protocols[0]->getNameAsString();
7211 Result += " \n";
7212
7213 for (unsigned i = 1; i != Protocols.size(); i++) {
7214 Result += "\t ,&_OBJC_PROTOCOL_";
7215 Result += Protocols[i]->getNameAsString();
7216 Result += "\n";
7217 }
7218 Result += "\t }\n};\n";
7219}
7220
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007221/// hasObjCExceptionAttribute - Return true if this class or any super
7222/// class has the __objc_exception__ attribute.
7223/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7224static bool hasObjCExceptionAttribute(ASTContext &Context,
7225 const ObjCInterfaceDecl *OID) {
7226 if (OID->hasAttr<ObjCExceptionAttr>())
7227 return true;
7228 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7229 return hasObjCExceptionAttribute(Context, Super);
7230 return false;
7231}
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007232
Fariborz Jahanian11671902012-02-07 17:11:38 +00007233void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7234 std::string &Result) {
7235 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7236
7237 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007238 if (CDecl->isImplicitInterfaceDecl())
7239 assert(false &&
7240 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian088959a2012-02-11 20:10:52 +00007241
Fariborz Jahanian45489622012-03-14 18:09:23 +00007242 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007243 SmallVector<ObjCIvarDecl *, 8> IVars;
7244
7245 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7246 IVD; IVD = IVD->getNextIvar()) {
7247 // Ignore unnamed bit-fields.
7248 if (!IVD->getDeclName())
7249 continue;
7250 IVars.push_back(IVD);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007251 }
7252
Fariborz Jahanian6b83dae2012-02-10 20:47:10 +00007253 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007254 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007255 CDecl);
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007256
7257 // Build _objc_method_list for class's instance methods if needed
7258 SmallVector<ObjCMethodDecl *, 32>
7259 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7260
7261 // If any of our property implementations have associated getters or
7262 // setters, produce metadata for them as well.
7263 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7264 PropEnd = IDecl->propimpl_end();
7265 Prop != PropEnd; ++Prop) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007266 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007267 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007268 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007269 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007270 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007271 if (!PD)
7272 continue;
7273 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007274 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007275 InstanceMethods.push_back(Getter);
7276 if (PD->isReadOnly())
7277 continue;
7278 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanianf687e7b2012-05-03 22:52:13 +00007279 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007280 InstanceMethods.push_back(Setter);
7281 }
7282
7283 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7284 "_OBJC_$_INSTANCE_METHODS_",
7285 IDecl->getNameAsString(), true);
7286
7287 SmallVector<ObjCMethodDecl *, 32>
7288 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7289
7290 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7291 "_OBJC_$_CLASS_METHODS_",
7292 IDecl->getNameAsString(), true);
Fariborz Jahanianbce367742012-02-14 19:31:35 +00007293
7294 // Protocols referenced in class declaration?
7295 // Protocol's super protocol list
7296 std::vector<ObjCProtocolDecl *> RefedProtocols;
7297 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7298 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7299 E = Protocols.end();
7300 I != E; ++I) {
7301 RefedProtocols.push_back(*I);
7302 // Must write out all protocol definitions in current qualifier list,
7303 // and in their nested qualifiers before writing out current definition.
7304 RewriteObjCProtocolMetaData(*I, Result);
7305 }
7306
7307 Write_protocol_list_initializer(Context, Result,
7308 RefedProtocols,
7309 "_OBJC_CLASS_PROTOCOLS_$_",
7310 IDecl->getNameAsString());
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007311
7312 // Protocol's property metadata.
7313 std::vector<ObjCPropertyDecl *> ClassProperties;
7314 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7315 E = CDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00007316 ClassProperties.push_back(*I);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007317
7318 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianee1db7a2012-03-22 17:39:35 +00007319 /* Container */IDecl,
Fariborz Jahanianc41d8282012-02-16 21:57:59 +00007320 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007321 CDecl->getNameAsString());
Fariborz Jahanianb1ba8852012-02-14 17:19:02 +00007322
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007323
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007324 // Data for initializing _class_ro_t metaclass meta-data
7325 uint32_t flags = CLS_META;
7326 std::string InstanceSize;
7327 std::string InstanceStart;
7328
7329
7330 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7331 if (classIsHidden)
7332 flags |= OBJC2_CLS_HIDDEN;
7333
7334 if (!CDecl->getSuperClass())
7335 // class is root
7336 flags |= CLS_ROOT;
7337 InstanceSize = "sizeof(struct _class_t)";
7338 InstanceStart = InstanceSize;
7339 Write__class_ro_t_initializer(Context, Result, flags,
7340 InstanceStart, InstanceSize,
7341 ClassMethods,
7342 0,
7343 0,
7344 0,
7345 "_OBJC_METACLASS_RO_$_",
7346 CDecl->getNameAsString());
7347
7348
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007349 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007350 flags = CLS;
7351 if (classIsHidden)
7352 flags |= OBJC2_CLS_HIDDEN;
7353
7354 if (hasObjCExceptionAttribute(*Context, CDecl))
7355 flags |= CLS_EXCEPTION;
7356
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007357 if (!CDecl->getSuperClass())
7358 // class is root
7359 flags |= CLS_ROOT;
7360
Fariborz Jahanian0a256882012-02-16 18:54:09 +00007361 InstanceSize.clear();
7362 InstanceStart.clear();
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007363 if (!ObjCSynthesizedStructs.count(CDecl)) {
7364 InstanceSize = "0";
7365 InstanceStart = "0";
7366 }
7367 else {
7368 InstanceSize = "sizeof(struct ";
7369 InstanceSize += CDecl->getNameAsString();
7370 InstanceSize += "_IMPL)";
7371
7372 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7373 if (IVD) {
Fariborz Jahanianaaf4d692012-04-11 21:12:36 +00007374 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianfdc06e32012-02-15 00:50:11 +00007375 }
7376 else
7377 InstanceStart = InstanceSize;
7378 }
7379 Write__class_ro_t_initializer(Context, Result, flags,
7380 InstanceStart, InstanceSize,
7381 InstanceMethods,
7382 RefedProtocols,
7383 IVars,
7384 ClassProperties,
7385 "_OBJC_CLASS_RO_$_",
7386 CDecl->getNameAsString());
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007387
7388 Write_class_t(Context, Result,
7389 "OBJC_METACLASS_$_",
7390 CDecl, /*metaclass*/true);
7391
7392 Write_class_t(Context, Result,
7393 "OBJC_CLASS_$_",
7394 CDecl, /*metaclass*/false);
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007395
7396 if (ImplementationIsNonLazy(IDecl))
7397 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian638252f2012-02-16 21:37:05 +00007398
Fariborz Jahanian11671902012-02-07 17:11:38 +00007399}
7400
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007401void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7402 int ClsDefCount = ClassImplementation.size();
7403 if (!ClsDefCount)
7404 return;
7405 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7406 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7407 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7408 for (int i = 0; i < ClsDefCount; i++) {
7409 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7410 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7411 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7412 Result += CDecl->getName(); Result += ",\n";
7413 }
7414 Result += "};\n";
7415}
7416
Fariborz Jahanian11671902012-02-07 17:11:38 +00007417void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7418 int ClsDefCount = ClassImplementation.size();
7419 int CatDefCount = CategoryImplementation.size();
7420
7421 // For each implemented class, write out all its meta data.
7422 for (int i = 0; i < ClsDefCount; i++)
7423 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7424
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007425 RewriteClassSetupInitHook(Result);
7426
Fariborz Jahanian11671902012-02-07 17:11:38 +00007427 // For each implemented category, write out all its meta data.
7428 for (int i = 0; i < CatDefCount; i++)
7429 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7430
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007431 RewriteCategorySetupInitHook(Result);
7432
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007433 if (ClsDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007434 if (LangOpts.MicrosoftExt)
7435 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007436 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7437 Result += llvm::utostr(ClsDefCount); Result += "]";
7438 Result +=
7439 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7440 "regular,no_dead_strip\")))= {\n";
7441 for (int i = 0; i < ClsDefCount; i++) {
7442 Result += "\t&OBJC_CLASS_$_";
7443 Result += ClassImplementation[i]->getNameAsString();
7444 Result += ",\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007445 }
Fariborz Jahaniane7a0c932012-02-17 00:06:14 +00007446 Result += "};\n";
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007447
7448 if (!DefinedNonLazyClasses.empty()) {
7449 if (LangOpts.MicrosoftExt)
7450 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7451 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7452 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7453 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7454 Result += ",\n";
7455 }
7456 Result += "};\n";
7457 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007458 }
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007459
7460 if (CatDefCount > 0) {
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007461 if (LangOpts.MicrosoftExt)
7462 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007463 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7464 Result += llvm::utostr(CatDefCount); Result += "]";
7465 Result +=
7466 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7467 "regular,no_dead_strip\")))= {\n";
7468 for (int i = 0; i < CatDefCount; i++) {
7469 Result += "\t&_OBJC_$_CATEGORY_";
7470 Result +=
7471 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7472 Result += "_$_";
7473 Result += CategoryImplementation[i]->getNameAsString();
7474 Result += ",\n";
7475 }
7476 Result += "};\n";
7477 }
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007478
7479 if (!DefinedNonLazyCategories.empty()) {
7480 if (LangOpts.MicrosoftExt)
7481 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7482 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7483 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7484 Result += "\t&_OBJC_$_CATEGORY_";
7485 Result +=
7486 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7487 Result += "_$_";
7488 Result += DefinedNonLazyCategories[i]->getNameAsString();
7489 Result += ",\n";
7490 }
7491 Result += "};\n";
7492 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007493}
7494
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007495void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7496 if (LangOpts.MicrosoftExt)
7497 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7498
7499 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7500 // version 0, ObjCABI is 2
Fariborz Jahanianb31e3af2012-03-15 17:05:33 +00007501 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanianddddca32012-03-14 21:44:09 +00007502}
7503
Fariborz Jahanian11671902012-02-07 17:11:38 +00007504/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7505/// implementation.
7506void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7507 std::string &Result) {
Fariborz Jahanian45489622012-03-14 18:09:23 +00007508 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007509 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7510 // Find category declaration for this implementation.
Douglas Gregor048fbfa2013-01-16 23:00:23 +00007511 ObjCCategoryDecl *CDecl
7512 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007513
7514 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007515 FullCategoryName += "_$_";
7516 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007517
7518 // Build _objc_method_list for class's instance methods if needed
7519 SmallVector<ObjCMethodDecl *, 32>
7520 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7521
7522 // If any of our property implementations have associated getters or
7523 // setters, produce metadata for them as well.
7524 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7525 PropEnd = IDecl->propimpl_end();
7526 Prop != PropEnd; ++Prop) {
David Blaikie2d7c57e2012-04-30 02:36:29 +00007527 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian11671902012-02-07 17:11:38 +00007528 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007529 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian11671902012-02-07 17:11:38 +00007530 continue;
David Blaikie2d7c57e2012-04-30 02:36:29 +00007531 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian11671902012-02-07 17:11:38 +00007532 if (!PD)
7533 continue;
7534 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7535 InstanceMethods.push_back(Getter);
7536 if (PD->isReadOnly())
7537 continue;
7538 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7539 InstanceMethods.push_back(Setter);
7540 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007541
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007542 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7543 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7544 FullCategoryName, true);
7545
7546 SmallVector<ObjCMethodDecl *, 32>
7547 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7548
7549 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7550 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7551 FullCategoryName, true);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007552
7553 // Protocols referenced in class declaration?
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007554 // Protocol's super protocol list
7555 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidise7f3ef32012-03-13 01:09:41 +00007556 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7557 E = CDecl->protocol_end();
7558
7559 I != E; ++I) {
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007560 RefedProtocols.push_back(*I);
7561 // Must write out all protocol definitions in current qualifier list,
7562 // and in their nested qualifiers before writing out current definition.
7563 RewriteObjCProtocolMetaData(*I, Result);
7564 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007565
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007566 Write_protocol_list_initializer(Context, Result,
7567 RefedProtocols,
7568 "_OBJC_CATEGORY_PROTOCOLS_$_",
7569 FullCategoryName);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007570
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007571 // Protocol's property metadata.
7572 std::vector<ObjCPropertyDecl *> ClassProperties;
7573 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7574 E = CDecl->prop_end(); I != E; ++I)
David Blaikie40ed2972012-06-06 20:45:41 +00007575 ClassProperties.push_back(*I);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007576
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007577 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahaniane9863b52012-05-03 23:19:33 +00007578 /* Container */IDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007579 "_OBJC_$_PROP_LIST_",
7580 FullCategoryName);
7581
7582 Write_category_t(*this, Context, Result,
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007583 CDecl,
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007584 ClassDecl,
Fariborz Jahanianf2055052012-02-17 18:40:41 +00007585 InstanceMethods,
7586 ClassMethods,
7587 RefedProtocols,
7588 ClassProperties);
7589
Fariborz Jahanian07a423d2012-03-14 23:18:19 +00007590 // Determine if this category is also "non-lazy".
7591 if (ImplementationIsNonLazy(IDecl))
7592 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahanian5ed21c32012-03-27 18:41:05 +00007593
7594}
7595
7596void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7597 int CatDefCount = CategoryImplementation.size();
7598 if (!CatDefCount)
7599 return;
7600 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7601 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7602 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7603 for (int i = 0; i < CatDefCount; i++) {
7604 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7605 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7606 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7607 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7608 Result += ClassDecl->getName();
7609 Result += "_$_";
7610 Result += CatDecl->getName();
7611 Result += ",\n";
7612 }
7613 Result += "};\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007614}
7615
7616// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7617/// class methods.
7618template<typename MethodIterator>
7619void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7620 MethodIterator MethodEnd,
7621 bool IsInstanceMethod,
7622 StringRef prefix,
7623 StringRef ClassName,
7624 std::string &Result) {
7625 if (MethodBegin == MethodEnd) return;
7626
7627 if (!objc_impl_method) {
7628 /* struct _objc_method {
7629 SEL _cmd;
7630 char *method_types;
7631 void *_imp;
7632 }
7633 */
7634 Result += "\nstruct _objc_method {\n";
7635 Result += "\tSEL _cmd;\n";
7636 Result += "\tchar *method_types;\n";
7637 Result += "\tvoid *_imp;\n";
7638 Result += "};\n";
7639
7640 objc_impl_method = true;
7641 }
7642
7643 // Build _objc_method_list for class's methods if needed
7644
7645 /* struct {
7646 struct _objc_method_list *next_method;
7647 int method_count;
7648 struct _objc_method method_list[];
7649 }
7650 */
7651 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian008dfe22012-03-11 19:41:56 +00007652 Result += "\n";
7653 if (LangOpts.MicrosoftExt) {
7654 if (IsInstanceMethod)
7655 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7656 else
7657 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7658 }
7659 Result += "static struct {\n";
Fariborz Jahanian11671902012-02-07 17:11:38 +00007660 Result += "\tstruct _objc_method_list *next_method;\n";
7661 Result += "\tint method_count;\n";
7662 Result += "\tstruct _objc_method method_list[";
7663 Result += utostr(NumMethods);
7664 Result += "];\n} _OBJC_";
7665 Result += prefix;
7666 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7667 Result += "_METHODS_";
7668 Result += ClassName;
7669 Result += " __attribute__ ((used, section (\"__OBJC, __";
7670 Result += IsInstanceMethod ? "inst" : "cls";
7671 Result += "_meth\")))= ";
7672 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7673
7674 Result += "\t,{{(SEL)\"";
7675 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7676 std::string MethodTypeString;
7677 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7678 Result += "\", \"";
7679 Result += MethodTypeString;
7680 Result += "\", (void *)";
7681 Result += MethodInternalNames[*MethodBegin];
7682 Result += "}\n";
7683 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7684 Result += "\t ,{(SEL)\"";
7685 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7686 std::string MethodTypeString;
7687 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7688 Result += "\", \"";
7689 Result += MethodTypeString;
7690 Result += "\", (void *)";
7691 Result += MethodInternalNames[*MethodBegin];
7692 Result += "}\n";
7693 }
7694 Result += "\t }\n};\n";
7695}
7696
7697Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7698 SourceRange OldRange = IV->getSourceRange();
7699 Expr *BaseExpr = IV->getBase();
7700
7701 // Rewrite the base, but without actually doing replaces.
7702 {
7703 DisableReplaceStmtScope S(*this);
7704 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7705 IV->setBase(BaseExpr);
7706 }
7707
7708 ObjCIvarDecl *D = IV->getDecl();
7709
7710 Expr *Replacement = IV;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007711
Fariborz Jahanian11671902012-02-07 17:11:38 +00007712 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7713 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian89919cc2012-05-08 23:54:35 +00007714 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian11671902012-02-07 17:11:38 +00007715 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7716 // lookup which class implements the instance variable.
7717 ObjCInterfaceDecl *clsDeclared = 0;
7718 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7719 clsDeclared);
7720 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7721
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007722 // Build name of symbol holding ivar offset.
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007723 std::string IvarOffsetName;
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007724 if (D->isBitField())
7725 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7726 else
7727 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahaniana854174a2012-03-20 17:13:39 +00007728
Fariborz Jahanian5e49eb92012-02-22 18:13:25 +00007729 ReferencedIvars[clsDeclared].insert(D);
7730
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007731 // cast offset to "char *".
7732 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7733 Context->getPointerType(Context->CharTy),
Fariborz Jahanian11671902012-02-07 17:11:38 +00007734 CK_BitCast,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007735 BaseExpr);
7736 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7737 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Rafael Espindola6ae7e502013-04-03 19:27:57 +00007738 Context->UnsignedLongTy, 0, SC_Extern);
John McCall113bee02012-03-10 09:33:50 +00007739 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7740 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007741 SourceLocation());
7742 BinaryOperator *addExpr =
7743 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7744 Context->getPointerType(Context->CharTy),
Lang Hames5de91cc2012-10-02 04:45:10 +00007745 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian11671902012-02-07 17:11:38 +00007746 // Don't forget the parens to enforce the proper binding.
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007747 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7748 SourceLocation(),
7749 addExpr);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007750 QualType IvarT = D->getType();
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007751 if (D->isBitField())
7752 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007753
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007754 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007755 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanianfaded5b2012-04-30 23:20:30 +00007756 RD = RD->getDefinition();
7757 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007758 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahaniand7c67772012-05-02 17:34:59 +00007759 ObjCContainerDecl *CDecl =
7760 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7761 // ivar in class extensions requires special treatment.
7762 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7763 CDecl = CatDecl->getClassInterface();
7764 std::string RecName = CDecl->getName();
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007765 RecName += "_IMPL";
7766 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7767 SourceLocation(), SourceLocation(),
7768 &Context->Idents.get(RecName.c_str()));
7769 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7770 unsigned UnsignedIntSize =
7771 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7772 Expr *Zero = IntegerLiteral::Create(*Context,
7773 llvm::APInt(UnsignedIntSize, 0),
7774 Context->UnsignedIntTy, SourceLocation());
7775 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7776 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7777 Zero);
7778 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7779 SourceLocation(),
7780 &Context->Idents.get(D->getNameAsString()),
7781 IvarT, 0,
7782 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smith2b013182012-06-10 03:12:00 +00007783 ICIS_NoInit);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007784 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7785 FD->getType(), VK_LValue,
7786 OK_Ordinary);
7787 IvarT = Context->getDecltypeType(ME, ME->getType());
7788 }
7789 }
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007790 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahaniandd5a59b2012-02-24 17:35:35 +00007791 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007792
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007793 castExpr = NoTypeInfoCStyleCastExpr(Context,
7794 castT,
7795 CK_BitCast,
7796 PE);
Fariborz Jahanianbf217c82012-04-27 22:48:54 +00007797
7798
Fariborz Jahanian1dc712f2012-02-29 00:26:20 +00007799 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007800 VK_LValue, OK_Ordinary,
7801 SourceLocation());
7802 PE = new (Context) ParenExpr(OldRange.getBegin(),
7803 OldRange.getEnd(),
7804 Exp);
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007805
7806 if (D->isBitField()) {
7807 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7808 SourceLocation(),
7809 &Context->Idents.get(D->getNameAsString()),
7810 D->getType(), 0,
7811 /*BitWidth=*/D->getBitWidth(),
7812 /*Mutable=*/true,
7813 ICIS_NoInit);
7814 MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(),
7815 FD->getType(), VK_LValue,
7816 OK_Ordinary);
7817 Replacement = ME;
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007818
Fariborz Jahanian57dd66b2013-02-07 01:53:15 +00007819 }
7820 else
7821 Replacement = PE;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007822 }
Fariborz Jahanian11671902012-02-07 17:11:38 +00007823
Fariborz Jahanianc481c0c2012-02-21 23:46:48 +00007824 ReplaceStmtWithRange(IV, Replacement, OldRange);
7825 return Replacement;
Fariborz Jahanian11671902012-02-07 17:11:38 +00007826}