blob: ecd509610a71d60bce9444153075329b7bb35a32 [file] [log] [blame]
Fariborz Jahanian64cb63a2012-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 Kremenek305c6132012-09-01 05:09:24 +000014#include "clang/Rewrite/Frontend/ASTConsumers.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000015#include "clang/AST/AST.h"
16#include "clang/AST/ASTConsumer.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000017#include "clang/AST/Attr.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000018#include "clang/AST/ParentMap.h"
Jordan Rose3f6f51e2013-02-08 22:30:41 +000019#include "clang/Basic/CharInfo.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000020#include "clang/Basic/Diagnostic.h"
Benjamin Kramer2fa67ef2012-12-01 15:09:41 +000021#include "clang/Basic/IdentifierTable.h"
22#include "clang/Basic/SourceManager.h"
Benjamin Kramer9852f582012-12-01 16:35:25 +000023#include "clang/Basic/TargetInfo.h"
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000024#include "clang/Lex/Lexer.h"
Chandler Carruth55fc8732012-12-04 09:13:33 +000025#include "clang/Rewrite/Core/Rewriter.h"
Benjamin Kramer2fa67ef2012-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 Jahanian64cb63a2012-02-07 17:11:38 +000030#include "llvm/Support/MemoryBuffer.h"
31#include "llvm/Support/raw_ostream.h"
Fariborz Jahanian64cb63a2012-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 Jahanian64cb63a2012-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 Jahaniandf474ec2012-03-23 00:00:49 +000078 Expr *GlobalConstructionExp;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +000079 unsigned RewriteFailedDiag;
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +000080 unsigned GlobalBlockRewriteFailedDiag;
Fariborz Jahanian64cb63a2012-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 Kramere5753592013-09-09 14:48:42 +0000105 FunctionDecl *SuperConstructorFunctionDecl;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000106 FunctionDecl *CurFunctionDef;
Fariborz Jahanian64cb63a2012-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 Jahaniancf4c60f2012-02-17 22:20:12 +0000113 llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCWrittenInterfaces;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000114 llvm::SmallPtrSet<TagDecl*, 32> GlobalDefinedTags;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000115 SmallVector<ObjCInterfaceDecl*, 32> ObjCInterfacesSeen;
Fariborz Jahanian88f7f752012-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 Gribenkocfa88f82013-01-12 19:30:44 +0000120 SmallVector<ObjCCategoryDecl *, 8> DefinedNonLazyCategories;
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000121
Fariborz Jahanian64cb63a2012-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 McCallf4b88a42012-03-10 09:33:50 +0000132 SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000133
John McCallf4b88a42012-03-10 09:33:50 +0000134 SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000135
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000136
Fariborz Jahanian64cb63a2012-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 Jahanian72c88f12012-02-22 18:13:25 +0000147 llvm::DenseMap<ObjCInterfaceDecl *,
148 llvm::SmallPtrSet<ObjCIvarDecl *, 8> > ReferencedIvars;
149
Fariborz Jahaniancd3b0362013-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 Jahanian31c4a4b2013-02-07 22:50:40 +0000156 SmallVector<FunctionDecl*, 32> FunctionDefinitionsSeen;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000157
Fariborz Jahanian64cb63a2012-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 Jahanianada71912013-02-08 00:27:34 +0000166 bool GenerateLineInfo;
Fariborz Jahanian64cb63a2012-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 Jahanian90af4e22012-02-14 17:19:02 +0000186 llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
Fariborz Jahanian64cb63a2012-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 Jahaniancf4c60f2012-02-17 22:20:12 +0000194 } else {
195 // Keep track of all interface declarations seen.
Fariborz Jahanianf3295272012-02-24 21:42:38 +0000196 ObjCInterfacesSeen.push_back(Class);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +0000197 break;
Fariborz Jahanian64cb63a2012-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 Jahanian31c4a4b2013-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 Jahanian64cb63a2012-02-07 17:11:38 +0000220 HandleTopLevelSingleDecl(*I);
221 }
222 return true;
223 }
224 void HandleTopLevelSingleDecl(Decl *D);
225 void HandleDeclInMainFile(Decl *D);
226 RewriteModernObjC(std::string inFile, raw_ostream *OS,
227 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahanianada71912013-02-08 00:27:34 +0000228 bool silenceMacroWarn, bool LineInfo);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000229
230 ~RewriteModernObjC() {}
231
232 virtual void HandleTranslationUnit(ASTContext &C);
233
234 void ReplaceStmt(Stmt *Old, Stmt *New) {
235 Stmt *ReplacingStmt = ReplacedNodes[Old];
236
237 if (ReplacingStmt)
238 return; // We can't rewrite the same node twice.
239
240 if (DisableReplaceStmt)
241 return;
242
243 // If replacement succeeded or warning disabled return with no warning.
244 if (!Rewrite.ReplaceStmt(Old, New)) {
245 ReplacedNodes[Old] = New;
246 return;
247 }
248 if (SilenceRewriteMacroWarning)
249 return;
250 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
251 << Old->getSourceRange();
252 }
253
254 void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
255 if (DisableReplaceStmt)
256 return;
257
258 // Measure the old text.
259 int Size = Rewrite.getRangeSize(SrcRange);
260 if (Size == -1) {
261 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
262 << Old->getSourceRange();
263 return;
264 }
265 // Get the new text.
266 std::string SStr;
267 llvm::raw_string_ostream S(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +0000268 New->printPretty(S, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000269 const std::string &Str = S.str();
270
271 // If replacement succeeded or warning disabled return with no warning.
272 if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
273 ReplacedNodes[Old] = New;
274 return;
275 }
276 if (SilenceRewriteMacroWarning)
277 return;
278 Diags.Report(Context->getFullLoc(Old->getLocStart()), RewriteFailedDiag)
279 << Old->getSourceRange();
280 }
281
282 void InsertText(SourceLocation Loc, StringRef Str,
283 bool InsertAfter = true) {
284 // If insertion succeeded or warning disabled return with no warning.
285 if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
286 SilenceRewriteMacroWarning)
287 return;
288
289 Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
290 }
291
292 void ReplaceText(SourceLocation Start, unsigned OrigLength,
293 StringRef Str) {
294 // If removal succeeded or warning disabled return with no warning.
295 if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
296 SilenceRewriteMacroWarning)
297 return;
298
299 Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
300 }
301
302 // Syntactic Rewriting.
303 void RewriteRecordBody(RecordDecl *RD);
304 void RewriteInclude();
Fariborz Jahanian96205962012-11-06 17:30:23 +0000305 void RewriteLineDirective(const Decl *D);
Fariborz Jahanianf616ae22012-11-06 23:25:49 +0000306 void ConvertSourceLocationToLineDirective(SourceLocation Loc,
307 std::string &LineString);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000308 void RewriteForwardClassDecl(DeclGroupRef D);
Craig Topper6b9240e2013-07-05 19:34:19 +0000309 void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000310 void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
311 const std::string &typedefString);
312 void RewriteImplementations();
313 void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
314 ObjCImplementationDecl *IMD,
315 ObjCCategoryImplDecl *CID);
316 void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
317 void RewriteImplementationDecl(Decl *Dcl);
318 void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
319 ObjCMethodDecl *MDecl, std::string &ResultStr);
320 void RewriteTypeIntoString(QualType T, std::string &ResultStr,
321 const FunctionType *&FPRetType);
322 void RewriteByRefString(std::string &ResultStr, const std::string &Name,
323 ValueDecl *VD, bool def=false);
324 void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
325 void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
326 void RewriteForwardProtocolDecl(DeclGroupRef D);
Craig Topper6b9240e2013-07-05 19:34:19 +0000327 void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000328 void RewriteMethodDeclaration(ObjCMethodDecl *Method);
329 void RewriteProperty(ObjCPropertyDecl *prop);
330 void RewriteFunctionDecl(FunctionDecl *FD);
331 void RewriteBlockPointerType(std::string& Str, QualType Type);
332 void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +0000333 void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000334 void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
335 void RewriteTypeOfDecl(VarDecl *VD);
336 void RewriteObjCQualifiedInterfaceTypes(Expr *E);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000337
338 std::string getIvarAccessString(ObjCIvarDecl *D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000339
340 // Expression Rewriting.
341 Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
342 Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
343 Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
344 Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
345 Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
346 Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
347 Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
Fariborz Jahanian55947042012-03-27 20:17:30 +0000348 Stmt *RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp);
Patrick Beardeb382ec2012-04-19 00:25:12 +0000349 Stmt *RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp);
Fariborz Jahanian86cff602012-03-30 23:35:47 +0000350 Stmt *RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000351 Stmt *RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000352 Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000353 Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
Fariborz Jahanian042b91d2012-05-23 23:47:20 +0000354 Stmt *RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000355 Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
356 Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
357 Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
358 SourceLocation OrigEnd);
359 Stmt *RewriteBreakStmt(BreakStmt *S);
360 Stmt *RewriteContinueStmt(ContinueStmt *S);
361 void RewriteCastExpr(CStyleCastExpr *CE);
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +0000362 void RewriteImplicitCastObjCExpr(CastExpr *IE);
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000363 void RewriteLinkageSpec(LinkageSpecDecl *LSD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000364
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000365 // Computes ivar bitfield group no.
366 unsigned ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV);
367 // Names field decl. for ivar bitfield group.
368 void ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV, std::string &Result);
369 // Names struct type for ivar bitfield group.
370 void ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV, std::string &Result);
371 // Names symbol for ivar bitfield group field offset.
372 void ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV, std::string &Result);
373 // Given an ivar bitfield, it builds (or finds) its group record type.
374 QualType GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV);
375 QualType SynthesizeBitfieldGroupStructType(
376 ObjCIvarDecl *IV,
377 SmallVectorImpl<ObjCIvarDecl *> &IVars);
378
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000379 // Block rewriting.
380 void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
381
382 // Block specific rewrite rules.
383 void RewriteBlockPointerDecl(NamedDecl *VD);
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +0000384 void RewriteByRefVar(VarDecl *VD, bool firstDecl, bool lastDecl);
John McCallf4b88a42012-03-10 09:33:50 +0000385 Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000386 Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
387 void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
388
389 void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
390 std::string &Result);
391
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000392 void RewriteObjCFieldDecl(FieldDecl *fieldDecl, std::string &Result);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +0000393 bool IsTagDefinedInsideClass(ObjCContainerDecl *IDecl, TagDecl *Tag,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +0000394 bool &IsNamedDefinition);
395 void RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
396 std::string &Result);
Fariborz Jahanian15f87772012-02-28 22:45:07 +0000397
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +0000398 bool RewriteObjCFieldDeclType(QualType &Type, std::string &Result);
399
Fariborz Jahanian72c88f12012-02-22 18:13:25 +0000400 void RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
401 std::string &Result);
402
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000403 virtual void Initialize(ASTContext &context);
404
Benjamin Kramer48d798c2012-06-02 10:20:41 +0000405 // Misc. AST transformation routines. Sometimes they end up calling
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000406 // rewriting routines on the new ASTs.
407 CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
408 Expr **args, unsigned nargs,
409 SourceLocation StartLoc=SourceLocation(),
410 SourceLocation EndLoc=SourceLocation());
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +0000411
412 Expr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +0000413 QualType returnType,
414 SmallVectorImpl<QualType> &ArgTypes,
415 SmallVectorImpl<Expr*> &MsgExprs,
416 ObjCMethodDecl *Method);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000417
418 Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
419 SourceLocation StartLoc=SourceLocation(),
420 SourceLocation EndLoc=SourceLocation());
421
422 void SynthCountByEnumWithState(std::string &buf);
423 void SynthMsgSendFunctionDecl();
424 void SynthMsgSendSuperFunctionDecl();
425 void SynthMsgSendStretFunctionDecl();
426 void SynthMsgSendFpretFunctionDecl();
427 void SynthMsgSendSuperStretFunctionDecl();
428 void SynthGetClassFunctionDecl();
429 void SynthGetMetaClassFunctionDecl();
430 void SynthGetSuperClassFunctionDecl();
431 void SynthSelGetUidFunctionDecl();
Benjamin Kramere5753592013-09-09 14:48:42 +0000432 void SynthSuperConstructorFunctionDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000433
434 // Rewriting metadata
435 template<typename MethodIterator>
436 void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
437 MethodIterator MethodEnd,
438 bool IsInstanceMethod,
439 StringRef prefix,
440 StringRef ClassName,
441 std::string &Result);
Fariborz Jahanianda9624a2012-02-08 19:53:58 +0000442 void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
443 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000444 void RewriteObjCProtocolListMetaData(
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000445 const ObjCList<ObjCProtocolDecl> &Prots,
446 StringRef prefix, StringRef ClassName, std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000447 void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000448 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000449 void RewriteClassSetupInitHook(std::string &Result);
Fariborz Jahaniane0335782012-03-27 18:41:05 +0000450
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000451 void RewriteMetaDataIntoBuffer(std::string &Result);
452 void WriteImageInfo(std::string &Result);
453 void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000454 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000455 void RewriteCategorySetupInitHook(std::string &Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000456
457 // Rewriting ivar
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000458 void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000459 std::string &Result);
Fariborz Jahanianb4ee8802012-04-30 16:57:52 +0000460 Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000461
462
463 std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
464 std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
465 StringRef funcName, std::string Tag);
466 std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
467 StringRef funcName, std::string Tag);
468 std::string SynthesizeBlockImpl(BlockExpr *CE,
469 std::string Tag, std::string Desc);
470 std::string SynthesizeBlockDescriptor(std::string DescTag,
471 std::string ImplTag,
472 int i, StringRef funcName,
473 unsigned hasCopy);
474 Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
475 void SynthesizeBlockLiterals(SourceLocation FunLocStart,
476 StringRef FunName);
477 FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
478 Stmt *SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper6b9240e2013-07-05 19:34:19 +0000479 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000480
481 // Misc. helper routines.
482 QualType getProtocolType();
483 void WarnAboutReturnGotoStmts(Stmt *S);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000484 void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
485 void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
486 void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
487
488 bool IsDeclStmtInForeachHeader(DeclStmt *DS);
489 void CollectBlockDeclRefInfo(BlockExpr *Exp);
490 void GetBlockDeclRefExprs(Stmt *S);
Craig Topper6b9240e2013-07-05 19:34:19 +0000491 void GetInnerBlockDeclRefExprs(Stmt *S,
492 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000493 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts);
494
495 // We avoid calling Type::isBlockPointerType(), since it operates on the
496 // canonical type. We only care if the top-level type is a closure pointer.
497 bool isTopLevelBlockPointerType(QualType T) {
498 return isa<BlockPointerType>(T);
499 }
500
501 /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
502 /// to a function pointer type and upon success, returns true; false
503 /// otherwise.
504 bool convertBlockPointerToFunctionPointer(QualType &T) {
505 if (isTopLevelBlockPointerType(T)) {
506 const BlockPointerType *BPT = T->getAs<BlockPointerType>();
507 T = Context->getPointerType(BPT->getPointeeType());
508 return true;
509 }
510 return false;
511 }
512
Fariborz Jahanian164d6f82012-02-13 18:57:49 +0000513 bool convertObjCTypeToCStyleType(QualType &T);
514
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000515 bool needToScanForQualifiers(QualType T);
516 QualType getSuperStructType();
517 QualType getConstantStringStructType();
518 QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
519 bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
520
521 void convertToUnqualifiedObjCType(QualType &T) {
Fariborz Jahaniane35abe12012-04-06 22:29:36 +0000522 if (T->isObjCQualifiedIdType()) {
523 bool isConst = T.isConstQualified();
524 T = isConst ? Context->getObjCIdType().withConst()
525 : Context->getObjCIdType();
526 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000527 else if (T->isObjCQualifiedClassType())
528 T = Context->getObjCClassType();
529 else if (T->isObjCObjectPointerType() &&
530 T->getPointeeType()->isObjCQualifiedInterfaceType()) {
531 if (const ObjCObjectPointerType * OBJPT =
532 T->getAsObjCInterfacePointerType()) {
533 const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
534 T = QualType(IFaceT, 0);
535 T = Context->getPointerType(T);
536 }
537 }
538 }
539
540 // FIXME: This predicate seems like it would be useful to add to ASTContext.
541 bool isObjCType(QualType T) {
542 if (!LangOpts.ObjC1 && !LangOpts.ObjC2)
543 return false;
544
545 QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
546
547 if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
548 OCT == Context->getCanonicalType(Context->getObjCClassType()))
549 return true;
550
551 if (const PointerType *PT = OCT->getAs<PointerType>()) {
552 if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
553 PT->getPointeeType()->isObjCQualifiedIdType())
554 return true;
555 }
556 return false;
557 }
558 bool PointerTypeTakesAnyBlockArguments(QualType QT);
559 bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
560 void GetExtentOfArgList(const char *Name, const char *&LParen,
561 const char *&RParen);
562
563 void QuoteDoublequotes(std::string &From, std::string &To) {
564 for (unsigned i = 0; i < From.length(); i++) {
565 if (From[i] == '"')
566 To += "\\\"";
567 else
568 To += From[i];
569 }
570 }
571
572 QualType getSimpleFunctionType(QualType result,
Jordan Rosebea522f2013-03-08 21:51:21 +0000573 ArrayRef<QualType> args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000574 bool variadic = false) {
575 if (result == Context->getObjCInstanceType())
576 result = Context->getObjCIdType();
577 FunctionProtoType::ExtProtoInfo fpi;
578 fpi.Variadic = variadic;
Jordan Rosebea522f2013-03-08 21:51:21 +0000579 return Context->getFunctionType(result, args, fpi);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000580 }
581
582 // Helper function: create a CStyleCastExpr with trivial type source info.
583 CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
584 CastKind Kind, Expr *E) {
585 TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
586 return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, 0, TInfo,
587 SourceLocation(), SourceLocation());
588 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +0000589
590 bool ImplementationIsNonLazy(const ObjCImplDecl *OD) const {
591 IdentifierInfo* II = &Context->Idents.get("load");
592 Selector LoadSel = Context->Selectors.getSelector(0, &II);
593 return OD->getClassMethod(LoadSel) != 0;
594 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000595 };
596
597}
598
599void RewriteModernObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
600 NamedDecl *D) {
601 if (const FunctionProtoType *fproto
602 = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
603 for (FunctionProtoType::arg_type_iterator I = fproto->arg_type_begin(),
604 E = fproto->arg_type_end(); I && (I != E); ++I)
605 if (isTopLevelBlockPointerType(*I)) {
606 // All the args are checked/rewritten. Don't call twice!
607 RewriteBlockPointerDecl(D);
608 break;
609 }
610 }
611}
612
613void RewriteModernObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
614 const PointerType *PT = funcType->getAs<PointerType>();
615 if (PT && PointerTypeTakesAnyBlockArguments(funcType))
616 RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
617}
618
619static bool IsHeaderFile(const std::string &Filename) {
620 std::string::size_type DotPos = Filename.rfind('.');
621
622 if (DotPos == std::string::npos) {
623 // no file extension
624 return false;
625 }
626
627 std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
628 // C header: .h
629 // C++ header: .hh or .H;
630 return Ext == "h" || Ext == "hh" || Ext == "H";
631}
632
633RewriteModernObjC::RewriteModernObjC(std::string inFile, raw_ostream* OS,
634 DiagnosticsEngine &D, const LangOptions &LOpts,
Fariborz Jahanianada71912013-02-08 00:27:34 +0000635 bool silenceMacroWarn,
636 bool LineInfo)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000637 : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(OS),
Fariborz Jahanianada71912013-02-08 00:27:34 +0000638 SilenceRewriteMacroWarning(silenceMacroWarn), GenerateLineInfo(LineInfo) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000639 IsHeader = IsHeaderFile(inFile);
640 RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
641 "rewriting sub-expression within a macro (may not be correct)");
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +0000642 // FIXME. This should be an error. But if block is not called, it is OK. And it
643 // may break including some headers.
644 GlobalBlockRewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
645 "rewriting block literal declared in global scope is not implemented");
646
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000647 TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
648 DiagnosticsEngine::Warning,
649 "rewriter doesn't support user-specified control flow semantics "
650 "for @try/@finally (code may not execute properly)");
651}
652
653ASTConsumer *clang::CreateModernObjCRewriter(const std::string& InFile,
654 raw_ostream* OS,
655 DiagnosticsEngine &Diags,
656 const LangOptions &LOpts,
Fariborz Jahanianada71912013-02-08 00:27:34 +0000657 bool SilenceRewriteMacroWarning,
658 bool LineInfo) {
659 return new RewriteModernObjC(InFile, OS, Diags, LOpts,
660 SilenceRewriteMacroWarning, LineInfo);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000661}
662
663void RewriteModernObjC::InitializeCommon(ASTContext &context) {
664 Context = &context;
665 SM = &Context->getSourceManager();
666 TUDecl = Context->getTranslationUnitDecl();
667 MsgSendFunctionDecl = 0;
668 MsgSendSuperFunctionDecl = 0;
669 MsgSendStretFunctionDecl = 0;
670 MsgSendSuperStretFunctionDecl = 0;
671 MsgSendFpretFunctionDecl = 0;
672 GetClassFunctionDecl = 0;
673 GetMetaClassFunctionDecl = 0;
674 GetSuperClassFunctionDecl = 0;
675 SelGetUidFunctionDecl = 0;
676 CFStringFunctionDecl = 0;
677 ConstantStringClassReference = 0;
678 NSStringRecord = 0;
679 CurMethodDef = 0;
680 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000681 GlobalVarDecl = 0;
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +0000682 GlobalConstructionExp = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000683 SuperStructDecl = 0;
684 ProtocolTypeDecl = 0;
685 ConstantStringDecl = 0;
686 BcLabelCount = 0;
Benjamin Kramere5753592013-09-09 14:48:42 +0000687 SuperConstructorFunctionDecl = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000688 NumObjCStringLiterals = 0;
689 PropParentMap = 0;
690 CurrentBody = 0;
691 DisableReplaceStmt = false;
692 objc_impl_method = false;
693
694 // Get the ID and start/end of the main file.
695 MainFileID = SM->getMainFileID();
696 const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
697 MainFileStart = MainBuf->getBufferStart();
698 MainFileEnd = MainBuf->getBufferEnd();
699
David Blaikie4e4d0842012-03-11 07:00:24 +0000700 Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000701}
702
703//===----------------------------------------------------------------------===//
704// Top Level Driver Code
705//===----------------------------------------------------------------------===//
706
707void RewriteModernObjC::HandleTopLevelSingleDecl(Decl *D) {
708 if (Diags.hasErrorOccurred())
709 return;
710
711 // Two cases: either the decl could be in the main file, or it could be in a
712 // #included file. If the former, rewrite it now. If the later, check to see
713 // if we rewrote the #include/#import.
714 SourceLocation Loc = D->getLocation();
715 Loc = SM->getExpansionLoc(Loc);
716
717 // If this is for a builtin, ignore it.
718 if (Loc.isInvalid()) return;
719
720 // Look for built-in declarations that we need to refer during the rewrite.
721 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
722 RewriteFunctionDecl(FD);
723 } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
724 // declared in <Foundation/NSString.h>
725 if (FVD->getName() == "_NSConstantStringClassReference") {
726 ConstantStringClassReference = FVD;
727 return;
728 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000729 } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
730 RewriteCategoryDecl(CD);
731 } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
732 if (PD->isThisDeclarationADefinition())
733 RewriteProtocolDecl(PD);
734 } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
Fariborz Jahanian8e86b2d2012-04-04 17:16:15 +0000735 // FIXME. This will not work in all situations and leaving it out
736 // is harmless.
737 // RewriteLinkageSpec(LSD);
738
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000739 // Recurse into linkage specifications
740 for (DeclContext::decl_iterator DI = LSD->decls_begin(),
741 DIEnd = LSD->decls_end();
742 DI != DIEnd; ) {
743 if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
744 if (!IFace->isThisDeclarationADefinition()) {
745 SmallVector<Decl *, 8> DG;
746 SourceLocation StartLoc = IFace->getLocStart();
747 do {
748 if (isa<ObjCInterfaceDecl>(*DI) &&
749 !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
750 StartLoc == (*DI)->getLocStart())
751 DG.push_back(*DI);
752 else
753 break;
754
755 ++DI;
756 } while (DI != DIEnd);
757 RewriteForwardClassDecl(DG);
758 continue;
759 }
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +0000760 else {
761 // Keep track of all interface declarations seen.
762 ObjCInterfacesSeen.push_back(IFace);
763 ++DI;
764 continue;
765 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000766 }
767
768 if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
769 if (!Proto->isThisDeclarationADefinition()) {
770 SmallVector<Decl *, 8> DG;
771 SourceLocation StartLoc = Proto->getLocStart();
772 do {
773 if (isa<ObjCProtocolDecl>(*DI) &&
774 !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
775 StartLoc == (*DI)->getLocStart())
776 DG.push_back(*DI);
777 else
778 break;
779
780 ++DI;
781 } while (DI != DIEnd);
782 RewriteForwardProtocolDecl(DG);
783 continue;
784 }
785 }
786
787 HandleTopLevelSingleDecl(*DI);
788 ++DI;
789 }
790 }
791 // If we have a decl in the main file, see if we should rewrite it.
Eli Friedman24146972013-08-22 00:27:10 +0000792 if (SM->isWrittenInMainFile(Loc))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000793 return HandleDeclInMainFile(D);
794}
795
796//===----------------------------------------------------------------------===//
797// Syntactic (non-AST) Rewriting Code
798//===----------------------------------------------------------------------===//
799
800void RewriteModernObjC::RewriteInclude() {
801 SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
802 StringRef MainBuf = SM->getBufferData(MainFileID);
803 const char *MainBufStart = MainBuf.begin();
804 const char *MainBufEnd = MainBuf.end();
805 size_t ImportLen = strlen("import");
806
807 // Loop over the whole file, looking for includes.
808 for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; ++BufPtr) {
809 if (*BufPtr == '#') {
810 if (++BufPtr == MainBufEnd)
811 return;
812 while (*BufPtr == ' ' || *BufPtr == '\t')
813 if (++BufPtr == MainBufEnd)
814 return;
815 if (!strncmp(BufPtr, "import", ImportLen)) {
816 // replace import with include
817 SourceLocation ImportLoc =
818 LocStart.getLocWithOffset(BufPtr-MainBufStart);
819 ReplaceText(ImportLoc, ImportLen, "include");
820 BufPtr += ImportLen;
821 }
822 }
823 }
824}
825
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000826static void WriteInternalIvarName(const ObjCInterfaceDecl *IDecl,
827 ObjCIvarDecl *IvarDecl, std::string &Result) {
828 Result += "OBJC_IVAR_$_";
829 Result += IDecl->getName();
830 Result += "$";
831 Result += IvarDecl->getName();
832}
833
834std::string
835RewriteModernObjC::getIvarAccessString(ObjCIvarDecl *D) {
836 const ObjCInterfaceDecl *ClassDecl = D->getContainingInterface();
837
838 // Build name of symbol holding ivar offset.
839 std::string IvarOffsetName;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000840 if (D->isBitField())
841 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
842 else
843 WriteInternalIvarName(ClassDecl, D, IvarOffsetName);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000844
845
846 std::string S = "(*(";
847 QualType IvarT = D->getType();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000848 if (D->isBitField())
849 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000850
851 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
852 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
853 RD = RD->getDefinition();
854 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
855 // decltype(((Foo_IMPL*)0)->bar) *
856 ObjCContainerDecl *CDecl =
857 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
858 // ivar in class extensions requires special treatment.
859 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
860 CDecl = CatDecl->getClassInterface();
861 std::string RecName = CDecl->getName();
862 RecName += "_IMPL";
863 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
864 SourceLocation(), SourceLocation(),
865 &Context->Idents.get(RecName.c_str()));
866 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
867 unsigned UnsignedIntSize =
868 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
869 Expr *Zero = IntegerLiteral::Create(*Context,
870 llvm::APInt(UnsignedIntSize, 0),
871 Context->UnsignedIntTy, SourceLocation());
872 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
873 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
874 Zero);
875 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
876 SourceLocation(),
877 &Context->Idents.get(D->getNameAsString()),
878 IvarT, 0,
879 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +0000880 ICIS_NoInit);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000881 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
882 FD->getType(), VK_LValue,
883 OK_Ordinary);
884 IvarT = Context->getDecltypeType(ME, ME->getType());
885 }
886 }
887 convertObjCTypeToCStyleType(IvarT);
888 QualType castT = Context->getPointerType(IvarT);
889 std::string TypeString(castT.getAsString(Context->getPrintingPolicy()));
890 S += TypeString;
891 S += ")";
892
893 // ((char *)self + IVAR_OFFSET_SYMBOL_NAME)
894 S += "((char *)self + ";
895 S += IvarOffsetName;
896 S += "))";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +0000897 if (D->isBitField()) {
898 S += ".";
899 S += D->getNameAsString();
900 }
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +0000901 ReferencedIvars[const_cast<ObjCInterfaceDecl *>(ClassDecl)].insert(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000902 return S;
903}
904
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000905/// mustSynthesizeSetterGetterMethod - returns true if setter or getter has not
906/// been found in the class implementation. In this case, it must be synthesized.
907static bool mustSynthesizeSetterGetterMethod(ObjCImplementationDecl *IMP,
908 ObjCPropertyDecl *PD,
909 bool getter) {
910 return getter ? !IMP->getInstanceMethod(PD->getGetterName())
911 : !IMP->getInstanceMethod(PD->getSetterName());
912
913}
914
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000915void RewriteModernObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
916 ObjCImplementationDecl *IMD,
917 ObjCCategoryImplDecl *CID) {
918 static bool objcGetPropertyDefined = false;
919 static bool objcSetPropertyDefined = false;
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000920 SourceLocation startGetterSetterLoc;
921
922 if (PID->getLocStart().isValid()) {
923 SourceLocation startLoc = PID->getLocStart();
924 InsertText(startLoc, "// ");
925 const char *startBuf = SM->getCharacterData(startLoc);
926 assert((*startBuf == '@') && "bogus @synthesize location");
927 const char *semiBuf = strchr(startBuf, ';');
928 assert((*semiBuf == ';') && "@synthesize: can't find ';'");
929 startGetterSetterLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
930 }
931 else
932 startGetterSetterLoc = IMD ? IMD->getLocEnd() : CID->getLocEnd();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000933
934 if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
935 return; // FIXME: is this correct?
936
937 // Generate the 'getter' function.
938 ObjCPropertyDecl *PD = PID->getPropertyDecl();
939 ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
Jordan Rose62bbe072013-03-15 21:41:35 +0000940 assert(IMD && OID && "Synthesized ivars must be attached to @implementation");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000941
Bill Wendlingad017fa2012-12-20 19:22:21 +0000942 unsigned Attributes = PD->getPropertyAttributes();
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000943 if (mustSynthesizeSetterGetterMethod(IMD, PD, true /*getter*/)) {
Bill Wendlingad017fa2012-12-20 19:22:21 +0000944 bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
945 (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000946 ObjCPropertyDecl::OBJC_PR_copy));
947 std::string Getr;
948 if (GenGetProperty && !objcGetPropertyDefined) {
949 objcGetPropertyDefined = true;
950 // FIXME. Is this attribute correct in all cases?
951 Getr = "\nextern \"C\" __declspec(dllimport) "
952 "id objc_getProperty(id, SEL, long, bool);\n";
953 }
954 RewriteObjCMethodDecl(OID->getContainingInterface(),
955 PD->getGetterMethodDecl(), Getr);
956 Getr += "{ ";
957 // Synthesize an explicit cast to gain access to the ivar.
958 // See objc-act.c:objc_synthesize_new_getter() for details.
959 if (GenGetProperty) {
960 // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
961 Getr += "typedef ";
962 const FunctionType *FPRetType = 0;
963 RewriteTypeIntoString(PD->getGetterMethodDecl()->getResultType(), Getr,
964 FPRetType);
965 Getr += " _TYPE";
966 if (FPRetType) {
967 Getr += ")"; // close the precedence "scope" for "*".
968
969 // Now, emit the argument types (if any).
970 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
971 Getr += "(";
972 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
973 if (i) Getr += ", ";
974 std::string ParamStr = FT->getArgType(i).getAsString(
975 Context->getPrintingPolicy());
976 Getr += ParamStr;
977 }
978 if (FT->isVariadic()) {
979 if (FT->getNumArgs()) Getr += ", ";
980 Getr += "...";
981 }
982 Getr += ")";
983 } else
984 Getr += "()";
985 }
986 Getr += ";\n";
987 Getr += "return (_TYPE)";
988 Getr += "objc_getProperty(self, _cmd, ";
989 RewriteIvarOffsetComputation(OID, Getr);
990 Getr += ", 1)";
991 }
992 else
993 Getr += "return " + getIvarAccessString(OID);
994 Getr += "; }";
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000995 InsertText(startGetterSetterLoc, Getr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +0000996 }
997
Fariborz Jahanian301e2e42012-05-03 22:52:13 +0000998 if (PD->isReadOnly() ||
999 !mustSynthesizeSetterGetterMethod(IMD, PD, false /*setter*/))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001000 return;
1001
1002 // Generate the 'setter' function.
1003 std::string Setr;
Bill Wendlingad017fa2012-12-20 19:22:21 +00001004 bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001005 ObjCPropertyDecl::OBJC_PR_copy);
1006 if (GenSetProperty && !objcSetPropertyDefined) {
1007 objcSetPropertyDefined = true;
1008 // FIXME. Is this attribute correct in all cases?
1009 Setr = "\nextern \"C\" __declspec(dllimport) "
1010 "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
1011 }
1012
1013 RewriteObjCMethodDecl(OID->getContainingInterface(),
1014 PD->getSetterMethodDecl(), Setr);
1015 Setr += "{ ";
1016 // Synthesize an explicit cast to initialize the ivar.
1017 // See objc-act.c:objc_synthesize_new_setter() for details.
1018 if (GenSetProperty) {
1019 Setr += "objc_setProperty (self, _cmd, ";
1020 RewriteIvarOffsetComputation(OID, Setr);
1021 Setr += ", (id)";
1022 Setr += PD->getName();
1023 Setr += ", ";
Bill Wendlingad017fa2012-12-20 19:22:21 +00001024 if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001025 Setr += "0, ";
1026 else
1027 Setr += "1, ";
Bill Wendlingad017fa2012-12-20 19:22:21 +00001028 if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001029 Setr += "1)";
1030 else
1031 Setr += "0)";
1032 }
1033 else {
1034 Setr += getIvarAccessString(OID) + " = ";
1035 Setr += PD->getName();
1036 }
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00001037 Setr += "; }\n";
1038 InsertText(startGetterSetterLoc, Setr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001039}
1040
1041static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
1042 std::string &typedefString) {
Fariborz Jahanianbfaa1112013-02-08 17:15:07 +00001043 typedefString += "\n#ifndef _REWRITER_typedef_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001044 typedefString += ForwardDecl->getNameAsString();
1045 typedefString += "\n";
1046 typedefString += "#define _REWRITER_typedef_";
1047 typedefString += ForwardDecl->getNameAsString();
1048 typedefString += "\n";
1049 typedefString += "typedef struct objc_object ";
1050 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001051 // typedef struct { } _objc_exc_Classname;
1052 typedefString += ";\ntypedef struct {} _objc_exc_";
1053 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001054 typedefString += ";\n#endif\n";
1055}
1056
1057void RewriteModernObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
1058 const std::string &typedefString) {
1059 SourceLocation startLoc = ClassDecl->getLocStart();
1060 const char *startBuf = SM->getCharacterData(startLoc);
1061 const char *semiPtr = strchr(startBuf, ';');
1062 // Replace the @class with typedefs corresponding to the classes.
1063 ReplaceText(startLoc, semiPtr-startBuf+1, typedefString);
1064}
1065
1066void RewriteModernObjC::RewriteForwardClassDecl(DeclGroupRef D) {
1067 std::string typedefString;
1068 for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; ++I) {
1069 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
1070 if (I == D.begin()) {
1071 // Translate to typedef's that forward reference structs with the same name
1072 // as the class. As a convenience, we include the original declaration
1073 // as a comment.
1074 typedefString += "// @class ";
1075 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianbfaa1112013-02-08 17:15:07 +00001076 typedefString += ";";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001077 }
1078 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1079 }
1080 DeclGroupRef::iterator I = D.begin();
1081 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
1082}
1083
1084void RewriteModernObjC::RewriteForwardClassDecl(
Craig Topper6b9240e2013-07-05 19:34:19 +00001085 const SmallVectorImpl<Decl *> &D) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001086 std::string typedefString;
1087 for (unsigned i = 0; i < D.size(); i++) {
1088 ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
1089 if (i == 0) {
1090 typedefString += "// @class ";
1091 typedefString += ForwardDecl->getNameAsString();
Fariborz Jahanianbfaa1112013-02-08 17:15:07 +00001092 typedefString += ";";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001093 }
1094 RewriteOneForwardClassDecl(ForwardDecl, typedefString);
1095 }
1096 RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
1097}
1098
1099void RewriteModernObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
1100 // When method is a synthesized one, such as a getter/setter there is
1101 // nothing to rewrite.
1102 if (Method->isImplicit())
1103 return;
1104 SourceLocation LocStart = Method->getLocStart();
1105 SourceLocation LocEnd = Method->getLocEnd();
1106
1107 if (SM->getExpansionLineNumber(LocEnd) >
1108 SM->getExpansionLineNumber(LocStart)) {
1109 InsertText(LocStart, "#if 0\n");
1110 ReplaceText(LocEnd, 1, ";\n#endif\n");
1111 } else {
1112 InsertText(LocStart, "// ");
1113 }
1114}
1115
1116void RewriteModernObjC::RewriteProperty(ObjCPropertyDecl *prop) {
1117 SourceLocation Loc = prop->getAtLoc();
1118
1119 ReplaceText(Loc, 0, "// ");
1120 // FIXME: handle properties that are declared across multiple lines.
1121}
1122
1123void RewriteModernObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
1124 SourceLocation LocStart = CatDecl->getLocStart();
1125
1126 // FIXME: handle category headers that are declared across multiple lines.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001127 if (CatDecl->getIvarRBraceLoc().isValid()) {
1128 ReplaceText(LocStart, 1, "/** ");
1129 ReplaceText(CatDecl->getIvarRBraceLoc(), 1, "**/ ");
1130 }
1131 else {
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001132 ReplaceText(LocStart, 0, "// ");
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001133 }
Fariborz Jahanianaf300292012-02-20 20:09:20 +00001134
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001135 for (ObjCCategoryDecl::prop_iterator I = CatDecl->prop_begin(),
1136 E = CatDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001137 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001138
1139 for (ObjCCategoryDecl::instmeth_iterator
1140 I = CatDecl->instmeth_begin(), E = CatDecl->instmeth_end();
1141 I != E; ++I)
1142 RewriteMethodDeclaration(*I);
1143 for (ObjCCategoryDecl::classmeth_iterator
1144 I = CatDecl->classmeth_begin(), E = CatDecl->classmeth_end();
1145 I != E; ++I)
1146 RewriteMethodDeclaration(*I);
1147
1148 // Lastly, comment out the @end.
1149 ReplaceText(CatDecl->getAtEndRange().getBegin(),
Fariborz Jahanianf9f30792013-04-03 19:11:21 +00001150 strlen("@end"), "/* @end */\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001151}
1152
1153void RewriteModernObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
1154 SourceLocation LocStart = PDecl->getLocStart();
1155 assert(PDecl->isThisDeclarationADefinition());
1156
1157 // FIXME: handle protocol headers that are declared across multiple lines.
1158 ReplaceText(LocStart, 0, "// ");
1159
1160 for (ObjCProtocolDecl::instmeth_iterator
1161 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
1162 I != E; ++I)
1163 RewriteMethodDeclaration(*I);
1164 for (ObjCProtocolDecl::classmeth_iterator
1165 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
1166 I != E; ++I)
1167 RewriteMethodDeclaration(*I);
1168
1169 for (ObjCInterfaceDecl::prop_iterator I = PDecl->prop_begin(),
1170 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001171 RewriteProperty(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001172
1173 // Lastly, comment out the @end.
1174 SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
Fariborz Jahanianf9f30792013-04-03 19:11:21 +00001175 ReplaceText(LocEnd, strlen("@end"), "/* @end */\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001176
1177 // Must comment out @optional/@required
1178 const char *startBuf = SM->getCharacterData(LocStart);
1179 const char *endBuf = SM->getCharacterData(LocEnd);
1180 for (const char *p = startBuf; p < endBuf; p++) {
1181 if (*p == '@' && !strncmp(p+1, "optional", strlen("optional"))) {
1182 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1183 ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1184
1185 }
1186 else if (*p == '@' && !strncmp(p+1, "required", strlen("required"))) {
1187 SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1188 ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1189
1190 }
1191 }
1192}
1193
1194void RewriteModernObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1195 SourceLocation LocStart = (*D.begin())->getLocStart();
1196 if (LocStart.isInvalid())
1197 llvm_unreachable("Invalid SourceLocation");
1198 // FIXME: handle forward protocol that are declared across multiple lines.
1199 ReplaceText(LocStart, 0, "// ");
1200}
1201
1202void
Craig Topper6b9240e2013-07-05 19:34:19 +00001203RewriteModernObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001204 SourceLocation LocStart = DG[0]->getLocStart();
1205 if (LocStart.isInvalid())
1206 llvm_unreachable("Invalid SourceLocation");
1207 // FIXME: handle forward protocol that are declared across multiple lines.
1208 ReplaceText(LocStart, 0, "// ");
1209}
1210
Fariborz Jahanianb3f904f2012-04-03 17:35:38 +00001211void
1212RewriteModernObjC::RewriteLinkageSpec(LinkageSpecDecl *LSD) {
1213 SourceLocation LocStart = LSD->getExternLoc();
1214 if (LocStart.isInvalid())
1215 llvm_unreachable("Invalid extern SourceLocation");
1216
1217 ReplaceText(LocStart, 0, "// ");
1218 if (!LSD->hasBraces())
1219 return;
1220 // FIXME. We don't rewrite well if '{' is not on same line as 'extern'.
1221 SourceLocation LocRBrace = LSD->getRBraceLoc();
1222 if (LocRBrace.isInvalid())
1223 llvm_unreachable("Invalid rbrace SourceLocation");
1224 ReplaceText(LocRBrace, 0, "// ");
1225}
1226
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001227void RewriteModernObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1228 const FunctionType *&FPRetType) {
1229 if (T->isObjCQualifiedIdType())
1230 ResultStr += "id";
1231 else if (T->isFunctionPointerType() ||
1232 T->isBlockPointerType()) {
1233 // needs special handling, since pointer-to-functions have special
1234 // syntax (where a decaration models use).
1235 QualType retType = T;
1236 QualType PointeeTy;
1237 if (const PointerType* PT = retType->getAs<PointerType>())
1238 PointeeTy = PT->getPointeeType();
1239 else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1240 PointeeTy = BPT->getPointeeType();
1241 if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1242 ResultStr += FPRetType->getResultType().getAsString(
1243 Context->getPrintingPolicy());
1244 ResultStr += "(*";
1245 }
1246 } else
1247 ResultStr += T.getAsString(Context->getPrintingPolicy());
1248}
1249
1250void RewriteModernObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1251 ObjCMethodDecl *OMD,
1252 std::string &ResultStr) {
1253 //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1254 const FunctionType *FPRetType = 0;
1255 ResultStr += "\nstatic ";
1256 RewriteTypeIntoString(OMD->getResultType(), ResultStr, FPRetType);
1257 ResultStr += " ";
1258
1259 // Unique method name
1260 std::string NameStr;
1261
1262 if (OMD->isInstanceMethod())
1263 NameStr += "_I_";
1264 else
1265 NameStr += "_C_";
1266
1267 NameStr += IDecl->getNameAsString();
1268 NameStr += "_";
1269
1270 if (ObjCCategoryImplDecl *CID =
1271 dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1272 NameStr += CID->getNameAsString();
1273 NameStr += "_";
1274 }
1275 // Append selector names, replacing ':' with '_'
1276 {
1277 std::string selString = OMD->getSelector().getAsString();
1278 int len = selString.size();
1279 for (int i = 0; i < len; i++)
1280 if (selString[i] == ':')
1281 selString[i] = '_';
1282 NameStr += selString;
1283 }
1284 // Remember this name for metadata emission
1285 MethodInternalNames[OMD] = NameStr;
1286 ResultStr += NameStr;
1287
1288 // Rewrite arguments
1289 ResultStr += "(";
1290
1291 // invisible arguments
1292 if (OMD->isInstanceMethod()) {
1293 QualType selfTy = Context->getObjCInterfaceType(IDecl);
1294 selfTy = Context->getPointerType(selfTy);
1295 if (!LangOpts.MicrosoftExt) {
1296 if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1297 ResultStr += "struct ";
1298 }
1299 // When rewriting for Microsoft, explicitly omit the structure name.
1300 ResultStr += IDecl->getNameAsString();
1301 ResultStr += " *";
1302 }
1303 else
1304 ResultStr += Context->getObjCClassType().getAsString(
1305 Context->getPrintingPolicy());
1306
1307 ResultStr += " self, ";
1308 ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1309 ResultStr += " _cmd";
1310
1311 // Method arguments.
1312 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
1313 E = OMD->param_end(); PI != E; ++PI) {
1314 ParmVarDecl *PDecl = *PI;
1315 ResultStr += ", ";
1316 if (PDecl->getType()->isObjCQualifiedIdType()) {
1317 ResultStr += "id ";
1318 ResultStr += PDecl->getNameAsString();
1319 } else {
1320 std::string Name = PDecl->getNameAsString();
1321 QualType QT = PDecl->getType();
1322 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian2610f902012-03-27 16:42:20 +00001323 (void)convertBlockPointerToFunctionPointer(QT);
1324 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001325 ResultStr += Name;
1326 }
1327 }
1328 if (OMD->isVariadic())
1329 ResultStr += ", ...";
1330 ResultStr += ") ";
1331
1332 if (FPRetType) {
1333 ResultStr += ")"; // close the precedence "scope" for "*".
1334
1335 // Now, emit the argument types (if any).
1336 if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1337 ResultStr += "(";
1338 for (unsigned i = 0, e = FT->getNumArgs(); i != e; ++i) {
1339 if (i) ResultStr += ", ";
1340 std::string ParamStr = FT->getArgType(i).getAsString(
1341 Context->getPrintingPolicy());
1342 ResultStr += ParamStr;
1343 }
1344 if (FT->isVariadic()) {
1345 if (FT->getNumArgs()) ResultStr += ", ";
1346 ResultStr += "...";
1347 }
1348 ResultStr += ")";
1349 } else {
1350 ResultStr += "()";
1351 }
1352 }
1353}
1354void RewriteModernObjC::RewriteImplementationDecl(Decl *OID) {
1355 ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1356 ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1357
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001358 if (IMD) {
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001359 if (IMD->getIvarRBraceLoc().isValid()) {
1360 ReplaceText(IMD->getLocStart(), 1, "/** ");
1361 ReplaceText(IMD->getIvarRBraceLoc(), 1, "**/ ");
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001362 }
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00001363 else {
1364 InsertText(IMD->getLocStart(), "// ");
1365 }
Fariborz Jahaniand2aea122012-02-19 19:00:05 +00001366 }
1367 else
1368 InsertText(CID->getLocStart(), "// ");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001369
1370 for (ObjCCategoryImplDecl::instmeth_iterator
1371 I = IMD ? IMD->instmeth_begin() : CID->instmeth_begin(),
1372 E = IMD ? IMD->instmeth_end() : CID->instmeth_end();
1373 I != E; ++I) {
1374 std::string ResultStr;
1375 ObjCMethodDecl *OMD = *I;
1376 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1377 SourceLocation LocStart = OMD->getLocStart();
1378 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1379
1380 const char *startBuf = SM->getCharacterData(LocStart);
1381 const char *endBuf = SM->getCharacterData(LocEnd);
1382 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1383 }
1384
1385 for (ObjCCategoryImplDecl::classmeth_iterator
1386 I = IMD ? IMD->classmeth_begin() : CID->classmeth_begin(),
1387 E = IMD ? IMD->classmeth_end() : CID->classmeth_end();
1388 I != E; ++I) {
1389 std::string ResultStr;
1390 ObjCMethodDecl *OMD = *I;
1391 RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1392 SourceLocation LocStart = OMD->getLocStart();
1393 SourceLocation LocEnd = OMD->getCompoundBody()->getLocStart();
1394
1395 const char *startBuf = SM->getCharacterData(LocStart);
1396 const char *endBuf = SM->getCharacterData(LocEnd);
1397 ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1398 }
1399 for (ObjCCategoryImplDecl::propimpl_iterator
1400 I = IMD ? IMD->propimpl_begin() : CID->propimpl_begin(),
1401 E = IMD ? IMD->propimpl_end() : CID->propimpl_end();
1402 I != E; ++I) {
David Blaikie581deb32012-06-06 20:45:41 +00001403 RewritePropertyImplDecl(*I, IMD, CID);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001404 }
1405
1406 InsertText(IMD ? IMD->getLocEnd() : CID->getLocEnd(), "// ");
1407}
1408
1409void RewriteModernObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00001410 // Do not synthesize more than once.
1411 if (ObjCSynthesizedStructs.count(ClassDecl))
1412 return;
1413 // Make sure super class's are written before current class is written.
1414 ObjCInterfaceDecl *SuperClass = ClassDecl->getSuperClass();
1415 while (SuperClass) {
1416 RewriteInterfaceDecl(SuperClass);
1417 SuperClass = SuperClass->getSuperClass();
1418 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001419 std::string ResultStr;
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001420 if (!ObjCWrittenInterfaces.count(ClassDecl->getCanonicalDecl())) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001421 // we haven't seen a forward decl - generate a typedef.
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001422 RewriteOneForwardClassDecl(ClassDecl, ResultStr);
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00001423 RewriteIvarOffsetSymbols(ClassDecl, ResultStr);
1424
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001425 RewriteObjCInternalStruct(ClassDecl, ResultStr);
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00001426 // Mark this typedef as having been written into its c++ equivalent.
1427 ObjCWrittenInterfaces.insert(ClassDecl->getCanonicalDecl());
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001428
1429 for (ObjCInterfaceDecl::prop_iterator I = ClassDecl->prop_begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001430 E = ClassDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00001431 RewriteProperty(*I);
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001432 for (ObjCInterfaceDecl::instmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001433 I = ClassDecl->instmeth_begin(), E = ClassDecl->instmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001434 I != E; ++I)
1435 RewriteMethodDeclaration(*I);
1436 for (ObjCInterfaceDecl::classmeth_iterator
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001437 I = ClassDecl->classmeth_begin(), E = ClassDecl->classmeth_end();
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001438 I != E; ++I)
1439 RewriteMethodDeclaration(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001440
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001441 // Lastly, comment out the @end.
1442 ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
Fariborz Jahanianf9f30792013-04-03 19:11:21 +00001443 "/* @end */\n");
Fariborz Jahanian4339bb32012-02-15 22:01:47 +00001444 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001445}
1446
1447Stmt *RewriteModernObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1448 SourceRange OldRange = PseudoOp->getSourceRange();
1449
1450 // We just magically know some things about the structure of this
1451 // expression.
1452 ObjCMessageExpr *OldMsg =
1453 cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1454 PseudoOp->getNumSemanticExprs() - 1));
1455
1456 // Because the rewriter doesn't allow us to rewrite rewritten code,
1457 // we need to suppress rewriting the sub-statements.
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001458 Expr *Base;
1459 SmallVector<Expr*, 2> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001460 {
1461 DisableReplaceStmtScope S(*this);
1462
1463 // Rebuild the base expression if we have one.
1464 Base = 0;
1465 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1466 Base = OldMsg->getInstanceReceiver();
1467 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1468 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1469 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001470
1471 unsigned numArgs = OldMsg->getNumArgs();
1472 for (unsigned i = 0; i < numArgs; i++) {
1473 Expr *Arg = OldMsg->getArg(i);
1474 if (isa<OpaqueValueExpr>(Arg))
1475 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1476 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1477 Args.push_back(Arg);
1478 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001479 }
1480
1481 // TODO: avoid this copy.
1482 SmallVector<SourceLocation, 1> SelLocs;
1483 OldMsg->getSelectorLocs(SelLocs);
1484
1485 ObjCMessageExpr *NewMsg = 0;
1486 switch (OldMsg->getReceiverKind()) {
1487 case ObjCMessageExpr::Class:
1488 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1489 OldMsg->getValueKind(),
1490 OldMsg->getLeftLoc(),
1491 OldMsg->getClassReceiverTypeInfo(),
1492 OldMsg->getSelector(),
1493 SelLocs,
1494 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001495 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001496 OldMsg->getRightLoc(),
1497 OldMsg->isImplicit());
1498 break;
1499
1500 case ObjCMessageExpr::Instance:
1501 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1502 OldMsg->getValueKind(),
1503 OldMsg->getLeftLoc(),
1504 Base,
1505 OldMsg->getSelector(),
1506 SelLocs,
1507 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001508 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001509 OldMsg->getRightLoc(),
1510 OldMsg->isImplicit());
1511 break;
1512
1513 case ObjCMessageExpr::SuperClass:
1514 case ObjCMessageExpr::SuperInstance:
1515 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1516 OldMsg->getValueKind(),
1517 OldMsg->getLeftLoc(),
1518 OldMsg->getSuperLoc(),
1519 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1520 OldMsg->getSuperType(),
1521 OldMsg->getSelector(),
1522 SelLocs,
1523 OldMsg->getMethodDecl(),
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001524 Args,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001525 OldMsg->getRightLoc(),
1526 OldMsg->isImplicit());
1527 break;
1528 }
1529
1530 Stmt *Replacement = SynthMessageExpr(NewMsg);
1531 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1532 return Replacement;
1533}
1534
1535Stmt *RewriteModernObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1536 SourceRange OldRange = PseudoOp->getSourceRange();
1537
1538 // We just magically know some things about the structure of this
1539 // expression.
1540 ObjCMessageExpr *OldMsg =
1541 cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1542
1543 // Because the rewriter doesn't allow us to rewrite rewritten code,
1544 // we need to suppress rewriting the sub-statements.
1545 Expr *Base = 0;
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001546 SmallVector<Expr*, 1> Args;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001547 {
1548 DisableReplaceStmtScope S(*this);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001549 // Rebuild the base expression if we have one.
1550 if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1551 Base = OldMsg->getInstanceReceiver();
1552 Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1553 Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1554 }
Fariborz Jahanian88ec6102012-04-10 22:06:54 +00001555 unsigned numArgs = OldMsg->getNumArgs();
1556 for (unsigned i = 0; i < numArgs; i++) {
1557 Expr *Arg = OldMsg->getArg(i);
1558 if (isa<OpaqueValueExpr>(Arg))
1559 Arg = cast<OpaqueValueExpr>(Arg)->getSourceExpr();
1560 Arg = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Arg));
1561 Args.push_back(Arg);
1562 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001563 }
1564
1565 // Intentionally empty.
1566 SmallVector<SourceLocation, 1> SelLocs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001567
1568 ObjCMessageExpr *NewMsg = 0;
1569 switch (OldMsg->getReceiverKind()) {
1570 case ObjCMessageExpr::Class:
1571 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1572 OldMsg->getValueKind(),
1573 OldMsg->getLeftLoc(),
1574 OldMsg->getClassReceiverTypeInfo(),
1575 OldMsg->getSelector(),
1576 SelLocs,
1577 OldMsg->getMethodDecl(),
1578 Args,
1579 OldMsg->getRightLoc(),
1580 OldMsg->isImplicit());
1581 break;
1582
1583 case ObjCMessageExpr::Instance:
1584 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1585 OldMsg->getValueKind(),
1586 OldMsg->getLeftLoc(),
1587 Base,
1588 OldMsg->getSelector(),
1589 SelLocs,
1590 OldMsg->getMethodDecl(),
1591 Args,
1592 OldMsg->getRightLoc(),
1593 OldMsg->isImplicit());
1594 break;
1595
1596 case ObjCMessageExpr::SuperClass:
1597 case ObjCMessageExpr::SuperInstance:
1598 NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1599 OldMsg->getValueKind(),
1600 OldMsg->getLeftLoc(),
1601 OldMsg->getSuperLoc(),
1602 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1603 OldMsg->getSuperType(),
1604 OldMsg->getSelector(),
1605 SelLocs,
1606 OldMsg->getMethodDecl(),
1607 Args,
1608 OldMsg->getRightLoc(),
1609 OldMsg->isImplicit());
1610 break;
1611 }
1612
1613 Stmt *Replacement = SynthMessageExpr(NewMsg);
1614 ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1615 return Replacement;
1616}
1617
1618/// SynthCountByEnumWithState - To print:
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001619/// ((NSUInteger (*)
1620/// (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001621/// (void *)objc_msgSend)((id)l_collection,
1622/// sel_registerName(
1623/// "countByEnumeratingWithState:objects:count:"),
1624/// &enumState,
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001625/// (id *)__rw_items, (NSUInteger)16)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001626///
1627void RewriteModernObjC::SynthCountByEnumWithState(std::string &buf) {
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001628 buf += "((_WIN_NSUInteger (*) (id, SEL, struct __objcFastEnumerationState *, "
1629 "id *, _WIN_NSUInteger))(void *)objc_msgSend)";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001630 buf += "\n\t\t";
1631 buf += "((id)l_collection,\n\t\t";
1632 buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1633 buf += "\n\t\t";
1634 buf += "&enumState, "
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001635 "(id *)__rw_items, (_WIN_NSUInteger)16)";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001636}
1637
1638/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1639/// statement to exit to its outer synthesized loop.
1640///
1641Stmt *RewriteModernObjC::RewriteBreakStmt(BreakStmt *S) {
1642 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1643 return S;
1644 // replace break with goto __break_label
1645 std::string buf;
1646
1647 SourceLocation startLoc = S->getLocStart();
1648 buf = "goto __break_label_";
1649 buf += utostr(ObjCBcLabelNo.back());
1650 ReplaceText(startLoc, strlen("break"), buf);
1651
1652 return 0;
1653}
1654
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001655void RewriteModernObjC::ConvertSourceLocationToLineDirective(
1656 SourceLocation Loc,
1657 std::string &LineString) {
Fariborz Jahanianada71912013-02-08 00:27:34 +00001658 if (Loc.isFileID() && GenerateLineInfo) {
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001659 LineString += "\n#line ";
1660 PresumedLoc PLoc = SM->getPresumedLoc(Loc);
1661 LineString += utostr(PLoc.getLine());
1662 LineString += " \"";
1663 LineString += Lexer::Stringify(PLoc.getFilename());
1664 LineString += "\"\n";
1665 }
1666}
1667
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001668/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1669/// statement to continue with its inner synthesized loop.
1670///
1671Stmt *RewriteModernObjC::RewriteContinueStmt(ContinueStmt *S) {
1672 if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1673 return S;
1674 // replace continue with goto __continue_label
1675 std::string buf;
1676
1677 SourceLocation startLoc = S->getLocStart();
1678 buf = "goto __continue_label_";
1679 buf += utostr(ObjCBcLabelNo.back());
1680 ReplaceText(startLoc, strlen("continue"), buf);
1681
1682 return 0;
1683}
1684
1685/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1686/// It rewrites:
1687/// for ( type elem in collection) { stmts; }
1688
1689/// Into:
1690/// {
1691/// type elem;
1692/// struct __objcFastEnumerationState enumState = { 0 };
1693/// id __rw_items[16];
1694/// id l_collection = (id)collection;
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001695/// NSUInteger limit = [l_collection countByEnumeratingWithState:&enumState
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001696/// objects:__rw_items count:16];
1697/// if (limit) {
1698/// unsigned long startMutations = *enumState.mutationsPtr;
1699/// do {
1700/// unsigned long counter = 0;
1701/// do {
1702/// if (startMutations != *enumState.mutationsPtr)
1703/// objc_enumerationMutation(l_collection);
1704/// elem = (type)enumState.itemsPtr[counter++];
1705/// stmts;
1706/// __continue_label: ;
1707/// } while (counter < limit);
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001708/// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1709/// objects:__rw_items count:16]));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001710/// elem = nil;
1711/// __break_label: ;
1712/// }
1713/// else
1714/// elem = nil;
1715/// }
1716///
1717Stmt *RewriteModernObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1718 SourceLocation OrigEnd) {
1719 assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1720 assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1721 "ObjCForCollectionStmt Statement stack mismatch");
1722 assert(!ObjCBcLabelNo.empty() &&
1723 "ObjCForCollectionStmt - Label No stack empty");
1724
1725 SourceLocation startLoc = S->getLocStart();
1726 const char *startBuf = SM->getCharacterData(startLoc);
1727 StringRef elementName;
1728 std::string elementTypeAsString;
1729 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001730 // line directive first.
1731 SourceLocation ForEachLoc = S->getForLoc();
1732 ConvertSourceLocationToLineDirective(ForEachLoc, buf);
1733 buf += "{\n\t";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001734 if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1735 // type elem;
1736 NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1737 QualType ElementType = cast<ValueDecl>(D)->getType();
1738 if (ElementType->isObjCQualifiedIdType() ||
1739 ElementType->isObjCQualifiedInterfaceType())
1740 // Simply use 'id' for all qualified types.
1741 elementTypeAsString = "id";
1742 else
1743 elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1744 buf += elementTypeAsString;
1745 buf += " ";
1746 elementName = D->getName();
1747 buf += elementName;
1748 buf += ";\n\t";
1749 }
1750 else {
1751 DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1752 elementName = DR->getDecl()->getName();
1753 ValueDecl *VD = cast<ValueDecl>(DR->getDecl());
1754 if (VD->getType()->isObjCQualifiedIdType() ||
1755 VD->getType()->isObjCQualifiedInterfaceType())
1756 // Simply use 'id' for all qualified types.
1757 elementTypeAsString = "id";
1758 else
1759 elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1760 }
1761
1762 // struct __objcFastEnumerationState enumState = { 0 };
1763 buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1764 // id __rw_items[16];
1765 buf += "id __rw_items[16];\n\t";
1766 // id l_collection = (id)
1767 buf += "id l_collection = (id)";
1768 // Find start location of 'collection' the hard way!
1769 const char *startCollectionBuf = startBuf;
1770 startCollectionBuf += 3; // skip 'for'
1771 startCollectionBuf = strchr(startCollectionBuf, '(');
1772 startCollectionBuf++; // skip '('
1773 // find 'in' and skip it.
1774 while (*startCollectionBuf != ' ' ||
1775 *(startCollectionBuf+1) != 'i' || *(startCollectionBuf+2) != 'n' ||
1776 (*(startCollectionBuf+3) != ' ' &&
1777 *(startCollectionBuf+3) != '[' && *(startCollectionBuf+3) != '('))
1778 startCollectionBuf++;
1779 startCollectionBuf += 3;
1780
1781 // Replace: "for (type element in" with string constructed thus far.
1782 ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1783 // Replace ')' in for '(' type elem in collection ')' with ';'
1784 SourceLocation rightParenLoc = S->getRParenLoc();
1785 const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1786 SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1787 buf = ";\n\t";
1788
1789 // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1790 // objects:__rw_items count:16];
1791 // which is synthesized into:
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001792 // NSUInteger limit =
1793 // ((NSUInteger (*)
1794 // (id, SEL, struct __objcFastEnumerationState *, id *, NSUInteger))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001795 // (void *)objc_msgSend)((id)l_collection,
1796 // sel_registerName(
1797 // "countByEnumeratingWithState:objects:count:"),
1798 // (struct __objcFastEnumerationState *)&state,
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001799 // (id *)__rw_items, (NSUInteger)16);
1800 buf += "_WIN_NSUInteger limit =\n\t\t";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001801 SynthCountByEnumWithState(buf);
1802 buf += ";\n\t";
1803 /// if (limit) {
1804 /// unsigned long startMutations = *enumState.mutationsPtr;
1805 /// do {
1806 /// unsigned long counter = 0;
1807 /// do {
1808 /// if (startMutations != *enumState.mutationsPtr)
1809 /// objc_enumerationMutation(l_collection);
1810 /// elem = (type)enumState.itemsPtr[counter++];
1811 buf += "if (limit) {\n\t";
1812 buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1813 buf += "do {\n\t\t";
1814 buf += "unsigned long counter = 0;\n\t\t";
1815 buf += "do {\n\t\t\t";
1816 buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1817 buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1818 buf += elementName;
1819 buf += " = (";
1820 buf += elementTypeAsString;
1821 buf += ")enumState.itemsPtr[counter++];";
1822 // Replace ')' in for '(' type elem in collection ')' with all of these.
1823 ReplaceText(lparenLoc, 1, buf);
1824
1825 /// __continue_label: ;
1826 /// } while (counter < limit);
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001827 /// } while ((limit = [l_collection countByEnumeratingWithState:&enumState
1828 /// objects:__rw_items count:16]));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001829 /// elem = nil;
1830 /// __break_label: ;
1831 /// }
1832 /// else
1833 /// elem = nil;
1834 /// }
1835 ///
1836 buf = ";\n\t";
1837 buf += "__continue_label_";
1838 buf += utostr(ObjCBcLabelNo.back());
1839 buf += ": ;";
1840 buf += "\n\t\t";
1841 buf += "} while (counter < limit);\n\t";
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001842 buf += "} while ((limit = ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001843 SynthCountByEnumWithState(buf);
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00001844 buf += "));\n\t";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001845 buf += elementName;
1846 buf += " = ((";
1847 buf += elementTypeAsString;
1848 buf += ")0);\n\t";
1849 buf += "__break_label_";
1850 buf += utostr(ObjCBcLabelNo.back());
1851 buf += ": ;\n\t";
1852 buf += "}\n\t";
1853 buf += "else\n\t\t";
1854 buf += elementName;
1855 buf += " = ((";
1856 buf += elementTypeAsString;
1857 buf += ")0);\n\t";
1858 buf += "}\n";
1859
1860 // Insert all these *after* the statement body.
1861 // FIXME: If this should support Obj-C++, support CXXTryStmt
1862 if (isa<CompoundStmt>(S->getBody())) {
1863 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1864 InsertText(endBodyLoc, buf);
1865 } else {
1866 /* Need to treat single statements specially. For example:
1867 *
1868 * for (A *a in b) if (stuff()) break;
1869 * for (A *a in b) xxxyy;
1870 *
1871 * The following code simply scans ahead to the semi to find the actual end.
1872 */
1873 const char *stmtBuf = SM->getCharacterData(OrigEnd);
1874 const char *semiBuf = strchr(stmtBuf, ';');
1875 assert(semiBuf && "Can't find ';'");
1876 SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1877 InsertText(endBodyLoc, buf);
1878 }
1879 Stmts.pop_back();
1880 ObjCBcLabelNo.pop_back();
1881 return 0;
1882}
1883
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001884static void Write_RethrowObject(std::string &buf) {
1885 buf += "{ struct _FIN { _FIN(id reth) : rethrow(reth) {}\n";
1886 buf += "\t~_FIN() { if (rethrow) objc_exception_throw(rethrow); }\n";
1887 buf += "\tid rethrow;\n";
1888 buf += "\t} _fin_force_rethow(_rethrow);";
1889}
1890
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001891/// RewriteObjCSynchronizedStmt -
1892/// This routine rewrites @synchronized(expr) stmt;
1893/// into:
1894/// objc_sync_enter(expr);
1895/// @try stmt @finally { objc_sync_exit(expr); }
1896///
1897Stmt *RewriteModernObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1898 // Get the start location and compute the semi location.
1899 SourceLocation startLoc = S->getLocStart();
1900 const char *startBuf = SM->getCharacterData(startLoc);
1901
1902 assert((*startBuf == '@') && "bogus @synchronized location");
1903
1904 std::string buf;
Fariborz Jahanian43f4f1e2012-11-07 00:43:05 +00001905 SourceLocation SynchLoc = S->getAtSynchronizedLoc();
1906 ConvertSourceLocationToLineDirective(SynchLoc, buf);
Fariborz Jahanian786e56f2013-09-17 17:51:48 +00001907 buf += "{ id _rethrow = 0; id _sync_obj = (id)";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001908
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001909 const char *lparenBuf = startBuf;
1910 while (*lparenBuf != '(') lparenBuf++;
1911 ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00001912
1913 buf = "; objc_sync_enter(_sync_obj);\n";
1914 buf += "try {\n\tstruct _SYNC_EXIT { _SYNC_EXIT(id arg) : sync_exit(arg) {}";
1915 buf += "\n\t~_SYNC_EXIT() {objc_sync_exit(sync_exit);}";
1916 buf += "\n\tid sync_exit;";
1917 buf += "\n\t} _sync_exit(_sync_obj);\n";
1918
1919 // We can't use S->getSynchExpr()->getLocEnd() to find the end location, since
1920 // the sync expression is typically a message expression that's already
1921 // been rewritten! (which implies the SourceLocation's are invalid).
1922 SourceLocation RParenExprLoc = S->getSynchBody()->getLocStart();
1923 const char *RParenExprLocBuf = SM->getCharacterData(RParenExprLoc);
1924 while (*RParenExprLocBuf != ')') RParenExprLocBuf--;
1925 RParenExprLoc = startLoc.getLocWithOffset(RParenExprLocBuf-startBuf);
1926
1927 SourceLocation LBranceLoc = S->getSynchBody()->getLocStart();
1928 const char *LBraceLocBuf = SM->getCharacterData(LBranceLoc);
1929 assert (*LBraceLocBuf == '{');
1930 ReplaceText(RParenExprLoc, (LBraceLocBuf - SM->getCharacterData(RParenExprLoc) + 1), buf);
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001931
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001932 SourceLocation startRBraceLoc = S->getSynchBody()->getLocEnd();
Matt Beaumont-Gay9ab511c2012-03-16 22:20:39 +00001933 assert((*SM->getCharacterData(startRBraceLoc) == '}') &&
1934 "bogus @synchronized block");
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001935
1936 buf = "} catch (id e) {_rethrow = e;}\n";
1937 Write_RethrowObject(buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001938 buf += "}\n";
Fariborz Jahanian542125f2012-03-16 21:33:16 +00001939 buf += "}\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001940
Fariborz Jahanianb655bf02012-03-16 21:43:45 +00001941 ReplaceText(startRBraceLoc, 1, buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001942
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001943 return 0;
1944}
1945
1946void RewriteModernObjC::WarnAboutReturnGotoStmts(Stmt *S)
1947{
1948 // Perform a bottom up traversal of all children.
1949 for (Stmt::child_range CI = S->children(); CI; ++CI)
1950 if (*CI)
1951 WarnAboutReturnGotoStmts(*CI);
1952
1953 if (isa<ReturnStmt>(S) || isa<GotoStmt>(S)) {
1954 Diags.Report(Context->getFullLoc(S->getLocStart()),
1955 TryFinallyContainsReturnDiag);
1956 }
1957 return;
1958}
1959
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001960Stmt *RewriteModernObjC::RewriteObjCAutoreleasePoolStmt(ObjCAutoreleasePoolStmt *S) {
1961 SourceLocation startLoc = S->getAtLoc();
1962 ReplaceText(startLoc, strlen("@autoreleasepool"), "/* @autoreleasepool */");
Fariborz Jahanianc9b72b62012-05-24 22:59:56 +00001963 ReplaceText(S->getSubStmt()->getLocStart(), 1,
1964 "{ __AtAutoreleasePool __autoreleasepool; ");
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00001965
1966 return 0;
1967}
1968
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001969Stmt *RewriteModernObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001970 ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt();
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001971 bool noCatch = S->getNumCatchStmts() == 0;
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001972 std::string buf;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001973 SourceLocation TryLocation = S->getAtTryLoc();
1974 ConvertSourceLocationToLineDirective(TryLocation, buf);
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001975
1976 if (finalStmt) {
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001977 if (noCatch)
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001978 buf += "{ id volatile _rethrow = 0;\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001979 else {
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00001980 buf += "{ id volatile _rethrow = 0;\ntry {\n";
Fariborz Jahanian220419a2012-03-15 23:50:33 +00001981 }
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001982 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001983 // Get the start location and compute the semi location.
1984 SourceLocation startLoc = S->getLocStart();
1985 const char *startBuf = SM->getCharacterData(startLoc);
1986
1987 assert((*startBuf == '@') && "bogus @try location");
Fariborz Jahanianb1228182012-03-15 22:42:15 +00001988 if (finalStmt)
1989 ReplaceText(startLoc, 1, buf);
1990 else
1991 // @try -> try
1992 ReplaceText(startLoc, 1, "");
1993
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001994 for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; ++I) {
1995 ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001996 VarDecl *catchDecl = Catch->getCatchParamDecl();
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00001997
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00001998 startLoc = Catch->getLocStart();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00001999 bool AtRemoved = false;
2000 if (catchDecl) {
2001 QualType t = catchDecl->getType();
2002 if (const ObjCObjectPointerType *Ptr = t->getAs<ObjCObjectPointerType>()) {
2003 // Should be a pointer to a class.
2004 ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
2005 if (IDecl) {
2006 std::string Result;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002007 ConvertSourceLocationToLineDirective(Catch->getLocStart(), Result);
2008
Fariborz Jahanian4c148812012-03-15 20:11:10 +00002009 startBuf = SM->getCharacterData(startLoc);
2010 assert((*startBuf == '@') && "bogus @catch location");
2011 SourceLocation rParenLoc = Catch->getRParenLoc();
2012 const char *rParenBuf = SM->getCharacterData(rParenLoc);
2013
2014 // _objc_exc_Foo *_e as argument to catch.
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002015 Result += "catch (_objc_exc_"; Result += IDecl->getNameAsString();
Fariborz Jahanian4c148812012-03-15 20:11:10 +00002016 Result += " *_"; Result += catchDecl->getNameAsString();
2017 Result += ")";
2018 ReplaceText(startLoc, rParenBuf-startBuf+1, Result);
2019 // Foo *e = (Foo *)_e;
2020 Result.clear();
2021 Result = "{ ";
2022 Result += IDecl->getNameAsString();
2023 Result += " *"; Result += catchDecl->getNameAsString();
2024 Result += " = ("; Result += IDecl->getNameAsString(); Result += "*)";
2025 Result += "_"; Result += catchDecl->getNameAsString();
2026
2027 Result += "; ";
2028 SourceLocation lBraceLoc = Catch->getCatchBody()->getLocStart();
2029 ReplaceText(lBraceLoc, 1, Result);
2030 AtRemoved = true;
2031 }
2032 }
2033 }
2034 if (!AtRemoved)
2035 // @catch -> catch
2036 ReplaceText(startLoc, 1, "");
Fariborz Jahanianc38503b2012-03-12 23:58:28 +00002037
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002038 }
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002039 if (finalStmt) {
2040 buf.clear();
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00002041 SourceLocation FinallyLoc = finalStmt->getLocStart();
2042
2043 if (noCatch) {
2044 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2045 buf += "catch (id e) {_rethrow = e;}\n";
2046 }
2047 else {
2048 buf += "}\n";
2049 ConvertSourceLocationToLineDirective(FinallyLoc, buf);
2050 buf += "catch (id e) {_rethrow = e;}\n";
2051 }
2052
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002053 SourceLocation startFinalLoc = finalStmt->getLocStart();
2054 ReplaceText(startFinalLoc, 8, buf);
2055 Stmt *body = finalStmt->getFinallyBody();
2056 SourceLocation startFinalBodyLoc = body->getLocStart();
2057 buf.clear();
Fariborz Jahanian542125f2012-03-16 21:33:16 +00002058 Write_RethrowObject(buf);
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002059 ReplaceText(startFinalBodyLoc, 1, buf);
2060
2061 SourceLocation endFinalBodyLoc = body->getLocEnd();
2062 ReplaceText(endFinalBodyLoc, 1, "}\n}");
Fariborz Jahanian22e2f852012-03-17 17:46:02 +00002063 // Now check for any return/continue/go statements within the @try.
2064 WarnAboutReturnGotoStmts(S->getTryBody());
Fariborz Jahanian220419a2012-03-15 23:50:33 +00002065 }
2066
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002067 return 0;
2068}
2069
2070// This can't be done with ReplaceStmt(S, ThrowExpr), since
2071// the throw expression is typically a message expression that's already
2072// been rewritten! (which implies the SourceLocation's are invalid).
2073Stmt *RewriteModernObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
2074 // Get the start location and compute the semi location.
2075 SourceLocation startLoc = S->getLocStart();
2076 const char *startBuf = SM->getCharacterData(startLoc);
2077
2078 assert((*startBuf == '@') && "bogus @throw location");
2079
2080 std::string buf;
2081 /* void objc_exception_throw(id) __attribute__((noreturn)); */
2082 if (S->getThrowExpr())
2083 buf = "objc_exception_throw(";
Fariborz Jahanian40539462012-03-16 16:52:06 +00002084 else
2085 buf = "throw";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002086
2087 // handle "@ throw" correctly.
2088 const char *wBuf = strchr(startBuf, 'w');
2089 assert((*wBuf == 'w') && "@throw: can't find 'w'");
2090 ReplaceText(startLoc, wBuf-startBuf+1, buf);
2091
Fariborz Jahaniana09cd812013-02-11 19:30:33 +00002092 SourceLocation endLoc = S->getLocEnd();
2093 const char *endBuf = SM->getCharacterData(endLoc);
2094 const char *semiBuf = strchr(endBuf, ';');
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002095 assert((*semiBuf == ';') && "@throw: can't find ';'");
2096 SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
Fariborz Jahanian40539462012-03-16 16:52:06 +00002097 if (S->getThrowExpr())
2098 ReplaceText(semiLoc, 1, ");");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002099 return 0;
2100}
2101
2102Stmt *RewriteModernObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
2103 // Create a new string expression.
2104 QualType StrType = Context->getPointerType(Context->CharTy);
2105 std::string StrEncoding;
2106 Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
2107 Expr *Replacement = StringLiteral::Create(*Context, StrEncoding,
2108 StringLiteral::Ascii, false,
2109 StrType, SourceLocation());
2110 ReplaceStmt(Exp, Replacement);
2111
2112 // Replace this subexpr in the parent.
2113 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2114 return Replacement;
2115}
2116
2117Stmt *RewriteModernObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
2118 if (!SelGetUidFunctionDecl)
2119 SynthSelGetUidFunctionDecl();
2120 assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
2121 // Create a call to sel_registerName("selName").
2122 SmallVector<Expr*, 8> SelExprs;
2123 QualType argType = Context->getPointerType(Context->CharTy);
2124 SelExprs.push_back(StringLiteral::Create(*Context,
2125 Exp->getSelector().getAsString(),
2126 StringLiteral::Ascii, false,
2127 argType, SourceLocation()));
2128 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2129 &SelExprs[0], SelExprs.size());
2130 ReplaceStmt(Exp, SelExp);
2131 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2132 return SelExp;
2133}
2134
2135CallExpr *RewriteModernObjC::SynthesizeCallToFunctionDecl(
2136 FunctionDecl *FD, Expr **args, unsigned nargs, SourceLocation StartLoc,
2137 SourceLocation EndLoc) {
2138 // Get the type, we will need to reference it in a couple spots.
2139 QualType msgSendType = FD->getType();
2140
2141 // Create a reference to the objc_msgSend() declaration.
2142 DeclRefExpr *DRE =
John McCallf4b88a42012-03-10 09:33:50 +00002143 new (Context) DeclRefExpr(FD, false, msgSendType, VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002144
2145 // Now, we cast the reference to a pointer to the objc_msgSend type.
2146 QualType pToFunc = Context->getPointerType(msgSendType);
2147 ImplicitCastExpr *ICE =
2148 ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2149 DRE, 0, VK_RValue);
2150
2151 const FunctionType *FT = msgSendType->getAs<FunctionType>();
2152
2153 CallExpr *Exp =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002154 new (Context) CallExpr(*Context, ICE, llvm::makeArrayRef(args, nargs),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002155 FT->getCallResultType(*Context),
2156 VK_RValue, EndLoc);
2157 return Exp;
2158}
2159
2160static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2161 const char *&startRef, const char *&endRef) {
2162 while (startBuf < endBuf) {
2163 if (*startBuf == '<')
2164 startRef = startBuf; // mark the start.
2165 if (*startBuf == '>') {
2166 if (startRef && *startRef == '<') {
2167 endRef = startBuf; // mark the end.
2168 return true;
2169 }
2170 return false;
2171 }
2172 startBuf++;
2173 }
2174 return false;
2175}
2176
2177static void scanToNextArgument(const char *&argRef) {
2178 int angle = 0;
2179 while (*argRef != ')' && (*argRef != ',' || angle > 0)) {
2180 if (*argRef == '<')
2181 angle++;
2182 else if (*argRef == '>')
2183 angle--;
2184 argRef++;
2185 }
2186 assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2187}
2188
2189bool RewriteModernObjC::needToScanForQualifiers(QualType T) {
2190 if (T->isObjCQualifiedIdType())
2191 return true;
2192 if (const PointerType *PT = T->getAs<PointerType>()) {
2193 if (PT->getPointeeType()->isObjCQualifiedIdType())
2194 return true;
2195 }
2196 if (T->isObjCObjectPointerType()) {
2197 T = T->getPointeeType();
2198 return T->isObjCQualifiedInterfaceType();
2199 }
2200 if (T->isArrayType()) {
2201 QualType ElemTy = Context->getBaseElementType(T);
2202 return needToScanForQualifiers(ElemTy);
2203 }
2204 return false;
2205}
2206
2207void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2208 QualType Type = E->getType();
2209 if (needToScanForQualifiers(Type)) {
2210 SourceLocation Loc, EndLoc;
2211
2212 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2213 Loc = ECE->getLParenLoc();
2214 EndLoc = ECE->getRParenLoc();
2215 } else {
2216 Loc = E->getLocStart();
2217 EndLoc = E->getLocEnd();
2218 }
2219 // This will defend against trying to rewrite synthesized expressions.
2220 if (Loc.isInvalid() || EndLoc.isInvalid())
2221 return;
2222
2223 const char *startBuf = SM->getCharacterData(Loc);
2224 const char *endBuf = SM->getCharacterData(EndLoc);
2225 const char *startRef = 0, *endRef = 0;
2226 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2227 // Get the locations of the startRef, endRef.
2228 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2229 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2230 // Comment out the protocol references.
2231 InsertText(LessLoc, "/*");
2232 InsertText(GreaterLoc, "*/");
2233 }
2234 }
2235}
2236
2237void RewriteModernObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2238 SourceLocation Loc;
2239 QualType Type;
2240 const FunctionProtoType *proto = 0;
2241 if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2242 Loc = VD->getLocation();
2243 Type = VD->getType();
2244 }
2245 else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2246 Loc = FD->getLocation();
2247 // Check for ObjC 'id' and class types that have been adorned with protocol
2248 // information (id<p>, C<p>*). The protocol references need to be rewritten!
2249 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2250 assert(funcType && "missing function type");
2251 proto = dyn_cast<FunctionProtoType>(funcType);
2252 if (!proto)
2253 return;
2254 Type = proto->getResultType();
2255 }
2256 else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2257 Loc = FD->getLocation();
2258 Type = FD->getType();
2259 }
Fariborz Jahanianf9f30792013-04-03 19:11:21 +00002260 else if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(Dcl)) {
2261 Loc = TD->getLocation();
2262 Type = TD->getUnderlyingType();
2263 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002264 else
2265 return;
2266
2267 if (needToScanForQualifiers(Type)) {
2268 // Since types are unique, we need to scan the buffer.
2269
2270 const char *endBuf = SM->getCharacterData(Loc);
2271 const char *startBuf = endBuf;
2272 while (*startBuf != ';' && *startBuf != '<' && startBuf != MainFileStart)
2273 startBuf--; // scan backward (from the decl location) for return type.
2274 const char *startRef = 0, *endRef = 0;
2275 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2276 // Get the locations of the startRef, endRef.
2277 SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2278 SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2279 // Comment out the protocol references.
2280 InsertText(LessLoc, "/*");
2281 InsertText(GreaterLoc, "*/");
2282 }
2283 }
2284 if (!proto)
2285 return; // most likely, was a variable
2286 // Now check arguments.
2287 const char *startBuf = SM->getCharacterData(Loc);
2288 const char *startFuncBuf = startBuf;
2289 for (unsigned i = 0; i < proto->getNumArgs(); i++) {
2290 if (needToScanForQualifiers(proto->getArgType(i))) {
2291 // Since types are unique, we need to scan the buffer.
2292
2293 const char *endBuf = startBuf;
2294 // scan forward (from the decl location) for argument types.
2295 scanToNextArgument(endBuf);
2296 const char *startRef = 0, *endRef = 0;
2297 if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2298 // Get the locations of the startRef, endRef.
2299 SourceLocation LessLoc =
2300 Loc.getLocWithOffset(startRef-startFuncBuf);
2301 SourceLocation GreaterLoc =
2302 Loc.getLocWithOffset(endRef-startFuncBuf+1);
2303 // Comment out the protocol references.
2304 InsertText(LessLoc, "/*");
2305 InsertText(GreaterLoc, "*/");
2306 }
2307 startBuf = ++endBuf;
2308 }
2309 else {
2310 // If the function name is derived from a macro expansion, then the
2311 // argument buffer will not follow the name. Need to speak with Chris.
2312 while (*startBuf && *startBuf != ')' && *startBuf != ',')
2313 startBuf++; // scan forward (from the decl location) for argument types.
2314 startBuf++;
2315 }
2316 }
2317}
2318
2319void RewriteModernObjC::RewriteTypeOfDecl(VarDecl *ND) {
2320 QualType QT = ND->getType();
2321 const Type* TypePtr = QT->getAs<Type>();
2322 if (!isa<TypeOfExprType>(TypePtr))
2323 return;
2324 while (isa<TypeOfExprType>(TypePtr)) {
2325 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2326 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2327 TypePtr = QT->getAs<Type>();
2328 }
2329 // FIXME. This will not work for multiple declarators; as in:
2330 // __typeof__(a) b,c,d;
2331 std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2332 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2333 const char *startBuf = SM->getCharacterData(DeclLoc);
2334 if (ND->getInit()) {
2335 std::string Name(ND->getNameAsString());
2336 TypeAsString += " " + Name + " = ";
2337 Expr *E = ND->getInit();
2338 SourceLocation startLoc;
2339 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2340 startLoc = ECE->getLParenLoc();
2341 else
2342 startLoc = E->getLocStart();
2343 startLoc = SM->getExpansionLoc(startLoc);
2344 const char *endBuf = SM->getCharacterData(startLoc);
2345 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2346 }
2347 else {
2348 SourceLocation X = ND->getLocEnd();
2349 X = SM->getExpansionLoc(X);
2350 const char *endBuf = SM->getCharacterData(X);
2351 ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2352 }
2353}
2354
2355// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2356void RewriteModernObjC::SynthSelGetUidFunctionDecl() {
2357 IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2358 SmallVector<QualType, 16> ArgTys;
2359 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2360 QualType getFuncType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002361 getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002362 SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002363 SourceLocation(),
2364 SourceLocation(),
2365 SelGetUidIdent, getFuncType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002366 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002367}
2368
2369void RewriteModernObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2370 // declared in <objc/objc.h>
2371 if (FD->getIdentifier() &&
2372 FD->getName() == "sel_registerName") {
2373 SelGetUidFunctionDecl = FD;
2374 return;
2375 }
2376 RewriteObjCQualifiedInterfaceTypes(FD);
2377}
2378
2379void RewriteModernObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2380 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2381 const char *argPtr = TypeString.c_str();
2382 if (!strchr(argPtr, '^')) {
2383 Str += TypeString;
2384 return;
2385 }
2386 while (*argPtr) {
2387 Str += (*argPtr == '^' ? '*' : *argPtr);
2388 argPtr++;
2389 }
2390}
2391
2392// FIXME. Consolidate this routine with RewriteBlockPointerType.
2393void RewriteModernObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2394 ValueDecl *VD) {
2395 QualType Type = VD->getType();
2396 std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2397 const char *argPtr = TypeString.c_str();
2398 int paren = 0;
2399 while (*argPtr) {
2400 switch (*argPtr) {
2401 case '(':
2402 Str += *argPtr;
2403 paren++;
2404 break;
2405 case ')':
2406 Str += *argPtr;
2407 paren--;
2408 break;
2409 case '^':
2410 Str += '*';
2411 if (paren == 1)
2412 Str += VD->getNameAsString();
2413 break;
2414 default:
2415 Str += *argPtr;
2416 break;
2417 }
2418 argPtr++;
2419 }
2420}
2421
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002422void RewriteModernObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2423 SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2424 const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2425 const FunctionProtoType *proto = dyn_cast<FunctionProtoType>(funcType);
2426 if (!proto)
2427 return;
2428 QualType Type = proto->getResultType();
2429 std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2430 FdStr += " ";
2431 FdStr += FD->getName();
2432 FdStr += "(";
2433 unsigned numArgs = proto->getNumArgs();
2434 for (unsigned i = 0; i < numArgs; i++) {
2435 QualType ArgType = proto->getArgType(i);
2436 RewriteBlockPointerType(FdStr, ArgType);
2437 if (i+1 < numArgs)
2438 FdStr += ", ";
2439 }
Fariborz Jahanianb5863da2012-04-19 16:30:28 +00002440 if (FD->isVariadic()) {
2441 FdStr += (numArgs > 0) ? ", ...);\n" : "...);\n";
2442 }
2443 else
2444 FdStr += ");\n";
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00002445 InsertText(FunLocStart, FdStr);
2446}
2447
Benjamin Kramere5753592013-09-09 14:48:42 +00002448// SynthSuperConstructorFunctionDecl - id __rw_objc_super(id obj, id super);
2449void RewriteModernObjC::SynthSuperConstructorFunctionDecl() {
2450 if (SuperConstructorFunctionDecl)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002451 return;
2452 IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2453 SmallVector<QualType, 16> ArgTys;
2454 QualType argT = Context->getObjCIdType();
2455 assert(!argT.isNull() && "Can't find 'id' type");
2456 ArgTys.push_back(argT);
2457 ArgTys.push_back(argT);
2458 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002459 ArgTys);
Benjamin Kramere5753592013-09-09 14:48:42 +00002460 SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002461 SourceLocation(),
2462 SourceLocation(),
2463 msgSendIdent, msgSendType,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002464 0, SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002465}
2466
2467// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2468void RewriteModernObjC::SynthMsgSendFunctionDecl() {
2469 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2470 SmallVector<QualType, 16> ArgTys;
2471 QualType argT = Context->getObjCIdType();
2472 assert(!argT.isNull() && "Can't find 'id' type");
2473 ArgTys.push_back(argT);
2474 argT = Context->getObjCSelType();
2475 assert(!argT.isNull() && "Can't find 'SEL' type");
2476 ArgTys.push_back(argT);
2477 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002478 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002479 MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002480 SourceLocation(),
2481 SourceLocation(),
2482 msgSendIdent, msgSendType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002483 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002484}
2485
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002486// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002487void RewriteModernObjC::SynthMsgSendSuperFunctionDecl() {
2488 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002489 SmallVector<QualType, 2> ArgTys;
2490 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002491 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002492 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002493 MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002494 SourceLocation(),
2495 SourceLocation(),
2496 msgSendIdent, msgSendType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002497 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002498}
2499
2500// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2501void RewriteModernObjC::SynthMsgSendStretFunctionDecl() {
2502 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2503 SmallVector<QualType, 16> ArgTys;
2504 QualType argT = Context->getObjCIdType();
2505 assert(!argT.isNull() && "Can't find 'id' type");
2506 ArgTys.push_back(argT);
2507 argT = Context->getObjCSelType();
2508 assert(!argT.isNull() && "Can't find 'SEL' type");
2509 ArgTys.push_back(argT);
2510 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002511 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002512 MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002513 SourceLocation(),
2514 SourceLocation(),
2515 msgSendIdent, msgSendType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002516 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002517}
2518
2519// SynthMsgSendSuperStretFunctionDecl -
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002520// id objc_msgSendSuper_stret(void);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002521void RewriteModernObjC::SynthMsgSendSuperStretFunctionDecl() {
2522 IdentifierInfo *msgSendIdent =
2523 &Context->Idents.get("objc_msgSendSuper_stret");
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00002524 SmallVector<QualType, 2> ArgTys;
2525 ArgTys.push_back(Context->VoidTy);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002526 QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002527 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002528 MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2529 SourceLocation(),
2530 SourceLocation(),
Chad Rosiere3b29882013-01-04 22:40:33 +00002531 msgSendIdent,
2532 msgSendType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002533 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002534}
2535
2536// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2537void RewriteModernObjC::SynthMsgSendFpretFunctionDecl() {
2538 IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2539 SmallVector<QualType, 16> ArgTys;
2540 QualType argT = Context->getObjCIdType();
2541 assert(!argT.isNull() && "Can't find 'id' type");
2542 ArgTys.push_back(argT);
2543 argT = Context->getObjCSelType();
2544 assert(!argT.isNull() && "Can't find 'SEL' type");
2545 ArgTys.push_back(argT);
2546 QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
Jordan Rosebea522f2013-03-08 21:51:21 +00002547 ArgTys, /*isVariadic=*/true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002548 MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002549 SourceLocation(),
2550 SourceLocation(),
2551 msgSendIdent, msgSendType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002552 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002553}
2554
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002555// SynthGetClassFunctionDecl - Class objc_getClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002556void RewriteModernObjC::SynthGetClassFunctionDecl() {
2557 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2558 SmallVector<QualType, 16> ArgTys;
2559 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002560 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002561 ArgTys);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002562 GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002563 SourceLocation(),
2564 SourceLocation(),
2565 getClassIdent, getClassType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002566 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002567}
2568
2569// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2570void RewriteModernObjC::SynthGetSuperClassFunctionDecl() {
2571 IdentifierInfo *getSuperClassIdent =
2572 &Context->Idents.get("class_getSuperclass");
2573 SmallVector<QualType, 16> ArgTys;
2574 ArgTys.push_back(Context->getObjCClassType());
2575 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002576 ArgTys);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002577 GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2578 SourceLocation(),
2579 SourceLocation(),
2580 getSuperClassIdent,
2581 getClassType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002582 SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002583}
2584
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002585// SynthGetMetaClassFunctionDecl - Class objc_getMetaClass(const char *name);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002586void RewriteModernObjC::SynthGetMetaClassFunctionDecl() {
2587 IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2588 SmallVector<QualType, 16> ArgTys;
2589 ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00002590 QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
Jordan Rosebea522f2013-03-08 21:51:21 +00002591 ArgTys);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002592 GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
Chad Rosiere3b29882013-01-04 22:40:33 +00002593 SourceLocation(),
2594 SourceLocation(),
2595 getClassIdent, getClassType,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002596 0, SC_Extern);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002597}
2598
2599Stmt *RewriteModernObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2600 QualType strType = getConstantStringStructType();
2601
2602 std::string S = "__NSConstantStringImpl_";
2603
2604 std::string tmpName = InFileName;
2605 unsigned i;
2606 for (i=0; i < tmpName.length(); i++) {
2607 char c = tmpName.at(i);
2608 // replace any non alphanumeric characters with '_'.
Jordan Rose3f6f51e2013-02-08 22:30:41 +00002609 if (!isAlphanumeric(c))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002610 tmpName[i] = '_';
2611 }
2612 S += tmpName;
2613 S += "_";
2614 S += utostr(NumObjCStringLiterals++);
2615
2616 Preamble += "static __NSConstantStringImpl " + S;
2617 Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2618 Preamble += "0x000007c8,"; // utf8_str
2619 // The pretty printer for StringLiteral handles escape characters properly.
2620 std::string prettyBufS;
2621 llvm::raw_string_ostream prettyBuf(prettyBufS);
Richard Smithd1420c62012-08-16 03:56:14 +00002622 Exp->getString()->printPretty(prettyBuf, 0, PrintingPolicy(LangOpts));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002623 Preamble += prettyBuf.str();
2624 Preamble += ",";
2625 Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2626
2627 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2628 SourceLocation(), &Context->Idents.get(S),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00002629 strType, 0, SC_Static);
John McCallf4b88a42012-03-10 09:33:50 +00002630 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false, strType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00002631 SourceLocation());
2632 Expr *Unop = new (Context) UnaryOperator(DRE, UO_AddrOf,
2633 Context->getPointerType(DRE->getType()),
2634 VK_RValue, OK_Ordinary,
2635 SourceLocation());
2636 // cast to NSConstantString *
2637 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2638 CK_CPointerToObjCPointerCast, Unop);
2639 ReplaceStmt(Exp, cast);
2640 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2641 return cast;
2642}
2643
Fariborz Jahanian55947042012-03-27 20:17:30 +00002644Stmt *RewriteModernObjC::RewriteObjCBoolLiteralExpr(ObjCBoolLiteralExpr *Exp) {
2645 unsigned IntSize =
2646 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2647
2648 Expr *FlagExp = IntegerLiteral::Create(*Context,
2649 llvm::APInt(IntSize, Exp->getValue()),
2650 Context->IntTy, Exp->getLocation());
2651 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Context->ObjCBuiltinBoolTy,
2652 CK_BitCast, FlagExp);
2653 ParenExpr *PE = new (Context) ParenExpr(Exp->getLocation(), Exp->getExprLoc(),
2654 cast);
2655 ReplaceStmt(Exp, PE);
2656 return PE;
2657}
2658
Patrick Beardeb382ec2012-04-19 00:25:12 +00002659Stmt *RewriteModernObjC::RewriteObjCBoxedExpr(ObjCBoxedExpr *Exp) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002660 // synthesize declaration of helper functions needed in this routine.
2661 if (!SelGetUidFunctionDecl)
2662 SynthSelGetUidFunctionDecl();
2663 // use objc_msgSend() for all.
2664 if (!MsgSendFunctionDecl)
2665 SynthMsgSendFunctionDecl();
2666 if (!GetClassFunctionDecl)
2667 SynthGetClassFunctionDecl();
2668
2669 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2670 SourceLocation StartLoc = Exp->getLocStart();
2671 SourceLocation EndLoc = Exp->getLocEnd();
2672
2673 // Synthesize a call to objc_msgSend().
2674 SmallVector<Expr*, 4> MsgExprs;
2675 SmallVector<Expr*, 4> ClsExprs;
2676 QualType argType = Context->getPointerType(Context->CharTy);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002677
Patrick Beardeb382ec2012-04-19 00:25:12 +00002678 // Create a call to objc_getClass("<BoxingClass>"). It will be the 1st argument.
2679 ObjCMethodDecl *BoxingMethod = Exp->getBoxingMethod();
2680 ObjCInterfaceDecl *BoxingClass = BoxingMethod->getClassInterface();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002681
Patrick Beardeb382ec2012-04-19 00:25:12 +00002682 IdentifierInfo *clsName = BoxingClass->getIdentifier();
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002683 ClsExprs.push_back(StringLiteral::Create(*Context,
2684 clsName->getName(),
2685 StringLiteral::Ascii, false,
2686 argType, SourceLocation()));
2687 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2688 &ClsExprs[0],
2689 ClsExprs.size(),
2690 StartLoc, EndLoc);
2691 MsgExprs.push_back(Cls);
2692
Patrick Beardeb382ec2012-04-19 00:25:12 +00002693 // Create a call to sel_registerName("<BoxingMethod>:"), etc.
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002694 // it will be the 2nd argument.
2695 SmallVector<Expr*, 4> SelExprs;
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002696 SelExprs.push_back(StringLiteral::Create(*Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002697 BoxingMethod->getSelector().getAsString(),
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002698 StringLiteral::Ascii, false,
2699 argType, SourceLocation()));
2700 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2701 &SelExprs[0], SelExprs.size(),
2702 StartLoc, EndLoc);
2703 MsgExprs.push_back(SelExp);
2704
Patrick Beardeb382ec2012-04-19 00:25:12 +00002705 // User provided sub-expression is the 3rd, and last, argument.
2706 Expr *subExpr = Exp->getSubExpr();
2707 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(subExpr)) {
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002708 QualType type = ICE->getType();
2709 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2710 CastKind CK = CK_BitCast;
2711 if (SubExpr->getType()->isIntegralType(*Context) && type->isBooleanType())
2712 CK = CK_IntegralToBoolean;
Patrick Beardeb382ec2012-04-19 00:25:12 +00002713 subExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002714 }
Patrick Beardeb382ec2012-04-19 00:25:12 +00002715 MsgExprs.push_back(subExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002716
2717 SmallVector<QualType, 4> ArgTypes;
2718 ArgTypes.push_back(Context->getObjCIdType());
2719 ArgTypes.push_back(Context->getObjCSelType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002720 for (ObjCMethodDecl::param_iterator PI = BoxingMethod->param_begin(),
2721 E = BoxingMethod->param_end(); PI != E; ++PI)
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002722 ArgTypes.push_back((*PI)->getType());
Patrick Beardeb382ec2012-04-19 00:25:12 +00002723
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002724 QualType returnType = Exp->getType();
2725 // Get the type, we will need to reference it in a couple spots.
2726 QualType msgSendType = MsgSendFlavor->getType();
2727
2728 // Create a reference to the objc_msgSend() declaration.
2729 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2730 VK_LValue, SourceLocation());
2731
2732 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
Patrick Beardeb382ec2012-04-19 00:25:12 +00002733 Context->getPointerType(Context->VoidTy),
2734 CK_BitCast, DRE);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002735
2736 // Now do the "normal" pointer to function cast.
2737 QualType castType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002738 getSimpleFunctionType(returnType, ArgTypes, BoxingMethod->isVariadic());
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002739 castType = Context->getPointerType(castType);
2740 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2741 cast);
2742
2743 // Don't forget the parens to enforce the proper binding.
2744 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2745
2746 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002747 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00002748 FT->getResultType(), VK_RValue,
2749 EndLoc);
2750 ReplaceStmt(Exp, CE);
2751 return CE;
2752}
2753
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002754Stmt *RewriteModernObjC::RewriteObjCArrayLiteralExpr(ObjCArrayLiteral *Exp) {
2755 // synthesize declaration of helper functions needed in this routine.
2756 if (!SelGetUidFunctionDecl)
2757 SynthSelGetUidFunctionDecl();
2758 // use objc_msgSend() for all.
2759 if (!MsgSendFunctionDecl)
2760 SynthMsgSendFunctionDecl();
2761 if (!GetClassFunctionDecl)
2762 SynthGetClassFunctionDecl();
2763
2764 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2765 SourceLocation StartLoc = Exp->getLocStart();
2766 SourceLocation EndLoc = Exp->getLocEnd();
2767
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002768 // Build the expression: __NSContainer_literal(int, ...).arr
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002769 QualType IntQT = Context->IntTy;
2770 QualType NSArrayFType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002771 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002772 std::string NSArrayFName("__NSContainer_literal");
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002773 FunctionDecl *NSArrayFD = SynthBlockInitFunctionDecl(NSArrayFName);
2774 DeclRefExpr *NSArrayDRE =
2775 new (Context) DeclRefExpr(NSArrayFD, false, NSArrayFType, VK_RValue,
2776 SourceLocation());
2777
2778 SmallVector<Expr*, 16> InitExprs;
2779 unsigned NumElements = Exp->getNumElements();
2780 unsigned UnsignedIntSize =
2781 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2782 Expr *count = IntegerLiteral::Create(*Context,
2783 llvm::APInt(UnsignedIntSize, NumElements),
2784 Context->UnsignedIntTy, SourceLocation());
2785 InitExprs.push_back(count);
2786 for (unsigned i = 0; i < NumElements; i++)
2787 InitExprs.push_back(Exp->getElement(i));
2788 Expr *NSArrayCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002789 new (Context) CallExpr(*Context, NSArrayDRE, InitExprs,
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002790 NSArrayFType, VK_LValue, SourceLocation());
2791
2792 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2793 SourceLocation(),
2794 &Context->Idents.get("arr"),
2795 Context->getPointerType(Context->VoidPtrTy), 0,
2796 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002797 ICIS_NoInit);
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002798 MemberExpr *ArrayLiteralME =
2799 new (Context) MemberExpr(NSArrayCallExpr, false, ARRFD,
2800 SourceLocation(),
2801 ARRFD->getType(), VK_LValue,
2802 OK_Ordinary);
2803 QualType ConstIdT = Context->getObjCIdType().withConst();
2804 CStyleCastExpr * ArrayLiteralObjects =
2805 NoTypeInfoCStyleCastExpr(Context,
2806 Context->getPointerType(ConstIdT),
2807 CK_BitCast,
2808 ArrayLiteralME);
2809
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002810 // Synthesize a call to objc_msgSend().
2811 SmallVector<Expr*, 32> MsgExprs;
2812 SmallVector<Expr*, 4> ClsExprs;
2813 QualType argType = Context->getPointerType(Context->CharTy);
2814 QualType expType = Exp->getType();
2815
2816 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2817 ObjCInterfaceDecl *Class =
2818 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2819
2820 IdentifierInfo *clsName = Class->getIdentifier();
2821 ClsExprs.push_back(StringLiteral::Create(*Context,
2822 clsName->getName(),
2823 StringLiteral::Ascii, false,
2824 argType, SourceLocation()));
2825 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
2826 &ClsExprs[0],
2827 ClsExprs.size(),
2828 StartLoc, EndLoc);
2829 MsgExprs.push_back(Cls);
2830
2831 // Create a call to sel_registerName("arrayWithObjects:count:").
2832 // it will be the 2nd argument.
2833 SmallVector<Expr*, 4> SelExprs;
2834 ObjCMethodDecl *ArrayMethod = Exp->getArrayWithObjectsMethod();
2835 SelExprs.push_back(StringLiteral::Create(*Context,
2836 ArrayMethod->getSelector().getAsString(),
2837 StringLiteral::Ascii, false,
2838 argType, SourceLocation()));
2839 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2840 &SelExprs[0], SelExprs.size(),
2841 StartLoc, EndLoc);
2842 MsgExprs.push_back(SelExp);
2843
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002844 // (const id [])objects
2845 MsgExprs.push_back(ArrayLiteralObjects);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002846
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00002847 // (NSUInteger)cnt
2848 Expr *cnt = IntegerLiteral::Create(*Context,
2849 llvm::APInt(UnsignedIntSize, NumElements),
2850 Context->UnsignedIntTy, SourceLocation());
2851 MsgExprs.push_back(cnt);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002852
2853
2854 SmallVector<QualType, 4> ArgTypes;
2855 ArgTypes.push_back(Context->getObjCIdType());
2856 ArgTypes.push_back(Context->getObjCSelType());
2857 for (ObjCMethodDecl::param_iterator PI = ArrayMethod->param_begin(),
2858 E = ArrayMethod->param_end(); PI != E; ++PI)
2859 ArgTypes.push_back((*PI)->getType());
2860
2861 QualType returnType = Exp->getType();
2862 // Get the type, we will need to reference it in a couple spots.
2863 QualType msgSendType = MsgSendFlavor->getType();
2864
2865 // Create a reference to the objc_msgSend() declaration.
2866 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
2867 VK_LValue, SourceLocation());
2868
2869 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2870 Context->getPointerType(Context->VoidTy),
2871 CK_BitCast, DRE);
2872
2873 // Now do the "normal" pointer to function cast.
2874 QualType castType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002875 getSimpleFunctionType(returnType, ArgTypes, ArrayMethod->isVariadic());
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002876 castType = Context->getPointerType(castType);
2877 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2878 cast);
2879
2880 // Don't forget the parens to enforce the proper binding.
2881 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2882
2883 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002884 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahanian86cff602012-03-30 23:35:47 +00002885 FT->getResultType(), VK_RValue,
2886 EndLoc);
2887 ReplaceStmt(Exp, CE);
2888 return CE;
2889}
2890
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002891Stmt *RewriteModernObjC::RewriteObjCDictionaryLiteralExpr(ObjCDictionaryLiteral *Exp) {
2892 // synthesize declaration of helper functions needed in this routine.
2893 if (!SelGetUidFunctionDecl)
2894 SynthSelGetUidFunctionDecl();
2895 // use objc_msgSend() for all.
2896 if (!MsgSendFunctionDecl)
2897 SynthMsgSendFunctionDecl();
2898 if (!GetClassFunctionDecl)
2899 SynthGetClassFunctionDecl();
2900
2901 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2902 SourceLocation StartLoc = Exp->getLocStart();
2903 SourceLocation EndLoc = Exp->getLocEnd();
2904
2905 // Build the expression: __NSContainer_literal(int, ...).arr
2906 QualType IntQT = Context->IntTy;
2907 QualType NSDictFType =
Jordan Rosebea522f2013-03-08 21:51:21 +00002908 getSimpleFunctionType(Context->VoidTy, IntQT, true);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002909 std::string NSDictFName("__NSContainer_literal");
2910 FunctionDecl *NSDictFD = SynthBlockInitFunctionDecl(NSDictFName);
2911 DeclRefExpr *NSDictDRE =
2912 new (Context) DeclRefExpr(NSDictFD, false, NSDictFType, VK_RValue,
2913 SourceLocation());
2914
2915 SmallVector<Expr*, 16> KeyExprs;
2916 SmallVector<Expr*, 16> ValueExprs;
2917
2918 unsigned NumElements = Exp->getNumElements();
2919 unsigned UnsignedIntSize =
2920 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
2921 Expr *count = IntegerLiteral::Create(*Context,
2922 llvm::APInt(UnsignedIntSize, NumElements),
2923 Context->UnsignedIntTy, SourceLocation());
2924 KeyExprs.push_back(count);
2925 ValueExprs.push_back(count);
2926 for (unsigned i = 0; i < NumElements; i++) {
2927 ObjCDictionaryElement Element = Exp->getKeyValueElement(i);
2928 KeyExprs.push_back(Element.Key);
2929 ValueExprs.push_back(Element.Value);
2930 }
2931
2932 // (const id [])objects
2933 Expr *NSValueCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002934 new (Context) CallExpr(*Context, NSDictDRE, ValueExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002935 NSDictFType, VK_LValue, SourceLocation());
2936
2937 FieldDecl *ARRFD = FieldDecl::Create(*Context, 0, SourceLocation(),
2938 SourceLocation(),
2939 &Context->Idents.get("arr"),
2940 Context->getPointerType(Context->VoidPtrTy), 0,
2941 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00002942 ICIS_NoInit);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002943 MemberExpr *DictLiteralValueME =
2944 new (Context) MemberExpr(NSValueCallExpr, false, ARRFD,
2945 SourceLocation(),
2946 ARRFD->getType(), VK_LValue,
2947 OK_Ordinary);
2948 QualType ConstIdT = Context->getObjCIdType().withConst();
2949 CStyleCastExpr * DictValueObjects =
2950 NoTypeInfoCStyleCastExpr(Context,
2951 Context->getPointerType(ConstIdT),
2952 CK_BitCast,
2953 DictLiteralValueME);
2954 // (const id <NSCopying> [])keys
2955 Expr *NSKeyCallExpr =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00002956 new (Context) CallExpr(*Context, NSDictDRE, KeyExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00002957 NSDictFType, VK_LValue, SourceLocation());
2958
2959 MemberExpr *DictLiteralKeyME =
2960 new (Context) MemberExpr(NSKeyCallExpr, false, ARRFD,
2961 SourceLocation(),
2962 ARRFD->getType(), VK_LValue,
2963 OK_Ordinary);
2964
2965 CStyleCastExpr * DictKeyObjects =
2966 NoTypeInfoCStyleCastExpr(Context,
2967 Context->getPointerType(ConstIdT),
2968 CK_BitCast,
2969 DictLiteralKeyME);
2970
2971
2972
2973 // Synthesize a call to objc_msgSend().
2974 SmallVector<Expr*, 32> MsgExprs;
2975 SmallVector<Expr*, 4> ClsExprs;
2976 QualType argType = Context->getPointerType(Context->CharTy);
2977 QualType expType = Exp->getType();
2978
2979 // Create a call to objc_getClass("NSArray"). It will be th 1st argument.
2980 ObjCInterfaceDecl *Class =
2981 expType->getPointeeType()->getAs<ObjCObjectType>()->getInterface();
2982
2983 IdentifierInfo *clsName = Class->getIdentifier();
2984 ClsExprs.push_back(StringLiteral::Create(*Context,
2985 clsName->getName(),
2986 StringLiteral::Ascii, false,
2987 argType, SourceLocation()));
2988 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();
2998 SelExprs.push_back(StringLiteral::Create(*Context,
2999 DictMethod->getSelector().getAsString(),
3000 StringLiteral::Ascii, false,
3001 argType, SourceLocation()));
3002 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3003 &SelExprs[0], SelExprs.size(),
3004 StartLoc, EndLoc);
3005 MsgExprs.push_back(SelExp);
3006
3007 // (const id [])objects
3008 MsgExprs.push_back(DictValueObjects);
3009
3010 // (const id <NSCopying> [])keys
3011 MsgExprs.push_back(DictKeyObjects);
3012
3013 // (NSUInteger)cnt
3014 Expr *cnt = IntegerLiteral::Create(*Context,
3015 llvm::APInt(UnsignedIntSize, NumElements),
3016 Context->UnsignedIntTy, SourceLocation());
3017 MsgExprs.push_back(cnt);
3018
3019
3020 SmallVector<QualType, 8> ArgTypes;
3021 ArgTypes.push_back(Context->getObjCIdType());
3022 ArgTypes.push_back(Context->getObjCSelType());
3023 for (ObjCMethodDecl::param_iterator PI = DictMethod->param_begin(),
3024 E = DictMethod->param_end(); PI != E; ++PI) {
3025 QualType T = (*PI)->getType();
3026 if (const PointerType* PT = T->getAs<PointerType>()) {
3027 QualType PointeeTy = PT->getPointeeType();
3028 convertToUnqualifiedObjCType(PointeeTy);
3029 T = Context->getPointerType(PointeeTy);
3030 }
3031 ArgTypes.push_back(T);
3032 }
3033
3034 QualType returnType = Exp->getType();
3035 // Get the type, we will need to reference it in a couple spots.
3036 QualType msgSendType = MsgSendFlavor->getType();
3037
3038 // Create a reference to the objc_msgSend() declaration.
3039 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
3040 VK_LValue, SourceLocation());
3041
3042 CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
3043 Context->getPointerType(Context->VoidTy),
3044 CK_BitCast, DRE);
3045
3046 // Now do the "normal" pointer to function cast.
3047 QualType castType =
Jordan Rosebea522f2013-03-08 21:51:21 +00003048 getSimpleFunctionType(returnType, ArgTypes, DictMethod->isVariadic());
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00003049 castType = Context->getPointerType(castType);
3050 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3051 cast);
3052
3053 // Don't forget the parens to enforce the proper binding.
3054 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3055
3056 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003057 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00003058 FT->getResultType(), VK_RValue,
3059 EndLoc);
3060 ReplaceStmt(Exp, CE);
3061 return CE;
3062}
3063
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003064// struct __rw_objc_super {
3065// struct objc_object *object; struct objc_object *superClass;
3066// };
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003067QualType RewriteModernObjC::getSuperStructType() {
3068 if (!SuperStructDecl) {
3069 SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3070 SourceLocation(), SourceLocation(),
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003071 &Context->Idents.get("__rw_objc_super"));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003072 QualType FieldTypes[2];
3073
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003074 // struct objc_object *object;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003075 FieldTypes[0] = Context->getObjCIdType();
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003076 // struct objc_object *superClass;
3077 FieldTypes[1] = Context->getObjCIdType();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003078
3079 // Create fields
3080 for (unsigned i = 0; i < 2; ++i) {
3081 SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
3082 SourceLocation(),
3083 SourceLocation(), 0,
3084 FieldTypes[i], 0,
3085 /*BitWidth=*/0,
3086 /*Mutable=*/false,
Richard Smithca523302012-06-10 03:12:00 +00003087 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003088 }
3089
3090 SuperStructDecl->completeDefinition();
3091 }
3092 return Context->getTagDeclType(SuperStructDecl);
3093}
3094
3095QualType RewriteModernObjC::getConstantStringStructType() {
3096 if (!ConstantStringDecl) {
3097 ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3098 SourceLocation(), SourceLocation(),
3099 &Context->Idents.get("__NSConstantStringImpl"));
3100 QualType FieldTypes[4];
3101
3102 // struct objc_object *receiver;
3103 FieldTypes[0] = Context->getObjCIdType();
3104 // int flags;
3105 FieldTypes[1] = Context->IntTy;
3106 // char *str;
3107 FieldTypes[2] = Context->getPointerType(Context->CharTy);
3108 // long length;
3109 FieldTypes[3] = Context->LongTy;
3110
3111 // Create fields
3112 for (unsigned i = 0; i < 4; ++i) {
3113 ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
3114 ConstantStringDecl,
3115 SourceLocation(),
3116 SourceLocation(), 0,
3117 FieldTypes[i], 0,
3118 /*BitWidth=*/0,
3119 /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00003120 ICIS_NoInit));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003121 }
3122
3123 ConstantStringDecl->completeDefinition();
3124 }
3125 return Context->getTagDeclType(ConstantStringDecl);
3126}
3127
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003128/// getFunctionSourceLocation - returns start location of a function
3129/// definition. Complication arises when function has declared as
3130/// extern "C" or extern "C" {...}
3131static SourceLocation getFunctionSourceLocation (RewriteModernObjC &R,
3132 FunctionDecl *FD) {
3133 if (FD->isExternC() && !FD->isMain()) {
3134 const DeclContext *DC = FD->getDeclContext();
3135 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3136 // if it is extern "C" {...}, return function decl's own location.
3137 if (!LSD->getRBraceLoc().isValid())
3138 return LSD->getExternLoc();
3139 }
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003140 if (FD->getStorageClass() != SC_None)
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003141 R.RewriteBlockLiteralFunctionDecl(FD);
3142 return FD->getTypeSpecStartLoc();
3143}
3144
Fariborz Jahanian96205962012-11-06 17:30:23 +00003145void RewriteModernObjC::RewriteLineDirective(const Decl *D) {
3146
3147 SourceLocation Location = D->getLocation();
3148
Fariborz Jahanianada71912013-02-08 00:27:34 +00003149 if (Location.isFileID() && GenerateLineInfo) {
Fariborz Jahanian3b45ca92012-11-07 18:15:53 +00003150 std::string LineString("\n#line ");
Fariborz Jahanian96205962012-11-06 17:30:23 +00003151 PresumedLoc PLoc = SM->getPresumedLoc(Location);
3152 LineString += utostr(PLoc.getLine());
3153 LineString += " \"";
NAKAMURA Takumiba529a92012-11-06 22:45:31 +00003154 LineString += Lexer::Stringify(PLoc.getFilename());
Fariborz Jahanian96205962012-11-06 17:30:23 +00003155 if (isa<ObjCMethodDecl>(D))
3156 LineString += "\"";
3157 else LineString += "\"\n";
3158
3159 Location = D->getLocStart();
3160 if (const FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
3161 if (FD->isExternC() && !FD->isMain()) {
3162 const DeclContext *DC = FD->getDeclContext();
3163 if (const LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(DC))
3164 // if it is extern "C" {...}, return function decl's own location.
3165 if (!LSD->getRBraceLoc().isValid())
3166 Location = LSD->getExternLoc();
3167 }
3168 }
3169 InsertText(Location, LineString);
3170 }
3171}
3172
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003173/// SynthMsgSendStretCallExpr - This routine translates message expression
3174/// into a call to objc_msgSend_stret() entry point. Tricky part is that
3175/// nil check on receiver must be performed before calling objc_msgSend_stret.
3176/// MsgSendStretFlavor - function declaration objc_msgSend_stret(...)
3177/// msgSendType - function type of objc_msgSend_stret(...)
3178/// returnType - Result type of the method being synthesized.
3179/// ArgTypes - type of the arguments passed to objc_msgSend_stret, starting with receiver type.
3180/// MsgExprs - list of argument expressions being passed to objc_msgSend_stret,
3181/// starting with receiver.
3182/// Method - Method being rewritten.
3183Expr *RewriteModernObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003184 QualType returnType,
3185 SmallVectorImpl<QualType> &ArgTypes,
3186 SmallVectorImpl<Expr*> &MsgExprs,
3187 ObjCMethodDecl *Method) {
3188 // Now do the "normal" pointer to function cast.
Jordan Rosebea522f2013-03-08 21:51:21 +00003189 QualType castType = getSimpleFunctionType(returnType, ArgTypes,
3190 Method ? Method->isVariadic()
3191 : false);
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003192 castType = Context->getPointerType(castType);
3193
3194 // build type for containing the objc_msgSend_stret object.
3195 static unsigned stretCount=0;
3196 std::string name = "__Stret"; name += utostr(stretCount);
Fariborz Jahanian2ca5af22012-07-25 21:48:36 +00003197 std::string str =
3198 "extern \"C\" void * __cdecl memset(void *_Dst, int _Val, size_t _Size);\n";
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003199 str += "namespace {\n";
Fariborz Jahanian2ca5af22012-07-25 21:48:36 +00003200 str += "struct "; str += name;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003201 str += " {\n\t";
3202 str += name;
3203 str += "(id receiver, SEL sel";
3204 for (unsigned i = 2; i < ArgTypes.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003205 std::string ArgName = "arg"; ArgName += utostr(i);
3206 ArgTypes[i].getAsStringInternal(ArgName, Context->getPrintingPolicy());
3207 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003208 }
3209 // could be vararg.
3210 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
Fariborz Jahanian6734ec42012-06-29 19:55:46 +00003211 std::string ArgName = "arg"; ArgName += utostr(i);
3212 MsgExprs[i]->getType().getAsStringInternal(ArgName,
3213 Context->getPrintingPolicy());
3214 str += ", "; str += ArgName;
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003215 }
3216
3217 str += ") {\n";
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003218 str += "\t unsigned size = sizeof(";
3219 str += returnType.getAsString(Context->getPrintingPolicy()); str += ");\n";
3220
3221 str += "\t if (size == 1 || size == 2 || size == 4 || size == 8)\n";
3222
3223 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3224 str += ")(void *)objc_msgSend)(receiver, sel";
3225 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3226 str += ", arg"; str += utostr(i);
3227 }
3228 // could be vararg.
3229 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3230 str += ", arg"; str += utostr(i);
3231 }
3232 str+= ");\n";
3233
3234 str += "\t else if (receiver == 0)\n";
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003235 str += "\t memset((void*)&s, 0, sizeof(s));\n";
3236 str += "\t else\n";
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003237
3238
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003239 str += "\t s = (("; str += castType.getAsString(Context->getPrintingPolicy());
3240 str += ")(void *)objc_msgSend_stret)(receiver, sel";
3241 for (unsigned i = 2; i < ArgTypes.size(); i++) {
3242 str += ", arg"; str += utostr(i);
3243 }
3244 // could be vararg.
3245 for (unsigned i = ArgTypes.size(); i < MsgExprs.size(); i++) {
3246 str += ", arg"; str += utostr(i);
3247 }
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003248 str += ");\n";
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003249
3250
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003251 str += "\t}\n";
3252 str += "\t"; str += returnType.getAsString(Context->getPrintingPolicy());
3253 str += " s;\n";
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003254 str += "};\n};\n\n";
Fariborz Jahaniana6e5a6e2012-08-21 18:56:50 +00003255 SourceLocation FunLocStart;
3256 if (CurFunctionDef)
3257 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
3258 else {
3259 assert(CurMethodDef && "SynthMsgSendStretCallExpr - CurMethodDef is null");
3260 FunLocStart = CurMethodDef->getLocStart();
3261 }
3262
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003263 InsertText(FunLocStart, str);
3264 ++stretCount;
3265
3266 // AST for __Stretn(receiver, args).s;
3267 IdentifierInfo *ID = &Context->Idents.get(name);
3268 FunctionDecl *FD = FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
Chad Rosiere3b29882013-01-04 22:40:33 +00003269 SourceLocation(), ID, castType, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003270 SC_Extern, false, false);
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003271 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, castType, VK_RValue,
3272 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003273 CallExpr *STCE = new (Context) CallExpr(*Context, DRE, MsgExprs,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003274 castType, VK_LValue, SourceLocation());
3275
3276 FieldDecl *FieldD = FieldDecl::Create(*Context, 0, SourceLocation(),
3277 SourceLocation(),
3278 &Context->Idents.get("s"),
3279 returnType, 0,
3280 /*BitWidth=*/0, /*Mutable=*/true,
3281 ICIS_NoInit);
3282 MemberExpr *ME = new (Context) MemberExpr(STCE, false, FieldD, SourceLocation(),
3283 FieldD->getType(), VK_LValue,
3284 OK_Ordinary);
3285
3286 return ME;
3287}
3288
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003289Stmt *RewriteModernObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
3290 SourceLocation StartLoc,
3291 SourceLocation EndLoc) {
3292 if (!SelGetUidFunctionDecl)
3293 SynthSelGetUidFunctionDecl();
3294 if (!MsgSendFunctionDecl)
3295 SynthMsgSendFunctionDecl();
3296 if (!MsgSendSuperFunctionDecl)
3297 SynthMsgSendSuperFunctionDecl();
3298 if (!MsgSendStretFunctionDecl)
3299 SynthMsgSendStretFunctionDecl();
3300 if (!MsgSendSuperStretFunctionDecl)
3301 SynthMsgSendSuperStretFunctionDecl();
3302 if (!MsgSendFpretFunctionDecl)
3303 SynthMsgSendFpretFunctionDecl();
3304 if (!GetClassFunctionDecl)
3305 SynthGetClassFunctionDecl();
3306 if (!GetSuperClassFunctionDecl)
3307 SynthGetSuperClassFunctionDecl();
3308 if (!GetMetaClassFunctionDecl)
3309 SynthGetMetaClassFunctionDecl();
3310
3311 // default to objc_msgSend().
3312 FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
3313 // May need to use objc_msgSend_stret() as well.
3314 FunctionDecl *MsgSendStretFlavor = 0;
3315 if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
3316 QualType resultType = mDecl->getResultType();
3317 if (resultType->isRecordType())
3318 MsgSendStretFlavor = MsgSendStretFunctionDecl;
3319 else if (resultType->isRealFloatingType())
3320 MsgSendFlavor = MsgSendFpretFunctionDecl;
3321 }
3322
3323 // Synthesize a call to objc_msgSend().
3324 SmallVector<Expr*, 8> MsgExprs;
3325 switch (Exp->getReceiverKind()) {
3326 case ObjCMessageExpr::SuperClass: {
3327 MsgSendFlavor = MsgSendSuperFunctionDecl;
3328 if (MsgSendStretFlavor)
3329 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3330 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3331
3332 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3333
3334 SmallVector<Expr*, 4> InitExprs;
3335
3336 // set the receiver to self, the first argument to all methods.
3337 InitExprs.push_back(
3338 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3339 CK_BitCast,
3340 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003341 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003342 Context->getObjCIdType(),
3343 VK_RValue,
3344 SourceLocation()))
3345 ); // set the 'receiver'.
3346
3347 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3348 SmallVector<Expr*, 8> ClsExprs;
3349 QualType argType = Context->getPointerType(Context->CharTy);
3350 ClsExprs.push_back(StringLiteral::Create(*Context,
3351 ClassDecl->getIdentifier()->getName(),
3352 StringLiteral::Ascii, false,
3353 argType, SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003354 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003355 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
3356 &ClsExprs[0],
3357 ClsExprs.size(),
3358 StartLoc,
3359 EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003360 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003361 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003362 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3363 &ClsExprs[0], ClsExprs.size(),
3364 StartLoc, EndLoc);
3365
3366 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3367 // To turn off a warning, type-cast to 'id'
3368 InitExprs.push_back( // set 'super class', using class_getSuperclass().
3369 NoTypeInfoCStyleCastExpr(Context,
3370 Context->getObjCIdType(),
3371 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003372 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003373 QualType superType = getSuperStructType();
3374 Expr *SuperRep;
3375
3376 if (LangOpts.MicrosoftExt) {
Benjamin Kramere5753592013-09-09 14:48:42 +00003377 SynthSuperConstructorFunctionDecl();
3378 // Simulate a constructor call...
3379 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003380 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003381 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003382 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003383 superType, VK_LValue,
3384 SourceLocation());
3385 // The code for super is a little tricky to prevent collision with
3386 // the structure definition in the header. The rewriter has it's own
3387 // internal definition (__rw_objc_super) that is uses. This is why
3388 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003389 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003390 //
3391 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3392 Context->getPointerType(SuperRep->getType()),
3393 VK_RValue, OK_Ordinary,
3394 SourceLocation());
3395 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3396 Context->getPointerType(superType),
3397 CK_BitCast, SuperRep);
3398 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003399 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003400 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003401 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003402 SourceLocation());
3403 TypeSourceInfo *superTInfo
3404 = Context->getTrivialTypeSourceInfo(superType);
3405 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3406 superType, VK_LValue,
3407 ILE, false);
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003408 // struct __rw_objc_super *
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003409 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3410 Context->getPointerType(SuperRep->getType()),
3411 VK_RValue, OK_Ordinary,
3412 SourceLocation());
3413 }
3414 MsgExprs.push_back(SuperRep);
3415 break;
3416 }
3417
3418 case ObjCMessageExpr::Class: {
3419 SmallVector<Expr*, 8> ClsExprs;
3420 QualType argType = Context->getPointerType(Context->CharTy);
3421 ObjCInterfaceDecl *Class
3422 = Exp->getClassReceiver()->getAs<ObjCObjectType>()->getInterface();
3423 IdentifierInfo *clsName = Class->getIdentifier();
3424 ClsExprs.push_back(StringLiteral::Create(*Context,
3425 clsName->getName(),
3426 StringLiteral::Ascii, false,
3427 argType, SourceLocation()));
3428 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3429 &ClsExprs[0],
3430 ClsExprs.size(),
3431 StartLoc, EndLoc);
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003432 CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
3433 Context->getObjCIdType(),
3434 CK_BitCast, Cls);
3435 MsgExprs.push_back(ArgExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003436 break;
3437 }
3438
3439 case ObjCMessageExpr::SuperInstance:{
3440 MsgSendFlavor = MsgSendSuperFunctionDecl;
3441 if (MsgSendStretFlavor)
3442 MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
3443 assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
3444 ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
3445 SmallVector<Expr*, 4> InitExprs;
3446
3447 InitExprs.push_back(
3448 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3449 CK_BitCast,
3450 new (Context) DeclRefExpr(CurMethodDef->getSelfDecl(),
John McCallf4b88a42012-03-10 09:33:50 +00003451 false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003452 Context->getObjCIdType(),
3453 VK_RValue, SourceLocation()))
3454 ); // set the 'receiver'.
3455
3456 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3457 SmallVector<Expr*, 8> ClsExprs;
3458 QualType argType = Context->getPointerType(Context->CharTy);
3459 ClsExprs.push_back(StringLiteral::Create(*Context,
3460 ClassDecl->getIdentifier()->getName(),
3461 StringLiteral::Ascii, false, argType,
3462 SourceLocation()));
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003463 // (Class)objc_getClass("CurrentClass")
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003464 CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl,
3465 &ClsExprs[0],
3466 ClsExprs.size(),
3467 StartLoc, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003468 ClsExprs.clear();
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00003469 ClsExprs.push_back(Cls);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003470 Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl,
3471 &ClsExprs[0], ClsExprs.size(),
3472 StartLoc, EndLoc);
3473
3474 // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
3475 // To turn off a warning, type-cast to 'id'
3476 InitExprs.push_back(
3477 // set 'super class', using class_getSuperclass().
3478 NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3479 CK_BitCast, Cls));
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003480 // struct __rw_objc_super
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003481 QualType superType = getSuperStructType();
3482 Expr *SuperRep;
3483
3484 if (LangOpts.MicrosoftExt) {
Benjamin Kramere5753592013-09-09 14:48:42 +00003485 SynthSuperConstructorFunctionDecl();
3486 // Simulate a constructor call...
3487 DeclRefExpr *DRE = new (Context) DeclRefExpr(SuperConstructorFunctionDecl,
John McCallf4b88a42012-03-10 09:33:50 +00003488 false, superType, VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003489 SourceLocation());
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003490 SuperRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003491 superType, VK_LValue, SourceLocation());
3492 // The code for super is a little tricky to prevent collision with
3493 // the structure definition in the header. The rewriter has it's own
3494 // internal definition (__rw_objc_super) that is uses. This is why
3495 // we need the cast below. For example:
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003496 // (struct __rw_objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003497 //
3498 SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
3499 Context->getPointerType(SuperRep->getType()),
3500 VK_RValue, OK_Ordinary,
3501 SourceLocation());
3502 SuperRep = NoTypeInfoCStyleCastExpr(Context,
3503 Context->getPointerType(superType),
3504 CK_BitCast, SuperRep);
3505 } else {
Fariborz Jahanianb20c46e2012-04-13 16:20:05 +00003506 // (struct __rw_objc_super) { <exprs from above> }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003507 InitListExpr *ILE =
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003508 new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003509 SourceLocation());
3510 TypeSourceInfo *superTInfo
3511 = Context->getTrivialTypeSourceInfo(superType);
3512 SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
3513 superType, VK_RValue, ILE,
3514 false);
3515 }
3516 MsgExprs.push_back(SuperRep);
3517 break;
3518 }
3519
3520 case ObjCMessageExpr::Instance: {
3521 // Remove all type-casts because it may contain objc-style types; e.g.
3522 // Foo<Proto> *.
3523 Expr *recExpr = Exp->getInstanceReceiver();
3524 while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
3525 recExpr = CE->getSubExpr();
3526 CastKind CK = recExpr->getType()->isObjCObjectPointerType()
3527 ? CK_BitCast : recExpr->getType()->isBlockPointerType()
3528 ? CK_BlockPointerToObjCPointerCast
3529 : CK_CPointerToObjCPointerCast;
3530
3531 recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3532 CK, recExpr);
3533 MsgExprs.push_back(recExpr);
3534 break;
3535 }
3536 }
3537
3538 // Create a call to sel_registerName("selName"), it will be the 2nd argument.
3539 SmallVector<Expr*, 8> SelExprs;
3540 QualType argType = Context->getPointerType(Context->CharTy);
3541 SelExprs.push_back(StringLiteral::Create(*Context,
3542 Exp->getSelector().getAsString(),
3543 StringLiteral::Ascii, false,
3544 argType, SourceLocation()));
3545 CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
3546 &SelExprs[0], SelExprs.size(),
3547 StartLoc,
3548 EndLoc);
3549 MsgExprs.push_back(SelExp);
3550
3551 // Now push any user supplied arguments.
3552 for (unsigned i = 0; i < Exp->getNumArgs(); i++) {
3553 Expr *userExpr = Exp->getArg(i);
3554 // Make all implicit casts explicit...ICE comes in handy:-)
3555 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
3556 // Reuse the ICE type, it is exactly what the doctor ordered.
3557 QualType type = ICE->getType();
3558 if (needToScanForQualifiers(type))
3559 type = Context->getObjCIdType();
3560 // Make sure we convert "type (^)(...)" to "type (*)(...)".
3561 (void)convertBlockPointerToFunctionPointer(type);
3562 const Expr *SubExpr = ICE->IgnoreParenImpCasts();
3563 CastKind CK;
3564 if (SubExpr->getType()->isIntegralType(*Context) &&
3565 type->isBooleanType()) {
3566 CK = CK_IntegralToBoolean;
3567 } else if (type->isObjCObjectPointerType()) {
3568 if (SubExpr->getType()->isBlockPointerType()) {
3569 CK = CK_BlockPointerToObjCPointerCast;
3570 } else if (SubExpr->getType()->isPointerType()) {
3571 CK = CK_CPointerToObjCPointerCast;
3572 } else {
3573 CK = CK_BitCast;
3574 }
3575 } else {
3576 CK = CK_BitCast;
3577 }
3578
3579 userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
3580 }
3581 // Make id<P...> cast into an 'id' cast.
3582 else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
3583 if (CE->getType()->isObjCQualifiedIdType()) {
3584 while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
3585 userExpr = CE->getSubExpr();
3586 CastKind CK;
3587 if (userExpr->getType()->isIntegralType(*Context)) {
3588 CK = CK_IntegralToPointer;
3589 } else if (userExpr->getType()->isBlockPointerType()) {
3590 CK = CK_BlockPointerToObjCPointerCast;
3591 } else if (userExpr->getType()->isPointerType()) {
3592 CK = CK_CPointerToObjCPointerCast;
3593 } else {
3594 CK = CK_BitCast;
3595 }
3596 userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
3597 CK, userExpr);
3598 }
3599 }
3600 MsgExprs.push_back(userExpr);
3601 // We've transferred the ownership to MsgExprs. For now, we *don't* null
3602 // out the argument in the original expression (since we aren't deleting
3603 // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
3604 //Exp->setArg(i, 0);
3605 }
3606 // Generate the funky cast.
3607 CastExpr *cast;
3608 SmallVector<QualType, 8> ArgTypes;
3609 QualType returnType;
3610
3611 // Push 'id' and 'SEL', the 2 implicit arguments.
3612 if (MsgSendFlavor == MsgSendSuperFunctionDecl)
3613 ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
3614 else
3615 ArgTypes.push_back(Context->getObjCIdType());
3616 ArgTypes.push_back(Context->getObjCSelType());
3617 if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
3618 // Push any user argument types.
3619 for (ObjCMethodDecl::param_iterator PI = OMD->param_begin(),
3620 E = OMD->param_end(); PI != E; ++PI) {
3621 QualType t = (*PI)->getType()->isObjCQualifiedIdType()
3622 ? Context->getObjCIdType()
3623 : (*PI)->getType();
3624 // Make sure we convert "t (^)(...)" to "t (*)(...)".
3625 (void)convertBlockPointerToFunctionPointer(t);
3626 ArgTypes.push_back(t);
3627 }
3628 returnType = Exp->getType();
3629 convertToUnqualifiedObjCType(returnType);
3630 (void)convertBlockPointerToFunctionPointer(returnType);
3631 } else {
3632 returnType = Context->getObjCIdType();
3633 }
3634 // Get the type, we will need to reference it in a couple spots.
3635 QualType msgSendType = MsgSendFlavor->getType();
3636
3637 // Create a reference to the objc_msgSend() declaration.
John McCallf4b88a42012-03-10 09:33:50 +00003638 DeclRefExpr *DRE = new (Context) DeclRefExpr(MsgSendFlavor, false, msgSendType,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003639 VK_LValue, SourceLocation());
3640
3641 // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
3642 // If we don't do this cast, we get the following bizarre warning/note:
3643 // xx.m:13: warning: function called through a non-compatible type
3644 // xx.m:13: note: if this code is reached, the program will abort
3645 cast = NoTypeInfoCStyleCastExpr(Context,
3646 Context->getPointerType(Context->VoidTy),
3647 CK_BitCast, DRE);
3648
3649 // Now do the "normal" pointer to function cast.
Jordan Rosebea522f2013-03-08 21:51:21 +00003650 // If we don't have a method decl, force a variadic cast.
3651 const ObjCMethodDecl *MD = Exp->getMethodDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003652 QualType castType =
Jordan Rosebea522f2013-03-08 21:51:21 +00003653 getSimpleFunctionType(returnType, ArgTypes, MD ? MD->isVariadic() : true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003654 castType = Context->getPointerType(castType);
3655 cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
3656 cast);
3657
3658 // Don't forget the parens to enforce the proper binding.
3659 ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
3660
3661 const FunctionType *FT = msgSendType->getAs<FunctionType>();
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00003662 CallExpr *CE = new (Context) CallExpr(*Context, PE, MsgExprs,
3663 FT->getResultType(), VK_RValue, EndLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003664 Stmt *ReplacingStmt = CE;
3665 if (MsgSendStretFlavor) {
3666 // We have the method which returns a struct/union. Must also generate
3667 // call to objc_msgSend_stret and hang both varieties on a conditional
3668 // expression which dictate which one to envoke depending on size of
3669 // method's return type.
3670
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003671 Expr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
3672 returnType,
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00003673 ArgTypes, MsgExprs,
3674 Exp->getMethodDecl());
Fariborz Jahanian426bb9c2013-09-09 19:59:59 +00003675 ReplacingStmt = STCE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003676 }
3677 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3678 return ReplacingStmt;
3679}
3680
3681Stmt *RewriteModernObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3682 Stmt *ReplacingStmt = SynthMessageExpr(Exp, Exp->getLocStart(),
3683 Exp->getLocEnd());
3684
3685 // Now do the actual rewrite.
3686 ReplaceStmt(Exp, ReplacingStmt);
3687
3688 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3689 return ReplacingStmt;
3690}
3691
3692// typedef struct objc_object Protocol;
3693QualType RewriteModernObjC::getProtocolType() {
3694 if (!ProtocolTypeDecl) {
3695 TypeSourceInfo *TInfo
3696 = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3697 ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3698 SourceLocation(), SourceLocation(),
3699 &Context->Idents.get("Protocol"),
3700 TInfo);
3701 }
3702 return Context->getTypeDeclType(ProtocolTypeDecl);
3703}
3704
3705/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3706/// a synthesized/forward data reference (to the protocol's metadata).
3707/// The forward references (and metadata) are generated in
3708/// RewriteModernObjC::HandleTranslationUnit().
3709Stmt *RewriteModernObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00003710 std::string Name = "_OBJC_PROTOCOL_REFERENCE_$_" +
3711 Exp->getProtocol()->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003712 IdentifierInfo *ID = &Context->Idents.get(Name);
3713 VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3714 SourceLocation(), ID, getProtocolType(), 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00003715 SC_Extern);
John McCallf4b88a42012-03-10 09:33:50 +00003716 DeclRefExpr *DRE = new (Context) DeclRefExpr(VD, false, getProtocolType(),
3717 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00003718 Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3719 Context->getPointerType(DRE->getType()),
3720 VK_RValue, OK_Ordinary, SourceLocation());
3721 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3722 CK_BitCast,
3723 DerefExpr);
3724 ReplaceStmt(Exp, castExpr);
3725 ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3726 // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3727 return castExpr;
3728
3729}
3730
3731bool RewriteModernObjC::BufferContainsPPDirectives(const char *startBuf,
3732 const char *endBuf) {
3733 while (startBuf < endBuf) {
3734 if (*startBuf == '#') {
3735 // Skip whitespace.
3736 for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3737 ;
3738 if (!strncmp(startBuf, "if", strlen("if")) ||
3739 !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3740 !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3741 !strncmp(startBuf, "define", strlen("define")) ||
3742 !strncmp(startBuf, "undef", strlen("undef")) ||
3743 !strncmp(startBuf, "else", strlen("else")) ||
3744 !strncmp(startBuf, "elif", strlen("elif")) ||
3745 !strncmp(startBuf, "endif", strlen("endif")) ||
3746 !strncmp(startBuf, "pragma", strlen("pragma")) ||
3747 !strncmp(startBuf, "include", strlen("include")) ||
3748 !strncmp(startBuf, "import", strlen("import")) ||
3749 !strncmp(startBuf, "include_next", strlen("include_next")))
3750 return true;
3751 }
3752 startBuf++;
3753 }
3754 return false;
3755}
3756
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003757/// IsTagDefinedInsideClass - This routine checks that a named tagged type
3758/// is defined inside an objective-c class. If so, it returns true.
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003759bool RewriteModernObjC::IsTagDefinedInsideClass(ObjCContainerDecl *IDecl,
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003760 TagDecl *Tag,
3761 bool &IsNamedDefinition) {
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003762 if (!IDecl)
3763 return false;
3764 SourceLocation TagLocation;
3765 if (RecordDecl *RD = dyn_cast<RecordDecl>(Tag)) {
3766 RD = RD->getDefinition();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003767 if (!RD || !RD->getDeclName().getAsIdentifierInfo())
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003768 return false;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003769 IsNamedDefinition = true;
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003770 TagLocation = RD->getLocation();
3771 return Context->getSourceManager().isBeforeInTranslationUnit(
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003772 IDecl->getLocation(), TagLocation);
3773 }
3774 if (EnumDecl *ED = dyn_cast<EnumDecl>(Tag)) {
3775 if (!ED || !ED->getDeclName().getAsIdentifierInfo())
3776 return false;
3777 IsNamedDefinition = true;
3778 TagLocation = ED->getLocation();
3779 return Context->getSourceManager().isBeforeInTranslationUnit(
3780 IDecl->getLocation(), TagLocation);
3781
Fariborz Jahanian89585e802012-04-30 19:46:53 +00003782 }
3783 return false;
3784}
3785
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003786/// RewriteObjCFieldDeclType - This routine rewrites a type into the buffer.
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003787/// It handles elaborated types, as well as enum types in the process.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003788bool RewriteModernObjC::RewriteObjCFieldDeclType(QualType &Type,
3789 std::string &Result) {
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003790 if (isa<TypedefType>(Type)) {
3791 Result += "\t";
3792 return false;
3793 }
3794
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003795 if (Type->isArrayType()) {
3796 QualType ElemTy = Context->getBaseElementType(Type);
3797 return RewriteObjCFieldDeclType(ElemTy, Result);
3798 }
3799 else if (Type->isRecordType()) {
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003800 RecordDecl *RD = Type->getAs<RecordType>()->getDecl();
3801 if (RD->isCompleteDefinition()) {
3802 if (RD->isStruct())
3803 Result += "\n\tstruct ";
3804 else if (RD->isUnion())
3805 Result += "\n\tunion ";
3806 else
3807 assert(false && "class not allowed as an ivar type");
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003808
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003809 Result += RD->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003810 if (GlobalDefinedTags.count(RD)) {
3811 // struct/union is defined globally, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003812 Result += " ";
3813 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003814 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003815 Result += " {\n";
3816 for (RecordDecl::field_iterator i = RD->field_begin(),
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003817 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00003818 FieldDecl *FD = *i;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003819 RewriteObjCFieldDecl(FD, Result);
3820 }
3821 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003822 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003823 }
3824 }
3825 else if (Type->isEnumeralType()) {
3826 EnumDecl *ED = Type->getAs<EnumType>()->getDecl();
3827 if (ED->isCompleteDefinition()) {
3828 Result += "\n\tenum ";
3829 Result += ED->getName();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003830 if (GlobalDefinedTags.count(ED)) {
3831 // Enum is globall defined, use it.
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003832 Result += " ";
3833 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003834 }
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003835
3836 Result += " {\n";
3837 for (EnumDecl::enumerator_iterator EC = ED->enumerator_begin(),
3838 ECEnd = ED->enumerator_end(); EC != ECEnd; ++EC) {
3839 Result += "\t"; Result += EC->getName(); Result += " = ";
3840 llvm::APSInt Val = EC->getInitVal();
3841 Result += Val.toString(10);
3842 Result += ",\n";
3843 }
3844 Result += "\t} ";
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003845 return true;
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003846 }
3847 }
3848
3849 Result += "\t";
3850 convertObjCTypeToCStyleType(Type);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003851 return false;
3852}
3853
3854
3855/// RewriteObjCFieldDecl - This routine rewrites a field into the buffer.
3856/// It handles elaborated types, as well as enum types in the process.
3857void RewriteModernObjC::RewriteObjCFieldDecl(FieldDecl *fieldDecl,
3858 std::string &Result) {
3859 QualType Type = fieldDecl->getType();
3860 std::string Name = fieldDecl->getNameAsString();
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003861
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003862 bool EleboratedType = RewriteObjCFieldDeclType(Type, Result);
3863 if (!EleboratedType)
3864 Type.getAsStringInternal(Name, Context->getPrintingPolicy());
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003865 Result += Name;
3866 if (fieldDecl->isBitField()) {
3867 Result += " : "; Result += utostr(fieldDecl->getBitWidthValue(*Context));
3868 }
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003869 else if (EleboratedType && Type->isArrayType()) {
Eli Friedman6febf122012-12-13 01:43:21 +00003870 const ArrayType *AT = Context->getAsArrayType(Type);
3871 do {
3872 if (const ConstantArrayType *CAT = dyn_cast<ConstantArrayType>(AT)) {
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003873 Result += "[";
3874 llvm::APInt Dim = CAT->getSize();
3875 Result += utostr(Dim.getZExtValue());
3876 Result += "]";
3877 }
Eli Friedman6febf122012-12-13 01:43:21 +00003878 AT = Context->getAsArrayType(AT->getElementType());
3879 } while (AT);
Fariborz Jahanian97c1fd62012-03-09 23:46:23 +00003880 }
3881
Fariborz Jahanian15f87772012-02-28 22:45:07 +00003882 Result += ";\n";
3883}
3884
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003885/// RewriteLocallyDefinedNamedAggregates - This routine rewrites locally defined
3886/// named aggregate types into the input buffer.
3887void RewriteModernObjC::RewriteLocallyDefinedNamedAggregates(FieldDecl *fieldDecl,
3888 std::string &Result) {
3889 QualType Type = fieldDecl->getType();
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00003890 if (isa<TypedefType>(Type))
3891 return;
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003892 if (Type->isArrayType())
3893 Type = Context->getBaseElementType(Type);
Fariborz Jahanianb68258f2012-05-01 17:46:45 +00003894 ObjCContainerDecl *IDecl =
3895 dyn_cast<ObjCContainerDecl>(fieldDecl->getDeclContext());
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00003896
3897 TagDecl *TD = 0;
3898 if (Type->isRecordType()) {
3899 TD = Type->getAs<RecordType>()->getDecl();
3900 }
3901 else if (Type->isEnumeralType()) {
3902 TD = Type->getAs<EnumType>()->getDecl();
3903 }
3904
3905 if (TD) {
3906 if (GlobalDefinedTags.count(TD))
3907 return;
3908
3909 bool IsNamedDefinition = false;
3910 if (IsTagDefinedInsideClass(IDecl, TD, IsNamedDefinition)) {
3911 RewriteObjCFieldDeclType(Type, Result);
3912 Result += ";";
3913 }
3914 if (IsNamedDefinition)
3915 GlobalDefinedTags.insert(TD);
3916 }
3917
3918}
3919
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00003920unsigned RewriteModernObjC::ObjCIvarBitfieldGroupNo(ObjCIvarDecl *IV) {
3921 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3922 if (ObjCInterefaceHasBitfieldGroups.count(CDecl)) {
3923 return IvarGroupNumber[IV];
3924 }
3925 unsigned GroupNo = 0;
3926 SmallVector<const ObjCIvarDecl *, 8> IVars;
3927 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3928 IVD; IVD = IVD->getNextIvar())
3929 IVars.push_back(IVD);
3930
3931 for (unsigned i = 0, e = IVars.size(); i < e; i++)
3932 if (IVars[i]->isBitField()) {
3933 IvarGroupNumber[IVars[i++]] = ++GroupNo;
3934 while (i < e && IVars[i]->isBitField())
3935 IvarGroupNumber[IVars[i++]] = GroupNo;
3936 if (i < e)
3937 --i;
3938 }
3939
3940 ObjCInterefaceHasBitfieldGroups.insert(CDecl);
3941 return IvarGroupNumber[IV];
3942}
3943
3944QualType RewriteModernObjC::SynthesizeBitfieldGroupStructType(
3945 ObjCIvarDecl *IV,
3946 SmallVectorImpl<ObjCIvarDecl *> &IVars) {
3947 std::string StructTagName;
3948 ObjCIvarBitfieldGroupType(IV, StructTagName);
3949 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct,
3950 Context->getTranslationUnitDecl(),
3951 SourceLocation(), SourceLocation(),
3952 &Context->Idents.get(StructTagName));
3953 for (unsigned i=0, e = IVars.size(); i < e; i++) {
3954 ObjCIvarDecl *Ivar = IVars[i];
3955 RD->addDecl(FieldDecl::Create(*Context, RD, SourceLocation(), SourceLocation(),
3956 &Context->Idents.get(Ivar->getName()),
3957 Ivar->getType(),
3958 0, /*Expr *BW */Ivar->getBitWidth(), false,
3959 ICIS_NoInit));
3960 }
3961 RD->completeDefinition();
3962 return Context->getTagDeclType(RD);
3963}
3964
3965QualType RewriteModernObjC::GetGroupRecordTypeForObjCIvarBitfield(ObjCIvarDecl *IV) {
3966 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
3967 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
3968 std::pair<const ObjCInterfaceDecl*, unsigned> tuple = std::make_pair(CDecl, GroupNo);
3969 if (GroupRecordType.count(tuple))
3970 return GroupRecordType[tuple];
3971
3972 SmallVector<ObjCIvarDecl *, 8> IVars;
3973 for (const ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
3974 IVD; IVD = IVD->getNextIvar()) {
3975 if (IVD->isBitField())
3976 IVars.push_back(const_cast<ObjCIvarDecl *>(IVD));
3977 else {
3978 if (!IVars.empty()) {
3979 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3980 // Generate the struct type for this group of bitfield ivars.
3981 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3982 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3983 IVars.clear();
3984 }
3985 }
3986 }
3987 if (!IVars.empty()) {
3988 // Do the last one.
3989 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IVars[0]);
3990 GroupRecordType[std::make_pair(CDecl, GroupNo)] =
3991 SynthesizeBitfieldGroupStructType(IVars[0], IVars);
3992 }
3993 QualType RetQT = GroupRecordType[tuple];
3994 assert(!RetQT.isNull() && "GetGroupRecordTypeForObjCIvarBitfield struct type is NULL");
3995
3996 return RetQT;
3997}
3998
3999/// ObjCIvarBitfieldGroupDecl - Names field decl. for ivar bitfield group.
4000/// Name would be: classname__GRBF_n where n is the group number for this ivar.
4001void RewriteModernObjC::ObjCIvarBitfieldGroupDecl(ObjCIvarDecl *IV,
4002 std::string &Result) {
4003 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
4004 Result += CDecl->getName();
4005 Result += "__GRBF_";
4006 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
4007 Result += utostr(GroupNo);
4008 return;
4009}
4010
4011/// ObjCIvarBitfieldGroupType - Names struct type for ivar bitfield group.
4012/// Name of the struct would be: classname__T_n where n is the group number for
4013/// this ivar.
4014void RewriteModernObjC::ObjCIvarBitfieldGroupType(ObjCIvarDecl *IV,
4015 std::string &Result) {
4016 const ObjCInterfaceDecl *CDecl = IV->getContainingInterface();
4017 Result += CDecl->getName();
4018 Result += "__T_";
4019 unsigned GroupNo = ObjCIvarBitfieldGroupNo(IV);
4020 Result += utostr(GroupNo);
4021 return;
4022}
4023
4024/// ObjCIvarBitfieldGroupOffset - Names symbol for ivar bitfield group field offset.
4025/// Name would be: OBJC_IVAR_$_classname__GRBF_n where n is the group number for
4026/// this ivar.
4027void RewriteModernObjC::ObjCIvarBitfieldGroupOffset(ObjCIvarDecl *IV,
4028 std::string &Result) {
4029 Result += "OBJC_IVAR_$_";
4030 ObjCIvarBitfieldGroupDecl(IV, Result);
4031}
4032
4033#define SKIP_BITFIELDS(IX, ENDIX, VEC) { \
4034 while ((IX < ENDIX) && VEC[IX]->isBitField()) \
4035 ++IX; \
4036 if (IX < ENDIX) \
4037 --IX; \
4038}
4039
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004040/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
4041/// an objective-c class with ivars.
4042void RewriteModernObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
4043 std::string &Result) {
4044 assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
4045 assert(CDecl->getName() != "" &&
4046 "Name missing in SynthesizeObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004047 ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004048 SmallVector<ObjCIvarDecl *, 8> IVars;
4049 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00004050 IVD; IVD = IVD->getNextIvar())
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004051 IVars.push_back(IVD);
Fariborz Jahanian9a2105b2012-03-06 17:16:27 +00004052
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004053 SourceLocation LocStart = CDecl->getLocStart();
4054 SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004055
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004056 const char *startBuf = SM->getCharacterData(LocStart);
4057 const char *endBuf = SM->getCharacterData(LocEnd);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004058
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004059 // If no ivars and no root or if its root, directly or indirectly,
4060 // have no ivars (thus not synthesized) then no need to synthesize this class.
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004061 if ((!CDecl->isThisDeclarationADefinition() || IVars.size() == 0) &&
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004062 (!RCDecl || !ObjCSynthesizedStructs.count(RCDecl))) {
4063 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4064 ReplaceText(LocStart, endBuf-startBuf, Result);
4065 return;
4066 }
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004067
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00004068 // Insert named struct/union definitions inside class to
4069 // outer scope. This follows semantics of locally defined
4070 // struct/unions in objective-c classes.
4071 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4072 RewriteLocallyDefinedNamedAggregates(IVars[i], Result);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004073
4074 // Insert named structs which are syntheized to group ivar bitfields
4075 // to outer scope as well.
4076 for (unsigned i = 0, e = IVars.size(); i < e; i++)
4077 if (IVars[i]->isBitField()) {
4078 ObjCIvarDecl *IV = IVars[i];
4079 QualType QT = GetGroupRecordTypeForObjCIvarBitfield(IV);
4080 RewriteObjCFieldDeclType(QT, Result);
4081 Result += ";";
4082 // skip over ivar bitfields in this group.
4083 SKIP_BITFIELDS(i , e, IVars);
4084 }
4085
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004086 Result += "\nstruct ";
4087 Result += CDecl->getNameAsString();
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004088 Result += "_IMPL {\n";
4089
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00004090 if (RCDecl && ObjCSynthesizedStructs.count(RCDecl)) {
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004091 Result += "\tstruct "; Result += RCDecl->getNameAsString();
4092 Result += "_IMPL "; Result += RCDecl->getNameAsString();
4093 Result += "_IVARS;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004094 }
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00004095
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004096 for (unsigned i = 0, e = IVars.size(); i < e; i++) {
4097 if (IVars[i]->isBitField()) {
4098 ObjCIvarDecl *IV = IVars[i];
4099 Result += "\tstruct ";
4100 ObjCIvarBitfieldGroupType(IV, Result); Result += " ";
4101 ObjCIvarBitfieldGroupDecl(IV, Result); Result += ";\n";
4102 // skip over ivar bitfields in this group.
4103 SKIP_BITFIELDS(i , e, IVars);
4104 }
4105 else
4106 RewriteObjCFieldDecl(IVars[i], Result);
4107 }
Fariborz Jahanian0b17b9a2012-02-12 21:36:23 +00004108
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00004109 Result += "};\n";
4110 endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
4111 ReplaceText(LocStart, endBuf-startBuf, Result);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00004112 // Mark this struct as having been generated.
4113 if (!ObjCSynthesizedStructs.insert(CDecl))
4114 llvm_unreachable("struct already synthesize- RewriteObjCInternalStruct");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004115}
4116
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004117/// RewriteIvarOffsetSymbols - Rewrite ivar offset symbols of those ivars which
4118/// have been referenced in an ivar access expression.
4119void RewriteModernObjC::RewriteIvarOffsetSymbols(ObjCInterfaceDecl *CDecl,
4120 std::string &Result) {
4121 // write out ivar offset symbols which have been referenced in an ivar
4122 // access expression.
4123 llvm::SmallPtrSet<ObjCIvarDecl *, 8> Ivars = ReferencedIvars[CDecl];
4124 if (Ivars.empty())
4125 return;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004126
4127 llvm::DenseSet<std::pair<const ObjCInterfaceDecl*, unsigned> > GroupSymbolOutput;
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004128 for (llvm::SmallPtrSet<ObjCIvarDecl *, 8>::iterator i = Ivars.begin(),
4129 e = Ivars.end(); i != e; i++) {
4130 ObjCIvarDecl *IvarDecl = (*i);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004131 const ObjCInterfaceDecl *IDecl = IvarDecl->getContainingInterface();
4132 unsigned GroupNo = 0;
4133 if (IvarDecl->isBitField()) {
4134 GroupNo = ObjCIvarBitfieldGroupNo(IvarDecl);
4135 if (GroupSymbolOutput.count(std::make_pair(IDecl, GroupNo)))
4136 continue;
4137 }
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00004138 Result += "\n";
4139 if (LangOpts.MicrosoftExt)
4140 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00004141 Result += "extern \"C\" ";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00004142 if (LangOpts.MicrosoftExt &&
4143 IvarDecl->getAccessControl() != ObjCIvarDecl::Private &&
Fariborz Jahanian297976d2012-03-29 17:51:09 +00004144 IvarDecl->getAccessControl() != ObjCIvarDecl::Package)
4145 Result += "__declspec(dllimport) ";
4146
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00004147 Result += "unsigned long ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00004148 if (IvarDecl->isBitField()) {
4149 ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
4150 GroupSymbolOutput.insert(std::make_pair(IDecl, GroupNo));
4151 }
4152 else
4153 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00004154 Result += ";";
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00004155 }
4156}
4157
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004158//===----------------------------------------------------------------------===//
4159// Meta Data Emission
4160//===----------------------------------------------------------------------===//
4161
4162
4163/// RewriteImplementations - This routine rewrites all method implementations
4164/// and emits meta-data.
4165
4166void RewriteModernObjC::RewriteImplementations() {
4167 int ClsDefCount = ClassImplementation.size();
4168 int CatDefCount = CategoryImplementation.size();
4169
4170 // Rewrite implemented methods
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00004171 for (int i = 0; i < ClsDefCount; i++) {
4172 ObjCImplementationDecl *OIMP = ClassImplementation[i];
4173 ObjCInterfaceDecl *CDecl = OIMP->getClassInterface();
4174 if (CDecl->isImplicitInterfaceDecl())
Fariborz Jahaniancf4c60f2012-02-17 22:20:12 +00004175 assert(false &&
4176 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00004177 RewriteImplementationDecl(OIMP);
4178 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004179
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00004180 for (int i = 0; i < CatDefCount; i++) {
4181 ObjCCategoryImplDecl *CIMP = CategoryImplementation[i];
4182 ObjCInterfaceDecl *CDecl = CIMP->getClassInterface();
4183 if (CDecl->isImplicitInterfaceDecl())
4184 assert(false &&
4185 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00004186 RewriteImplementationDecl(CIMP);
4187 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004188}
4189
4190void RewriteModernObjC::RewriteByRefString(std::string &ResultStr,
4191 const std::string &Name,
4192 ValueDecl *VD, bool def) {
4193 assert(BlockByRefDeclNo.count(VD) &&
4194 "RewriteByRefString: ByRef decl missing");
4195 if (def)
4196 ResultStr += "struct ";
4197 ResultStr += "__Block_byref_" + Name +
4198 "_" + utostr(BlockByRefDeclNo[VD]) ;
4199}
4200
4201static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
4202 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4203 return (Var->isFunctionOrMethodVarDecl() && !Var->hasLocalStorage());
4204 return false;
4205}
4206
4207std::string RewriteModernObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
4208 StringRef funcName,
4209 std::string Tag) {
4210 const FunctionType *AFT = CE->getFunctionType();
4211 QualType RT = AFT->getResultType();
4212 std::string StructRef = "struct " + Tag;
Fariborz Jahanianf616ae22012-11-06 23:25:49 +00004213 SourceLocation BlockLoc = CE->getExprLoc();
4214 std::string S;
4215 ConvertSourceLocationToLineDirective(BlockLoc, S);
4216
4217 S += "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
4218 funcName.str() + "_block_func_" + utostr(i);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004219
4220 BlockDecl *BD = CE->getBlockDecl();
4221
4222 if (isa<FunctionNoProtoType>(AFT)) {
4223 // No user-supplied arguments. Still need to pass in a pointer to the
4224 // block (to reference imported block decl refs).
4225 S += "(" + StructRef + " *__cself)";
4226 } else if (BD->param_empty()) {
4227 S += "(" + StructRef + " *__cself)";
4228 } else {
4229 const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
4230 assert(FT && "SynthesizeBlockFunc: No function proto");
4231 S += '(';
4232 // first add the implicit argument.
4233 S += StructRef + " *__cself, ";
4234 std::string ParamStr;
4235 for (BlockDecl::param_iterator AI = BD->param_begin(),
4236 E = BD->param_end(); AI != E; ++AI) {
4237 if (AI != BD->param_begin()) S += ", ";
4238 ParamStr = (*AI)->getNameAsString();
4239 QualType QT = (*AI)->getType();
Fariborz Jahanian2610f902012-03-27 16:42:20 +00004240 (void)convertBlockPointerToFunctionPointer(QT);
4241 QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004242 S += ParamStr;
4243 }
4244 if (FT->isVariadic()) {
4245 if (!BD->param_empty()) S += ", ";
4246 S += "...";
4247 }
4248 S += ')';
4249 }
4250 S += " {\n";
4251
4252 // Create local declarations to avoid rewriting all closure decl ref exprs.
4253 // First, emit a declaration for all "by ref" decls.
Craig Topper09d19ef2013-07-04 03:08:24 +00004254 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004255 E = BlockByRefDecls.end(); I != E; ++I) {
4256 S += " ";
4257 std::string Name = (*I)->getNameAsString();
4258 std::string TypeString;
4259 RewriteByRefString(TypeString, Name, (*I));
4260 TypeString += " *";
4261 Name = TypeString + Name;
4262 S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
4263 }
4264 // Next, emit a declaration for all "by copy" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00004265 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004266 E = BlockByCopyDecls.end(); I != E; ++I) {
4267 S += " ";
4268 // Handle nested closure invocation. For example:
4269 //
4270 // void (^myImportedClosure)(void);
4271 // myImportedClosure = ^(void) { setGlobalInt(x + y); };
4272 //
4273 // void (^anotherClosure)(void);
4274 // anotherClosure = ^(void) {
4275 // myImportedClosure(); // import and invoke the closure
4276 // };
4277 //
4278 if (isTopLevelBlockPointerType((*I)->getType())) {
4279 RewriteBlockPointerTypeVariable(S, (*I));
4280 S += " = (";
4281 RewriteBlockPointerType(S, (*I)->getType());
4282 S += ")";
4283 S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
4284 }
4285 else {
4286 std::string Name = (*I)->getNameAsString();
4287 QualType QT = (*I)->getType();
4288 if (HasLocalVariableExternalStorage(*I))
4289 QT = Context->getPointerType(QT);
4290 QT.getAsStringInternal(Name, Context->getPrintingPolicy());
4291 S += Name + " = __cself->" +
4292 (*I)->getNameAsString() + "; // bound by copy\n";
4293 }
4294 }
4295 std::string RewrittenStr = RewrittenBlockExprs[CE];
4296 const char *cstr = RewrittenStr.c_str();
4297 while (*cstr++ != '{') ;
4298 S += cstr;
4299 S += "\n";
4300 return S;
4301}
4302
4303std::string RewriteModernObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
4304 StringRef funcName,
4305 std::string Tag) {
4306 std::string StructRef = "struct " + Tag;
4307 std::string S = "static void __";
4308
4309 S += funcName;
4310 S += "_block_copy_" + utostr(i);
4311 S += "(" + StructRef;
4312 S += "*dst, " + StructRef;
4313 S += "*src) {";
4314 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4315 E = ImportedBlockDecls.end(); I != E; ++I) {
4316 ValueDecl *VD = (*I);
4317 S += "_Block_object_assign((void*)&dst->";
4318 S += (*I)->getNameAsString();
4319 S += ", (void*)src->";
4320 S += (*I)->getNameAsString();
4321 if (BlockByRefDeclsPtrSet.count((*I)))
4322 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4323 else if (VD->getType()->isBlockPointerType())
4324 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4325 else
4326 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4327 }
4328 S += "}\n";
4329
4330 S += "\nstatic void __";
4331 S += funcName;
4332 S += "_block_dispose_" + utostr(i);
4333 S += "(" + StructRef;
4334 S += "*src) {";
4335 for (llvm::SmallPtrSet<ValueDecl*,8>::iterator I = ImportedBlockDecls.begin(),
4336 E = ImportedBlockDecls.end(); I != E; ++I) {
4337 ValueDecl *VD = (*I);
4338 S += "_Block_object_dispose((void*)src->";
4339 S += (*I)->getNameAsString();
4340 if (BlockByRefDeclsPtrSet.count((*I)))
4341 S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
4342 else if (VD->getType()->isBlockPointerType())
4343 S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
4344 else
4345 S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
4346 }
4347 S += "}\n";
4348 return S;
4349}
4350
4351std::string RewriteModernObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
4352 std::string Desc) {
4353 std::string S = "\nstruct " + Tag;
4354 std::string Constructor = " " + Tag;
4355
4356 S += " {\n struct __block_impl impl;\n";
4357 S += " struct " + Desc;
4358 S += "* Desc;\n";
4359
4360 Constructor += "(void *fp, "; // Invoke function pointer.
4361 Constructor += "struct " + Desc; // Descriptor pointer.
4362 Constructor += " *desc";
4363
4364 if (BlockDeclRefs.size()) {
4365 // Output all "by copy" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00004366 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004367 E = BlockByCopyDecls.end(); I != E; ++I) {
4368 S += " ";
4369 std::string FieldName = (*I)->getNameAsString();
4370 std::string ArgName = "_" + FieldName;
4371 // Handle nested closure invocation. For example:
4372 //
4373 // void (^myImportedBlock)(void);
4374 // myImportedBlock = ^(void) { setGlobalInt(x + y); };
4375 //
4376 // void (^anotherBlock)(void);
4377 // anotherBlock = ^(void) {
4378 // myImportedBlock(); // import and invoke the closure
4379 // };
4380 //
4381 if (isTopLevelBlockPointerType((*I)->getType())) {
4382 S += "struct __block_impl *";
4383 Constructor += ", void *" + ArgName;
4384 } else {
4385 QualType QT = (*I)->getType();
4386 if (HasLocalVariableExternalStorage(*I))
4387 QT = Context->getPointerType(QT);
4388 QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
4389 QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
4390 Constructor += ", " + ArgName;
4391 }
4392 S += FieldName + ";\n";
4393 }
4394 // Output all "by ref" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00004395 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004396 E = BlockByRefDecls.end(); I != E; ++I) {
4397 S += " ";
4398 std::string FieldName = (*I)->getNameAsString();
4399 std::string ArgName = "_" + FieldName;
4400 {
4401 std::string TypeString;
4402 RewriteByRefString(TypeString, FieldName, (*I));
4403 TypeString += " *";
4404 FieldName = TypeString + FieldName;
4405 ArgName = TypeString + ArgName;
4406 Constructor += ", " + ArgName;
4407 }
4408 S += FieldName + "; // by ref\n";
4409 }
4410 // Finish writing the constructor.
4411 Constructor += ", int flags=0)";
4412 // Initialize all "by copy" arguments.
4413 bool firsTime = true;
Craig Topper09d19ef2013-07-04 03:08:24 +00004414 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004415 E = BlockByCopyDecls.end(); I != E; ++I) {
4416 std::string Name = (*I)->getNameAsString();
4417 if (firsTime) {
4418 Constructor += " : ";
4419 firsTime = false;
4420 }
4421 else
4422 Constructor += ", ";
4423 if (isTopLevelBlockPointerType((*I)->getType()))
4424 Constructor += Name + "((struct __block_impl *)_" + Name + ")";
4425 else
4426 Constructor += Name + "(_" + Name + ")";
4427 }
4428 // Initialize all "by ref" arguments.
Craig Topper09d19ef2013-07-04 03:08:24 +00004429 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004430 E = BlockByRefDecls.end(); I != E; ++I) {
4431 std::string Name = (*I)->getNameAsString();
4432 if (firsTime) {
4433 Constructor += " : ";
4434 firsTime = false;
4435 }
4436 else
4437 Constructor += ", ";
4438 Constructor += Name + "(_" + Name + "->__forwarding)";
4439 }
4440
4441 Constructor += " {\n";
4442 if (GlobalVarDecl)
4443 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4444 else
4445 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4446 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4447
4448 Constructor += " Desc = desc;\n";
4449 } else {
4450 // Finish writing the constructor.
4451 Constructor += ", int flags=0) {\n";
4452 if (GlobalVarDecl)
4453 Constructor += " impl.isa = &_NSConcreteGlobalBlock;\n";
4454 else
4455 Constructor += " impl.isa = &_NSConcreteStackBlock;\n";
4456 Constructor += " impl.Flags = flags;\n impl.FuncPtr = fp;\n";
4457 Constructor += " Desc = desc;\n";
4458 }
4459 Constructor += " ";
4460 Constructor += "}\n";
4461 S += Constructor;
4462 S += "};\n";
4463 return S;
4464}
4465
4466std::string RewriteModernObjC::SynthesizeBlockDescriptor(std::string DescTag,
4467 std::string ImplTag, int i,
4468 StringRef FunName,
4469 unsigned hasCopy) {
4470 std::string S = "\nstatic struct " + DescTag;
4471
Fariborz Jahanian8b08adb2012-05-03 21:44:12 +00004472 S += " {\n size_t reserved;\n";
4473 S += " size_t Block_size;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004474 if (hasCopy) {
4475 S += " void (*copy)(struct ";
4476 S += ImplTag; S += "*, struct ";
4477 S += ImplTag; S += "*);\n";
4478
4479 S += " void (*dispose)(struct ";
4480 S += ImplTag; S += "*);\n";
4481 }
4482 S += "} ";
4483
4484 S += DescTag + "_DATA = { 0, sizeof(struct ";
4485 S += ImplTag + ")";
4486 if (hasCopy) {
4487 S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
4488 S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
4489 }
4490 S += "};\n";
4491 return S;
4492}
4493
4494void RewriteModernObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
4495 StringRef FunName) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004496 bool RewriteSC = (GlobalVarDecl &&
4497 !Blocks.empty() &&
4498 GlobalVarDecl->getStorageClass() == SC_Static &&
4499 GlobalVarDecl->getType().getCVRQualifiers());
4500 if (RewriteSC) {
4501 std::string SC(" void __");
4502 SC += GlobalVarDecl->getNameAsString();
4503 SC += "() {}";
4504 InsertText(FunLocStart, SC);
4505 }
4506
4507 // Insert closures that were part of the function.
4508 for (unsigned i = 0, count=0; i < Blocks.size(); i++) {
4509 CollectBlockDeclRefInfo(Blocks[i]);
4510 // Need to copy-in the inner copied-in variables not actually used in this
4511 // block.
4512 for (int j = 0; j < InnerDeclRefsCount[i]; j++) {
John McCallf4b88a42012-03-10 09:33:50 +00004513 DeclRefExpr *Exp = InnerDeclRefs[count++];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004514 ValueDecl *VD = Exp->getDecl();
4515 BlockDeclRefs.push_back(Exp);
John McCallf4b88a42012-03-10 09:33:50 +00004516 if (!VD->hasAttr<BlocksAttr>()) {
4517 if (!BlockByCopyDeclsPtrSet.count(VD)) {
4518 BlockByCopyDeclsPtrSet.insert(VD);
4519 BlockByCopyDecls.push_back(VD);
4520 }
4521 continue;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004522 }
John McCallf4b88a42012-03-10 09:33:50 +00004523
4524 if (!BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004525 BlockByRefDeclsPtrSet.insert(VD);
4526 BlockByRefDecls.push_back(VD);
4527 }
John McCallf4b88a42012-03-10 09:33:50 +00004528
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004529 // imported objects in the inner blocks not used in the outer
4530 // blocks must be copied/disposed in the outer block as well.
John McCallf4b88a42012-03-10 09:33:50 +00004531 if (VD->getType()->isObjCObjectPointerType() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004532 VD->getType()->isBlockPointerType())
4533 ImportedBlockDecls.insert(VD);
4534 }
4535
4536 std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
4537 std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
4538
4539 std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
4540
4541 InsertText(FunLocStart, CI);
4542
4543 std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
4544
4545 InsertText(FunLocStart, CF);
4546
4547 if (ImportedBlockDecls.size()) {
4548 std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
4549 InsertText(FunLocStart, HF);
4550 }
4551 std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
4552 ImportedBlockDecls.size() > 0);
4553 InsertText(FunLocStart, BD);
4554
4555 BlockDeclRefs.clear();
4556 BlockByRefDecls.clear();
4557 BlockByRefDeclsPtrSet.clear();
4558 BlockByCopyDecls.clear();
4559 BlockByCopyDeclsPtrSet.clear();
4560 ImportedBlockDecls.clear();
4561 }
4562 if (RewriteSC) {
4563 // Must insert any 'const/volatile/static here. Since it has been
4564 // removed as result of rewriting of block literals.
4565 std::string SC;
4566 if (GlobalVarDecl->getStorageClass() == SC_Static)
4567 SC = "static ";
4568 if (GlobalVarDecl->getType().isConstQualified())
4569 SC += "const ";
4570 if (GlobalVarDecl->getType().isVolatileQualified())
4571 SC += "volatile ";
4572 if (GlobalVarDecl->getType().isRestrictQualified())
4573 SC += "restrict ";
4574 InsertText(FunLocStart, SC);
4575 }
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004576 if (GlobalConstructionExp) {
4577 // extra fancy dance for global literal expression.
4578
4579 // Always the latest block expression on the block stack.
4580 std::string Tag = "__";
4581 Tag += FunName;
4582 Tag += "_block_impl_";
4583 Tag += utostr(Blocks.size()-1);
4584 std::string globalBuf = "static ";
4585 globalBuf += Tag; globalBuf += " ";
4586 std::string SStr;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004587
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004588 llvm::raw_string_ostream constructorExprBuf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00004589 GlobalConstructionExp->printPretty(constructorExprBuf, 0,
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00004590 PrintingPolicy(LangOpts));
4591 globalBuf += constructorExprBuf.str();
4592 globalBuf += ";\n";
4593 InsertText(FunLocStart, globalBuf);
4594 GlobalConstructionExp = 0;
4595 }
4596
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004597 Blocks.clear();
4598 InnerDeclRefsCount.clear();
4599 InnerDeclRefs.clear();
4600 RewrittenBlockExprs.clear();
4601}
4602
4603void RewriteModernObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
Fariborz Jahanian04189532012-04-25 17:56:48 +00004604 SourceLocation FunLocStart =
4605 (!Blocks.empty()) ? getFunctionSourceLocation(*this, FD)
4606 : FD->getTypeSpecStartLoc();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004607 StringRef FuncName = FD->getName();
4608
4609 SynthesizeBlockLiterals(FunLocStart, FuncName);
4610}
4611
4612static void BuildUniqueMethodName(std::string &Name,
4613 ObjCMethodDecl *MD) {
4614 ObjCInterfaceDecl *IFace = MD->getClassInterface();
4615 Name = IFace->getName();
4616 Name += "__" + MD->getSelector().getAsString();
4617 // Convert colons to underscores.
4618 std::string::size_type loc = 0;
4619 while ((loc = Name.find(":", loc)) != std::string::npos)
4620 Name.replace(loc, 1, "_");
4621}
4622
4623void RewriteModernObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
4624 //fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
4625 //SourceLocation FunLocStart = MD->getLocStart();
4626 SourceLocation FunLocStart = MD->getLocStart();
4627 std::string FuncName;
4628 BuildUniqueMethodName(FuncName, MD);
4629 SynthesizeBlockLiterals(FunLocStart, FuncName);
4630}
4631
4632void RewriteModernObjC::GetBlockDeclRefExprs(Stmt *S) {
4633 for (Stmt::child_range CI = S->children(); CI; ++CI)
4634 if (*CI) {
4635 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI))
4636 GetBlockDeclRefExprs(CBE->getBody());
4637 else
4638 GetBlockDeclRefExprs(*CI);
4639 }
4640 // Handle specific things.
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004641 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4642 if (DRE->refersToEnclosingLocal()) {
4643 // FIXME: Handle enums.
4644 if (!isa<FunctionDecl>(DRE->getDecl()))
4645 BlockDeclRefs.push_back(DRE);
4646 if (HasLocalVariableExternalStorage(DRE->getDecl()))
4647 BlockDeclRefs.push_back(DRE);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004648 }
Fariborz Jahanian0e976812012-04-16 23:00:57 +00004649 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004650
4651 return;
4652}
4653
Craig Topper6b9240e2013-07-05 19:34:19 +00004654void RewriteModernObjC::GetInnerBlockDeclRefExprs(Stmt *S,
4655 SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004656 llvm::SmallPtrSet<const DeclContext *, 8> &InnerContexts) {
4657 for (Stmt::child_range CI = S->children(); CI; ++CI)
4658 if (*CI) {
4659 if (BlockExpr *CBE = dyn_cast<BlockExpr>(*CI)) {
4660 InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
4661 GetInnerBlockDeclRefExprs(CBE->getBody(),
4662 InnerBlockDeclRefs,
4663 InnerContexts);
4664 }
4665 else
4666 GetInnerBlockDeclRefExprs(*CI,
4667 InnerBlockDeclRefs,
4668 InnerContexts);
4669
4670 }
4671 // Handle specific things.
John McCallf4b88a42012-03-10 09:33:50 +00004672 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4673 if (DRE->refersToEnclosingLocal()) {
4674 if (!isa<FunctionDecl>(DRE->getDecl()) &&
4675 !InnerContexts.count(DRE->getDecl()->getDeclContext()))
4676 InnerBlockDeclRefs.push_back(DRE);
4677 if (VarDecl *Var = dyn_cast<VarDecl>(DRE->getDecl()))
4678 if (Var->isFunctionOrMethodVarDecl())
4679 ImportedLocalExternalDecls.insert(Var);
4680 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004681 }
4682
4683 return;
4684}
4685
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004686/// convertObjCTypeToCStyleType - This routine converts such objc types
4687/// as qualified objects, and blocks to their closest c/c++ types that
4688/// it can. It returns true if input type was modified.
4689bool RewriteModernObjC::convertObjCTypeToCStyleType(QualType &T) {
4690 QualType oldT = T;
4691 convertBlockPointerToFunctionPointer(T);
4692 if (T->isFunctionPointerType()) {
4693 QualType PointeeTy;
4694 if (const PointerType* PT = T->getAs<PointerType>()) {
4695 PointeeTy = PT->getPointeeType();
4696 if (const FunctionType *FT = PointeeTy->getAs<FunctionType>()) {
4697 T = convertFunctionTypeOfBlocks(FT);
4698 T = Context->getPointerType(T);
4699 }
4700 }
4701 }
4702
4703 convertToUnqualifiedObjCType(T);
4704 return T != oldT;
4705}
4706
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004707/// convertFunctionTypeOfBlocks - This routine converts a function type
4708/// whose result type may be a block pointer or whose argument type(s)
4709/// might be block pointers to an equivalent function type replacing
4710/// all block pointers to function pointers.
4711QualType RewriteModernObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
4712 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4713 // FTP will be null for closures that don't take arguments.
4714 // Generate a funky cast.
4715 SmallVector<QualType, 8> ArgTypes;
4716 QualType Res = FT->getResultType();
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004717 bool modified = convertObjCTypeToCStyleType(Res);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004718
4719 if (FTP) {
4720 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4721 E = FTP->arg_type_end(); I && (I != E); ++I) {
4722 QualType t = *I;
4723 // Make sure we convert "t (^)(...)" to "t (*)(...)".
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004724 if (convertObjCTypeToCStyleType(t))
4725 modified = true;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004726 ArgTypes.push_back(t);
4727 }
4728 }
4729 QualType FuncType;
Fariborz Jahanian164d6f82012-02-13 18:57:49 +00004730 if (modified)
Jordan Rosebea522f2013-03-08 21:51:21 +00004731 FuncType = getSimpleFunctionType(Res, ArgTypes);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004732 else FuncType = QualType(FT, 0);
4733 return FuncType;
4734}
4735
4736Stmt *RewriteModernObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
4737 // Navigate to relevant type information.
4738 const BlockPointerType *CPT = 0;
4739
4740 if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
4741 CPT = DRE->getType()->getAs<BlockPointerType>();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004742 } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
4743 CPT = MExpr->getType()->getAs<BlockPointerType>();
4744 }
4745 else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
4746 return SynthesizeBlockCall(Exp, PRE->getSubExpr());
4747 }
4748 else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
4749 CPT = IEXPR->getType()->getAs<BlockPointerType>();
4750 else if (const ConditionalOperator *CEXPR =
4751 dyn_cast<ConditionalOperator>(BlockExp)) {
4752 Expr *LHSExp = CEXPR->getLHS();
4753 Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
4754 Expr *RHSExp = CEXPR->getRHS();
4755 Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
4756 Expr *CONDExp = CEXPR->getCond();
4757 ConditionalOperator *CondExpr =
4758 new (Context) ConditionalOperator(CONDExp,
4759 SourceLocation(), cast<Expr>(LHSStmt),
4760 SourceLocation(), cast<Expr>(RHSStmt),
4761 Exp->getType(), VK_RValue, OK_Ordinary);
4762 return CondExpr;
4763 } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
4764 CPT = IRE->getType()->getAs<BlockPointerType>();
4765 } else if (const PseudoObjectExpr *POE
4766 = dyn_cast<PseudoObjectExpr>(BlockExp)) {
4767 CPT = POE->getType()->castAs<BlockPointerType>();
4768 } else {
4769 assert(1 && "RewriteBlockClass: Bad type");
4770 }
4771 assert(CPT && "RewriteBlockClass: Bad type");
4772 const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
4773 assert(FT && "RewriteBlockClass: Bad type");
4774 const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
4775 // FTP will be null for closures that don't take arguments.
4776
4777 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4778 SourceLocation(), SourceLocation(),
4779 &Context->Idents.get("__block_impl"));
4780 QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
4781
4782 // Generate a funky cast.
4783 SmallVector<QualType, 8> ArgTypes;
4784
4785 // Push the block argument type.
4786 ArgTypes.push_back(PtrBlock);
4787 if (FTP) {
4788 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
4789 E = FTP->arg_type_end(); I && (I != E); ++I) {
4790 QualType t = *I;
4791 // Make sure we convert "t (^)(...)" to "t (*)(...)".
4792 if (!convertBlockPointerToFunctionPointer(t))
4793 convertToUnqualifiedObjCType(t);
4794 ArgTypes.push_back(t);
4795 }
4796 }
4797 // Now do the pointer to function cast.
Jordan Rosebea522f2013-03-08 21:51:21 +00004798 QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004799
4800 PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
4801
4802 CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
4803 CK_BitCast,
4804 const_cast<Expr*>(BlockExp));
4805 // Don't forget the parens to enforce the proper binding.
4806 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4807 BlkCast);
4808 //PE->dump();
4809
4810 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4811 SourceLocation(),
4812 &Context->Idents.get("FuncPtr"),
4813 Context->VoidPtrTy, 0,
4814 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004815 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004816 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
4817 FD->getType(), VK_LValue,
4818 OK_Ordinary);
4819
4820
4821 CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
4822 CK_BitCast, ME);
4823 PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
4824
4825 SmallVector<Expr*, 8> BlkExprs;
4826 // Add the implicit argument.
4827 BlkExprs.push_back(BlkCast);
4828 // Add the user arguments.
4829 for (CallExpr::arg_iterator I = Exp->arg_begin(),
4830 E = Exp->arg_end(); I != E; ++I) {
4831 BlkExprs.push_back(*I);
4832 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00004833 CallExpr *CE = new (Context) CallExpr(*Context, PE, BlkExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004834 Exp->getType(), VK_RValue,
4835 SourceLocation());
4836 return CE;
4837}
4838
4839// We need to return the rewritten expression to handle cases where the
John McCallf4b88a42012-03-10 09:33:50 +00004840// DeclRefExpr is embedded in another expression being rewritten.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004841// For example:
4842//
4843// int main() {
4844// __block Foo *f;
4845// __block int i;
4846//
4847// void (^myblock)() = ^() {
John McCallf4b88a42012-03-10 09:33:50 +00004848// [f test]; // f is a DeclRefExpr embedded in a message (which is being rewritten).
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004849// i = 77;
4850// };
4851//}
John McCallf4b88a42012-03-10 09:33:50 +00004852Stmt *RewriteModernObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004853 // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
4854 // for each DeclRefExp where BYREFVAR is name of the variable.
John McCallf4b88a42012-03-10 09:33:50 +00004855 ValueDecl *VD = DeclRefExp->getDecl();
4856 bool isArrow = DeclRefExp->refersToEnclosingLocal();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004857
4858 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
4859 SourceLocation(),
4860 &Context->Idents.get("__forwarding"),
4861 Context->VoidPtrTy, 0,
4862 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004863 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004864 MemberExpr *ME = new (Context) MemberExpr(DeclRefExp, isArrow,
4865 FD, SourceLocation(),
4866 FD->getType(), VK_LValue,
4867 OK_Ordinary);
4868
4869 StringRef Name = VD->getName();
4870 FD = FieldDecl::Create(*Context, 0, SourceLocation(), SourceLocation(),
4871 &Context->Idents.get(Name),
4872 Context->VoidPtrTy, 0,
4873 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00004874 ICIS_NoInit);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004875 ME = new (Context) MemberExpr(ME, true, FD, SourceLocation(),
4876 DeclRefExp->getType(), VK_LValue, OK_Ordinary);
4877
4878
4879
4880 // Need parens to enforce precedence.
4881 ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
4882 DeclRefExp->getExprLoc(),
4883 ME);
4884 ReplaceStmt(DeclRefExp, PE);
4885 return PE;
4886}
4887
4888// Rewrites the imported local variable V with external storage
4889// (static, extern, etc.) as *V
4890//
4891Stmt *RewriteModernObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
4892 ValueDecl *VD = DRE->getDecl();
4893 if (VarDecl *Var = dyn_cast<VarDecl>(VD))
4894 if (!ImportedLocalExternalDecls.count(Var))
4895 return DRE;
4896 Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
4897 VK_LValue, OK_Ordinary,
4898 DRE->getLocation());
4899 // Need parens to enforce precedence.
4900 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
4901 Exp);
4902 ReplaceStmt(DRE, PE);
4903 return PE;
4904}
4905
4906void RewriteModernObjC::RewriteCastExpr(CStyleCastExpr *CE) {
4907 SourceLocation LocStart = CE->getLParenLoc();
4908 SourceLocation LocEnd = CE->getRParenLoc();
4909
4910 // Need to avoid trying to rewrite synthesized casts.
4911 if (LocStart.isInvalid())
4912 return;
4913 // Need to avoid trying to rewrite casts contained in macros.
4914 if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
4915 return;
4916
4917 const char *startBuf = SM->getCharacterData(LocStart);
4918 const char *endBuf = SM->getCharacterData(LocEnd);
4919 QualType QT = CE->getType();
4920 const Type* TypePtr = QT->getAs<Type>();
4921 if (isa<TypeOfExprType>(TypePtr)) {
4922 const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
4923 QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
4924 std::string TypeAsString = "(";
4925 RewriteBlockPointerType(TypeAsString, QT);
4926 TypeAsString += ")";
4927 ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
4928 return;
4929 }
4930 // advance the location to startArgList.
4931 const char *argPtr = startBuf;
4932
4933 while (*argPtr++ && (argPtr < endBuf)) {
4934 switch (*argPtr) {
4935 case '^':
4936 // Replace the '^' with '*'.
4937 LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
4938 ReplaceText(LocStart, 1, "*");
4939 break;
4940 }
4941 }
4942 return;
4943}
4944
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004945void RewriteModernObjC::RewriteImplicitCastObjCExpr(CastExpr *IC) {
4946 CastKind CastKind = IC->getCastKind();
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004947 if (CastKind != CK_BlockPointerToObjCPointerCast &&
4948 CastKind != CK_AnyPointerToBlockPointerCast)
4949 return;
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004950
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00004951 QualType QT = IC->getType();
4952 (void)convertBlockPointerToFunctionPointer(QT);
4953 std::string TypeString(QT.getAsString(Context->getPrintingPolicy()));
4954 std::string Str = "(";
4955 Str += TypeString;
4956 Str += ")";
4957 InsertText(IC->getSubExpr()->getLocStart(), &Str[0], Str.size());
4958
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00004959 return;
4960}
4961
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00004962void RewriteModernObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
4963 SourceLocation DeclLoc = FD->getLocation();
4964 unsigned parenCount = 0;
4965
4966 // We have 1 or more arguments that have closure pointers.
4967 const char *startBuf = SM->getCharacterData(DeclLoc);
4968 const char *startArgList = strchr(startBuf, '(');
4969
4970 assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
4971
4972 parenCount++;
4973 // advance the location to startArgList.
4974 DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
4975 assert((DeclLoc.isValid()) && "Invalid DeclLoc");
4976
4977 const char *argPtr = startArgList;
4978
4979 while (*argPtr++ && parenCount) {
4980 switch (*argPtr) {
4981 case '^':
4982 // Replace the '^' with '*'.
4983 DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
4984 ReplaceText(DeclLoc, 1, "*");
4985 break;
4986 case '(':
4987 parenCount++;
4988 break;
4989 case ')':
4990 parenCount--;
4991 break;
4992 }
4993 }
4994 return;
4995}
4996
4997bool RewriteModernObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
4998 const FunctionProtoType *FTP;
4999 const PointerType *PT = QT->getAs<PointerType>();
5000 if (PT) {
5001 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
5002 } else {
5003 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5004 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5005 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5006 }
5007 if (FTP) {
5008 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
5009 E = FTP->arg_type_end(); I != E; ++I)
5010 if (isTopLevelBlockPointerType(*I))
5011 return true;
5012 }
5013 return false;
5014}
5015
5016bool RewriteModernObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
5017 const FunctionProtoType *FTP;
5018 const PointerType *PT = QT->getAs<PointerType>();
5019 if (PT) {
5020 FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
5021 } else {
5022 const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
5023 assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
5024 FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
5025 }
5026 if (FTP) {
5027 for (FunctionProtoType::arg_type_iterator I = FTP->arg_type_begin(),
5028 E = FTP->arg_type_end(); I != E; ++I) {
5029 if ((*I)->isObjCQualifiedIdType())
5030 return true;
5031 if ((*I)->isObjCObjectPointerType() &&
5032 (*I)->getPointeeType()->isObjCQualifiedInterfaceType())
5033 return true;
5034 }
5035
5036 }
5037 return false;
5038}
5039
5040void RewriteModernObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
5041 const char *&RParen) {
5042 const char *argPtr = strchr(Name, '(');
5043 assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
5044
5045 LParen = argPtr; // output the start.
5046 argPtr++; // skip past the left paren.
5047 unsigned parenCount = 1;
5048
5049 while (*argPtr && parenCount) {
5050 switch (*argPtr) {
5051 case '(': parenCount++; break;
5052 case ')': parenCount--; break;
5053 default: break;
5054 }
5055 if (parenCount) argPtr++;
5056 }
5057 assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
5058 RParen = argPtr; // output the end
5059}
5060
5061void RewriteModernObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
5062 if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
5063 RewriteBlockPointerFunctionArgs(FD);
5064 return;
5065 }
5066 // Handle Variables and Typedefs.
5067 SourceLocation DeclLoc = ND->getLocation();
5068 QualType DeclT;
5069 if (VarDecl *VD = dyn_cast<VarDecl>(ND))
5070 DeclT = VD->getType();
5071 else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
5072 DeclT = TDD->getUnderlyingType();
5073 else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
5074 DeclT = FD->getType();
5075 else
5076 llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
5077
5078 const char *startBuf = SM->getCharacterData(DeclLoc);
5079 const char *endBuf = startBuf;
5080 // scan backward (from the decl location) for the end of the previous decl.
5081 while (*startBuf != '^' && *startBuf != ';' && startBuf != MainFileStart)
5082 startBuf--;
5083 SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
5084 std::string buf;
5085 unsigned OrigLength=0;
5086 // *startBuf != '^' if we are dealing with a pointer to function that
5087 // may take block argument types (which will be handled below).
5088 if (*startBuf == '^') {
5089 // Replace the '^' with '*', computing a negative offset.
5090 buf = '*';
5091 startBuf++;
5092 OrigLength++;
5093 }
5094 while (*startBuf != ')') {
5095 buf += *startBuf;
5096 startBuf++;
5097 OrigLength++;
5098 }
5099 buf += ')';
5100 OrigLength++;
5101
5102 if (PointerTypeTakesAnyBlockArguments(DeclT) ||
5103 PointerTypeTakesAnyObjCQualifiedType(DeclT)) {
5104 // Replace the '^' with '*' for arguments.
5105 // Replace id<P> with id/*<>*/
5106 DeclLoc = ND->getLocation();
5107 startBuf = SM->getCharacterData(DeclLoc);
5108 const char *argListBegin, *argListEnd;
5109 GetExtentOfArgList(startBuf, argListBegin, argListEnd);
5110 while (argListBegin < argListEnd) {
5111 if (*argListBegin == '^')
5112 buf += '*';
5113 else if (*argListBegin == '<') {
5114 buf += "/*";
5115 buf += *argListBegin++;
Dmitri Gribenko1ad23d62012-09-10 21:20:09 +00005116 OrigLength++;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005117 while (*argListBegin != '>') {
5118 buf += *argListBegin++;
5119 OrigLength++;
5120 }
5121 buf += *argListBegin;
5122 buf += "*/";
5123 }
5124 else
5125 buf += *argListBegin;
5126 argListBegin++;
5127 OrigLength++;
5128 }
5129 buf += ')';
5130 OrigLength++;
5131 }
5132 ReplaceText(Start, OrigLength, buf);
5133
5134 return;
5135}
5136
5137
5138/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
5139/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
5140/// struct Block_byref_id_object *src) {
5141/// _Block_object_assign (&_dest->object, _src->object,
5142/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5143/// [|BLOCK_FIELD_IS_WEAK]) // object
5144/// _Block_object_assign(&_dest->object, _src->object,
5145/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5146/// [|BLOCK_FIELD_IS_WEAK]) // block
5147/// }
5148/// And:
5149/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
5150/// _Block_object_dispose(_src->object,
5151/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
5152/// [|BLOCK_FIELD_IS_WEAK]) // object
5153/// _Block_object_dispose(_src->object,
5154/// BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
5155/// [|BLOCK_FIELD_IS_WEAK]) // block
5156/// }
5157
5158std::string RewriteModernObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
5159 int flag) {
5160 std::string S;
5161 if (CopyDestroyCache.count(flag))
5162 return S;
5163 CopyDestroyCache.insert(flag);
5164 S = "static void __Block_byref_id_object_copy_";
5165 S += utostr(flag);
5166 S += "(void *dst, void *src) {\n";
5167
5168 // offset into the object pointer is computed as:
5169 // void * + void* + int + int + void* + void *
5170 unsigned IntSize =
5171 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5172 unsigned VoidPtrSize =
5173 static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
5174
5175 unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
5176 S += " _Block_object_assign((char*)dst + ";
5177 S += utostr(offset);
5178 S += ", *(void * *) ((char*)src + ";
5179 S += utostr(offset);
5180 S += "), ";
5181 S += utostr(flag);
5182 S += ");\n}\n";
5183
5184 S += "static void __Block_byref_id_object_dispose_";
5185 S += utostr(flag);
5186 S += "(void *src) {\n";
5187 S += " _Block_object_dispose(*(void * *) ((char*)src + ";
5188 S += utostr(offset);
5189 S += "), ";
5190 S += utostr(flag);
5191 S += ");\n}\n";
5192 return S;
5193}
5194
5195/// RewriteByRefVar - For each __block typex ND variable this routine transforms
5196/// the declaration into:
5197/// struct __Block_byref_ND {
5198/// void *__isa; // NULL for everything except __weak pointers
5199/// struct __Block_byref_ND *__forwarding;
5200/// int32_t __flags;
5201/// int32_t __size;
5202/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
5203/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
5204/// typex ND;
5205/// };
5206///
5207/// It then replaces declaration of ND variable with:
5208/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
5209/// __size=sizeof(struct __Block_byref_ND),
5210/// ND=initializer-if-any};
5211///
5212///
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005213void RewriteModernObjC::RewriteByRefVar(VarDecl *ND, bool firstDecl,
5214 bool lastDecl) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005215 int flag = 0;
5216 int isa = 0;
5217 SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
5218 if (DeclLoc.isInvalid())
5219 // If type location is missing, it is because of missing type (a warning).
5220 // Use variable's location which is good for this case.
5221 DeclLoc = ND->getLocation();
5222 const char *startBuf = SM->getCharacterData(DeclLoc);
5223 SourceLocation X = ND->getLocEnd();
5224 X = SM->getExpansionLoc(X);
5225 const char *endBuf = SM->getCharacterData(X);
5226 std::string Name(ND->getNameAsString());
5227 std::string ByrefType;
5228 RewriteByRefString(ByrefType, Name, ND, true);
5229 ByrefType += " {\n";
5230 ByrefType += " void *__isa;\n";
5231 RewriteByRefString(ByrefType, Name, ND);
5232 ByrefType += " *__forwarding;\n";
5233 ByrefType += " int __flags;\n";
5234 ByrefType += " int __size;\n";
5235 // Add void *__Block_byref_id_object_copy;
5236 // void *__Block_byref_id_object_dispose; if needed.
5237 QualType Ty = ND->getType();
Fariborz Jahanianb15c8982012-11-28 23:12:17 +00005238 bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005239 if (HasCopyAndDispose) {
5240 ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
5241 ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
5242 }
5243
5244 QualType T = Ty;
5245 (void)convertBlockPointerToFunctionPointer(T);
5246 T.getAsStringInternal(Name, Context->getPrintingPolicy());
5247
5248 ByrefType += " " + Name + ";\n";
5249 ByrefType += "};\n";
5250 // Insert this type in global scope. It is needed by helper function.
5251 SourceLocation FunLocStart;
5252 if (CurFunctionDef)
Fariborz Jahanianb75f8de2012-04-19 00:50:01 +00005253 FunLocStart = getFunctionSourceLocation(*this, CurFunctionDef);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005254 else {
5255 assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
5256 FunLocStart = CurMethodDef->getLocStart();
5257 }
5258 InsertText(FunLocStart, ByrefType);
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005259
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005260 if (Ty.isObjCGCWeak()) {
5261 flag |= BLOCK_FIELD_IS_WEAK;
5262 isa = 1;
5263 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005264 if (HasCopyAndDispose) {
5265 flag = BLOCK_BYREF_CALLER;
5266 QualType Ty = ND->getType();
5267 // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
5268 if (Ty->isBlockPointerType())
5269 flag |= BLOCK_FIELD_IS_BLOCK;
5270 else
5271 flag |= BLOCK_FIELD_IS_OBJECT;
5272 std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
5273 if (!HF.empty())
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00005274 Preamble += HF;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005275 }
5276
5277 // struct __Block_byref_ND ND =
5278 // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
5279 // initializer-if-any};
5280 bool hasInit = (ND->getInit() != 0);
Fariborz Jahanian104dbf92012-04-11 23:57:12 +00005281 // FIXME. rewriter does not support __block c++ objects which
5282 // require construction.
Fariborz Jahanian65a7c682012-04-26 23:20:25 +00005283 if (hasInit)
5284 if (CXXConstructExpr *CExp = dyn_cast<CXXConstructExpr>(ND->getInit())) {
5285 CXXConstructorDecl *CXXDecl = CExp->getConstructor();
5286 if (CXXDecl && CXXDecl->isDefaultConstructor())
5287 hasInit = false;
5288 }
5289
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005290 unsigned flags = 0;
5291 if (HasCopyAndDispose)
5292 flags |= BLOCK_HAS_COPY_DISPOSE;
5293 Name = ND->getNameAsString();
5294 ByrefType.clear();
5295 RewriteByRefString(ByrefType, Name, ND);
5296 std::string ForwardingCastType("(");
5297 ForwardingCastType += ByrefType + " *)";
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005298 ByrefType += " " + Name + " = {(void*)";
5299 ByrefType += utostr(isa);
5300 ByrefType += "," + ForwardingCastType + "&" + Name + ", ";
5301 ByrefType += utostr(flags);
5302 ByrefType += ", ";
5303 ByrefType += "sizeof(";
5304 RewriteByRefString(ByrefType, Name, ND);
5305 ByrefType += ")";
5306 if (HasCopyAndDispose) {
5307 ByrefType += ", __Block_byref_id_object_copy_";
5308 ByrefType += utostr(flag);
5309 ByrefType += ", __Block_byref_id_object_dispose_";
5310 ByrefType += utostr(flag);
5311 }
5312
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005313 if (!firstDecl) {
5314 // In multiple __block declarations, and for all but 1st declaration,
5315 // find location of the separating comma. This would be start location
5316 // where new text is to be inserted.
5317 DeclLoc = ND->getLocation();
5318 const char *startDeclBuf = SM->getCharacterData(DeclLoc);
5319 const char *commaBuf = startDeclBuf;
5320 while (*commaBuf != ',')
5321 commaBuf--;
5322 assert((*commaBuf == ',') && "RewriteByRefVar: can't find ','");
5323 DeclLoc = DeclLoc.getLocWithOffset(commaBuf - startDeclBuf);
5324 startBuf = commaBuf;
5325 }
5326
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005327 if (!hasInit) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005328 ByrefType += "};\n";
5329 unsigned nameSize = Name.size();
5330 // for block or function pointer declaration. Name is aleady
5331 // part of the declaration.
5332 if (Ty->isBlockPointerType() || Ty->isFunctionPointerType())
5333 nameSize = 1;
5334 ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
5335 }
5336 else {
Fariborz Jahanian8247c4e2012-04-24 16:45:27 +00005337 ByrefType += ", ";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005338 SourceLocation startLoc;
5339 Expr *E = ND->getInit();
5340 if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
5341 startLoc = ECE->getLParenLoc();
5342 else
5343 startLoc = E->getLocStart();
5344 startLoc = SM->getExpansionLoc(startLoc);
5345 endBuf = SM->getCharacterData(startLoc);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005346 ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005347
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005348 const char separator = lastDecl ? ';' : ',';
5349 const char *startInitializerBuf = SM->getCharacterData(startLoc);
5350 const char *separatorBuf = strchr(startInitializerBuf, separator);
5351 assert((*separatorBuf == separator) &&
5352 "RewriteByRefVar: can't find ';' or ','");
5353 SourceLocation separatorLoc =
5354 startLoc.getLocWithOffset(separatorBuf-startInitializerBuf);
5355
5356 InsertText(separatorLoc, lastDecl ? "}" : "};\n");
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005357 }
5358 return;
5359}
5360
5361void RewriteModernObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
5362 // Add initializers for any closure decl refs.
5363 GetBlockDeclRefExprs(Exp->getBody());
5364 if (BlockDeclRefs.size()) {
5365 // Unique all "by copy" declarations.
5366 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005367 if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005368 if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5369 BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5370 BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
5371 }
5372 }
5373 // Unique all "by ref" declarations.
5374 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005375 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005376 if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
5377 BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
5378 BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
5379 }
5380 }
5381 // Find any imported blocks...they will need special attention.
5382 for (unsigned i = 0; i < BlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005383 if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005384 BlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5385 BlockDeclRefs[i]->getType()->isBlockPointerType())
5386 ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
5387 }
5388}
5389
5390FunctionDecl *RewriteModernObjC::SynthBlockInitFunctionDecl(StringRef name) {
5391 IdentifierInfo *ID = &Context->Idents.get(name);
5392 QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
5393 return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
5394 SourceLocation(), ID, FType, 0, SC_Extern,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00005395 false, false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005396}
5397
5398Stmt *RewriteModernObjC::SynthBlockInitExpr(BlockExpr *Exp,
Craig Topper6b9240e2013-07-05 19:34:19 +00005399 const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005400
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005401 const BlockDecl *block = Exp->getBlockDecl();
Fariborz Jahaniand13c2c22012-03-22 19:54:39 +00005402
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005403 Blocks.push_back(Exp);
5404
5405 CollectBlockDeclRefInfo(Exp);
5406
5407 // Add inner imported variables now used in current block.
5408 int countOfInnerDecls = 0;
5409 if (!InnerBlockDeclRefs.empty()) {
5410 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++) {
John McCallf4b88a42012-03-10 09:33:50 +00005411 DeclRefExpr *Exp = InnerBlockDeclRefs[i];
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005412 ValueDecl *VD = Exp->getDecl();
John McCallf4b88a42012-03-10 09:33:50 +00005413 if (!VD->hasAttr<BlocksAttr>() && !BlockByCopyDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005414 // We need to save the copied-in variables in nested
5415 // blocks because it is needed at the end for some of the API generations.
5416 // See SynthesizeBlockLiterals routine.
5417 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5418 BlockDeclRefs.push_back(Exp);
5419 BlockByCopyDeclsPtrSet.insert(VD);
5420 BlockByCopyDecls.push_back(VD);
5421 }
John McCallf4b88a42012-03-10 09:33:50 +00005422 if (VD->hasAttr<BlocksAttr>() && !BlockByRefDeclsPtrSet.count(VD)) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005423 InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
5424 BlockDeclRefs.push_back(Exp);
5425 BlockByRefDeclsPtrSet.insert(VD);
5426 BlockByRefDecls.push_back(VD);
5427 }
5428 }
5429 // Find any imported blocks...they will need special attention.
5430 for (unsigned i = 0; i < InnerBlockDeclRefs.size(); i++)
John McCallf4b88a42012-03-10 09:33:50 +00005431 if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005432 InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType() ||
5433 InnerBlockDeclRefs[i]->getType()->isBlockPointerType())
5434 ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
5435 }
5436 InnerDeclRefsCount.push_back(countOfInnerDecls);
5437
5438 std::string FuncName;
5439
5440 if (CurFunctionDef)
5441 FuncName = CurFunctionDef->getNameAsString();
5442 else if (CurMethodDef)
5443 BuildUniqueMethodName(FuncName, CurMethodDef);
5444 else if (GlobalVarDecl)
5445 FuncName = std::string(GlobalVarDecl->getNameAsString());
5446
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005447 bool GlobalBlockExpr =
5448 block->getDeclContext()->getRedeclContext()->isFileContext();
5449
5450 if (GlobalBlockExpr && !GlobalVarDecl) {
5451 Diags.Report(block->getLocation(), GlobalBlockRewriteFailedDiag);
5452 GlobalBlockExpr = false;
5453 }
5454
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005455 std::string BlockNumber = utostr(Blocks.size()-1);
5456
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005457 std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
5458
5459 // Get a pointer to the function type so we can cast appropriately.
5460 QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
5461 QualType FType = Context->getPointerType(BFT);
5462
5463 FunctionDecl *FD;
5464 Expr *NewRep;
5465
Benjamin Kramere5753592013-09-09 14:48:42 +00005466 // Simulate a constructor call...
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005467 std::string Tag;
5468
5469 if (GlobalBlockExpr)
5470 Tag = "__global_";
5471 else
5472 Tag = "__";
5473 Tag += FuncName + "_block_impl_" + BlockNumber;
5474
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005475 FD = SynthBlockInitFunctionDecl(Tag);
John McCallf4b88a42012-03-10 09:33:50 +00005476 DeclRefExpr *DRE = new (Context) DeclRefExpr(FD, false, FType, VK_RValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005477 SourceLocation());
5478
5479 SmallVector<Expr*, 4> InitExprs;
5480
5481 // Initialize the block function.
5482 FD = SynthBlockInitFunctionDecl(Func);
John McCallf4b88a42012-03-10 09:33:50 +00005483 DeclRefExpr *Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5484 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005485 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5486 CK_BitCast, Arg);
5487 InitExprs.push_back(castExpr);
5488
5489 // Initialize the block descriptor.
5490 std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
5491
5492 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl,
5493 SourceLocation(), SourceLocation(),
5494 &Context->Idents.get(DescData.c_str()),
5495 Context->VoidPtrTy, 0,
Rafael Espindolad2615cc2013-04-03 19:27:57 +00005496 SC_Static);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005497 UnaryOperator *DescRefExpr =
John McCallf4b88a42012-03-10 09:33:50 +00005498 new (Context) UnaryOperator(new (Context) DeclRefExpr(NewVD, false,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005499 Context->VoidPtrTy,
5500 VK_LValue,
5501 SourceLocation()),
5502 UO_AddrOf,
5503 Context->getPointerType(Context->VoidPtrTy),
5504 VK_RValue, OK_Ordinary,
5505 SourceLocation());
5506 InitExprs.push_back(DescRefExpr);
5507
5508 // Add initializers for any closure decl refs.
5509 if (BlockDeclRefs.size()) {
5510 Expr *Exp;
5511 // Output all "by copy" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00005512 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005513 E = BlockByCopyDecls.end(); I != E; ++I) {
5514 if (isObjCType((*I)->getType())) {
5515 // FIXME: Conform to ABI ([[obj retain] autorelease]).
5516 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005517 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5518 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005519 if (HasLocalVariableExternalStorage(*I)) {
5520 QualType QT = (*I)->getType();
5521 QT = Context->getPointerType(QT);
5522 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5523 OK_Ordinary, SourceLocation());
5524 }
5525 } else if (isTopLevelBlockPointerType((*I)->getType())) {
5526 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005527 Arg = new (Context) DeclRefExpr(FD, false, FD->getType(),
5528 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005529 Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy,
5530 CK_BitCast, Arg);
5531 } else {
5532 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005533 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(),
5534 VK_LValue, SourceLocation());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005535 if (HasLocalVariableExternalStorage(*I)) {
5536 QualType QT = (*I)->getType();
5537 QT = Context->getPointerType(QT);
5538 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
5539 OK_Ordinary, SourceLocation());
5540 }
5541
5542 }
5543 InitExprs.push_back(Exp);
5544 }
5545 // Output all "by ref" declarations.
Craig Topper09d19ef2013-07-04 03:08:24 +00005546 for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005547 E = BlockByRefDecls.end(); I != E; ++I) {
5548 ValueDecl *ND = (*I);
5549 std::string Name(ND->getNameAsString());
5550 std::string RecName;
5551 RewriteByRefString(RecName, Name, ND, true);
5552 IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
5553 + sizeof("struct"));
5554 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
5555 SourceLocation(), SourceLocation(),
5556 II);
5557 assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
5558 QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
5559
5560 FD = SynthBlockInitFunctionDecl((*I)->getName());
John McCallf4b88a42012-03-10 09:33:50 +00005561 Exp = new (Context) DeclRefExpr(FD, false, FD->getType(), VK_LValue,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005562 SourceLocation());
5563 bool isNestedCapturedVar = false;
5564 if (block)
5565 for (BlockDecl::capture_const_iterator ci = block->capture_begin(),
5566 ce = block->capture_end(); ci != ce; ++ci) {
5567 const VarDecl *variable = ci->getVariable();
5568 if (variable == ND && ci->isNested()) {
5569 assert (ci->isByRef() &&
5570 "SynthBlockInitExpr - captured block variable is not byref");
5571 isNestedCapturedVar = true;
5572 break;
5573 }
5574 }
5575 // captured nested byref variable has its address passed. Do not take
5576 // its address again.
5577 if (!isNestedCapturedVar)
5578 Exp = new (Context) UnaryOperator(Exp, UO_AddrOf,
5579 Context->getPointerType(Exp->getType()),
5580 VK_RValue, OK_Ordinary, SourceLocation());
5581 Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
5582 InitExprs.push_back(Exp);
5583 }
5584 }
5585 if (ImportedBlockDecls.size()) {
5586 // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
5587 int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
5588 unsigned IntSize =
5589 static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
5590 Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
5591 Context->IntTy, SourceLocation());
5592 InitExprs.push_back(FlagExp);
5593 }
Benjamin Kramer3b6bef92012-08-24 11:54:20 +00005594 NewRep = new (Context) CallExpr(*Context, DRE, InitExprs,
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005595 FType, VK_LValue, SourceLocation());
Fariborz Jahaniandf474ec2012-03-23 00:00:49 +00005596
5597 if (GlobalBlockExpr) {
5598 assert (GlobalConstructionExp == 0 &&
5599 "SynthBlockInitExpr - GlobalConstructionExp must be null");
5600 GlobalConstructionExp = NewRep;
5601 NewRep = DRE;
5602 }
5603
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005604 NewRep = new (Context) UnaryOperator(NewRep, UO_AddrOf,
5605 Context->getPointerType(NewRep->getType()),
5606 VK_RValue, OK_Ordinary, SourceLocation());
5607 NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
5608 NewRep);
5609 BlockDeclRefs.clear();
5610 BlockByRefDecls.clear();
5611 BlockByRefDeclsPtrSet.clear();
5612 BlockByCopyDecls.clear();
5613 BlockByCopyDeclsPtrSet.clear();
5614 ImportedBlockDecls.clear();
5615 return NewRep;
5616}
5617
5618bool RewriteModernObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
5619 if (const ObjCForCollectionStmt * CS =
5620 dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
5621 return CS->getElement() == DS;
5622 return false;
5623}
5624
5625//===----------------------------------------------------------------------===//
5626// Function Body / Expression rewriting
5627//===----------------------------------------------------------------------===//
5628
5629Stmt *RewriteModernObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
5630 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5631 isa<DoStmt>(S) || isa<ForStmt>(S))
5632 Stmts.push_back(S);
5633 else if (isa<ObjCForCollectionStmt>(S)) {
5634 Stmts.push_back(S);
5635 ObjCBcLabelNo.push_back(++BcLabelCount);
5636 }
5637
5638 // Pseudo-object operations and ivar references need special
5639 // treatment because we're going to recursively rewrite them.
5640 if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
5641 if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
5642 return RewritePropertyOrImplicitSetter(PseudoOp);
5643 } else {
5644 return RewritePropertyOrImplicitGetter(PseudoOp);
5645 }
5646 } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
5647 return RewriteObjCIvarRefExpr(IvarRefExpr);
5648 }
Fariborz Jahanian9ffd1ae2013-02-08 18:57:50 +00005649 else if (isa<OpaqueValueExpr>(S))
5650 S = cast<OpaqueValueExpr>(S)->getSourceExpr();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005651
5652 SourceRange OrigStmtRange = S->getSourceRange();
5653
5654 // Perform a bottom up rewrite of all children.
5655 for (Stmt::child_range CI = S->children(); CI; ++CI)
5656 if (*CI) {
5657 Stmt *childStmt = (*CI);
5658 Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
5659 if (newStmt) {
5660 *CI = newStmt;
5661 }
5662 }
5663
5664 if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
John McCallf4b88a42012-03-10 09:33:50 +00005665 SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005666 llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
5667 InnerContexts.insert(BE->getBlockDecl());
5668 ImportedLocalExternalDecls.clear();
5669 GetInnerBlockDeclRefExprs(BE->getBody(),
5670 InnerBlockDeclRefs, InnerContexts);
5671 // Rewrite the block body in place.
5672 Stmt *SaveCurrentBody = CurrentBody;
5673 CurrentBody = BE->getBody();
5674 PropParentMap = 0;
5675 // block literal on rhs of a property-dot-sytax assignment
5676 // must be replaced by its synthesize ast so getRewrittenText
5677 // works as expected. In this case, what actually ends up on RHS
5678 // is the blockTranscribed which is the helper function for the
5679 // block literal; as in: self.c = ^() {[ace ARR];};
5680 bool saveDisableReplaceStmt = DisableReplaceStmt;
5681 DisableReplaceStmt = false;
5682 RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
5683 DisableReplaceStmt = saveDisableReplaceStmt;
5684 CurrentBody = SaveCurrentBody;
5685 PropParentMap = 0;
5686 ImportedLocalExternalDecls.clear();
5687 // Now we snarf the rewritten text and stash it away for later use.
5688 std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
5689 RewrittenBlockExprs[BE] = Str;
5690
5691 Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
5692
5693 //blockTranscribed->dump();
5694 ReplaceStmt(S, blockTranscribed);
5695 return blockTranscribed;
5696 }
5697 // Handle specific things.
5698 if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
5699 return RewriteAtEncode(AtEncode);
5700
5701 if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
5702 return RewriteAtSelector(AtSelector);
5703
5704 if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
5705 return RewriteObjCStringLiteral(AtString);
Fariborz Jahanian55947042012-03-27 20:17:30 +00005706
5707 if (ObjCBoolLiteralExpr *BoolLitExpr = dyn_cast<ObjCBoolLiteralExpr>(S))
5708 return RewriteObjCBoolLiteralExpr(BoolLitExpr);
Fariborz Jahanian0f9b18e2012-03-30 16:49:36 +00005709
Patrick Beardeb382ec2012-04-19 00:25:12 +00005710 if (ObjCBoxedExpr *BoxedExpr = dyn_cast<ObjCBoxedExpr>(S))
5711 return RewriteObjCBoxedExpr(BoxedExpr);
Fariborz Jahanian86cff602012-03-30 23:35:47 +00005712
5713 if (ObjCArrayLiteral *ArrayLitExpr = dyn_cast<ObjCArrayLiteral>(S))
5714 return RewriteObjCArrayLiteralExpr(ArrayLitExpr);
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00005715
5716 if (ObjCDictionaryLiteral *DictionaryLitExpr =
5717 dyn_cast<ObjCDictionaryLiteral>(S))
5718 return RewriteObjCDictionaryLiteralExpr(DictionaryLitExpr);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005719
5720 if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
5721#if 0
5722 // Before we rewrite it, put the original message expression in a comment.
5723 SourceLocation startLoc = MessExpr->getLocStart();
5724 SourceLocation endLoc = MessExpr->getLocEnd();
5725
5726 const char *startBuf = SM->getCharacterData(startLoc);
5727 const char *endBuf = SM->getCharacterData(endLoc);
5728
5729 std::string messString;
5730 messString += "// ";
5731 messString.append(startBuf, endBuf-startBuf+1);
5732 messString += "\n";
5733
5734 // FIXME: Missing definition of
5735 // InsertText(clang::SourceLocation, char const*, unsigned int).
5736 // InsertText(startLoc, messString.c_str(), messString.size());
5737 // Tried this, but it didn't work either...
5738 // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
5739#endif
5740 return RewriteMessageExpr(MessExpr);
5741 }
5742
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00005743 if (ObjCAutoreleasePoolStmt *StmtAutoRelease =
5744 dyn_cast<ObjCAutoreleasePoolStmt>(S)) {
5745 return RewriteObjCAutoreleasePoolStmt(StmtAutoRelease);
5746 }
5747
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005748 if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
5749 return RewriteObjCTryStmt(StmtTry);
5750
5751 if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
5752 return RewriteObjCSynchronizedStmt(StmtTry);
5753
5754 if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
5755 return RewriteObjCThrowStmt(StmtThrow);
5756
5757 if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
5758 return RewriteObjCProtocolExpr(ProtocolExp);
5759
5760 if (ObjCForCollectionStmt *StmtForCollection =
5761 dyn_cast<ObjCForCollectionStmt>(S))
5762 return RewriteObjCForCollectionStmt(StmtForCollection,
5763 OrigStmtRange.getEnd());
5764 if (BreakStmt *StmtBreakStmt =
5765 dyn_cast<BreakStmt>(S))
5766 return RewriteBreakStmt(StmtBreakStmt);
5767 if (ContinueStmt *StmtContinueStmt =
5768 dyn_cast<ContinueStmt>(S))
5769 return RewriteContinueStmt(StmtContinueStmt);
5770
5771 // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
5772 // and cast exprs.
5773 if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
5774 // FIXME: What we're doing here is modifying the type-specifier that
5775 // precedes the first Decl. In the future the DeclGroup should have
5776 // a separate type-specifier that we can rewrite.
5777 // NOTE: We need to avoid rewriting the DeclStmt if it is within
5778 // the context of an ObjCForCollectionStmt. For example:
5779 // NSArray *someArray;
5780 // for (id <FooProtocol> index in someArray) ;
5781 // This is because RewriteObjCForCollectionStmt() does textual rewriting
5782 // and it depends on the original text locations/positions.
5783 if (Stmts.empty() || !IsDeclStmtInForeachHeader(DS))
5784 RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
5785
5786 // Blocks rewrite rules.
5787 for (DeclStmt::decl_iterator DI = DS->decl_begin(), DE = DS->decl_end();
5788 DI != DE; ++DI) {
5789 Decl *SD = *DI;
5790 if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
5791 if (isTopLevelBlockPointerType(ND->getType()))
5792 RewriteBlockPointerDecl(ND);
5793 else if (ND->getType()->isFunctionPointerType())
5794 CheckFunctionPointerDecl(ND->getType(), ND);
5795 if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
5796 if (VD->hasAttr<BlocksAttr>()) {
5797 static unsigned uniqueByrefDeclCount = 0;
5798 assert(!BlockByRefDeclNo.count(ND) &&
5799 "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
5800 BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
Fariborz Jahanian4fe261c2012-04-24 19:38:45 +00005801 RewriteByRefVar(VD, (DI == DS->decl_begin()), ((DI+1) == DE));
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005802 }
5803 else
5804 RewriteTypeOfDecl(VD);
5805 }
5806 }
5807 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
5808 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5809 RewriteBlockPointerDecl(TD);
5810 else if (TD->getUnderlyingType()->isFunctionPointerType())
5811 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
5812 }
5813 }
5814 }
5815
5816 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
5817 RewriteObjCQualifiedInterfaceTypes(CE);
5818
5819 if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
5820 isa<DoStmt>(S) || isa<ForStmt>(S)) {
5821 assert(!Stmts.empty() && "Statement stack is empty");
5822 assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
5823 isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
5824 && "Statement stack mismatch");
5825 Stmts.pop_back();
5826 }
5827 // Handle blocks rewriting.
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005828 if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
5829 ValueDecl *VD = DRE->getDecl();
5830 if (VD->hasAttr<BlocksAttr>())
5831 return RewriteBlockDeclRefExpr(DRE);
5832 if (HasLocalVariableExternalStorage(VD))
5833 return RewriteLocalVariableExternalStorage(DRE);
5834 }
5835
5836 if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
5837 if (CE->getCallee()->getType()->isBlockPointerType()) {
5838 Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
5839 ReplaceStmt(S, BlockCall);
5840 return BlockCall;
5841 }
5842 }
5843 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
5844 RewriteCastExpr(CE);
5845 }
Fariborz Jahanianf1ee6872012-04-10 00:08:18 +00005846 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5847 RewriteImplicitCastObjCExpr(ICE);
5848 }
Fariborz Jahanian43aa1c32012-04-16 22:14:01 +00005849#if 0
Fariborz Jahanian653b7cf2012-04-13 18:00:54 +00005850
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005851 if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
5852 CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
5853 ICE->getSubExpr(),
5854 SourceLocation());
5855 // Get the new text.
5856 std::string SStr;
5857 llvm::raw_string_ostream Buf(SStr);
Richard Smithd1420c62012-08-16 03:56:14 +00005858 Replacement->printPretty(Buf);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005859 const std::string &Str = Buf.str();
5860
5861 printf("CAST = %s\n", &Str[0]);
5862 InsertText(ICE->getSubExpr()->getLocStart(), &Str[0], Str.size());
5863 delete S;
5864 return Replacement;
5865 }
5866#endif
5867 // Return this stmt unmodified.
5868 return S;
5869}
5870
5871void RewriteModernObjC::RewriteRecordBody(RecordDecl *RD) {
5872 for (RecordDecl::field_iterator i = RD->field_begin(),
5873 e = RD->field_end(); i != e; ++i) {
David Blaikie581deb32012-06-06 20:45:41 +00005874 FieldDecl *FD = *i;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005875 if (isTopLevelBlockPointerType(FD->getType()))
5876 RewriteBlockPointerDecl(FD);
5877 if (FD->getType()->isObjCQualifiedIdType() ||
5878 FD->getType()->isObjCQualifiedInterfaceType())
5879 RewriteObjCQualifiedInterfaceTypes(FD);
5880 }
5881}
5882
5883/// HandleDeclInMainFile - This is called for each top-level decl defined in the
5884/// main file of the input.
5885void RewriteModernObjC::HandleDeclInMainFile(Decl *D) {
5886 switch (D->getKind()) {
5887 case Decl::Function: {
5888 FunctionDecl *FD = cast<FunctionDecl>(D);
5889 if (FD->isOverloadedOperator())
5890 return;
5891
5892 // Since function prototypes don't have ParmDecl's, we check the function
5893 // prototype. This enables us to rewrite function declarations and
5894 // definitions using the same code.
5895 RewriteBlocksInFunctionProtoType(FD->getType(), FD);
5896
Argyrios Kyrtzidis9335df32012-02-12 04:48:45 +00005897 if (!FD->isThisDeclarationADefinition())
5898 break;
5899
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005900 // FIXME: If this should support Obj-C++, support CXXTryStmt
5901 if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
5902 CurFunctionDef = FD;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005903 CurrentBody = Body;
5904 Body =
5905 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5906 FD->setBody(Body);
5907 CurrentBody = 0;
5908 if (PropParentMap) {
5909 delete PropParentMap;
5910 PropParentMap = 0;
5911 }
5912 // This synthesizes and inserts the block "impl" struct, invoke function,
5913 // and any copy/dispose helper functions.
5914 InsertBlockLiteralsWithinFunction(FD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005915 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005916 CurFunctionDef = 0;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005917 }
5918 break;
5919 }
5920 case Decl::ObjCMethod: {
5921 ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
5922 if (CompoundStmt *Body = MD->getCompoundBody()) {
5923 CurMethodDef = MD;
5924 CurrentBody = Body;
5925 Body =
5926 cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
5927 MD->setBody(Body);
5928 CurrentBody = 0;
5929 if (PropParentMap) {
5930 delete PropParentMap;
5931 PropParentMap = 0;
5932 }
5933 InsertBlockLiteralsWithinMethod(MD);
Fariborz Jahanian96205962012-11-06 17:30:23 +00005934 RewriteLineDirective(D);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005935 CurMethodDef = 0;
5936 }
5937 break;
5938 }
5939 case Decl::ObjCImplementation: {
5940 ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
5941 ClassImplementation.push_back(CI);
5942 break;
5943 }
5944 case Decl::ObjCCategoryImpl: {
5945 ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
5946 CategoryImplementation.push_back(CI);
5947 break;
5948 }
5949 case Decl::Var: {
5950 VarDecl *VD = cast<VarDecl>(D);
5951 RewriteObjCQualifiedInterfaceTypes(VD);
5952 if (isTopLevelBlockPointerType(VD->getType()))
5953 RewriteBlockPointerDecl(VD);
5954 else if (VD->getType()->isFunctionPointerType()) {
5955 CheckFunctionPointerDecl(VD->getType(), VD);
5956 if (VD->getInit()) {
5957 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5958 RewriteCastExpr(CE);
5959 }
5960 }
5961 } else if (VD->getType()->isRecordType()) {
5962 RecordDecl *RD = VD->getType()->getAs<RecordType>()->getDecl();
5963 if (RD->isCompleteDefinition())
5964 RewriteRecordBody(RD);
5965 }
5966 if (VD->getInit()) {
5967 GlobalVarDecl = VD;
5968 CurrentBody = VD->getInit();
5969 RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
5970 CurrentBody = 0;
5971 if (PropParentMap) {
5972 delete PropParentMap;
5973 PropParentMap = 0;
5974 }
5975 SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
5976 GlobalVarDecl = 0;
5977
5978 // This is needed for blocks.
5979 if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
5980 RewriteCastExpr(CE);
5981 }
5982 }
5983 break;
5984 }
5985 case Decl::TypeAlias:
5986 case Decl::Typedef: {
5987 if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
5988 if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
5989 RewriteBlockPointerDecl(TD);
5990 else if (TD->getUnderlyingType()->isFunctionPointerType())
5991 CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
Fariborz Jahanianf9f30792013-04-03 19:11:21 +00005992 else
5993 RewriteObjCQualifiedInterfaceTypes(TD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00005994 }
5995 break;
5996 }
5997 case Decl::CXXRecord:
5998 case Decl::Record: {
5999 RecordDecl *RD = cast<RecordDecl>(D);
6000 if (RD->isCompleteDefinition())
6001 RewriteRecordBody(RD);
6002 break;
6003 }
6004 default:
6005 break;
6006 }
6007 // Nothing yet.
6008}
6009
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006010/// Write_ProtocolExprReferencedMetadata - This routine writer out the
6011/// protocol reference symbols in the for of:
6012/// struct _protocol_t *PROTOCOL_REF = &PROTOCOL_METADATA.
6013static void Write_ProtocolExprReferencedMetadata(ASTContext *Context,
6014 ObjCProtocolDecl *PDecl,
6015 std::string &Result) {
6016 // Also output .objc_protorefs$B section and its meta-data.
6017 if (Context->getLangOpts().MicrosoftExt)
Fariborz Jahanianbd78cfa2012-04-27 21:39:49 +00006018 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006019 Result += "struct _protocol_t *";
6020 Result += "_OBJC_PROTOCOL_REFERENCE_$_";
6021 Result += PDecl->getNameAsString();
6022 Result += " = &";
6023 Result += "_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
6024 Result += ";\n";
6025}
6026
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006027void RewriteModernObjC::HandleTranslationUnit(ASTContext &C) {
6028 if (Diags.hasErrorOccurred())
6029 return;
6030
6031 RewriteInclude();
6032
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00006033 for (unsigned i = 0, e = FunctionDefinitionsSeen.size(); i < e; i++) {
6034 // translation of function bodies were postponed untill all class and
6035 // their extensions and implementations are seen. This is because, we
6036 // cannot build grouping structs for bitfields untill they are all seen.
6037 FunctionDecl *FDecl = FunctionDefinitionsSeen[i];
6038 HandleTopLevelSingleDecl(FDecl);
6039 }
6040
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006041 // Here's a great place to add any extra declarations that may be needed.
6042 // Write out meta data for each @protocol(<expr>).
6043 for (llvm::SmallPtrSet<ObjCProtocolDecl *,8>::iterator I = ProtocolExprDecls.begin(),
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006044 E = ProtocolExprDecls.end(); I != E; ++I) {
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006045 RewriteObjCProtocolMetaData(*I, Preamble);
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006046 Write_ProtocolExprReferencedMetadata(Context, (*I), Preamble);
6047 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006048
6049 InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00006050
6051 if (ClassImplementation.size() || CategoryImplementation.size())
6052 RewriteImplementations();
6053
Fariborz Jahanian57317782012-02-21 23:58:41 +00006054 for (unsigned i = 0, e = ObjCInterfacesSeen.size(); i < e; i++) {
6055 ObjCInterfaceDecl *CDecl = ObjCInterfacesSeen[i];
6056 // Write struct declaration for the class matching its ivar declarations.
6057 // Note that for modern abi, this is postponed until the end of TU
6058 // because class extensions and the implementation might declare their own
6059 // private ivars.
6060 RewriteInterfaceDecl(CDecl);
6061 }
Fariborz Jahanian31c4a4b2013-02-07 22:50:40 +00006062
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006063 // Get the buffer corresponding to MainFileID. If we haven't changed it, then
6064 // we are done.
6065 if (const RewriteBuffer *RewriteBuf =
6066 Rewrite.getRewriteBufferFor(MainFileID)) {
6067 //printf("Changed:\n");
6068 *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
6069 } else {
6070 llvm::errs() << "No changes\n";
6071 }
6072
6073 if (ClassImplementation.size() || CategoryImplementation.size() ||
6074 ProtocolExprDecls.size()) {
6075 // Rewrite Objective-c meta data*
6076 std::string ResultStr;
6077 RewriteMetaDataIntoBuffer(ResultStr);
6078 // Emit metadata.
6079 *OutFile << ResultStr;
6080 }
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006081 // Emit ImageInfo;
6082 {
6083 std::string ResultStr;
6084 WriteImageInfo(ResultStr);
6085 *OutFile << ResultStr;
6086 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006087 OutFile->flush();
6088}
6089
6090void RewriteModernObjC::Initialize(ASTContext &context) {
6091 InitializeCommon(context);
6092
Fariborz Jahanian6991bc52012-03-10 17:45:38 +00006093 Preamble += "#ifndef __OBJC2__\n";
6094 Preamble += "#define __OBJC2__\n";
6095 Preamble += "#endif\n";
6096
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006097 // declaring objc_selector outside the parameter list removes a silly
6098 // scope related warning...
6099 if (IsHeader)
6100 Preamble = "#pragma once\n";
6101 Preamble += "struct objc_selector; struct objc_class;\n";
Fariborz Jahaniane2d87bc2012-04-12 23:52:52 +00006102 Preamble += "struct __rw_objc_super { \n\tstruct objc_object *object; ";
6103 Preamble += "\n\tstruct objc_object *superClass; ";
6104 // Add a constructor for creating temporary objects.
6105 Preamble += "\n\t__rw_objc_super(struct objc_object *o, struct objc_object *s) ";
6106 Preamble += ": object(o), superClass(s) {} ";
6107 Preamble += "\n};\n";
6108
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006109 if (LangOpts.MicrosoftExt) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006110 // Define all sections using syntax that makes sense.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006111 // These are currently generated.
6112 Preamble += "\n#pragma section(\".objc_classlist$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006113 Preamble += "#pragma section(\".objc_catlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006114 Preamble += "#pragma section(\".objc_imageinfo$B\", long, read, write)\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006115 Preamble += "#pragma section(\".objc_nlclslist$B\", long, read, write)\n";
6116 Preamble += "#pragma section(\".objc_nlcatlist$B\", long, read, write)\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006117 // These are generated but not necessary for functionality.
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00006118 Preamble += "#pragma section(\".cat_cls_meth$B\", long, read, write)\n";
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00006119 Preamble += "#pragma section(\".inst_meth$B\", long, read, write)\n";
6120 Preamble += "#pragma section(\".cls_meth$B\", long, read, write)\n";
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006121 Preamble += "#pragma section(\".objc_ivar$B\", long, read, write)\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006122
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00006123 // These need be generated for performance. Currently they are not,
6124 // using API calls instead.
6125 Preamble += "#pragma section(\".objc_selrefs$B\", long, read, write)\n";
6126 Preamble += "#pragma section(\".objc_classrefs$B\", long, read, write)\n";
6127 Preamble += "#pragma section(\".objc_superrefs$B\", long, read, write)\n";
6128
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006129 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006130 Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
6131 Preamble += "typedef struct objc_object Protocol;\n";
6132 Preamble += "#define _REWRITER_typedef_Protocol\n";
6133 Preamble += "#endif\n";
6134 if (LangOpts.MicrosoftExt) {
6135 Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
6136 Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00006137 }
6138 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006139 Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
Fariborz Jahanian5cf6b6c2012-03-21 23:41:04 +00006140
6141 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend(void);\n";
6142 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper(void);\n";
6143 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_stret(void);\n";
6144 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSendSuper_stret(void);\n";
6145 Preamble += "__OBJC_RW_DLLIMPORT void objc_msgSend_fpret(void);\n";
6146
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00006147 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006148 Preamble += "(const char *);\n";
6149 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
6150 Preamble += "(struct objc_class *);\n";
Fariborz Jahanian20e181a2012-05-08 20:55:55 +00006151 Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *objc_getMetaClass";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006152 Preamble += "(const char *);\n";
Fariborz Jahanian55261af2012-03-19 18:11:32 +00006153 Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006154 // @synchronized hooks.
Aaron Ballman2d234d732012-09-06 16:44:16 +00006155 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter( struct objc_object *);\n";
6156 Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit( struct objc_object *);\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006157 Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
Fariborz Jahaniane38f08a2013-09-05 17:17:32 +00006158 Preamble += "#ifdef _WIN64\n";
6159 Preamble += "typedef unsigned long long _WIN_NSUInteger;\n";
6160 Preamble += "#else\n";
6161 Preamble += "typedef unsigned int _WIN_NSUInteger;\n";
6162 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006163 Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
6164 Preamble += "struct __objcFastEnumerationState {\n\t";
6165 Preamble += "unsigned long state;\n\t";
6166 Preamble += "void **itemsPtr;\n\t";
6167 Preamble += "unsigned long *mutationsPtr;\n\t";
6168 Preamble += "unsigned long extra[5];\n};\n";
6169 Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
6170 Preamble += "#define __FASTENUMERATIONSTATE\n";
6171 Preamble += "#endif\n";
6172 Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
6173 Preamble += "struct __NSConstantStringImpl {\n";
6174 Preamble += " int *isa;\n";
6175 Preamble += " int flags;\n";
6176 Preamble += " char *str;\n";
6177 Preamble += " long length;\n";
6178 Preamble += "};\n";
6179 Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
6180 Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
6181 Preamble += "#else\n";
6182 Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
6183 Preamble += "#endif\n";
6184 Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
6185 Preamble += "#endif\n";
6186 // Blocks preamble.
6187 Preamble += "#ifndef BLOCK_IMPL\n";
6188 Preamble += "#define BLOCK_IMPL\n";
6189 Preamble += "struct __block_impl {\n";
6190 Preamble += " void *isa;\n";
6191 Preamble += " int Flags;\n";
6192 Preamble += " int Reserved;\n";
6193 Preamble += " void *FuncPtr;\n";
6194 Preamble += "};\n";
6195 Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
6196 Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
6197 Preamble += "extern \"C\" __declspec(dllexport) "
6198 "void _Block_object_assign(void *, const void *, const int);\n";
6199 Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
6200 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
6201 Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
6202 Preamble += "#else\n";
6203 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
6204 Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
6205 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
6206 Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
6207 Preamble += "#endif\n";
6208 Preamble += "#endif\n";
6209 if (LangOpts.MicrosoftExt) {
6210 Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
6211 Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
6212 Preamble += "#ifndef KEEP_ATTRIBUTES\n"; // We use this for clang tests.
6213 Preamble += "#define __attribute__(X)\n";
6214 Preamble += "#endif\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006215 Preamble += "#ifndef __weak\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006216 Preamble += "#define __weak\n";
Fariborz Jahanian5ce28272012-04-12 16:33:31 +00006217 Preamble += "#endif\n";
6218 Preamble += "#ifndef __block\n";
6219 Preamble += "#define __block\n";
6220 Preamble += "#endif\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006221 }
6222 else {
6223 Preamble += "#define __block\n";
6224 Preamble += "#define __weak\n";
6225 }
Fariborz Jahanianbe8d55c2012-06-29 18:27:08 +00006226
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006227 // Declarations required for modern objective-c array and dictionary literals.
6228 Preamble += "\n#include <stdarg.h>\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006229 Preamble += "struct __NSContainer_literal {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006230 Preamble += " void * *arr;\n";
Fariborz Jahaniane35abe12012-04-06 22:29:36 +00006231 Preamble += " __NSContainer_literal (unsigned int count, ...) {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006232 Preamble += "\tva_list marker;\n";
6233 Preamble += "\tva_start(marker, count);\n";
6234 Preamble += "\tarr = new void *[count];\n";
6235 Preamble += "\tfor (unsigned i = 0; i < count; i++)\n";
6236 Preamble += "\t arr[i] = va_arg(marker, void *);\n";
6237 Preamble += "\tva_end( marker );\n";
6238 Preamble += " };\n";
Fariborz Jahanian13a9c022012-05-02 23:53:46 +00006239 Preamble += " ~__NSContainer_literal() {\n";
Fariborz Jahanianb0f245c2012-04-06 19:47:36 +00006240 Preamble += "\tdelete[] arr;\n";
6241 Preamble += " }\n";
6242 Preamble += "};\n";
6243
Fariborz Jahanian042b91d2012-05-23 23:47:20 +00006244 // Declaration required for implementation of @autoreleasepool statement.
6245 Preamble += "extern \"C\" __declspec(dllimport) void * objc_autoreleasePoolPush(void);\n";
6246 Preamble += "extern \"C\" __declspec(dllimport) void objc_autoreleasePoolPop(void *);\n\n";
6247 Preamble += "struct __AtAutoreleasePool {\n";
6248 Preamble += " __AtAutoreleasePool() {atautoreleasepoolobj = objc_autoreleasePoolPush();}\n";
6249 Preamble += " ~__AtAutoreleasePool() {objc_autoreleasePoolPop(atautoreleasepoolobj);}\n";
6250 Preamble += " void * atautoreleasepoolobj;\n";
6251 Preamble += "};\n";
6252
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006253 // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
6254 // as this avoids warning in any 64bit/32bit compilation model.
6255 Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
6256}
6257
6258/// RewriteIvarOffsetComputation - This rutine synthesizes computation of
6259/// ivar offset.
6260void RewriteModernObjC::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
6261 std::string &Result) {
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006262 Result += "__OFFSETOFIVAR__(struct ";
6263 Result += ivar->getContainingInterface()->getNameAsString();
6264 if (LangOpts.MicrosoftExt)
6265 Result += "_IMPL";
6266 Result += ", ";
6267 if (ivar->isBitField())
6268 ObjCIvarBitfieldGroupDecl(ivar, Result);
6269 else
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006270 Result += ivar->getNameAsString();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006271 Result += ")";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006272}
6273
6274/// WriteModernMetadataDeclarations - Writes out metadata declarations for modern ABI.
6275/// struct _prop_t {
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006276/// const char *name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006277/// char *attributes;
6278/// }
6279
6280/// struct _prop_list_t {
6281/// uint32_t entsize; // sizeof(struct _prop_t)
6282/// uint32_t count_of_properties;
6283/// struct _prop_t prop_list[count_of_properties];
6284/// }
6285
6286/// struct _protocol_t;
6287
6288/// struct _protocol_list_t {
6289/// long protocol_count; // Note, this is 32/64 bit
6290/// struct _protocol_t * protocol_list[protocol_count];
6291/// }
6292
6293/// struct _objc_method {
6294/// SEL _cmd;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006295/// const char *method_type;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006296/// char *_imp;
6297/// }
6298
6299/// struct _method_list_t {
6300/// uint32_t entsize; // sizeof(struct _objc_method)
6301/// uint32_t method_count;
6302/// struct _objc_method method_list[method_count];
6303/// }
6304
6305/// struct _protocol_t {
6306/// id isa; // NULL
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006307/// const char *protocol_name;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006308/// const struct _protocol_list_t * protocol_list; // super protocols
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006309/// const struct method_list_t *instance_methods;
6310/// const struct method_list_t *class_methods;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006311/// const struct method_list_t *optionalInstanceMethods;
6312/// const struct method_list_t *optionalClassMethods;
6313/// const struct _prop_list_t * properties;
6314/// const uint32_t size; // sizeof(struct _protocol_t)
6315/// const uint32_t flags; // = 0
6316/// const char ** extendedMethodTypes;
6317/// }
6318
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006319/// struct _ivar_t {
6320/// unsigned long int *offset; // pointer to ivar offset location
Fariborz Jahanianae932952012-02-10 20:47:10 +00006321/// const char *name;
6322/// const char *type;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006323/// uint32_t alignment;
6324/// uint32_t size;
6325/// }
6326
6327/// struct _ivar_list_t {
6328/// uint32 entsize; // sizeof(struct _ivar_t)
6329/// uint32 count;
Fariborz Jahanianae932952012-02-10 20:47:10 +00006330/// struct _ivar_t list[count];
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006331/// }
6332
6333/// struct _class_ro_t {
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006334/// uint32_t flags;
6335/// uint32_t instanceStart;
6336/// uint32_t instanceSize;
6337/// uint32_t reserved; // only when building for 64bit targets
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006338/// const uint8_t *ivarLayout;
6339/// const char *name;
6340/// const struct _method_list_t *baseMethods;
6341/// const struct _protocol_list_t *baseProtocols;
6342/// const struct _ivar_list_t *ivars;
6343/// const uint8_t *weakIvarLayout;
6344/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006345/// }
6346
6347/// struct _class_t {
6348/// struct _class_t *isa;
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006349/// struct _class_t *superclass;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006350/// void *cache;
6351/// IMP *vtable;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006352/// struct _class_ro_t *ro;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006353/// }
6354
6355/// struct _category_t {
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006356/// const char *name;
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006357/// struct _class_t *cls;
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006358/// const struct _method_list_t *instance_methods;
6359/// const struct _method_list_t *class_methods;
6360/// const struct _protocol_list_t *protocols;
6361/// const struct _prop_list_t *properties;
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006362/// }
6363
6364/// MessageRefTy - LLVM for:
6365/// struct _message_ref_t {
6366/// IMP messenger;
6367/// SEL name;
6368/// };
6369
6370/// SuperMessageRefTy - LLVM for:
6371/// struct _super_message_ref_t {
6372/// SUPER_IMP messenger;
6373/// SEL name;
6374/// };
6375
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006376static void WriteModernMetadataDeclarations(ASTContext *Context, std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006377 static bool meta_data_declared = false;
6378 if (meta_data_declared)
6379 return;
6380
6381 Result += "\nstruct _prop_t {\n";
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006382 Result += "\tconst char *name;\n";
6383 Result += "\tconst char *attributes;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006384 Result += "};\n";
6385
6386 Result += "\nstruct _protocol_t;\n";
6387
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006388 Result += "\nstruct _objc_method {\n";
6389 Result += "\tstruct objc_selector * _cmd;\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006390 Result += "\tconst char *method_type;\n";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006391 Result += "\tvoid *_imp;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006392 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006393
6394 Result += "\nstruct _protocol_t {\n";
6395 Result += "\tvoid * isa; // NULL\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006396 Result += "\tconst char *protocol_name;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006397 Result += "\tconst struct _protocol_list_t * protocol_list; // super protocols\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006398 Result += "\tconst struct method_list_t *instance_methods;\n";
6399 Result += "\tconst struct method_list_t *class_methods;\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006400 Result += "\tconst struct method_list_t *optionalInstanceMethods;\n";
6401 Result += "\tconst struct method_list_t *optionalClassMethods;\n";
6402 Result += "\tconst struct _prop_list_t * properties;\n";
6403 Result += "\tconst unsigned int size; // sizeof(struct _protocol_t)\n";
6404 Result += "\tconst unsigned int flags; // = 0\n";
6405 Result += "\tconst char ** extendedMethodTypes;\n";
6406 Result += "};\n";
6407
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006408 Result += "\nstruct _ivar_t {\n";
6409 Result += "\tunsigned long int *offset; // pointer to ivar offset location\n";
Fariborz Jahanianae932952012-02-10 20:47:10 +00006410 Result += "\tconst char *name;\n";
6411 Result += "\tconst char *type;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006412 Result += "\tunsigned int alignment;\n";
6413 Result += "\tunsigned int size;\n";
6414 Result += "};\n";
6415
6416 Result += "\nstruct _class_ro_t {\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006417 Result += "\tunsigned int flags;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006418 Result += "\tunsigned int instanceStart;\n";
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006419 Result += "\tunsigned int instanceSize;\n";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006420 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6421 if (Triple.getArch() == llvm::Triple::x86_64)
Fariborz Jahanian249cd102012-03-24 16:53:16 +00006422 Result += "\tunsigned int reserved;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006423 Result += "\tconst unsigned char *ivarLayout;\n";
6424 Result += "\tconst char *name;\n";
6425 Result += "\tconst struct _method_list_t *baseMethods;\n";
6426 Result += "\tconst struct _objc_protocol_list *baseProtocols;\n";
6427 Result += "\tconst struct _ivar_list_t *ivars;\n";
6428 Result += "\tconst unsigned char *weakIvarLayout;\n";
6429 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006430 Result += "};\n";
6431
6432 Result += "\nstruct _class_t {\n";
6433 Result += "\tstruct _class_t *isa;\n";
Fariborz Jahanianfd4ce2c2012-03-20 17:34:50 +00006434 Result += "\tstruct _class_t *superclass;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006435 Result += "\tvoid *cache;\n";
6436 Result += "\tvoid *vtable;\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006437 Result += "\tstruct _class_ro_t *ro;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006438 Result += "};\n";
6439
6440 Result += "\nstruct _category_t {\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006441 Result += "\tconst char *name;\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006442 Result += "\tstruct _class_t *cls;\n";
Fariborz Jahanian4e825df2012-03-21 16:23:16 +00006443 Result += "\tconst struct _method_list_t *instance_methods;\n";
6444 Result += "\tconst struct _method_list_t *class_methods;\n";
6445 Result += "\tconst struct _protocol_list_t *protocols;\n";
6446 Result += "\tconst struct _prop_list_t *properties;\n";
Fariborz Jahanian42e9a352012-02-10 00:04:22 +00006447 Result += "};\n";
6448
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006449 Result += "extern \"C\" __declspec(dllimport) struct objc_cache _objc_empty_cache;\n";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006450 Result += "#pragma warning(disable:4273)\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00006451 meta_data_declared = true;
6452}
6453
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006454static void Write_protocol_list_t_TypeDecl(std::string &Result,
6455 long super_protocol_count) {
6456 Result += "struct /*_protocol_list_t*/"; Result += " {\n";
6457 Result += "\tlong protocol_count; // Note, this is 32/64 bit\n";
6458 Result += "\tstruct _protocol_t *super_protocols[";
6459 Result += utostr(super_protocol_count); Result += "];\n";
6460 Result += "}";
6461}
6462
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006463static void Write_method_list_t_TypeDecl(std::string &Result,
6464 unsigned int method_count) {
6465 Result += "struct /*_method_list_t*/"; Result += " {\n";
6466 Result += "\tunsigned int entsize; // sizeof(struct _objc_method)\n";
6467 Result += "\tunsigned int method_count;\n";
6468 Result += "\tstruct _objc_method method_list[";
6469 Result += utostr(method_count); Result += "];\n";
6470 Result += "}";
6471}
6472
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006473static void Write__prop_list_t_TypeDecl(std::string &Result,
6474 unsigned int property_count) {
6475 Result += "struct /*_prop_list_t*/"; Result += " {\n";
6476 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6477 Result += "\tunsigned int count_of_properties;\n";
6478 Result += "\tstruct _prop_t prop_list[";
6479 Result += utostr(property_count); Result += "];\n";
6480 Result += "}";
6481}
6482
Fariborz Jahanianae932952012-02-10 20:47:10 +00006483static void Write__ivar_list_t_TypeDecl(std::string &Result,
6484 unsigned int ivar_count) {
6485 Result += "struct /*_ivar_list_t*/"; Result += " {\n";
6486 Result += "\tunsigned int entsize; // sizeof(struct _prop_t)\n";
6487 Result += "\tunsigned int count;\n";
6488 Result += "\tstruct _ivar_t ivar_list[";
6489 Result += utostr(ivar_count); Result += "];\n";
6490 Result += "}";
6491}
6492
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00006493static void Write_protocol_list_initializer(ASTContext *Context, std::string &Result,
6494 ArrayRef<ObjCProtocolDecl *> SuperProtocols,
6495 StringRef VarName,
6496 StringRef ProtocolName) {
6497 if (SuperProtocols.size() > 0) {
6498 Result += "\nstatic ";
6499 Write_protocol_list_t_TypeDecl(Result, SuperProtocols.size());
6500 Result += " "; Result += VarName;
6501 Result += ProtocolName;
6502 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6503 Result += "\t"; Result += utostr(SuperProtocols.size()); Result += ",\n";
6504 for (unsigned i = 0, e = SuperProtocols.size(); i < e; i++) {
6505 ObjCProtocolDecl *SuperPD = SuperProtocols[i];
6506 Result += "\t&"; Result += "_OBJC_PROTOCOL_";
6507 Result += SuperPD->getNameAsString();
6508 if (i == e-1)
6509 Result += "\n};\n";
6510 else
6511 Result += ",\n";
6512 }
6513 }
6514}
6515
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006516static void Write_method_list_t_initializer(RewriteModernObjC &RewriteObj,
6517 ASTContext *Context, std::string &Result,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006518 ArrayRef<ObjCMethodDecl *> Methods,
6519 StringRef VarName,
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006520 StringRef TopLevelDeclName,
6521 bool MethodImpl) {
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006522 if (Methods.size() > 0) {
6523 Result += "\nstatic ";
6524 Write_method_list_t_TypeDecl(Result, Methods.size());
6525 Result += " "; Result += VarName;
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006526 Result += TopLevelDeclName;
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006527 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6528 Result += "\t"; Result += "sizeof(_objc_method)"; Result += ",\n";
6529 Result += "\t"; Result += utostr(Methods.size()); Result += ",\n";
6530 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6531 ObjCMethodDecl *MD = Methods[i];
6532 if (i == 0)
6533 Result += "\t{{(struct objc_selector *)\"";
6534 else
6535 Result += "\t{(struct objc_selector *)\"";
6536 Result += (MD)->getSelector().getAsString(); Result += "\"";
6537 Result += ", ";
6538 std::string MethodTypeString;
6539 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString);
6540 Result += "\""; Result += MethodTypeString; Result += "\"";
6541 Result += ", ";
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006542 if (!MethodImpl)
6543 Result += "0";
6544 else {
6545 Result += "(void *)";
6546 Result += RewriteObj.MethodInternalNames[MD];
6547 }
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006548 if (i == e-1)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006549 Result += "}}\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006550 else
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00006551 Result += "},\n";
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00006552 }
6553 Result += "};\n";
6554 }
6555}
6556
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006557static void Write_prop_list_t_initializer(RewriteModernObjC &RewriteObj,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00006558 ASTContext *Context, std::string &Result,
6559 ArrayRef<ObjCPropertyDecl *> Properties,
6560 const Decl *Container,
6561 StringRef VarName,
6562 StringRef ProtocolName) {
6563 if (Properties.size() > 0) {
6564 Result += "\nstatic ";
6565 Write__prop_list_t_TypeDecl(Result, Properties.size());
6566 Result += " "; Result += VarName;
6567 Result += ProtocolName;
6568 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6569 Result += "\t"; Result += "sizeof(_prop_t)"; Result += ",\n";
6570 Result += "\t"; Result += utostr(Properties.size()); Result += ",\n";
6571 for (unsigned i = 0, e = Properties.size(); i < e; i++) {
6572 ObjCPropertyDecl *PropDecl = Properties[i];
6573 if (i == 0)
6574 Result += "\t{{\"";
6575 else
6576 Result += "\t{\"";
6577 Result += PropDecl->getName(); Result += "\",";
6578 std::string PropertyTypeString, QuotePropertyTypeString;
6579 Context->getObjCEncodingForPropertyDecl(PropDecl, Container, PropertyTypeString);
6580 RewriteObj.QuoteDoublequotes(PropertyTypeString, QuotePropertyTypeString);
6581 Result += "\""; Result += QuotePropertyTypeString; Result += "\"";
6582 if (i == e-1)
6583 Result += "}}\n";
6584 else
6585 Result += "},\n";
6586 }
6587 Result += "};\n";
6588 }
6589}
6590
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006591// Metadata flags
6592enum MetaDataDlags {
6593 CLS = 0x0,
6594 CLS_META = 0x1,
6595 CLS_ROOT = 0x2,
6596 OBJC2_CLS_HIDDEN = 0x10,
6597 CLS_EXCEPTION = 0x20,
6598
6599 /// (Obsolete) ARC-specific: this class has a .release_ivars method
6600 CLS_HAS_IVAR_RELEASER = 0x40,
6601 /// class was compiled with -fobjc-arr
6602 CLS_COMPILED_BY_ARC = 0x80 // (1<<7)
6603};
6604
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006605static void Write__class_ro_t_initializer(ASTContext *Context, std::string &Result,
6606 unsigned int flags,
6607 const std::string &InstanceStart,
6608 const std::string &InstanceSize,
6609 ArrayRef<ObjCMethodDecl *>baseMethods,
6610 ArrayRef<ObjCProtocolDecl *>baseProtocols,
6611 ArrayRef<ObjCIvarDecl *>ivars,
6612 ArrayRef<ObjCPropertyDecl *>Properties,
6613 StringRef VarName,
6614 StringRef ClassName) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006615 Result += "\nstatic struct _class_ro_t ";
6616 Result += VarName; Result += ClassName;
6617 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6618 Result += "\t";
6619 Result += llvm::utostr(flags); Result += ", ";
6620 Result += InstanceStart; Result += ", ";
6621 Result += InstanceSize; Result += ", \n";
6622 Result += "\t";
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00006623 const llvm::Triple &Triple(Context->getTargetInfo().getTriple());
6624 if (Triple.getArch() == llvm::Triple::x86_64)
6625 // uint32_t const reserved; // only when building for 64bit targets
6626 Result += "(unsigned int)0, \n\t";
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006627 // const uint8_t * const ivarLayout;
6628 Result += "0, \n\t";
6629 Result += "\""; Result += ClassName; Result += "\",\n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006630 bool metaclass = ((flags & CLS_META) != 0);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006631 if (baseMethods.size() > 0) {
6632 Result += "(const struct _method_list_t *)&";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006633 if (metaclass)
6634 Result += "_OBJC_$_CLASS_METHODS_";
6635 else
6636 Result += "_OBJC_$_INSTANCE_METHODS_";
6637 Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006638 Result += ",\n\t";
6639 }
6640 else
6641 Result += "0, \n\t";
6642
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006643 if (!metaclass && baseProtocols.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006644 Result += "(const struct _objc_protocol_list *)&";
6645 Result += "_OBJC_CLASS_PROTOCOLS_$_"; Result += ClassName;
6646 Result += ",\n\t";
6647 }
6648 else
6649 Result += "0, \n\t";
6650
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006651 if (!metaclass && ivars.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006652 Result += "(const struct _ivar_list_t *)&";
6653 Result += "_OBJC_$_INSTANCE_VARIABLES_"; Result += ClassName;
6654 Result += ",\n\t";
6655 }
6656 else
6657 Result += "0, \n\t";
6658
6659 // weakIvarLayout
6660 Result += "0, \n\t";
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00006661 if (!metaclass && Properties.size() > 0) {
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006662 Result += "(const struct _prop_list_t *)&";
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00006663 Result += "_OBJC_$_PROP_LIST_"; Result += ClassName;
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00006664 Result += ",\n";
6665 }
6666 else
6667 Result += "0, \n";
6668
6669 Result += "};\n";
6670}
6671
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006672static void Write_class_t(ASTContext *Context, std::string &Result,
6673 StringRef VarName,
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006674 const ObjCInterfaceDecl *CDecl, bool metaclass) {
6675 bool rootClass = (!CDecl->getSuperClass());
6676 const ObjCInterfaceDecl *RootClass = CDecl;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006677
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006678 if (!rootClass) {
6679 // Find the Root class
6680 RootClass = CDecl->getSuperClass();
6681 while (RootClass->getSuperClass()) {
6682 RootClass = RootClass->getSuperClass();
6683 }
6684 }
6685
6686 if (metaclass && rootClass) {
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006687 // Need to handle a case of use of forward declaration.
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006688 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006689 Result += "extern \"C\" ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006690 if (CDecl->getImplementation())
6691 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006692 else
6693 Result += "__declspec(dllimport) ";
6694
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006695 Result += "struct _class_t OBJC_CLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006696 Result += CDecl->getNameAsString();
6697 Result += ";\n";
6698 }
6699 // Also, for possibility of 'super' metadata class not having been defined yet.
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006700 if (!rootClass) {
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006701 ObjCInterfaceDecl *SuperClass = CDecl->getSuperClass();
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006702 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006703 Result += "extern \"C\" ";
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006704 if (SuperClass->getImplementation())
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006705 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006706 else
6707 Result += "__declspec(dllimport) ";
6708
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006709 Result += "struct _class_t ";
Fariborz Jahaniance0d8972012-03-10 18:25:06 +00006710 Result += VarName;
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006711 Result += SuperClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006712 Result += ";\n";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006713
Fariborz Jahanian868e9852012-03-29 19:04:10 +00006714 if (metaclass && RootClass != SuperClass) {
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006715 Result += "extern \"C\" ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006716 if (RootClass->getImplementation())
6717 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006718 else
6719 Result += "__declspec(dllimport) ";
6720
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006721 Result += "struct _class_t ";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006722 Result += VarName;
6723 Result += RootClass->getNameAsString();
6724 Result += ";\n";
6725 }
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006726 }
6727
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006728 Result += "\nextern \"C\" __declspec(dllexport) struct _class_t ";
6729 Result += VarName; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006730 Result += " __attribute__ ((used, section (\"__DATA,__objc_data\"))) = {\n";
6731 Result += "\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006732 if (metaclass) {
6733 if (!rootClass) {
6734 Result += "0, // &"; Result += VarName;
6735 Result += RootClass->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006736 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006737 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006738 Result += CDecl->getSuperClass()->getNameAsString();
6739 Result += ",\n\t";
6740 }
6741 else {
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006742 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006743 Result += CDecl->getNameAsString();
6744 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006745 Result += "0, // &OBJC_CLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006746 Result += ",\n\t";
6747 }
6748 }
6749 else {
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006750 Result += "0, // &OBJC_METACLASS_$_";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006751 Result += CDecl->getNameAsString();
6752 Result += ",\n\t";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006753 if (!rootClass) {
6754 Result += "0, // &"; Result += VarName;
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006755 Result += CDecl->getSuperClass()->getNameAsString();
6756 Result += ",\n\t";
6757 }
6758 else
6759 Result += "0,\n\t";
6760 }
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006761 Result += "0, // (void *)&_objc_empty_cache,\n\t";
6762 Result += "0, // unused, was (void *)&_objc_empty_vtable,\n\t";
6763 if (metaclass)
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006764 Result += "&_OBJC_METACLASS_RO_$_";
6765 else
6766 Result += "&_OBJC_CLASS_RO_$_";
6767 Result += CDecl->getNameAsString();
6768 Result += ",\n};\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006769
6770 // Add static function to initialize some of the meta-data fields.
6771 // avoid doing it twice.
6772 if (metaclass)
6773 return;
6774
6775 const ObjCInterfaceDecl *SuperClass =
6776 rootClass ? CDecl : CDecl->getSuperClass();
6777
6778 Result += "static void OBJC_CLASS_SETUP_$_";
6779 Result += CDecl->getNameAsString();
6780 Result += "(void ) {\n";
6781 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6782 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006783 Result += RootClass->getNameAsString(); Result += ";\n";
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006784
6785 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
Fariborz Jahanian452eac12012-03-20 21:09:58 +00006786 Result += ".superclass = ";
6787 if (rootClass)
6788 Result += "&OBJC_CLASS_$_";
6789 else
6790 Result += "&OBJC_METACLASS_$_";
6791
Fariborz Jahaniana03e40c2012-03-20 19:54:33 +00006792 Result += SuperClass->getNameAsString(); Result += ";\n";
6793
6794 Result += "\tOBJC_METACLASS_$_"; Result += CDecl->getNameAsString();
6795 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6796
6797 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6798 Result += ".isa = "; Result += "&OBJC_METACLASS_$_";
6799 Result += CDecl->getNameAsString(); Result += ";\n";
6800
6801 if (!rootClass) {
6802 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6803 Result += ".superclass = "; Result += "&OBJC_CLASS_$_";
6804 Result += SuperClass->getNameAsString(); Result += ";\n";
6805 }
6806
6807 Result += "\tOBJC_CLASS_$_"; Result += CDecl->getNameAsString();
6808 Result += ".cache = "; Result += "&_objc_empty_cache"; Result += ";\n";
6809 Result += "}\n";
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00006810}
6811
Fariborz Jahanian61186122012-02-17 18:40:41 +00006812static void Write_category_t(RewriteModernObjC &RewriteObj, ASTContext *Context,
6813 std::string &Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006814 ObjCCategoryDecl *CatDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006815 ObjCInterfaceDecl *ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00006816 ArrayRef<ObjCMethodDecl *> InstanceMethods,
6817 ArrayRef<ObjCMethodDecl *> ClassMethods,
6818 ArrayRef<ObjCProtocolDecl *> RefedProtocols,
6819 ArrayRef<ObjCPropertyDecl *> ClassProperties) {
Fariborz Jahaniane0335782012-03-27 18:41:05 +00006820 StringRef CatName = CatDecl->getName();
NAKAMURA Takumi20f89392012-03-21 03:21:46 +00006821 StringRef ClassName = ClassDecl->getName();
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006822 // must declare an extern class object in case this class is not implemented
6823 // in this TU.
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006824 Result += "\n";
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006825 Result += "extern \"C\" ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006826 if (ClassDecl->getImplementation())
6827 Result += "__declspec(dllexport) ";
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006828 else
6829 Result += "__declspec(dllimport) ";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00006830
Fariborz Jahanian3f162c32012-03-27 16:21:30 +00006831 Result += "struct _class_t ";
Fariborz Jahanian8c00a1b2012-02-17 20:33:00 +00006832 Result += "OBJC_CLASS_$_"; Result += ClassName;
6833 Result += ";\n";
6834
Fariborz Jahanian61186122012-02-17 18:40:41 +00006835 Result += "\nstatic struct _category_t ";
6836 Result += "_OBJC_$_CATEGORY_";
6837 Result += ClassName; Result += "_$_"; Result += CatName;
6838 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6839 Result += "{\n";
6840 Result += "\t\""; Result += ClassName; Result += "\",\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006841 Result += "\t0, // &"; Result += "OBJC_CLASS_$_"; Result += ClassName;
Fariborz Jahanian61186122012-02-17 18:40:41 +00006842 Result += ",\n";
6843 if (InstanceMethods.size() > 0) {
6844 Result += "\t(const struct _method_list_t *)&";
6845 Result += "_OBJC_$_CATEGORY_INSTANCE_METHODS_";
6846 Result += ClassName; Result += "_$_"; Result += CatName;
6847 Result += ",\n";
6848 }
6849 else
6850 Result += "\t0,\n";
6851
6852 if (ClassMethods.size() > 0) {
6853 Result += "\t(const struct _method_list_t *)&";
6854 Result += "_OBJC_$_CATEGORY_CLASS_METHODS_";
6855 Result += ClassName; Result += "_$_"; Result += CatName;
6856 Result += ",\n";
6857 }
6858 else
6859 Result += "\t0,\n";
6860
6861 if (RefedProtocols.size() > 0) {
6862 Result += "\t(const struct _protocol_list_t *)&";
6863 Result += "_OBJC_CATEGORY_PROTOCOLS_$_";
6864 Result += ClassName; Result += "_$_"; Result += CatName;
6865 Result += ",\n";
6866 }
6867 else
6868 Result += "\t0,\n";
6869
6870 if (ClassProperties.size() > 0) {
6871 Result += "\t(const struct _prop_list_t *)&"; Result += "_OBJC_$_PROP_LIST_";
6872 Result += ClassName; Result += "_$_"; Result += CatName;
6873 Result += ",\n";
6874 }
6875 else
6876 Result += "\t0,\n";
6877
6878 Result += "};\n";
Fariborz Jahanian4b2fe6e2012-03-20 21:41:28 +00006879
6880 // Add static function to initialize the class pointer in the category structure.
6881 Result += "static void OBJC_CATEGORY_SETUP_$_";
6882 Result += ClassDecl->getNameAsString();
6883 Result += "_$_";
6884 Result += CatName;
6885 Result += "(void ) {\n";
6886 Result += "\t_OBJC_$_CATEGORY_";
6887 Result += ClassDecl->getNameAsString();
6888 Result += "_$_";
6889 Result += CatName;
6890 Result += ".cls = "; Result += "&OBJC_CLASS_$_"; Result += ClassName;
6891 Result += ";\n}\n";
Fariborz Jahanian61186122012-02-17 18:40:41 +00006892}
6893
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00006894static void Write__extendedMethodTypes_initializer(RewriteModernObjC &RewriteObj,
6895 ASTContext *Context, std::string &Result,
6896 ArrayRef<ObjCMethodDecl *> Methods,
6897 StringRef VarName,
6898 StringRef ProtocolName) {
6899 if (Methods.size() == 0)
6900 return;
6901
6902 Result += "\nstatic const char *";
6903 Result += VarName; Result += ProtocolName;
6904 Result += " [] __attribute__ ((used, section (\"__DATA,__objc_const\"))) = \n";
6905 Result += "{\n";
6906 for (unsigned i = 0, e = Methods.size(); i < e; i++) {
6907 ObjCMethodDecl *MD = Methods[i];
6908 std::string MethodTypeString, QuoteMethodTypeString;
6909 Context->getObjCEncodingForMethodDecl(MD, MethodTypeString, true);
6910 RewriteObj.QuoteDoublequotes(MethodTypeString, QuoteMethodTypeString);
6911 Result += "\t\""; Result += QuoteMethodTypeString; Result += "\"";
6912 if (i == e-1)
6913 Result += "\n};\n";
6914 else {
6915 Result += ",\n";
6916 }
6917 }
6918}
6919
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006920static void Write_IvarOffsetVar(RewriteModernObjC &RewriteObj,
6921 ASTContext *Context,
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006922 std::string &Result,
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006923 ArrayRef<ObjCIvarDecl *> Ivars,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006924 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006925 // FIXME. visibilty of offset symbols may have to be set; for Darwin
6926 // this is what happens:
6927 /**
6928 if (Ivar->getAccessControl() == ObjCIvarDecl::Private ||
6929 Ivar->getAccessControl() == ObjCIvarDecl::Package ||
6930 Class->getVisibility() == HiddenVisibility)
6931 Visibility shoud be: HiddenVisibility;
6932 else
6933 Visibility shoud be: DefaultVisibility;
6934 */
6935
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006936 Result += "\n";
6937 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6938 ObjCIvarDecl *IvarDecl = Ivars[i];
Fariborz Jahanian40a777a2012-03-12 16:46:58 +00006939 if (Context->getLangOpts().MicrosoftExt)
6940 Result += "__declspec(allocate(\".objc_ivar$B\")) ";
6941
6942 if (!Context->getLangOpts().MicrosoftExt ||
6943 IvarDecl->getAccessControl() == ObjCIvarDecl::Private ||
Fariborz Jahanian117591f2012-03-10 01:34:42 +00006944 IvarDecl->getAccessControl() == ObjCIvarDecl::Package)
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006945 Result += "extern \"C\" unsigned long int ";
Fariborz Jahaniand1c84d32012-03-10 00:53:02 +00006946 else
Fariborz Jahanian297976d2012-03-29 17:51:09 +00006947 Result += "extern \"C\" __declspec(dllexport) unsigned long int ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006948 if (Ivars[i]->isBitField())
6949 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
6950 else
6951 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006952 Result += " __attribute__ ((used, section (\"__DATA,__objc_ivar\")))";
6953 Result += " = ";
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00006954 RewriteObj.RewriteIvarOffsetComputation(IvarDecl, Result);
6955 Result += ";\n";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006956 if (Ivars[i]->isBitField()) {
6957 // skip over rest of the ivar bitfields.
6958 SKIP_BITFIELDS(i , e, Ivars);
6959 }
Fariborz Jahaniandb649232012-02-13 20:59:02 +00006960 }
6961}
6962
Fariborz Jahanianae932952012-02-10 20:47:10 +00006963static void Write__ivar_list_t_initializer(RewriteModernObjC &RewriteObj,
6964 ASTContext *Context, std::string &Result,
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006965 ArrayRef<ObjCIvarDecl *> OriginalIvars,
Fariborz Jahanianae932952012-02-10 20:47:10 +00006966 StringRef VarName,
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006967 ObjCInterfaceDecl *CDecl) {
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006968 if (OriginalIvars.size() > 0) {
6969 Write_IvarOffsetVar(RewriteObj, Context, Result, OriginalIvars, CDecl);
6970 SmallVector<ObjCIvarDecl *, 8> Ivars;
6971 // strip off all but the first ivar bitfield from each group of ivars.
6972 // Such ivars in the ivar list table will be replaced by their grouping struct
6973 // 'ivar'.
6974 for (unsigned i = 0, e = OriginalIvars.size(); i < e; i++) {
6975 if (OriginalIvars[i]->isBitField()) {
6976 Ivars.push_back(OriginalIvars[i]);
6977 // skip over rest of the ivar bitfields.
6978 SKIP_BITFIELDS(i , e, OriginalIvars);
6979 }
6980 else
6981 Ivars.push_back(OriginalIvars[i]);
6982 }
Fariborz Jahanian07e52882012-02-13 21:34:45 +00006983
Fariborz Jahanianae932952012-02-10 20:47:10 +00006984 Result += "\nstatic ";
6985 Write__ivar_list_t_TypeDecl(Result, Ivars.size());
6986 Result += " "; Result += VarName;
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006987 Result += CDecl->getNameAsString();
Fariborz Jahanianae932952012-02-10 20:47:10 +00006988 Result += " __attribute__ ((used, section (\"__DATA,__objc_const\"))) = {\n";
6989 Result += "\t"; Result += "sizeof(_ivar_t)"; Result += ",\n";
6990 Result += "\t"; Result += utostr(Ivars.size()); Result += ",\n";
6991 for (unsigned i =0, e = Ivars.size(); i < e; i++) {
6992 ObjCIvarDecl *IvarDecl = Ivars[i];
6993 if (i == 0)
6994 Result += "\t{{";
6995 else
6996 Result += "\t {";
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00006997 Result += "(unsigned long int *)&";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00006998 if (Ivars[i]->isBitField())
6999 RewriteObj.ObjCIvarBitfieldGroupOffset(IvarDecl, Result);
7000 else
7001 WriteInternalIvarName(CDecl, IvarDecl, Result);
Fariborz Jahaniandb649232012-02-13 20:59:02 +00007002 Result += ", ";
Fariborz Jahanianae932952012-02-10 20:47:10 +00007003
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007004 Result += "\"";
7005 if (Ivars[i]->isBitField())
7006 RewriteObj.ObjCIvarBitfieldGroupDecl(Ivars[i], Result);
7007 else
7008 Result += IvarDecl->getName();
7009 Result += "\", ";
7010
7011 QualType IVQT = IvarDecl->getType();
7012 if (IvarDecl->isBitField())
7013 IVQT = RewriteObj.GetGroupRecordTypeForObjCIvarBitfield(IvarDecl);
7014
Fariborz Jahanianae932952012-02-10 20:47:10 +00007015 std::string IvarTypeString, QuoteIvarTypeString;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007016 Context->getObjCEncodingForType(IVQT, IvarTypeString,
Fariborz Jahanianae932952012-02-10 20:47:10 +00007017 IvarDecl);
7018 RewriteObj.QuoteDoublequotes(IvarTypeString, QuoteIvarTypeString);
7019 Result += "\""; Result += QuoteIvarTypeString; Result += "\", ";
7020
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007021 // FIXME. this alignment represents the host alignment and need be changed to
7022 // represent the target alignment.
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007023 unsigned Align = Context->getTypeAlign(IVQT)/8;
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007024 Align = llvm::Log2_32(Align);
Fariborz Jahanianae932952012-02-10 20:47:10 +00007025 Result += llvm::utostr(Align); Result += ", ";
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007026 CharUnits Size = Context->getTypeSizeInChars(IVQT);
Fariborz Jahaniana63b4222012-02-10 23:18:24 +00007027 Result += llvm::utostr(Size.getQuantity());
Fariborz Jahanianae932952012-02-10 20:47:10 +00007028 if (i == e-1)
7029 Result += "}}\n";
7030 else
7031 Result += "},\n";
7032 }
7033 Result += "};\n";
7034 }
7035}
7036
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007037/// RewriteObjCProtocolMetaData - Rewrite protocols meta-data.
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007038void RewriteModernObjC::RewriteObjCProtocolMetaData(ObjCProtocolDecl *PDecl,
7039 std::string &Result) {
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007040
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007041 // Do not synthesize the protocol more than once.
7042 if (ObjCSynthesizedProtocols.count(PDecl->getCanonicalDecl()))
7043 return;
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007044 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007045
7046 if (ObjCProtocolDecl *Def = PDecl->getDefinition())
7047 PDecl = Def;
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007048 // Must write out all protocol definitions in current qualifier list,
7049 // and in their nested qualifiers before writing out current definition.
7050 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7051 E = PDecl->protocol_end(); I != E; ++I)
7052 RewriteObjCProtocolMetaData(*I, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007053
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007054 // Construct method lists.
7055 std::vector<ObjCMethodDecl *> InstanceMethods, ClassMethods;
7056 std::vector<ObjCMethodDecl *> OptInstanceMethods, OptClassMethods;
7057 for (ObjCProtocolDecl::instmeth_iterator
7058 I = PDecl->instmeth_begin(), E = PDecl->instmeth_end();
7059 I != E; ++I) {
7060 ObjCMethodDecl *MD = *I;
7061 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7062 OptInstanceMethods.push_back(MD);
7063 } else {
7064 InstanceMethods.push_back(MD);
7065 }
7066 }
7067
7068 for (ObjCProtocolDecl::classmeth_iterator
7069 I = PDecl->classmeth_begin(), E = PDecl->classmeth_end();
7070 I != E; ++I) {
7071 ObjCMethodDecl *MD = *I;
7072 if (MD->getImplementationControl() == ObjCMethodDecl::Optional) {
7073 OptClassMethods.push_back(MD);
7074 } else {
7075 ClassMethods.push_back(MD);
7076 }
7077 }
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00007078 std::vector<ObjCMethodDecl *> AllMethods;
7079 for (unsigned i = 0, e = InstanceMethods.size(); i < e; i++)
7080 AllMethods.push_back(InstanceMethods[i]);
7081 for (unsigned i = 0, e = ClassMethods.size(); i < e; i++)
7082 AllMethods.push_back(ClassMethods[i]);
7083 for (unsigned i = 0, e = OptInstanceMethods.size(); i < e; i++)
7084 AllMethods.push_back(OptInstanceMethods[i]);
7085 for (unsigned i = 0, e = OptClassMethods.size(); i < e; i++)
7086 AllMethods.push_back(OptClassMethods[i]);
7087
7088 Write__extendedMethodTypes_initializer(*this, Context, Result,
7089 AllMethods,
7090 "_OBJC_PROTOCOL_METHOD_TYPES_",
7091 PDecl->getNameAsString());
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007092 // Protocol's super protocol list
7093 std::vector<ObjCProtocolDecl *> SuperProtocols;
7094 for (ObjCProtocolDecl::protocol_iterator I = PDecl->protocol_begin(),
7095 E = PDecl->protocol_end(); I != E; ++I)
7096 SuperProtocols.push_back(*I);
7097
7098 Write_protocol_list_initializer(Context, Result, SuperProtocols,
7099 "_OBJC_PROTOCOL_REFS_",
7100 PDecl->getNameAsString());
7101
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007102 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007103 "_OBJC_PROTOCOL_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007104 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007105
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007106 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007107 "_OBJC_PROTOCOL_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007108 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007109
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007110 Write_method_list_t_initializer(*this, Context, Result, OptInstanceMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007111 "_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007112 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007113
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007114 Write_method_list_t_initializer(*this, Context, Result, OptClassMethods,
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007115 "_OBJC_PROTOCOL_OPT_CLASS_METHODS_",
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007116 PDecl->getNameAsString(), false);
Fariborz Jahanian77e4bca2012-02-07 20:15:08 +00007117
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007118 // Protocol's property metadata.
7119 std::vector<ObjCPropertyDecl *> ProtocolProperties;
7120 for (ObjCContainerDecl::prop_iterator I = PDecl->prop_begin(),
7121 E = PDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007122 ProtocolProperties.push_back(*I);
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007123
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007124 Write_prop_list_t_initializer(*this, Context, Result, ProtocolProperties,
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007125 /* Container */0,
7126 "_OBJC_PROTOCOL_PROPERTIES_",
7127 PDecl->getNameAsString());
Fariborz Jahanianda35eac2012-02-07 23:31:52 +00007128
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007129 // Writer out root metadata for current protocol: struct _protocol_t
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007130 Result += "\n";
7131 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00007132 Result += "static ";
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007133 Result += "struct _protocol_t _OBJC_PROTOCOL_";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007134 Result += PDecl->getNameAsString();
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007135 Result += " __attribute__ ((used, section (\"__DATA,__datacoal_nt,coalesced\"))) = {\n";
7136 Result += "\t0,\n"; // id is; is null
7137 Result += "\t\""; Result += PDecl->getNameAsString(); Result += "\",\n";
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007138 if (SuperProtocols.size() > 0) {
7139 Result += "\t(const struct _protocol_list_t *)&"; Result += "_OBJC_PROTOCOL_REFS_";
7140 Result += PDecl->getNameAsString(); Result += ",\n";
7141 }
7142 else
7143 Result += "\t0,\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007144 if (InstanceMethods.size() > 0) {
7145 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_INSTANCE_METHODS_";
7146 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007147 }
7148 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007149 Result += "\t0,\n";
7150
7151 if (ClassMethods.size() > 0) {
7152 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_CLASS_METHODS_";
7153 Result += PDecl->getNameAsString(); Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007154 }
7155 else
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007156 Result += "\t0,\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007157
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007158 if (OptInstanceMethods.size() > 0) {
7159 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_INSTANCE_METHODS_";
7160 Result += PDecl->getNameAsString(); Result += ",\n";
7161 }
7162 else
7163 Result += "\t0,\n";
7164
7165 if (OptClassMethods.size() > 0) {
7166 Result += "\t(const struct method_list_t *)&_OBJC_PROTOCOL_OPT_CLASS_METHODS_";
7167 Result += PDecl->getNameAsString(); Result += ",\n";
7168 }
7169 else
7170 Result += "\t0,\n";
7171
7172 if (ProtocolProperties.size() > 0) {
7173 Result += "\t(const struct _prop_list_t *)&_OBJC_PROTOCOL_PROPERTIES_";
7174 Result += PDecl->getNameAsString(); Result += ",\n";
7175 }
7176 else
7177 Result += "\t0,\n";
7178
7179 Result += "\t"; Result += "sizeof(_protocol_t)"; Result += ",\n";
7180 Result += "\t0,\n";
7181
Fariborz Jahaniane0adbd82012-02-08 22:23:26 +00007182 if (AllMethods.size() > 0) {
7183 Result += "\t(const char **)&"; Result += "_OBJC_PROTOCOL_METHOD_TYPES_";
7184 Result += PDecl->getNameAsString();
7185 Result += "\n};\n";
7186 }
7187 else
7188 Result += "\t0\n};\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007189
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007190 if (LangOpts.MicrosoftExt)
Fariborz Jahanian8590d862012-04-14 17:13:08 +00007191 Result += "static ";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007192 Result += "struct _protocol_t *";
7193 Result += "_OBJC_LABEL_PROTOCOL_$_"; Result += PDecl->getNameAsString();
7194 Result += " = &_OBJC_PROTOCOL_"; Result += PDecl->getNameAsString();
7195 Result += ";\n";
Fariborz Jahanian82848c22012-02-08 00:50:52 +00007196
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007197 // Mark this protocol as having been generated.
7198 if (!ObjCSynthesizedProtocols.insert(PDecl->getCanonicalDecl()))
7199 llvm_unreachable("protocol already synthesized");
7200
7201}
7202
7203void RewriteModernObjC::RewriteObjCProtocolListMetaData(
7204 const ObjCList<ObjCProtocolDecl> &Protocols,
7205 StringRef prefix, StringRef ClassName,
7206 std::string &Result) {
7207 if (Protocols.empty()) return;
7208
7209 for (unsigned i = 0; i != Protocols.size(); i++)
Fariborz Jahanianda9624a2012-02-08 19:53:58 +00007210 RewriteObjCProtocolMetaData(Protocols[i], Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007211
7212 // Output the top lovel protocol meta-data for the class.
7213 /* struct _objc_protocol_list {
7214 struct _objc_protocol_list *next;
7215 int protocol_count;
7216 struct _objc_protocol *class_protocols[];
7217 }
7218 */
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007219 Result += "\n";
7220 if (LangOpts.MicrosoftExt)
7221 Result += "__declspec(allocate(\".cat_cls_meth$B\")) ";
7222 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007223 Result += "\tstruct _objc_protocol_list *next;\n";
7224 Result += "\tint protocol_count;\n";
7225 Result += "\tstruct _objc_protocol *class_protocols[";
7226 Result += utostr(Protocols.size());
7227 Result += "];\n} _OBJC_";
7228 Result += prefix;
7229 Result += "_PROTOCOLS_";
7230 Result += ClassName;
7231 Result += " __attribute__ ((used, section (\"__OBJC, __cat_cls_meth\")))= "
7232 "{\n\t0, ";
7233 Result += utostr(Protocols.size());
7234 Result += "\n";
7235
7236 Result += "\t,{&_OBJC_PROTOCOL_";
7237 Result += Protocols[0]->getNameAsString();
7238 Result += " \n";
7239
7240 for (unsigned i = 1; i != Protocols.size(); i++) {
7241 Result += "\t ,&_OBJC_PROTOCOL_";
7242 Result += Protocols[i]->getNameAsString();
7243 Result += "\n";
7244 }
7245 Result += "\t }\n};\n";
7246}
7247
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007248/// hasObjCExceptionAttribute - Return true if this class or any super
7249/// class has the __objc_exception__ attribute.
7250/// FIXME. Move this to ASTContext.cpp as it is also used for IRGen.
7251static bool hasObjCExceptionAttribute(ASTContext &Context,
7252 const ObjCInterfaceDecl *OID) {
7253 if (OID->hasAttr<ObjCExceptionAttr>())
7254 return true;
7255 if (const ObjCInterfaceDecl *Super = OID->getSuperClass())
7256 return hasObjCExceptionAttribute(Context, Super);
7257 return false;
7258}
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007259
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007260void RewriteModernObjC::RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
7261 std::string &Result) {
7262 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7263
7264 // Explicitly declared @interface's are already synthesized.
Fariborz Jahanianae932952012-02-10 20:47:10 +00007265 if (CDecl->isImplicitInterfaceDecl())
7266 assert(false &&
7267 "Legacy implicit interface rewriting not supported in moder abi");
Fariborz Jahanian8f1fed02012-02-11 20:10:52 +00007268
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007269 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanianae932952012-02-10 20:47:10 +00007270 SmallVector<ObjCIvarDecl *, 8> IVars;
7271
7272 for (ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7273 IVD; IVD = IVD->getNextIvar()) {
7274 // Ignore unnamed bit-fields.
7275 if (!IVD->getDeclName())
7276 continue;
7277 IVars.push_back(IVD);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007278 }
7279
Fariborz Jahanianae932952012-02-10 20:47:10 +00007280 Write__ivar_list_t_initializer(*this, Context, Result, IVars,
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007281 "_OBJC_$_INSTANCE_VARIABLES_",
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007282 CDecl);
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007283
7284 // Build _objc_method_list for class's instance methods if needed
7285 SmallVector<ObjCMethodDecl *, 32>
7286 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7287
7288 // If any of our property implementations have associated getters or
7289 // setters, produce metadata for them as well.
7290 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7291 PropEnd = IDecl->propimpl_end();
7292 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007293 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007294 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007295 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007296 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007297 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007298 if (!PD)
7299 continue;
7300 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007301 if (mustSynthesizeSetterGetterMethod(IDecl, PD, true /*getter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007302 InstanceMethods.push_back(Getter);
7303 if (PD->isReadOnly())
7304 continue;
7305 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
Fariborz Jahanian301e2e42012-05-03 22:52:13 +00007306 if (mustSynthesizeSetterGetterMethod(IDecl, PD, false /*setter*/))
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007307 InstanceMethods.push_back(Setter);
7308 }
7309
7310 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7311 "_OBJC_$_INSTANCE_METHODS_",
7312 IDecl->getNameAsString(), true);
7313
7314 SmallVector<ObjCMethodDecl *, 32>
7315 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7316
7317 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7318 "_OBJC_$_CLASS_METHODS_",
7319 IDecl->getNameAsString(), true);
Fariborz Jahanian0a525342012-02-14 19:31:35 +00007320
7321 // Protocols referenced in class declaration?
7322 // Protocol's super protocol list
7323 std::vector<ObjCProtocolDecl *> RefedProtocols;
7324 const ObjCList<ObjCProtocolDecl> &Protocols = CDecl->getReferencedProtocols();
7325 for (ObjCList<ObjCProtocolDecl>::iterator I = Protocols.begin(),
7326 E = Protocols.end();
7327 I != E; ++I) {
7328 RefedProtocols.push_back(*I);
7329 // Must write out all protocol definitions in current qualifier list,
7330 // and in their nested qualifiers before writing out current definition.
7331 RewriteObjCProtocolMetaData(*I, Result);
7332 }
7333
7334 Write_protocol_list_initializer(Context, Result,
7335 RefedProtocols,
7336 "_OBJC_CLASS_PROTOCOLS_$_",
7337 IDecl->getNameAsString());
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007338
7339 // Protocol's property metadata.
7340 std::vector<ObjCPropertyDecl *> ClassProperties;
7341 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7342 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007343 ClassProperties.push_back(*I);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007344
7345 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanian2df089d2012-03-22 17:39:35 +00007346 /* Container */IDecl,
Fariborz Jahanianeeabf382012-02-16 21:57:59 +00007347 "_OBJC_$_PROP_LIST_",
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007348 CDecl->getNameAsString());
Fariborz Jahanian90af4e22012-02-14 17:19:02 +00007349
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007350
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007351 // Data for initializing _class_ro_t metaclass meta-data
7352 uint32_t flags = CLS_META;
7353 std::string InstanceSize;
7354 std::string InstanceStart;
7355
7356
7357 bool classIsHidden = CDecl->getVisibility() == HiddenVisibility;
7358 if (classIsHidden)
7359 flags |= OBJC2_CLS_HIDDEN;
7360
7361 if (!CDecl->getSuperClass())
7362 // class is root
7363 flags |= CLS_ROOT;
7364 InstanceSize = "sizeof(struct _class_t)";
7365 InstanceStart = InstanceSize;
7366 Write__class_ro_t_initializer(Context, Result, flags,
7367 InstanceStart, InstanceSize,
7368 ClassMethods,
7369 0,
7370 0,
7371 0,
7372 "_OBJC_METACLASS_RO_$_",
7373 CDecl->getNameAsString());
7374
7375
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007376 // Data for initializing _class_ro_t meta-data
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007377 flags = CLS;
7378 if (classIsHidden)
7379 flags |= OBJC2_CLS_HIDDEN;
7380
7381 if (hasObjCExceptionAttribute(*Context, CDecl))
7382 flags |= CLS_EXCEPTION;
7383
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007384 if (!CDecl->getSuperClass())
7385 // class is root
7386 flags |= CLS_ROOT;
7387
Fariborz Jahanian6ade3432012-02-16 18:54:09 +00007388 InstanceSize.clear();
7389 InstanceStart.clear();
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007390 if (!ObjCSynthesizedStructs.count(CDecl)) {
7391 InstanceSize = "0";
7392 InstanceStart = "0";
7393 }
7394 else {
7395 InstanceSize = "sizeof(struct ";
7396 InstanceSize += CDecl->getNameAsString();
7397 InstanceSize += "_IMPL)";
7398
7399 ObjCIvarDecl *IVD = CDecl->all_declared_ivar_begin();
7400 if (IVD) {
Fariborz Jahanianacee1c92012-04-11 21:12:36 +00007401 RewriteIvarOffsetComputation(IVD, InstanceStart);
Fariborz Jahanianf1c1d9a2012-02-15 00:50:11 +00007402 }
7403 else
7404 InstanceStart = InstanceSize;
7405 }
7406 Write__class_ro_t_initializer(Context, Result, flags,
7407 InstanceStart, InstanceSize,
7408 InstanceMethods,
7409 RefedProtocols,
7410 IVars,
7411 ClassProperties,
7412 "_OBJC_CLASS_RO_$_",
7413 CDecl->getNameAsString());
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007414
7415 Write_class_t(Context, Result,
7416 "OBJC_METACLASS_$_",
7417 CDecl, /*metaclass*/true);
7418
7419 Write_class_t(Context, Result,
7420 "OBJC_CLASS_$_",
7421 CDecl, /*metaclass*/false);
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007422
7423 if (ImplementationIsNonLazy(IDecl))
7424 DefinedNonLazyClasses.push_back(CDecl);
Fariborz Jahanian3f77c7b2012-02-16 21:37:05 +00007425
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007426}
7427
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007428void RewriteModernObjC::RewriteClassSetupInitHook(std::string &Result) {
7429 int ClsDefCount = ClassImplementation.size();
7430 if (!ClsDefCount)
7431 return;
7432 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7433 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7434 Result += "static void *OBJC_CLASS_SETUP[] = {\n";
7435 for (int i = 0; i < ClsDefCount; i++) {
7436 ObjCImplementationDecl *IDecl = ClassImplementation[i];
7437 ObjCInterfaceDecl *CDecl = IDecl->getClassInterface();
7438 Result += "\t(void *)&OBJC_CLASS_SETUP_$_";
7439 Result += CDecl->getName(); Result += ",\n";
7440 }
7441 Result += "};\n";
7442}
7443
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007444void RewriteModernObjC::RewriteMetaDataIntoBuffer(std::string &Result) {
7445 int ClsDefCount = ClassImplementation.size();
7446 int CatDefCount = CategoryImplementation.size();
7447
7448 // For each implemented class, write out all its meta data.
7449 for (int i = 0; i < ClsDefCount; i++)
7450 RewriteObjCClassMetaData(ClassImplementation[i], Result);
7451
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007452 RewriteClassSetupInitHook(Result);
7453
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007454 // For each implemented category, write out all its meta data.
7455 for (int i = 0; i < CatDefCount; i++)
7456 RewriteObjCCategoryImplDecl(CategoryImplementation[i], Result);
7457
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007458 RewriteCategorySetupInitHook(Result);
7459
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007460 if (ClsDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007461 if (LangOpts.MicrosoftExt)
7462 Result += "__declspec(allocate(\".objc_classlist$B\")) ";
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007463 Result += "static struct _class_t *L_OBJC_LABEL_CLASS_$ [";
7464 Result += llvm::utostr(ClsDefCount); Result += "]";
7465 Result +=
7466 " __attribute__((used, section (\"__DATA, __objc_classlist,"
7467 "regular,no_dead_strip\")))= {\n";
7468 for (int i = 0; i < ClsDefCount; i++) {
7469 Result += "\t&OBJC_CLASS_$_";
7470 Result += ClassImplementation[i]->getNameAsString();
7471 Result += ",\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007472 }
Fariborz Jahaniandf795672012-02-17 00:06:14 +00007473 Result += "};\n";
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007474
7475 if (!DefinedNonLazyClasses.empty()) {
7476 if (LangOpts.MicrosoftExt)
7477 Result += "__declspec(allocate(\".objc_nlclslist$B\")) \n";
7478 Result += "static struct _class_t *_OBJC_LABEL_NONLAZY_CLASS_$[] = {\n\t";
7479 for (unsigned i = 0, e = DefinedNonLazyClasses.size(); i < e; i++) {
7480 Result += "\t&OBJC_CLASS_$_"; Result += DefinedNonLazyClasses[i]->getNameAsString();
7481 Result += ",\n";
7482 }
7483 Result += "};\n";
7484 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007485 }
Fariborz Jahanian61186122012-02-17 18:40:41 +00007486
7487 if (CatDefCount > 0) {
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007488 if (LangOpts.MicrosoftExt)
7489 Result += "__declspec(allocate(\".objc_catlist$B\")) ";
Fariborz Jahanian61186122012-02-17 18:40:41 +00007490 Result += "static struct _category_t *L_OBJC_LABEL_CATEGORY_$ [";
7491 Result += llvm::utostr(CatDefCount); Result += "]";
7492 Result +=
7493 " __attribute__((used, section (\"__DATA, __objc_catlist,"
7494 "regular,no_dead_strip\")))= {\n";
7495 for (int i = 0; i < CatDefCount; i++) {
7496 Result += "\t&_OBJC_$_CATEGORY_";
7497 Result +=
7498 CategoryImplementation[i]->getClassInterface()->getNameAsString();
7499 Result += "_$_";
7500 Result += CategoryImplementation[i]->getNameAsString();
7501 Result += ",\n";
7502 }
7503 Result += "};\n";
7504 }
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007505
7506 if (!DefinedNonLazyCategories.empty()) {
7507 if (LangOpts.MicrosoftExt)
7508 Result += "__declspec(allocate(\".objc_nlcatlist$B\")) \n";
7509 Result += "static struct _category_t *_OBJC_LABEL_NONLAZY_CATEGORY_$[] = {\n\t";
7510 for (unsigned i = 0, e = DefinedNonLazyCategories.size(); i < e; i++) {
7511 Result += "\t&_OBJC_$_CATEGORY_";
7512 Result +=
7513 DefinedNonLazyCategories[i]->getClassInterface()->getNameAsString();
7514 Result += "_$_";
7515 Result += DefinedNonLazyCategories[i]->getNameAsString();
7516 Result += ",\n";
7517 }
7518 Result += "};\n";
7519 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007520}
7521
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007522void RewriteModernObjC::WriteImageInfo(std::string &Result) {
7523 if (LangOpts.MicrosoftExt)
7524 Result += "__declspec(allocate(\".objc_imageinfo$B\")) \n";
7525
7526 Result += "static struct IMAGE_INFO { unsigned version; unsigned flag; } ";
7527 // version 0, ObjCABI is 2
Fariborz Jahanian30650eb2012-03-15 17:05:33 +00007528 Result += "_OBJC_IMAGE_INFO = { 0, 2 };\n";
Fariborz Jahanian10cde2f2012-03-14 21:44:09 +00007529}
7530
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007531/// RewriteObjCCategoryImplDecl - Rewrite metadata for each category
7532/// implementation.
7533void RewriteModernObjC::RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *IDecl,
7534 std::string &Result) {
Fariborz Jahaniande5d9462012-03-14 18:09:23 +00007535 WriteModernMetadataDeclarations(Context, Result);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007536 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7537 // Find category declaration for this implementation.
Douglas Gregord3297242013-01-16 23:00:23 +00007538 ObjCCategoryDecl *CDecl
7539 = ClassDecl->FindCategoryDeclaration(IDecl->getIdentifier());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007540
7541 std::string FullCategoryName = ClassDecl->getNameAsString();
Fariborz Jahanian61186122012-02-17 18:40:41 +00007542 FullCategoryName += "_$_";
7543 FullCategoryName += CDecl->getNameAsString();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007544
7545 // Build _objc_method_list for class's instance methods if needed
7546 SmallVector<ObjCMethodDecl *, 32>
7547 InstanceMethods(IDecl->instmeth_begin(), IDecl->instmeth_end());
7548
7549 // If any of our property implementations have associated getters or
7550 // setters, produce metadata for them as well.
7551 for (ObjCImplDecl::propimpl_iterator Prop = IDecl->propimpl_begin(),
7552 PropEnd = IDecl->propimpl_end();
7553 Prop != PropEnd; ++Prop) {
David Blaikie262bc182012-04-30 02:36:29 +00007554 if (Prop->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007555 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007556 if (!Prop->getPropertyIvarDecl())
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007557 continue;
David Blaikie262bc182012-04-30 02:36:29 +00007558 ObjCPropertyDecl *PD = Prop->getPropertyDecl();
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007559 if (!PD)
7560 continue;
7561 if (ObjCMethodDecl *Getter = PD->getGetterMethodDecl())
7562 InstanceMethods.push_back(Getter);
7563 if (PD->isReadOnly())
7564 continue;
7565 if (ObjCMethodDecl *Setter = PD->getSetterMethodDecl())
7566 InstanceMethods.push_back(Setter);
7567 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007568
Fariborz Jahanian61186122012-02-17 18:40:41 +00007569 Write_method_list_t_initializer(*this, Context, Result, InstanceMethods,
7570 "_OBJC_$_CATEGORY_INSTANCE_METHODS_",
7571 FullCategoryName, true);
7572
7573 SmallVector<ObjCMethodDecl *, 32>
7574 ClassMethods(IDecl->classmeth_begin(), IDecl->classmeth_end());
7575
7576 Write_method_list_t_initializer(*this, Context, Result, ClassMethods,
7577 "_OBJC_$_CATEGORY_CLASS_METHODS_",
7578 FullCategoryName, true);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007579
7580 // Protocols referenced in class declaration?
Fariborz Jahanian61186122012-02-17 18:40:41 +00007581 // Protocol's super protocol list
7582 std::vector<ObjCProtocolDecl *> RefedProtocols;
Argyrios Kyrtzidisa5f44412012-03-13 01:09:41 +00007583 for (ObjCInterfaceDecl::protocol_iterator I = CDecl->protocol_begin(),
7584 E = CDecl->protocol_end();
7585
7586 I != E; ++I) {
Fariborz Jahanian61186122012-02-17 18:40:41 +00007587 RefedProtocols.push_back(*I);
7588 // Must write out all protocol definitions in current qualifier list,
7589 // and in their nested qualifiers before writing out current definition.
7590 RewriteObjCProtocolMetaData(*I, Result);
7591 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007592
Fariborz Jahanian61186122012-02-17 18:40:41 +00007593 Write_protocol_list_initializer(Context, Result,
7594 RefedProtocols,
7595 "_OBJC_CATEGORY_PROTOCOLS_$_",
7596 FullCategoryName);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007597
Fariborz Jahanian61186122012-02-17 18:40:41 +00007598 // Protocol's property metadata.
7599 std::vector<ObjCPropertyDecl *> ClassProperties;
7600 for (ObjCContainerDecl::prop_iterator I = CDecl->prop_begin(),
7601 E = CDecl->prop_end(); I != E; ++I)
David Blaikie581deb32012-06-06 20:45:41 +00007602 ClassProperties.push_back(*I);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007603
Fariborz Jahanian61186122012-02-17 18:40:41 +00007604 Write_prop_list_t_initializer(*this, Context, Result, ClassProperties,
Fariborz Jahanianebfa2722012-05-03 23:19:33 +00007605 /* Container */IDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007606 "_OBJC_$_PROP_LIST_",
7607 FullCategoryName);
7608
7609 Write_category_t(*this, Context, Result,
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007610 CDecl,
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007611 ClassDecl,
Fariborz Jahanian61186122012-02-17 18:40:41 +00007612 InstanceMethods,
7613 ClassMethods,
7614 RefedProtocols,
7615 ClassProperties);
7616
Fariborz Jahanian88f7f752012-03-14 23:18:19 +00007617 // Determine if this category is also "non-lazy".
7618 if (ImplementationIsNonLazy(IDecl))
7619 DefinedNonLazyCategories.push_back(CDecl);
Fariborz Jahaniane0335782012-03-27 18:41:05 +00007620
7621}
7622
7623void RewriteModernObjC::RewriteCategorySetupInitHook(std::string &Result) {
7624 int CatDefCount = CategoryImplementation.size();
7625 if (!CatDefCount)
7626 return;
7627 Result += "#pragma section(\".objc_inithooks$B\", long, read, write)\n";
7628 Result += "__declspec(allocate(\".objc_inithooks$B\")) ";
7629 Result += "static void *OBJC_CATEGORY_SETUP[] = {\n";
7630 for (int i = 0; i < CatDefCount; i++) {
7631 ObjCCategoryImplDecl *IDecl = CategoryImplementation[i];
7632 ObjCCategoryDecl *CatDecl= IDecl->getCategoryDecl();
7633 ObjCInterfaceDecl *ClassDecl = IDecl->getClassInterface();
7634 Result += "\t(void *)&OBJC_CATEGORY_SETUP_$_";
7635 Result += ClassDecl->getName();
7636 Result += "_$_";
7637 Result += CatDecl->getName();
7638 Result += ",\n";
7639 }
7640 Result += "};\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007641}
7642
7643// RewriteObjCMethodsMetaData - Rewrite methods metadata for instance or
7644/// class methods.
7645template<typename MethodIterator>
7646void RewriteModernObjC::RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
7647 MethodIterator MethodEnd,
7648 bool IsInstanceMethod,
7649 StringRef prefix,
7650 StringRef ClassName,
7651 std::string &Result) {
7652 if (MethodBegin == MethodEnd) return;
7653
7654 if (!objc_impl_method) {
7655 /* struct _objc_method {
7656 SEL _cmd;
7657 char *method_types;
7658 void *_imp;
7659 }
7660 */
7661 Result += "\nstruct _objc_method {\n";
7662 Result += "\tSEL _cmd;\n";
7663 Result += "\tchar *method_types;\n";
7664 Result += "\tvoid *_imp;\n";
7665 Result += "};\n";
7666
7667 objc_impl_method = true;
7668 }
7669
7670 // Build _objc_method_list for class's methods if needed
7671
7672 /* struct {
7673 struct _objc_method_list *next_method;
7674 int method_count;
7675 struct _objc_method method_list[];
7676 }
7677 */
7678 unsigned NumMethods = std::distance(MethodBegin, MethodEnd);
Fariborz Jahanian1ca052c2012-03-11 19:41:56 +00007679 Result += "\n";
7680 if (LangOpts.MicrosoftExt) {
7681 if (IsInstanceMethod)
7682 Result += "__declspec(allocate(\".inst_meth$B\")) ";
7683 else
7684 Result += "__declspec(allocate(\".cls_meth$B\")) ";
7685 }
7686 Result += "static struct {\n";
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007687 Result += "\tstruct _objc_method_list *next_method;\n";
7688 Result += "\tint method_count;\n";
7689 Result += "\tstruct _objc_method method_list[";
7690 Result += utostr(NumMethods);
7691 Result += "];\n} _OBJC_";
7692 Result += prefix;
7693 Result += IsInstanceMethod ? "INSTANCE" : "CLASS";
7694 Result += "_METHODS_";
7695 Result += ClassName;
7696 Result += " __attribute__ ((used, section (\"__OBJC, __";
7697 Result += IsInstanceMethod ? "inst" : "cls";
7698 Result += "_meth\")))= ";
7699 Result += "{\n\t0, " + utostr(NumMethods) + "\n";
7700
7701 Result += "\t,{{(SEL)\"";
7702 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7703 std::string MethodTypeString;
7704 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7705 Result += "\", \"";
7706 Result += MethodTypeString;
7707 Result += "\", (void *)";
7708 Result += MethodInternalNames[*MethodBegin];
7709 Result += "}\n";
7710 for (++MethodBegin; MethodBegin != MethodEnd; ++MethodBegin) {
7711 Result += "\t ,{(SEL)\"";
7712 Result += (*MethodBegin)->getSelector().getAsString().c_str();
7713 std::string MethodTypeString;
7714 Context->getObjCEncodingForMethodDecl(*MethodBegin, MethodTypeString);
7715 Result += "\", \"";
7716 Result += MethodTypeString;
7717 Result += "\", (void *)";
7718 Result += MethodInternalNames[*MethodBegin];
7719 Result += "}\n";
7720 }
7721 Result += "\t }\n};\n";
7722}
7723
7724Stmt *RewriteModernObjC::RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) {
7725 SourceRange OldRange = IV->getSourceRange();
7726 Expr *BaseExpr = IV->getBase();
7727
7728 // Rewrite the base, but without actually doing replaces.
7729 {
7730 DisableReplaceStmtScope S(*this);
7731 BaseExpr = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(BaseExpr));
7732 IV->setBase(BaseExpr);
7733 }
7734
7735 ObjCIvarDecl *D = IV->getDecl();
7736
7737 Expr *Replacement = IV;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007738
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007739 if (BaseExpr->getType()->isObjCObjectPointerType()) {
7740 const ObjCInterfaceType *iFaceDecl =
Fariborz Jahanian163d3ce2012-05-08 23:54:35 +00007741 dyn_cast<ObjCInterfaceType>(BaseExpr->getType()->getPointeeType());
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007742 assert(iFaceDecl && "RewriteObjCIvarRefExpr - iFaceDecl is null");
7743 // lookup which class implements the instance variable.
7744 ObjCInterfaceDecl *clsDeclared = 0;
7745 iFaceDecl->getDecl()->lookupInstanceVariable(D->getIdentifier(),
7746 clsDeclared);
7747 assert(clsDeclared && "RewriteObjCIvarRefExpr(): Can't find class");
7748
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007749 // Build name of symbol holding ivar offset.
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007750 std::string IvarOffsetName;
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007751 if (D->isBitField())
7752 ObjCIvarBitfieldGroupOffset(D, IvarOffsetName);
7753 else
7754 WriteInternalIvarName(clsDeclared, D, IvarOffsetName);
Fariborz Jahanian7cb2a1b2012-03-20 17:13:39 +00007755
Fariborz Jahanian72c88f12012-02-22 18:13:25 +00007756 ReferencedIvars[clsDeclared].insert(D);
7757
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007758 // cast offset to "char *".
7759 CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context,
7760 Context->getPointerType(Context->CharTy),
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007761 CK_BitCast,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007762 BaseExpr);
7763 VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
7764 SourceLocation(), &Context->Idents.get(IvarOffsetName),
Rafael Espindolad2615cc2013-04-03 19:27:57 +00007765 Context->UnsignedLongTy, 0, SC_Extern);
John McCallf4b88a42012-03-10 09:33:50 +00007766 DeclRefExpr *DRE = new (Context) DeclRefExpr(NewVD, false,
7767 Context->UnsignedLongTy, VK_LValue,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007768 SourceLocation());
7769 BinaryOperator *addExpr =
7770 new (Context) BinaryOperator(castExpr, DRE, BO_Add,
7771 Context->getPointerType(Context->CharTy),
Lang Hamesbe9af122012-10-02 04:45:10 +00007772 VK_RValue, OK_Ordinary, SourceLocation(), false);
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007773 // Don't forget the parens to enforce the proper binding.
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007774 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(),
7775 SourceLocation(),
7776 addExpr);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007777 QualType IvarT = D->getType();
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007778 if (D->isBitField())
7779 IvarT = GetGroupRecordTypeForObjCIvarBitfield(D);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007780
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007781 if (!isa<TypedefType>(IvarT) && IvarT->isRecordType()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007782 RecordDecl *RD = IvarT->getAs<RecordType>()->getDecl();
Fariborz Jahanian8fba8942012-04-30 23:20:30 +00007783 RD = RD->getDefinition();
7784 if (RD && !RD->getDeclName().getAsIdentifierInfo()) {
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007785 // decltype(((Foo_IMPL*)0)->bar) *
Fariborz Jahanianf5eac482012-05-02 17:34:59 +00007786 ObjCContainerDecl *CDecl =
7787 dyn_cast<ObjCContainerDecl>(D->getDeclContext());
7788 // ivar in class extensions requires special treatment.
7789 if (ObjCCategoryDecl *CatDecl = dyn_cast<ObjCCategoryDecl>(CDecl))
7790 CDecl = CatDecl->getClassInterface();
7791 std::string RecName = CDecl->getName();
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007792 RecName += "_IMPL";
7793 RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
7794 SourceLocation(), SourceLocation(),
7795 &Context->Idents.get(RecName.c_str()));
7796 QualType PtrStructIMPL = Context->getPointerType(Context->getTagDeclType(RD));
7797 unsigned UnsignedIntSize =
7798 static_cast<unsigned>(Context->getTypeSize(Context->UnsignedIntTy));
7799 Expr *Zero = IntegerLiteral::Create(*Context,
7800 llvm::APInt(UnsignedIntSize, 0),
7801 Context->UnsignedIntTy, SourceLocation());
7802 Zero = NoTypeInfoCStyleCastExpr(Context, PtrStructIMPL, CK_BitCast, Zero);
7803 ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
7804 Zero);
7805 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7806 SourceLocation(),
7807 &Context->Idents.get(D->getNameAsString()),
7808 IvarT, 0,
7809 /*BitWidth=*/0, /*Mutable=*/true,
Richard Smithca523302012-06-10 03:12:00 +00007810 ICIS_NoInit);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007811 MemberExpr *ME = new (Context) MemberExpr(PE, true, FD, SourceLocation(),
7812 FD->getType(), VK_LValue,
7813 OK_Ordinary);
7814 IvarT = Context->getDecltypeType(ME, ME->getType());
7815 }
7816 }
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007817 convertObjCTypeToCStyleType(IvarT);
Fariborz Jahanian0d6e22a2012-02-24 17:35:35 +00007818 QualType castT = Context->getPointerType(IvarT);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007819
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007820 castExpr = NoTypeInfoCStyleCastExpr(Context,
7821 castT,
7822 CK_BitCast,
7823 PE);
Fariborz Jahanian27fc81b2012-04-27 22:48:54 +00007824
7825
Fariborz Jahanian8e0913d2012-02-29 00:26:20 +00007826 Expr *Exp = new (Context) UnaryOperator(castExpr, UO_Deref, IvarT,
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007827 VK_LValue, OK_Ordinary,
7828 SourceLocation());
7829 PE = new (Context) ParenExpr(OldRange.getBegin(),
7830 OldRange.getEnd(),
7831 Exp);
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007832
7833 if (D->isBitField()) {
7834 FieldDecl *FD = FieldDecl::Create(*Context, 0, SourceLocation(),
7835 SourceLocation(),
7836 &Context->Idents.get(D->getNameAsString()),
7837 D->getType(), 0,
7838 /*BitWidth=*/D->getBitWidth(),
7839 /*Mutable=*/true,
7840 ICIS_NoInit);
7841 MemberExpr *ME = new (Context) MemberExpr(PE, /*isArrow*/false, FD, SourceLocation(),
7842 FD->getType(), VK_LValue,
7843 OK_Ordinary);
7844 Replacement = ME;
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007845
Fariborz Jahaniancd3b0362013-02-07 01:53:15 +00007846 }
7847 else
7848 Replacement = PE;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007849 }
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007850
Fariborz Jahaniane7b3fa72012-02-21 23:46:48 +00007851 ReplaceStmtWithRange(IV, Replacement, OldRange);
7852 return Replacement;
Fariborz Jahanian64cb63a2012-02-07 17:11:38 +00007853}