Coverage Report

Created: 2020-02-25 14:32

/Users/buildslave/jenkins/workspace/coverage/llvm-project/clang/lib/Frontend/Rewrite/RewriteObjC.cpp
Line
Count
Source (jump to first uncovered line)
1
//===--- RewriteObjC.cpp - Playground for the code rewriter ---------------===//
2
//
3
// Part of the LLVM Project, under the Apache License v2.0 with LLVM Exceptions.
4
// See https://llvm.org/LICENSE.txt for license information.
5
// SPDX-License-Identifier: Apache-2.0 WITH LLVM-exception
6
//
7
//===----------------------------------------------------------------------===//
8
//
9
// Hacks and fun related to the code rewriter.
10
//
11
//===----------------------------------------------------------------------===//
12
13
#include "clang/Rewrite/Frontend/ASTConsumers.h"
14
#include "clang/AST/AST.h"
15
#include "clang/AST/ASTConsumer.h"
16
#include "clang/AST/Attr.h"
17
#include "clang/AST/ParentMap.h"
18
#include "clang/Basic/CharInfo.h"
19
#include "clang/Basic/Diagnostic.h"
20
#include "clang/Basic/IdentifierTable.h"
21
#include "clang/Basic/SourceManager.h"
22
#include "clang/Config/config.h"
23
#include "clang/Lex/Lexer.h"
24
#include "clang/Rewrite/Core/Rewriter.h"
25
#include "llvm/ADT/DenseSet.h"
26
#include "llvm/ADT/SmallPtrSet.h"
27
#include "llvm/ADT/StringExtras.h"
28
#include "llvm/Support/MemoryBuffer.h"
29
#include "llvm/Support/raw_ostream.h"
30
#include <memory>
31
32
#if CLANG_ENABLE_OBJC_REWRITER
33
34
using namespace clang;
35
using llvm::utostr;
36
37
namespace {
38
  class RewriteObjC : public ASTConsumer {
39
  protected:
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
    };
61
    static const int OBJC_ABI_VERSION = 7;
62
63
    Rewriter Rewrite;
64
    DiagnosticsEngine &Diags;
65
    const LangOptions &LangOpts;
66
    ASTContext *Context;
67
    SourceManager *SM;
68
    TranslationUnitDecl *TUDecl;
69
    FileID MainFileID;
70
    const char *MainFileStart, *MainFileEnd;
71
    Stmt *CurrentBody;
72
    ParentMap *PropParentMap; // created lazily.
73
    std::string InFileName;
74
    std::unique_ptr<raw_ostream> OutFile;
75
    std::string Preamble;
76
77
    TypeDecl *ProtocolTypeDecl;
78
    VarDecl *GlobalVarDecl;
79
    unsigned RewriteFailedDiag;
80
    // ObjC string constant support.
81
    unsigned NumObjCStringLiterals;
82
    VarDecl *ConstantStringClassReference;
83
    RecordDecl *NSStringRecord;
84
85
    // ObjC foreach break/continue generation support.
86
    int BcLabelCount;
87
88
    unsigned TryFinallyContainsReturnDiag;
89
    // Needed for super.
90
    ObjCMethodDecl *CurMethodDef;
91
    RecordDecl *SuperStructDecl;
92
    RecordDecl *ConstantStringDecl;
93
94
    FunctionDecl *MsgSendFunctionDecl;
95
    FunctionDecl *MsgSendSuperFunctionDecl;
96
    FunctionDecl *MsgSendStretFunctionDecl;
97
    FunctionDecl *MsgSendSuperStretFunctionDecl;
98
    FunctionDecl *MsgSendFpretFunctionDecl;
99
    FunctionDecl *GetClassFunctionDecl;
100
    FunctionDecl *GetMetaClassFunctionDecl;
101
    FunctionDecl *GetSuperClassFunctionDecl;
102
    FunctionDecl *SelGetUidFunctionDecl;
103
    FunctionDecl *CFStringFunctionDecl;
104
    FunctionDecl *SuperConstructorFunctionDecl;
105
    FunctionDecl *CurFunctionDef;
106
    FunctionDecl *CurFunctionDeclToDeclareForBlock;
107
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;
113
    llvm::SmallPtrSet<ObjCInterfaceDecl*, 8> ObjCForwardDecls;
114
    llvm::DenseMap<ObjCMethodDecl*, std::string> MethodInternalNames;
115
    SmallVector<Stmt *, 32> Stmts;
116
    SmallVector<int, 8> ObjCBcLabelNo;
117
    // Remember all the @protocol(<expr>) expressions.
118
    llvm::SmallPtrSet<ObjCProtocolDecl *, 32> ProtocolExprDecls;
119
120
    llvm::DenseSet<uint64_t> CopyDestroyCache;
121
122
    // Block expressions.
123
    SmallVector<BlockExpr *, 32> Blocks;
124
    SmallVector<int, 32> InnerDeclRefsCount;
125
    SmallVector<DeclRefExpr *, 32> InnerDeclRefs;
126
127
    SmallVector<DeclRefExpr *, 32> BlockDeclRefs;
128
129
    // Block related declarations.
130
    SmallVector<ValueDecl *, 8> BlockByCopyDecls;
131
    llvm::SmallPtrSet<ValueDecl *, 8> BlockByCopyDeclsPtrSet;
132
    SmallVector<ValueDecl *, 8> BlockByRefDecls;
133
    llvm::SmallPtrSet<ValueDecl *, 8> BlockByRefDeclsPtrSet;
134
    llvm::DenseMap<ValueDecl *, unsigned> BlockByRefDeclNo;
135
    llvm::SmallPtrSet<ValueDecl *, 8> ImportedBlockDecls;
136
    llvm::SmallPtrSet<VarDecl *, 8> ImportedLocalExternalDecls;
137
138
    llvm::DenseMap<BlockExpr *, std::string> RewrittenBlockExprs;
139
140
    // This maps an original source AST to it's rewritten form. This allows
141
    // us to avoid rewriting the same node twice (which is very uncommon).
142
    // This is needed to support some of the exotic property rewriting.
143
    llvm::DenseMap<Stmt *, Stmt *> ReplacedNodes;
144
145
    // Needed for header files being rewritten
146
    bool IsHeader;
147
    bool SilenceRewriteMacroWarning;
148
    bool objc_impl_method;
149
150
    bool DisableReplaceStmt;
151
    class DisableReplaceStmtScope {
152
      RewriteObjC &R;
153
      bool SavedValue;
154
155
    public:
156
      DisableReplaceStmtScope(RewriteObjC &R)
157
79
        : R(R), SavedValue(R.DisableReplaceStmt) {
158
79
        R.DisableReplaceStmt = true;
159
79
      }
160
161
79
      ~DisableReplaceStmtScope() {
162
79
        R.DisableReplaceStmt = SavedValue;
163
79
      }
164
    };
165
166
    void InitializeCommon(ASTContext &context);
167
168
  public:
169
    // Top Level Driver code.
170
439
    bool HandleTopLevelDecl(DeclGroupRef D) override {
171
949
      for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; 
++I510
) {
172
533
        if (ObjCInterfaceDecl *Class = dyn_cast<ObjCInterfaceDecl>(*I)) {
173
135
          if (!Class->isThisDeclarationADefinition()) {
174
17
            RewriteForwardClassDecl(D);
175
17
            break;
176
17
          }
177
516
        }
178
516
179
516
        if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>(*I)) {
180
27
          if (!Proto->isThisDeclarationADefinition()) {
181
6
            RewriteForwardProtocolDecl(D);
182
6
            break;
183
6
          }
184
510
        }
185
510
186
510
        HandleTopLevelSingleDecl(*I);
187
510
      }
188
439
      return true;
189
439
    }
190
191
    void HandleTopLevelSingleDecl(Decl *D);
192
    void HandleDeclInMainFile(Decl *D);
193
    RewriteObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
194
                DiagnosticsEngine &D, const LangOptions &LOpts,
195
                bool silenceMacroWarn);
196
197
86
    ~RewriteObjC() override {}
198
199
    void HandleTranslationUnit(ASTContext &C) override;
200
201
227
    void ReplaceStmt(Stmt *Old, Stmt *New) {
202
227
      ReplaceStmtWithRange(Old, New, Old->getSourceRange());
203
227
    }
204
205
306
    void ReplaceStmtWithRange(Stmt *Old, Stmt *New, SourceRange SrcRange) {
206
306
      assert(Old != nullptr && New != nullptr && "Expected non-null Stmt's");
207
306
208
306
      Stmt *ReplacingStmt = ReplacedNodes[Old];
209
306
      if (ReplacingStmt)
210
0
        return; // We can't rewrite the same node twice.
211
306
212
306
      if (DisableReplaceStmt)
213
24
        return;
214
282
215
282
      // Measure the old text.
216
282
      int Size = Rewrite.getRangeSize(SrcRange);
217
282
      if (Size == -1) {
218
0
        Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
219
0
            << Old->getSourceRange();
220
0
        return;
221
0
      }
222
282
      // Get the new text.
223
282
      std::string SStr;
224
282
      llvm::raw_string_ostream S(SStr);
225
282
      New->printPretty(S, nullptr, PrintingPolicy(LangOpts));
226
282
      const std::string &Str = S.str();
227
282
228
282
      // If replacement succeeded or warning disabled return with no warning.
229
282
      if (!Rewrite.ReplaceText(SrcRange.getBegin(), Size, Str)) {
230
282
        ReplacedNodes[Old] = New;
231
282
        return;
232
282
      }
233
0
      if (SilenceRewriteMacroWarning)
234
0
        return;
235
0
      Diags.Report(Context->getFullLoc(Old->getBeginLoc()), RewriteFailedDiag)
236
0
          << Old->getSourceRange();
237
0
    }
238
239
    void InsertText(SourceLocation Loc, StringRef Str,
240
817
                    bool InsertAfter = true) {
241
817
      // If insertion succeeded or warning disabled return with no warning.
242
817
      if (!Rewrite.InsertText(Loc, Str, InsertAfter) ||
243
817
          
SilenceRewriteMacroWarning0
)
244
817
        return;
245
0
246
0
      Diags.Report(Context->getFullLoc(Loc), RewriteFailedDiag);
247
0
    }
248
249
    void ReplaceText(SourceLocation Start, unsigned OrigLength,
250
599
                     StringRef Str) {
251
599
      // If removal succeeded or warning disabled return with no warning.
252
599
      if (!Rewrite.ReplaceText(Start, OrigLength, Str) ||
253
599
          
SilenceRewriteMacroWarning0
)
254
599
        return;
255
0
256
0
      Diags.Report(Context->getFullLoc(Start), RewriteFailedDiag);
257
0
    }
258
259
    // Syntactic Rewriting.
260
    void RewriteRecordBody(RecordDecl *RD);
261
    void RewriteInclude();
262
    void RewriteForwardClassDecl(DeclGroupRef D);
263
    void RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &DG);
264
    void RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
265
                                     const std::string &typedefString);
266
    void RewriteImplementations();
267
    void RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
268
                                 ObjCImplementationDecl *IMD,
269
                                 ObjCCategoryImplDecl *CID);
270
    void RewriteInterfaceDecl(ObjCInterfaceDecl *Dcl);
271
    void RewriteImplementationDecl(Decl *Dcl);
272
    void RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
273
                               ObjCMethodDecl *MDecl, std::string &ResultStr);
274
    void RewriteTypeIntoString(QualType T, std::string &ResultStr,
275
                               const FunctionType *&FPRetType);
276
    void RewriteByRefString(std::string &ResultStr, const std::string &Name,
277
                            ValueDecl *VD, bool def=false);
278
    void RewriteCategoryDecl(ObjCCategoryDecl *Dcl);
279
    void RewriteProtocolDecl(ObjCProtocolDecl *Dcl);
280
    void RewriteForwardProtocolDecl(DeclGroupRef D);
281
    void RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG);
282
    void RewriteMethodDeclaration(ObjCMethodDecl *Method);
283
    void RewriteProperty(ObjCPropertyDecl *prop);
284
    void RewriteFunctionDecl(FunctionDecl *FD);
285
    void RewriteBlockPointerType(std::string& Str, QualType Type);
286
    void RewriteBlockPointerTypeVariable(std::string& Str, ValueDecl *VD);
287
    void RewriteBlockLiteralFunctionDecl(FunctionDecl *FD);
288
    void RewriteObjCQualifiedInterfaceTypes(Decl *Dcl);
289
    void RewriteTypeOfDecl(VarDecl *VD);
290
    void RewriteObjCQualifiedInterfaceTypes(Expr *E);
291
292
    // Expression Rewriting.
293
    Stmt *RewriteFunctionBodyOrGlobalInitializer(Stmt *S);
294
    Stmt *RewriteAtEncode(ObjCEncodeExpr *Exp);
295
    Stmt *RewritePropertyOrImplicitGetter(PseudoObjectExpr *Pseudo);
296
    Stmt *RewritePropertyOrImplicitSetter(PseudoObjectExpr *Pseudo);
297
    Stmt *RewriteAtSelector(ObjCSelectorExpr *Exp);
298
    Stmt *RewriteMessageExpr(ObjCMessageExpr *Exp);
299
    Stmt *RewriteObjCStringLiteral(ObjCStringLiteral *Exp);
300
    Stmt *RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp);
301
    void RewriteTryReturnStmts(Stmt *S);
302
    void RewriteSyncReturnStmts(Stmt *S, std::string buf);
303
    Stmt *RewriteObjCTryStmt(ObjCAtTryStmt *S);
304
    Stmt *RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S);
305
    Stmt *RewriteObjCThrowStmt(ObjCAtThrowStmt *S);
306
    Stmt *RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
307
                                       SourceLocation OrigEnd);
308
    Stmt *RewriteBreakStmt(BreakStmt *S);
309
    Stmt *RewriteContinueStmt(ContinueStmt *S);
310
    void RewriteCastExpr(CStyleCastExpr *CE);
311
312
    // Block rewriting.
313
    void RewriteBlocksInFunctionProtoType(QualType funcType, NamedDecl *D);
314
315
    // Block specific rewrite rules.
316
    void RewriteBlockPointerDecl(NamedDecl *VD);
317
    void RewriteByRefVar(VarDecl *VD);
318
    Stmt *RewriteBlockDeclRefExpr(DeclRefExpr *VD);
319
    Stmt *RewriteLocalVariableExternalStorage(DeclRefExpr *DRE);
320
    void RewriteBlockPointerFunctionArgs(FunctionDecl *FD);
321
322
    void RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
323
                                      std::string &Result);
324
325
    void Initialize(ASTContext &context) override = 0;
326
327
    // Metadata Rewriting.
328
    virtual void RewriteMetaDataIntoBuffer(std::string &Result) = 0;
329
    virtual void RewriteObjCProtocolListMetaData(const ObjCList<ObjCProtocolDecl> &Prots,
330
                                                 StringRef prefix,
331
                                                 StringRef ClassName,
332
                                                 std::string &Result) = 0;
333
    virtual void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
334
                                             std::string &Result) = 0;
335
    virtual void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
336
                                     StringRef prefix,
337
                                     StringRef ClassName,
338
                                     std::string &Result) = 0;
339
    virtual void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
340
                                          std::string &Result) = 0;
341
342
    // Rewriting ivar access
343
    virtual Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) = 0;
344
    virtual void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
345
                                         std::string &Result) = 0;
346
347
    // Misc. AST transformation routines. Sometimes they end up calling
348
    // rewriting routines on the new ASTs.
349
    CallExpr *SynthesizeCallToFunctionDecl(FunctionDecl *FD,
350
                                           ArrayRef<Expr *> Args,
351
                                           SourceLocation StartLoc=SourceLocation(),
352
                                           SourceLocation EndLoc=SourceLocation());
353
    CallExpr *SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
354
                                        QualType msgSendType,
355
                                        QualType returnType,
356
                                        SmallVectorImpl<QualType> &ArgTypes,
357
                                        SmallVectorImpl<Expr*> &MsgExprs,
358
                                        ObjCMethodDecl *Method);
359
    Stmt *SynthMessageExpr(ObjCMessageExpr *Exp,
360
                           SourceLocation StartLoc=SourceLocation(),
361
                           SourceLocation EndLoc=SourceLocation());
362
363
    void SynthCountByEnumWithState(std::string &buf);
364
    void SynthMsgSendFunctionDecl();
365
    void SynthMsgSendSuperFunctionDecl();
366
    void SynthMsgSendStretFunctionDecl();
367
    void SynthMsgSendFpretFunctionDecl();
368
    void SynthMsgSendSuperStretFunctionDecl();
369
    void SynthGetClassFunctionDecl();
370
    void SynthGetMetaClassFunctionDecl();
371
    void SynthGetSuperClassFunctionDecl();
372
    void SynthSelGetUidFunctionDecl();
373
    void SynthSuperConstructorFunctionDecl();
374
375
    std::string SynthesizeByrefCopyDestroyHelper(VarDecl *VD, int flag);
376
    std::string SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
377
                                      StringRef funcName, std::string Tag);
378
    std::string SynthesizeBlockFunc(BlockExpr *CE, int i,
379
                                      StringRef funcName, std::string Tag);
380
    std::string SynthesizeBlockImpl(BlockExpr *CE,
381
                                    std::string Tag, std::string Desc);
382
    std::string SynthesizeBlockDescriptor(std::string DescTag,
383
                                          std::string ImplTag,
384
                                          int i, StringRef funcName,
385
                                          unsigned hasCopy);
386
    Stmt *SynthesizeBlockCall(CallExpr *Exp, const Expr* BlockExp);
387
    void SynthesizeBlockLiterals(SourceLocation FunLocStart,
388
                                 StringRef FunName);
389
    FunctionDecl *SynthBlockInitFunctionDecl(StringRef name);
390
    Stmt *SynthBlockInitExpr(BlockExpr *Exp,
391
            const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs);
392
393
    // Misc. helper routines.
394
    QualType getProtocolType();
395
    void WarnAboutReturnGotoStmts(Stmt *S);
396
    void HasReturnStmts(Stmt *S, bool &hasReturns);
397
    void CheckFunctionPointerDecl(QualType dType, NamedDecl *ND);
398
    void InsertBlockLiteralsWithinFunction(FunctionDecl *FD);
399
    void InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD);
400
401
    bool IsDeclStmtInForeachHeader(DeclStmt *DS);
402
    void CollectBlockDeclRefInfo(BlockExpr *Exp);
403
    void GetBlockDeclRefExprs(Stmt *S);
404
    void GetInnerBlockDeclRefExprs(Stmt *S,
405
                SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
406
                llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts);
407
408
    // We avoid calling Type::isBlockPointerType(), since it operates on the
409
    // canonical type. We only care if the top-level type is a closure pointer.
410
845
    bool isTopLevelBlockPointerType(QualType T) {
411
845
      return isa<BlockPointerType>(T);
412
845
    }
413
414
    /// convertBlockPointerToFunctionPointer - Converts a block-pointer type
415
    /// to a function pointer type and upon success, returns true; false
416
    /// otherwise.
417
324
    bool convertBlockPointerToFunctionPointer(QualType &T) {
418
324
      if (isTopLevelBlockPointerType(T)) {
419
14
        const auto *BPT = T->castAs<BlockPointerType>();
420
14
        T = Context->getPointerType(BPT->getPointeeType());
421
14
        return true;
422
14
      }
423
310
      return false;
424
310
    }
425
426
    bool needToScanForQualifiers(QualType T);
427
    QualType getSuperStructType();
428
    QualType getConstantStringStructType();
429
    QualType convertFunctionTypeOfBlocks(const FunctionType *FT);
430
    bool BufferContainsPPDirectives(const char *startBuf, const char *endBuf);
431
432
109
    void convertToUnqualifiedObjCType(QualType &T) {
433
109
      if (T->isObjCQualifiedIdType())
434
2
        T = Context->getObjCIdType();
435
107
      else if (T->isObjCQualifiedClassType())
436
0
        T = Context->getObjCClassType();
437
107
      else if (T->isObjCObjectPointerType() &&
438
107
               
T->getPointeeType()->isObjCQualifiedInterfaceType()56
) {
439
12
        if (const ObjCObjectPointerType * OBJPT =
440
12
              T->getAsObjCInterfacePointerType()) {
441
12
          const ObjCInterfaceType *IFaceT = OBJPT->getInterfaceType();
442
12
          T = QualType(IFaceT, 0);
443
12
          T = Context->getPointerType(T);
444
12
        }
445
12
     }
446
109
    }
447
448
    // FIXME: This predicate seems like it would be useful to add to ASTContext.
449
42
    bool isObjCType(QualType T) {
450
42
      if (!LangOpts.ObjC)
451
0
        return false;
452
42
453
42
      QualType OCT = Context->getCanonicalType(T).getUnqualifiedType();
454
42
455
42
      if (OCT == Context->getCanonicalType(Context->getObjCIdType()) ||
456
42
          
OCT == Context->getCanonicalType(Context->getObjCClassType())35
)
457
7
        return true;
458
35
459
35
      if (const PointerType *PT = OCT->getAs<PointerType>()) {
460
2
        if (isa<ObjCInterfaceType>(PT->getPointeeType()) ||
461
2
            PT->getPointeeType()->isObjCQualifiedIdType())
462
0
          return true;
463
35
      }
464
35
      return false;
465
35
    }
466
    bool PointerTypeTakesAnyBlockArguments(QualType QT);
467
    bool PointerTypeTakesAnyObjCQualifiedType(QualType QT);
468
    void GetExtentOfArgList(const char *Name, const char *&LParen,
469
                            const char *&RParen);
470
471
43
    void QuoteDoublequotes(std::string &From, std::string &To) {
472
347
      for (unsigned i = 0; i < From.length(); 
i++304
) {
473
304
        if (From[i] == '"')
474
38
          To += "\\\"";
475
266
        else
476
266
          To += From[i];
477
304
      }
478
43
    }
479
480
    QualType getSimpleFunctionType(QualType result,
481
                                   ArrayRef<QualType> args,
482
435
                                   bool variadic = false) {
483
435
      if (result == Context->getObjCInstanceType())
484
0
        result =  Context->getObjCIdType();
485
435
      FunctionProtoType::ExtProtoInfo fpi;
486
435
      fpi.Variadic = variadic;
487
435
      return Context->getFunctionType(result, args, fpi);
488
435
    }
489
490
    // Helper function: create a CStyleCastExpr with trivial type source info.
491
    CStyleCastExpr* NoTypeInfoCStyleCastExpr(ASTContext *Ctx, QualType Ty,
492
620
                                             CastKind Kind, Expr *E) {
493
620
      TypeSourceInfo *TInfo = Ctx->getTrivialTypeSourceInfo(Ty, SourceLocation());
494
620
      return CStyleCastExpr::Create(*Ctx, Ty, VK_RValue, Kind, E, nullptr,
495
620
                                    TInfo, SourceLocation(), SourceLocation());
496
620
    }
497
498
139
    StringLiteral *getStringLiteral(StringRef Str) {
499
139
      QualType StrType = Context->getConstantArrayType(
500
139
          Context->CharTy, llvm::APInt(32, Str.size() + 1), nullptr,
501
139
          ArrayType::Normal, 0);
502
139
      return StringLiteral::Create(*Context, Str, StringLiteral::Ascii,
503
139
                                   /*Pascal=*/false, StrType, SourceLocation());
504
139
    }
505
  };
506
507
  class RewriteObjCFragileABI : public RewriteObjC {
508
  public:
509
    RewriteObjCFragileABI(std::string inFile, std::unique_ptr<raw_ostream> OS,
510
                          DiagnosticsEngine &D, const LangOptions &LOpts,
511
                          bool silenceMacroWarn)
512
86
        : RewriteObjC(inFile, std::move(OS), D, LOpts, silenceMacroWarn) {}
513
514
86
    ~RewriteObjCFragileABI() override {}
515
    void Initialize(ASTContext &context) override;
516
517
    // Rewriting metadata
518
    template<typename MethodIterator>
519
    void RewriteObjCMethodsMetaData(MethodIterator MethodBegin,
520
                                    MethodIterator MethodEnd,
521
                                    bool IsInstanceMethod,
522
                                    StringRef prefix,
523
                                    StringRef ClassName,
524
                                    std::string &Result);
525
    void RewriteObjCProtocolMetaData(ObjCProtocolDecl *Protocol,
526
                                     StringRef prefix, StringRef ClassName,
527
                                     std::string &Result) override;
528
    void RewriteObjCProtocolListMetaData(
529
          const ObjCList<ObjCProtocolDecl> &Prots,
530
          StringRef prefix, StringRef ClassName, std::string &Result) override;
531
    void RewriteObjCClassMetaData(ObjCImplementationDecl *IDecl,
532
                                  std::string &Result) override;
533
    void RewriteMetaDataIntoBuffer(std::string &Result) override;
534
    void RewriteObjCCategoryImplDecl(ObjCCategoryImplDecl *CDecl,
535
                                     std::string &Result) override;
536
537
    // Rewriting ivar
538
    void RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,
539
                                      std::string &Result) override;
540
    Stmt *RewriteObjCIvarRefExpr(ObjCIvarRefExpr *IV) override;
541
  };
542
} // end anonymous namespace
543
544
void RewriteObjC::RewriteBlocksInFunctionProtoType(QualType funcType,
545
136
                                                   NamedDecl *D) {
546
136
  if (const FunctionProtoType *fproto
547
113
      = dyn_cast<FunctionProtoType>(funcType.IgnoreParens())) {
548
113
    for (const auto &I : fproto->param_types())
549
101
      if (isTopLevelBlockPointerType(I)) {
550
20
        // All the args are checked/rewritten. Don't call twice!
551
20
        RewriteBlockPointerDecl(D);
552
20
        break;
553
20
      }
554
113
  }
555
136
}
556
557
1
void RewriteObjC::CheckFunctionPointerDecl(QualType funcType, NamedDecl *ND) {
558
1
  const PointerType *PT = funcType->getAs<PointerType>();
559
1
  if (PT && PointerTypeTakesAnyBlockArguments(funcType))
560
0
    RewriteBlocksInFunctionProtoType(PT->getPointeeType(), ND);
561
1
}
562
563
86
static bool IsHeaderFile(const std::string &Filename) {
564
86
  std::string::size_type DotPos = Filename.rfind('.');
565
86
566
86
  if (DotPos == std::string::npos) {
567
0
    // no file extension
568
0
    return false;
569
0
  }
570
86
571
86
  std::string Ext = std::string(Filename.begin()+DotPos+1, Filename.end());
572
86
  // C header: .h
573
86
  // C++ header: .hh or .H;
574
86
  return Ext == "h" || Ext == "hh" || Ext == "H";
575
86
}
576
577
RewriteObjC::RewriteObjC(std::string inFile, std::unique_ptr<raw_ostream> OS,
578
                         DiagnosticsEngine &D, const LangOptions &LOpts,
579
                         bool silenceMacroWarn)
580
    : Diags(D), LangOpts(LOpts), InFileName(inFile), OutFile(std::move(OS)),
581
86
      SilenceRewriteMacroWarning(silenceMacroWarn) {
582
86
  IsHeader = IsHeaderFile(inFile);
583
86
  RewriteFailedDiag = Diags.getCustomDiagID(DiagnosticsEngine::Warning,
584
86
               "rewriting sub-expression within a macro (may not be correct)");
585
86
  TryFinallyContainsReturnDiag = Diags.getCustomDiagID(
586
86
               DiagnosticsEngine::Warning,
587
86
               "rewriter doesn't support user-specified control flow semantics "
588
86
               "for @try/@finally (code may not execute properly)");
589
86
}
590
591
std::unique_ptr<ASTConsumer>
592
clang::CreateObjCRewriter(const std::string &InFile,
593
                          std::unique_ptr<raw_ostream> OS,
594
                          DiagnosticsEngine &Diags, const LangOptions &LOpts,
595
86
                          bool SilenceRewriteMacroWarning) {
596
86
  return std::make_unique<RewriteObjCFragileABI>(
597
86
      InFile, std::move(OS), Diags, LOpts, SilenceRewriteMacroWarning);
598
86
}
599
600
86
void RewriteObjC::InitializeCommon(ASTContext &context) {
601
86
  Context = &context;
602
86
  SM = &Context->getSourceManager();
603
86
  TUDecl = Context->getTranslationUnitDecl();
604
86
  MsgSendFunctionDecl = nullptr;
605
86
  MsgSendSuperFunctionDecl = nullptr;
606
86
  MsgSendStretFunctionDecl = nullptr;
607
86
  MsgSendSuperStretFunctionDecl = nullptr;
608
86
  MsgSendFpretFunctionDecl = nullptr;
609
86
  GetClassFunctionDecl = nullptr;
610
86
  GetMetaClassFunctionDecl = nullptr;
611
86
  GetSuperClassFunctionDecl = nullptr;
612
86
  SelGetUidFunctionDecl = nullptr;
613
86
  CFStringFunctionDecl = nullptr;
614
86
  ConstantStringClassReference = nullptr;
615
86
  NSStringRecord = nullptr;
616
86
  CurMethodDef = nullptr;
617
86
  CurFunctionDef = nullptr;
618
86
  CurFunctionDeclToDeclareForBlock = nullptr;
619
86
  GlobalVarDecl = nullptr;
620
86
  SuperStructDecl = nullptr;
621
86
  ProtocolTypeDecl = nullptr;
622
86
  ConstantStringDecl = nullptr;
623
86
  BcLabelCount = 0;
624
86
  SuperConstructorFunctionDecl = nullptr;
625
86
  NumObjCStringLiterals = 0;
626
86
  PropParentMap = nullptr;
627
86
  CurrentBody = nullptr;
628
86
  DisableReplaceStmt = false;
629
86
  objc_impl_method = false;
630
86
631
86
  // Get the ID and start/end of the main file.
632
86
  MainFileID = SM->getMainFileID();
633
86
  const llvm::MemoryBuffer *MainBuf = SM->getBuffer(MainFileID);
634
86
  MainFileStart = MainBuf->getBufferStart();
635
86
  MainFileEnd = MainBuf->getBufferEnd();
636
86
637
86
  Rewrite.setSourceMgr(Context->getSourceManager(), Context->getLangOpts());
638
86
}
639
640
//===----------------------------------------------------------------------===//
641
// Top Level Driver Code
642
//===----------------------------------------------------------------------===//
643
644
524
void RewriteObjC::HandleTopLevelSingleDecl(Decl *D) {
645
524
  if (Diags.hasErrorOccurred())
646
0
    return;
647
524
648
524
  // Two cases: either the decl could be in the main file, or it could be in a
649
524
  // #included file.  If the former, rewrite it now.  If the later, check to see
650
524
  // if we rewrote the #include/#import.
651
524
  SourceLocation Loc = D->getLocation();
652
524
  Loc = SM->getExpansionLoc(Loc);
653
524
654
524
  // If this is for a builtin, ignore it.
655
524
  if (Loc.isInvalid()) 
return0
;
656
524
657
524
  // Look for built-in declarations that we need to refer during the rewrite.
658
524
  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(D)) {
659
136
    RewriteFunctionDecl(FD);
660
388
  } else if (VarDecl *FVD = dyn_cast<VarDecl>(D)) {
661
17
    // declared in <Foundation/NSString.h>
662
17
    if (FVD->getName() == "_NSConstantStringClassReference") {
663
0
      ConstantStringClassReference = FVD;
664
0
      return;
665
0
    }
666
371
  } else if (ObjCInterfaceDecl *ID = dyn_cast<ObjCInterfaceDecl>(D)) {
667
118
    if (ID->isThisDeclarationADefinition())
668
118
      RewriteInterfaceDecl(ID);
669
253
  } else if (ObjCCategoryDecl *CD = dyn_cast<ObjCCategoryDecl>(D)) {
670
6
    RewriteCategoryDecl(CD);
671
247
  } else if (ObjCProtocolDecl *PD = dyn_cast<ObjCProtocolDecl>(D)) {
672
21
    if (PD->isThisDeclarationADefinition())
673
21
      RewriteProtocolDecl(PD);
674
226
  } else if (LinkageSpecDecl *LSD = dyn_cast<LinkageSpecDecl>(D)) {
675
13
    // Recurse into linkage specifications
676
13
    for (DeclContext::decl_iterator DI = LSD->decls_begin(),
677
13
                                 DIEnd = LSD->decls_end();
678
27
         DI != DIEnd; ) {
679
14
      if (ObjCInterfaceDecl *IFace = dyn_cast<ObjCInterfaceDecl>((*DI))) {
680
0
        if (!IFace->isThisDeclarationADefinition()) {
681
0
          SmallVector<Decl *, 8> DG;
682
0
          SourceLocation StartLoc = IFace->getBeginLoc();
683
0
          do {
684
0
            if (isa<ObjCInterfaceDecl>(*DI) &&
685
0
                !cast<ObjCInterfaceDecl>(*DI)->isThisDeclarationADefinition() &&
686
0
                StartLoc == (*DI)->getBeginLoc())
687
0
              DG.push_back(*DI);
688
0
            else
689
0
              break;
690
0
691
0
            ++DI;
692
0
          } while (DI != DIEnd);
693
0
          RewriteForwardClassDecl(DG);
694
0
          continue;
695
0
        }
696
14
      }
697
14
698
14
      if (ObjCProtocolDecl *Proto = dyn_cast<ObjCProtocolDecl>((*DI))) {
699
0
        if (!Proto->isThisDeclarationADefinition()) {
700
0
          SmallVector<Decl *, 8> DG;
701
0
          SourceLocation StartLoc = Proto->getBeginLoc();
702
0
          do {
703
0
            if (isa<ObjCProtocolDecl>(*DI) &&
704
0
                !cast<ObjCProtocolDecl>(*DI)->isThisDeclarationADefinition() &&
705
0
                StartLoc == (*DI)->getBeginLoc())
706
0
              DG.push_back(*DI);
707
0
            else
708
0
              break;
709
0
710
0
            ++DI;
711
0
          } while (DI != DIEnd);
712
0
          RewriteForwardProtocolDecl(DG);
713
0
          continue;
714
0
        }
715
14
      }
716
14
717
14
      HandleTopLevelSingleDecl(*DI);
718
14
      ++DI;
719
14
    }
720
13
  }
721
524
  // If we have a decl in the main file, see if we should rewrite it.
722
524
  if (SM->isWrittenInMainFile(Loc))
723
522
    return HandleDeclInMainFile(D);
724
524
}
725
726
//===----------------------------------------------------------------------===//
727
// Syntactic (non-AST) Rewriting Code
728
//===----------------------------------------------------------------------===//
729
730
86
void RewriteObjC::RewriteInclude() {
731
86
  SourceLocation LocStart = SM->getLocForStartOfFile(MainFileID);
732
86
  StringRef MainBuf = SM->getBufferData(MainFileID);
733
86
  const char *MainBufStart = MainBuf.begin();
734
86
  const char *MainBufEnd = MainBuf.end();
735
86
  size_t ImportLen = strlen("import");
736
86
737
86
  // Loop over the whole file, looking for includes.
738
60.1k
  for (const char *BufPtr = MainBufStart; BufPtr < MainBufEnd; 
++BufPtr60.0k
) {
739
60.0k
    if (*BufPtr == '#') {
740
23
      if (++BufPtr == MainBufEnd)
741
0
        return;
742
44
      
while (23
*BufPtr == ' ' ||
*BufPtr == '\t'23
)
743
21
        if (++BufPtr == MainBufEnd)
744
0
          return;
745
23
      if (!strncmp(BufPtr, "import", ImportLen)) {
746
0
        // replace import with include
747
0
        SourceLocation ImportLoc =
748
0
          LocStart.getLocWithOffset(BufPtr-MainBufStart);
749
0
        ReplaceText(ImportLoc, ImportLen, "include");
750
0
        BufPtr += ImportLen;
751
0
      }
752
23
    }
753
60.0k
  }
754
86
}
755
756
3
static std::string getIvarAccessString(ObjCIvarDecl *OID) {
757
3
  const ObjCInterfaceDecl *ClassDecl = OID->getContainingInterface();
758
3
  std::string S;
759
3
  S = "((struct ";
760
3
  S += ClassDecl->getIdentifier()->getName();
761
3
  S += "_IMPL *)self)->";
762
3
  S += OID->getName();
763
3
  return S;
764
3
}
765
766
void RewriteObjC::RewritePropertyImplDecl(ObjCPropertyImplDecl *PID,
767
                                          ObjCImplementationDecl *IMD,
768
12
                                          ObjCCategoryImplDecl *CID) {
769
12
  static bool objcGetPropertyDefined = false;
770
12
  static bool objcSetPropertyDefined = false;
771
12
  SourceLocation startLoc = PID->getBeginLoc();
772
12
  InsertText(startLoc, "// ");
773
12
  const char *startBuf = SM->getCharacterData(startLoc);
774
12
  assert((*startBuf == '@') && "bogus @synthesize location");
775
12
  const char *semiBuf = strchr(startBuf, ';');
776
12
  assert((*semiBuf == ';') && "@synthesize: can't find ';'");
777
12
  SourceLocation onePastSemiLoc =
778
12
    startLoc.getLocWithOffset(semiBuf-startBuf+1);
779
12
780
12
  if (PID->getPropertyImplementation() == ObjCPropertyImplDecl::Dynamic)
781
2
    return; // FIXME: is this correct?
782
10
783
10
  // Generate the 'getter' function.
784
10
  ObjCPropertyDecl *PD = PID->getPropertyDecl();
785
10
  ObjCIvarDecl *OID = PID->getPropertyIvarDecl();
786
10
787
10
  if (!OID)
788
0
    return;
789
10
790
10
  unsigned Attributes = PD->getPropertyAttributes();
791
10
  if (PID->getGetterMethodDecl() && !PID->getGetterMethodDecl()->isDefined()) {
792
9
    bool GenGetProperty = !(Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic) &&
793
9
                          (Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
794
9
                                         ObjCPropertyDecl::OBJC_PR_copy));
795
9
    std::string Getr;
796
9
    if (GenGetProperty && 
!objcGetPropertyDefined7
) {
797
5
      objcGetPropertyDefined = true;
798
5
      // FIXME. Is this attribute correct in all cases?
799
5
      Getr = "\nextern \"C\" __declspec(dllimport) "
800
5
            "id objc_getProperty(id, SEL, long, bool);\n";
801
5
    }
802
9
    RewriteObjCMethodDecl(OID->getContainingInterface(),
803
9
                          PID->getGetterMethodDecl(), Getr);
804
9
    Getr += "{ ";
805
9
    // Synthesize an explicit cast to gain access to the ivar.
806
9
    // See objc-act.c:objc_synthesize_new_getter() for details.
807
9
    if (GenGetProperty) {
808
7
      // return objc_getProperty(self, _cmd, offsetof(ClassDecl, OID), 1)
809
7
      Getr += "typedef ";
810
7
      const FunctionType *FPRetType = nullptr;
811
7
      RewriteTypeIntoString(PID->getGetterMethodDecl()->getReturnType(), Getr,
812
7
                            FPRetType);
813
7
      Getr += " _TYPE";
814
7
      if (FPRetType) {
815
1
        Getr += ")"; // close the precedence "scope" for "*".
816
1
817
1
        // Now, emit the argument types (if any).
818
1
        if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)){
819
1
          Getr += "(";
820
1
          for (unsigned i = 0, e = FT->getNumParams(); i != e; 
++i0
) {
821
0
            if (i) Getr += ", ";
822
0
            std::string ParamStr =
823
0
                FT->getParamType(i).getAsString(Context->getPrintingPolicy());
824
0
            Getr += ParamStr;
825
0
          }
826
1
          if (FT->isVariadic()) {
827
0
            if (FT->getNumParams())
828
0
              Getr += ", ";
829
0
            Getr += "...";
830
0
          }
831
1
          Getr += ")";
832
1
        } else
833
0
          Getr += "()";
834
1
      }
835
7
      Getr += ";\n";
836
7
      Getr += "return (_TYPE)";
837
7
      Getr += "objc_getProperty(self, _cmd, ";
838
7
      RewriteIvarOffsetComputation(OID, Getr);
839
7
      Getr += ", 1)";
840
7
    }
841
2
    else
842
2
      Getr += "return " + getIvarAccessString(OID);
843
9
    Getr += "; }";
844
9
    InsertText(onePastSemiLoc, Getr);
845
9
  }
846
10
847
10
  if (PD->isReadOnly() || 
!PID->getSetterMethodDecl()9
||
848
10
      
PID->getSetterMethodDecl()->isDefined()9
)
849
2
    return;
850
8
851
8
  // Generate the 'setter' function.
852
8
  std::string Setr;
853
8
  bool GenSetProperty = Attributes & (ObjCPropertyDecl::OBJC_PR_retain |
854
8
                                      ObjCPropertyDecl::OBJC_PR_copy);
855
8
  if (GenSetProperty && 
!objcSetPropertyDefined7
) {
856
5
    objcSetPropertyDefined = true;
857
5
    // FIXME. Is this attribute correct in all cases?
858
5
    Setr = "\nextern \"C\" __declspec(dllimport) "
859
5
    "void objc_setProperty (id, SEL, long, id, bool, bool);\n";
860
5
  }
861
8
862
8
  RewriteObjCMethodDecl(OID->getContainingInterface(),
863
8
                        PID->getSetterMethodDecl(), Setr);
864
8
  Setr += "{ ";
865
8
  // Synthesize an explicit cast to initialize the ivar.
866
8
  // See objc-act.c:objc_synthesize_new_setter() for details.
867
8
  if (GenSetProperty) {
868
7
    Setr += "objc_setProperty (self, _cmd, ";
869
7
    RewriteIvarOffsetComputation(OID, Setr);
870
7
    Setr += ", (id)";
871
7
    Setr += PD->getName();
872
7
    Setr += ", ";
873
7
    if (Attributes & ObjCPropertyDecl::OBJC_PR_nonatomic)
874
0
      Setr += "0, ";
875
7
    else
876
7
      Setr += "1, ";
877
7
    if (Attributes & ObjCPropertyDecl::OBJC_PR_copy)
878
3
      Setr += "1)";
879
4
    else
880
4
      Setr += "0)";
881
7
  }
882
1
  else {
883
1
    Setr += getIvarAccessString(OID) + " = ";
884
1
    Setr += PD->getName();
885
1
  }
886
8
  Setr += "; }";
887
8
  InsertText(onePastSemiLoc, Setr);
888
8
}
889
890
static void RewriteOneForwardClassDecl(ObjCInterfaceDecl *ForwardDecl,
891
27
                                       std::string &typedefString) {
892
27
  typedefString += "#ifndef _REWRITER_typedef_";
893
27
  typedefString += ForwardDecl->getNameAsString();
894
27
  typedefString += "\n";
895
27
  typedefString += "#define _REWRITER_typedef_";
896
27
  typedefString += ForwardDecl->getNameAsString();
897
27
  typedefString += "\n";
898
27
  typedefString += "typedef struct objc_object ";
899
27
  typedefString += ForwardDecl->getNameAsString();
900
27
  typedefString += ";\n#endif\n";
901
27
}
902
903
void RewriteObjC::RewriteForwardClassEpilogue(ObjCInterfaceDecl *ClassDecl,
904
17
                                              const std::string &typedefString) {
905
17
  SourceLocation startLoc = ClassDecl->getBeginLoc();
906
17
  const char *startBuf = SM->getCharacterData(startLoc);
907
17
  const char *semiPtr = strchr(startBuf, ';');
908
17
  // Replace the @class with typedefs corresponding to the classes.
909
17
  ReplaceText(startLoc, semiPtr - startBuf + 1, typedefString);
910
17
}
911
912
17
void RewriteObjC::RewriteForwardClassDecl(DeclGroupRef D) {
913
17
  std::string typedefString;
914
44
  for (DeclGroupRef::iterator I = D.begin(), E = D.end(); I != E; 
++I27
) {
915
27
    ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(*I);
916
27
    if (I == D.begin()) {
917
17
      // Translate to typedef's that forward reference structs with the same name
918
17
      // as the class. As a convenience, we include the original declaration
919
17
      // as a comment.
920
17
      typedefString += "// @class ";
921
17
      typedefString += ForwardDecl->getNameAsString();
922
17
      typedefString += ";\n";
923
17
    }
924
27
    RewriteOneForwardClassDecl(ForwardDecl, typedefString);
925
27
  }
926
17
  DeclGroupRef::iterator I = D.begin();
927
17
  RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(*I), typedefString);
928
17
}
929
930
0
void RewriteObjC::RewriteForwardClassDecl(const SmallVectorImpl<Decl *> &D) {
931
0
  std::string typedefString;
932
0
  for (unsigned i = 0; i < D.size(); i++) {
933
0
    ObjCInterfaceDecl *ForwardDecl = cast<ObjCInterfaceDecl>(D[i]);
934
0
    if (i == 0) {
935
0
      typedefString += "// @class ";
936
0
      typedefString += ForwardDecl->getNameAsString();
937
0
      typedefString += ";\n";
938
0
    }
939
0
    RewriteOneForwardClassDecl(ForwardDecl, typedefString);
940
0
  }
941
0
  RewriteForwardClassEpilogue(cast<ObjCInterfaceDecl>(D[0]), typedefString);
942
0
}
943
944
123
void RewriteObjC::RewriteMethodDeclaration(ObjCMethodDecl *Method) {
945
123
  // When method is a synthesized one, such as a getter/setter there is
946
123
  // nothing to rewrite.
947
123
  if (Method->isImplicit())
948
42
    return;
949
81
  SourceLocation LocStart = Method->getBeginLoc();
950
81
  SourceLocation LocEnd = Method->getEndLoc();
951
81
952
81
  if (SM->getExpansionLineNumber(LocEnd) >
953
81
      SM->getExpansionLineNumber(LocStart)) {
954
0
    InsertText(LocStart, "#if 0\n");
955
0
    ReplaceText(LocEnd, 1, ";\n#endif\n");
956
81
  } else {
957
81
    InsertText(LocStart, "// ");
958
81
  }
959
81
}
960
961
23
void RewriteObjC::RewriteProperty(ObjCPropertyDecl *prop) {
962
23
  SourceLocation Loc = prop->getAtLoc();
963
23
964
23
  ReplaceText(Loc, 0, "// ");
965
23
  // FIXME: handle properties that are declared across multiple lines.
966
23
}
967
968
6
void RewriteObjC::RewriteCategoryDecl(ObjCCategoryDecl *CatDecl) {
969
6
  SourceLocation LocStart = CatDecl->getBeginLoc();
970
6
971
6
  // FIXME: handle category headers that are declared across multiple lines.
972
6
  ReplaceText(LocStart, 0, "// ");
973
6
974
6
  for (auto *I : CatDecl->instance_properties())
975
1
    RewriteProperty(I);
976
6
  for (auto *I : CatDecl->instance_methods())
977
6
    RewriteMethodDeclaration(I);
978
6
  for (auto *I : CatDecl->class_methods())
979
0
    RewriteMethodDeclaration(I);
980
6
981
6
  // Lastly, comment out the @end.
982
6
  ReplaceText(CatDecl->getAtEndRange().getBegin(),
983
6
              strlen("@end"), "/* @end */");
984
6
}
985
986
21
void RewriteObjC::RewriteProtocolDecl(ObjCProtocolDecl *PDecl) {
987
21
  SourceLocation LocStart = PDecl->getBeginLoc();
988
21
  assert(PDecl->isThisDeclarationADefinition());
989
21
990
21
  // FIXME: handle protocol headers that are declared across multiple lines.
991
21
  ReplaceText(LocStart, 0, "// ");
992
21
993
21
  for (auto *I : PDecl->instance_methods())
994
13
    RewriteMethodDeclaration(I);
995
21
  for (auto *I : PDecl->class_methods())
996
1
    RewriteMethodDeclaration(I);
997
21
  for (auto *I : PDecl->instance_properties())
998
2
    RewriteProperty(I);
999
21
1000
21
  // Lastly, comment out the @end.
1001
21
  SourceLocation LocEnd = PDecl->getAtEndRange().getBegin();
1002
21
  ReplaceText(LocEnd, strlen("@end"), "/* @end */");
1003
21
1004
21
  // Must comment out @optional/@required
1005
21
  const char *startBuf = SM->getCharacterData(LocStart);
1006
21
  const char *endBuf = SM->getCharacterData(LocEnd);
1007
998
  for (const char *p = startBuf; p < endBuf; 
p++977
) {
1008
977
    if (*p == '@' && 
!strncmp(p+1, "optional", strlen("optional"))25
) {
1009
2
      SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1010
2
      ReplaceText(OptionalLoc, strlen("@optional"), "/* @optional */");
1011
2
1012
2
    }
1013
975
    else if (*p == '@' && 
!strncmp(p+1, "required", strlen("required"))23
) {
1014
0
      SourceLocation OptionalLoc = LocStart.getLocWithOffset(p-startBuf);
1015
0
      ReplaceText(OptionalLoc, strlen("@required"), "/* @required */");
1016
0
1017
0
    }
1018
977
  }
1019
21
}
1020
1021
6
void RewriteObjC::RewriteForwardProtocolDecl(DeclGroupRef D) {
1022
6
  SourceLocation LocStart = (*D.begin())->getBeginLoc();
1023
6
  if (LocStart.isInvalid())
1024
6
    
llvm_unreachable0
("Invalid SourceLocation");
1025
6
  // FIXME: handle forward protocol that are declared across multiple lines.
1026
6
  ReplaceText(LocStart, 0, "// ");
1027
6
}
1028
1029
void
1030
0
RewriteObjC::RewriteForwardProtocolDecl(const SmallVectorImpl<Decl *> &DG) {
1031
0
  SourceLocation LocStart = DG[0]->getBeginLoc();
1032
0
  if (LocStart.isInvalid())
1033
0
    llvm_unreachable("Invalid SourceLocation");
1034
0
  // FIXME: handle forward protocol that are declared across multiple lines.
1035
0
  ReplaceText(LocStart, 0, "// ");
1036
0
}
1037
1038
void RewriteObjC::RewriteTypeIntoString(QualType T, std::string &ResultStr,
1039
101
                                        const FunctionType *&FPRetType) {
1040
101
  if (T->isObjCQualifiedIdType())
1041
2
    ResultStr += "id";
1042
99
  else if (T->isFunctionPointerType() ||
1043
99
           T->isBlockPointerType()) {
1044
3
    // needs special handling, since pointer-to-functions have special
1045
3
    // syntax (where a decaration models use).
1046
3
    QualType retType = T;
1047
3
    QualType PointeeTy;
1048
3
    if (const PointerType* PT = retType->getAs<PointerType>())
1049
0
      PointeeTy = PT->getPointeeType();
1050
3
    else if (const BlockPointerType *BPT = retType->getAs<BlockPointerType>())
1051
3
      PointeeTy = BPT->getPointeeType();
1052
3
    if ((FPRetType = PointeeTy->getAs<FunctionType>())) {
1053
3
      ResultStr +=
1054
3
          FPRetType->getReturnType().getAsString(Context->getPrintingPolicy());
1055
3
      ResultStr += "(*";
1056
3
    }
1057
3
  } else
1058
96
    ResultStr += T.getAsString(Context->getPrintingPolicy());
1059
101
}
1060
1061
void RewriteObjC::RewriteObjCMethodDecl(const ObjCInterfaceDecl *IDecl,
1062
                                        ObjCMethodDecl *OMD,
1063
94
                                        std::string &ResultStr) {
1064
94
  //fprintf(stderr,"In RewriteObjCMethodDecl\n");
1065
94
  const FunctionType *FPRetType = nullptr;
1066
94
  ResultStr += "\nstatic ";
1067
94
  RewriteTypeIntoString(OMD->getReturnType(), ResultStr, FPRetType);
1068
94
  ResultStr += " ";
1069
94
1070
94
  // Unique method name
1071
94
  std::string NameStr;
1072
94
1073
94
  if (OMD->isInstanceMethod())
1074
88
    NameStr += "_I_";
1075
6
  else
1076
6
    NameStr += "_C_";
1077
94
1078
94
  NameStr += IDecl->getNameAsString();
1079
94
  NameStr += "_";
1080
94
1081
94
  if (ObjCCategoryImplDecl *CID =
1082
6
      dyn_cast<ObjCCategoryImplDecl>(OMD->getDeclContext())) {
1083
6
    NameStr += CID->getNameAsString();
1084
6
    NameStr += "_";
1085
6
  }
1086
94
  // Append selector names, replacing ':' with '_'
1087
94
  {
1088
94
    std::string selString = OMD->getSelector().getAsString();
1089
94
    int len = selString.size();
1090
1.11k
    for (int i = 0; i < len; 
i++1.02k
)
1091
1.02k
      if (selString[i] == ':')
1092
47
        selString[i] = '_';
1093
94
    NameStr += selString;
1094
94
  }
1095
94
  // Remember this name for metadata emission
1096
94
  MethodInternalNames[OMD] = NameStr;
1097
94
  ResultStr += NameStr;
1098
94
1099
94
  // Rewrite arguments
1100
94
  ResultStr += "(";
1101
94
1102
94
  // invisible arguments
1103
94
  if (OMD->isInstanceMethod()) {
1104
88
    QualType selfTy = Context->getObjCInterfaceType(IDecl);
1105
88
    selfTy = Context->getPointerType(selfTy);
1106
88
    if (!LangOpts.MicrosoftExt) {
1107
30
      if (ObjCSynthesizedStructs.count(const_cast<ObjCInterfaceDecl*>(IDecl)))
1108
8
        ResultStr += "struct ";
1109
30
    }
1110
88
    // When rewriting for Microsoft, explicitly omit the structure name.
1111
88
    ResultStr += IDecl->getNameAsString();
1112
88
    ResultStr += " *";
1113
88
  }
1114
6
  else
1115
6
    ResultStr += Context->getObjCClassType().getAsString(
1116
6
      Context->getPrintingPolicy());
1117
94
1118
94
  ResultStr += " self, ";
1119
94
  ResultStr += Context->getObjCSelType().getAsString(Context->getPrintingPolicy());
1120
94
  ResultStr += " _cmd";
1121
94
1122
94
  // Method arguments.
1123
94
  for (const auto *PDecl : OMD->parameters()) {
1124
47
    ResultStr += ", ";
1125
47
    if (PDecl->getType()->isObjCQualifiedIdType()) {
1126
1
      ResultStr += "id ";
1127
1
      ResultStr += PDecl->getNameAsString();
1128
46
    } else {
1129
46
      std::string Name = PDecl->getNameAsString();
1130
46
      QualType QT = PDecl->getType();
1131
46
      // Make sure we convert "t (^)(...)" to "t (*)(...)".
1132
46
      (void)convertBlockPointerToFunctionPointer(QT);
1133
46
      QT.getAsStringInternal(Name, Context->getPrintingPolicy());
1134
46
      ResultStr += Name;
1135
46
    }
1136
47
  }
1137
94
  if (OMD->isVariadic())
1138
1
    ResultStr += ", ...";
1139
94
  ResultStr += ") ";
1140
94
1141
94
  if (FPRetType) {
1142
2
    ResultStr += ")"; // close the precedence "scope" for "*".
1143
2
1144
2
    // Now, emit the argument types (if any).
1145
2
    if (const FunctionProtoType *FT = dyn_cast<FunctionProtoType>(FPRetType)) {
1146
2
      ResultStr += "(";
1147
2
      for (unsigned i = 0, e = FT->getNumParams(); i != e; 
++i0
) {
1148
0
        if (i) ResultStr += ", ";
1149
0
        std::string ParamStr =
1150
0
            FT->getParamType(i).getAsString(Context->getPrintingPolicy());
1151
0
        ResultStr += ParamStr;
1152
0
      }
1153
2
      if (FT->isVariadic()) {
1154
0
        if (FT->getNumParams())
1155
0
          ResultStr += ", ";
1156
0
        ResultStr += "...";
1157
0
      }
1158
2
      ResultStr += ")";
1159
2
    } else {
1160
0
      ResultStr += "()";
1161
0
    }
1162
2
  }
1163
94
}
1164
1165
70
void RewriteObjC::RewriteImplementationDecl(Decl *OID) {
1166
70
  ObjCImplementationDecl *IMD = dyn_cast<ObjCImplementationDecl>(OID);
1167
70
  ObjCCategoryImplDecl *CID = dyn_cast<ObjCCategoryImplDecl>(OID);
1168
70
  assert((IMD || CID) && "Unknown ImplementationDecl");
1169
70
1170
70
  InsertText(IMD ? 
IMD->getBeginLoc()64
:
CID->getBeginLoc()6
, "// ");
1171
70
1172
88
  for (auto *OMD : IMD ? 
IMD->instance_methods()64
:
CID->instance_methods()6
) {
1173
88
    if (!OMD->getBody())
1174
17
      continue;
1175
71
    std::string ResultStr;
1176
71
    RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1177
71
    SourceLocation LocStart = OMD->getBeginLoc();
1178
71
    SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
1179
71
1180
71
    const char *startBuf = SM->getCharacterData(LocStart);
1181
71
    const char *endBuf = SM->getCharacterData(LocEnd);
1182
71
    ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1183
71
  }
1184
70
1185
70
  for (auto *OMD : IMD ? 
IMD->class_methods()64
:
CID->class_methods()6
) {
1186
6
    if (!OMD->getBody())
1187
0
      continue;
1188
6
    std::string ResultStr;
1189
6
    RewriteObjCMethodDecl(OMD->getClassInterface(), OMD, ResultStr);
1190
6
    SourceLocation LocStart = OMD->getBeginLoc();
1191
6
    SourceLocation LocEnd = OMD->getCompoundBody()->getBeginLoc();
1192
6
1193
6
    const char *startBuf = SM->getCharacterData(LocStart);
1194
6
    const char *endBuf = SM->getCharacterData(LocEnd);
1195
6
    ReplaceText(LocStart, endBuf-startBuf, ResultStr);
1196
6
  }
1197
70
  for (auto *I : IMD ? 
IMD->property_impls()64
:
CID->property_impls()6
)
1198
12
    RewritePropertyImplDecl(I, IMD, CID);
1199
70
1200
70
  InsertText(IMD ? 
IMD->getEndLoc()64
:
CID->getEndLoc()6
, "// ");
1201
70
}
1202
1203
118
void RewriteObjC::RewriteInterfaceDecl(ObjCInterfaceDecl *ClassDecl) {
1204
118
  std::string ResultStr;
1205
118
  if (!ObjCForwardDecls.count(ClassDecl->getCanonicalDecl())) {
1206
118
    // we haven't seen a forward decl - generate a typedef.
1207
118
    ResultStr = "#ifndef _REWRITER_typedef_";
1208
118
    ResultStr += ClassDecl->getNameAsString();
1209
118
    ResultStr += "\n";
1210
118
    ResultStr += "#define _REWRITER_typedef_";
1211
118
    ResultStr += ClassDecl->getNameAsString();
1212
118
    ResultStr += "\n";
1213
118
    ResultStr += "typedef struct objc_object ";
1214
118
    ResultStr += ClassDecl->getNameAsString();
1215
118
    ResultStr += ";\n#endif\n";
1216
118
    // Mark this typedef as having been generated.
1217
118
    ObjCForwardDecls.insert(ClassDecl->getCanonicalDecl());
1218
118
  }
1219
118
  RewriteObjCInternalStruct(ClassDecl, ResultStr);
1220
118
1221
118
  for (auto *I : ClassDecl->instance_properties())
1222
20
    RewriteProperty(I);
1223
118
  for (auto *I : ClassDecl->instance_methods())
1224
92
    RewriteMethodDeclaration(I);
1225
118
  for (auto *I : ClassDecl->class_methods())
1226
11
    RewriteMethodDeclaration(I);
1227
118
1228
118
  // Lastly, comment out the @end.
1229
118
  ReplaceText(ClassDecl->getAtEndRange().getBegin(), strlen("@end"),
1230
118
              "/* @end */");
1231
118
}
1232
1233
14
Stmt *RewriteObjC::RewritePropertyOrImplicitSetter(PseudoObjectExpr *PseudoOp) {
1234
14
  SourceRange OldRange = PseudoOp->getSourceRange();
1235
14
1236
14
  // We just magically know some things about the structure of this
1237
14
  // expression.
1238
14
  ObjCMessageExpr *OldMsg =
1239
14
    cast<ObjCMessageExpr>(PseudoOp->getSemanticExpr(
1240
14
                            PseudoOp->getNumSemanticExprs() - 1));
1241
14
1242
14
  // Because the rewriter doesn't allow us to rewrite rewritten code,
1243
14
  // we need to suppress rewriting the sub-statements.
1244
14
  Expr *Base, *RHS;
1245
14
  {
1246
14
    DisableReplaceStmtScope S(*this);
1247
14
1248
14
    // Rebuild the base expression if we have one.
1249
14
    Base = nullptr;
1250
14
    if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1251
14
      Base = OldMsg->getInstanceReceiver();
1252
14
      Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1253
14
      Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1254
14
    }
1255
14
1256
14
    // Rebuild the RHS.
1257
14
    RHS = cast<BinaryOperator>(PseudoOp->getSyntacticForm())->getRHS();
1258
14
    RHS = cast<OpaqueValueExpr>(RHS)->getSourceExpr();
1259
14
    RHS = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(RHS));
1260
14
  }
1261
14
1262
14
  // TODO: avoid this copy.
1263
14
  SmallVector<SourceLocation, 1> SelLocs;
1264
14
  OldMsg->getSelectorLocs(SelLocs);
1265
14
1266
14
  ObjCMessageExpr *NewMsg = nullptr;
1267
14
  switch (OldMsg->getReceiverKind()) {
1268
0
  case ObjCMessageExpr::Class:
1269
0
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1270
0
                                     OldMsg->getValueKind(),
1271
0
                                     OldMsg->getLeftLoc(),
1272
0
                                     OldMsg->getClassReceiverTypeInfo(),
1273
0
                                     OldMsg->getSelector(),
1274
0
                                     SelLocs,
1275
0
                                     OldMsg->getMethodDecl(),
1276
0
                                     RHS,
1277
0
                                     OldMsg->getRightLoc(),
1278
0
                                     OldMsg->isImplicit());
1279
0
    break;
1280
0
1281
14
  case ObjCMessageExpr::Instance:
1282
14
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1283
14
                                     OldMsg->getValueKind(),
1284
14
                                     OldMsg->getLeftLoc(),
1285
14
                                     Base,
1286
14
                                     OldMsg->getSelector(),
1287
14
                                     SelLocs,
1288
14
                                     OldMsg->getMethodDecl(),
1289
14
                                     RHS,
1290
14
                                     OldMsg->getRightLoc(),
1291
14
                                     OldMsg->isImplicit());
1292
14
    break;
1293
0
1294
0
  case ObjCMessageExpr::SuperClass:
1295
0
  case ObjCMessageExpr::SuperInstance:
1296
0
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1297
0
                                     OldMsg->getValueKind(),
1298
0
                                     OldMsg->getLeftLoc(),
1299
0
                                     OldMsg->getSuperLoc(),
1300
0
                 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1301
0
                                     OldMsg->getSuperType(),
1302
0
                                     OldMsg->getSelector(),
1303
0
                                     SelLocs,
1304
0
                                     OldMsg->getMethodDecl(),
1305
0
                                     RHS,
1306
0
                                     OldMsg->getRightLoc(),
1307
0
                                     OldMsg->isImplicit());
1308
0
    break;
1309
14
  }
1310
14
1311
14
  Stmt *Replacement = SynthMessageExpr(NewMsg);
1312
14
  ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1313
14
  return Replacement;
1314
14
}
1315
1316
22
Stmt *RewriteObjC::RewritePropertyOrImplicitGetter(PseudoObjectExpr *PseudoOp) {
1317
22
  SourceRange OldRange = PseudoOp->getSourceRange();
1318
22
1319
22
  // We just magically know some things about the structure of this
1320
22
  // expression.
1321
22
  ObjCMessageExpr *OldMsg =
1322
22
    cast<ObjCMessageExpr>(PseudoOp->getResultExpr()->IgnoreImplicit());
1323
22
1324
22
  // Because the rewriter doesn't allow us to rewrite rewritten code,
1325
22
  // we need to suppress rewriting the sub-statements.
1326
22
  Expr *Base = nullptr;
1327
22
  {
1328
22
    DisableReplaceStmtScope S(*this);
1329
22
1330
22
    // Rebuild the base expression if we have one.
1331
22
    if (OldMsg->getReceiverKind() == ObjCMessageExpr::Instance) {
1332
22
      Base = OldMsg->getInstanceReceiver();
1333
22
      Base = cast<OpaqueValueExpr>(Base)->getSourceExpr();
1334
22
      Base = cast<Expr>(RewriteFunctionBodyOrGlobalInitializer(Base));
1335
22
    }
1336
22
  }
1337
22
1338
22
  // Intentionally empty.
1339
22
  SmallVector<SourceLocation, 1> SelLocs;
1340
22
  SmallVector<Expr*, 1> Args;
1341
22
1342
22
  ObjCMessageExpr *NewMsg = nullptr;
1343
22
  switch (OldMsg->getReceiverKind()) {
1344
0
  case ObjCMessageExpr::Class:
1345
0
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1346
0
                                     OldMsg->getValueKind(),
1347
0
                                     OldMsg->getLeftLoc(),
1348
0
                                     OldMsg->getClassReceiverTypeInfo(),
1349
0
                                     OldMsg->getSelector(),
1350
0
                                     SelLocs,
1351
0
                                     OldMsg->getMethodDecl(),
1352
0
                                     Args,
1353
0
                                     OldMsg->getRightLoc(),
1354
0
                                     OldMsg->isImplicit());
1355
0
    break;
1356
0
1357
22
  case ObjCMessageExpr::Instance:
1358
22
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1359
22
                                     OldMsg->getValueKind(),
1360
22
                                     OldMsg->getLeftLoc(),
1361
22
                                     Base,
1362
22
                                     OldMsg->getSelector(),
1363
22
                                     SelLocs,
1364
22
                                     OldMsg->getMethodDecl(),
1365
22
                                     Args,
1366
22
                                     OldMsg->getRightLoc(),
1367
22
                                     OldMsg->isImplicit());
1368
22
    break;
1369
0
1370
0
  case ObjCMessageExpr::SuperClass:
1371
0
  case ObjCMessageExpr::SuperInstance:
1372
0
    NewMsg = ObjCMessageExpr::Create(*Context, OldMsg->getType(),
1373
0
                                     OldMsg->getValueKind(),
1374
0
                                     OldMsg->getLeftLoc(),
1375
0
                                     OldMsg->getSuperLoc(),
1376
0
                 OldMsg->getReceiverKind() == ObjCMessageExpr::SuperInstance,
1377
0
                                     OldMsg->getSuperType(),
1378
0
                                     OldMsg->getSelector(),
1379
0
                                     SelLocs,
1380
0
                                     OldMsg->getMethodDecl(),
1381
0
                                     Args,
1382
0
                                     OldMsg->getRightLoc(),
1383
0
                                     OldMsg->isImplicit());
1384
0
    break;
1385
22
  }
1386
22
1387
22
  Stmt *Replacement = SynthMessageExpr(NewMsg);
1388
22
  ReplaceStmtWithRange(PseudoOp, Replacement, OldRange);
1389
22
  return Replacement;
1390
22
}
1391
1392
/// SynthCountByEnumWithState - To print:
1393
/// ((unsigned int (*)
1394
///  (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1395
///  (void *)objc_msgSend)((id)l_collection,
1396
///                        sel_registerName(
1397
///                          "countByEnumeratingWithState:objects:count:"),
1398
///                        &enumState,
1399
///                        (id *)__rw_items, (unsigned int)16)
1400
///
1401
36
void RewriteObjC::SynthCountByEnumWithState(std::string &buf) {
1402
36
  buf += "((unsigned int (*) (id, SEL, struct __objcFastEnumerationState *, "
1403
36
  "id *, unsigned int))(void *)objc_msgSend)";
1404
36
  buf += "\n\t\t";
1405
36
  buf += "((id)l_collection,\n\t\t";
1406
36
  buf += "sel_registerName(\"countByEnumeratingWithState:objects:count:\"),";
1407
36
  buf += "\n\t\t";
1408
36
  buf += "&enumState, "
1409
36
         "(id *)__rw_items, (unsigned int)16)";
1410
36
}
1411
1412
/// RewriteBreakStmt - Rewrite for a break-stmt inside an ObjC2's foreach
1413
/// statement to exit to its outer synthesized loop.
1414
///
1415
6
Stmt *RewriteObjC::RewriteBreakStmt(BreakStmt *S) {
1416
6
  if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1417
4
    return S;
1418
2
  // replace break with goto __break_label
1419
2
  std::string buf;
1420
2
1421
2
  SourceLocation startLoc = S->getBeginLoc();
1422
2
  buf = "goto __break_label_";
1423
2
  buf += utostr(ObjCBcLabelNo.back());
1424
2
  ReplaceText(startLoc, strlen("break"), buf);
1425
2
1426
2
  return nullptr;
1427
2
}
1428
1429
/// RewriteContinueStmt - Rewrite for a continue-stmt inside an ObjC2's foreach
1430
/// statement to continue with its inner synthesized loop.
1431
///
1432
2
Stmt *RewriteObjC::RewriteContinueStmt(ContinueStmt *S) {
1433
2
  if (Stmts.empty() || !isa<ObjCForCollectionStmt>(Stmts.back()))
1434
0
    return S;
1435
2
  // replace continue with goto __continue_label
1436
2
  std::string buf;
1437
2
1438
2
  SourceLocation startLoc = S->getBeginLoc();
1439
2
  buf = "goto __continue_label_";
1440
2
  buf += utostr(ObjCBcLabelNo.back());
1441
2
  ReplaceText(startLoc, strlen("continue"), buf);
1442
2
1443
2
  return nullptr;
1444
2
}
1445
1446
/// RewriteObjCForCollectionStmt - Rewriter for ObjC2's foreach statement.
1447
///  It rewrites:
1448
/// for ( type elem in collection) { stmts; }
1449
1450
/// Into:
1451
/// {
1452
///   type elem;
1453
///   struct __objcFastEnumerationState enumState = { 0 };
1454
///   id __rw_items[16];
1455
///   id l_collection = (id)collection;
1456
///   unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1457
///                                       objects:__rw_items count:16];
1458
/// if (limit) {
1459
///   unsigned long startMutations = *enumState.mutationsPtr;
1460
///   do {
1461
///        unsigned long counter = 0;
1462
///        do {
1463
///             if (startMutations != *enumState.mutationsPtr)
1464
///               objc_enumerationMutation(l_collection);
1465
///             elem = (type)enumState.itemsPtr[counter++];
1466
///             stmts;
1467
///             __continue_label: ;
1468
///        } while (counter < limit);
1469
///   } while (limit = [l_collection countByEnumeratingWithState:&enumState
1470
///                                  objects:__rw_items count:16]);
1471
///   elem = nil;
1472
///   __break_label: ;
1473
///  }
1474
///  else
1475
///       elem = nil;
1476
///  }
1477
///
1478
Stmt *RewriteObjC::RewriteObjCForCollectionStmt(ObjCForCollectionStmt *S,
1479
18
                                                SourceLocation OrigEnd) {
1480
18
  assert(!Stmts.empty() && "ObjCForCollectionStmt - Statement stack empty");
1481
18
  assert(isa<ObjCForCollectionStmt>(Stmts.back()) &&
1482
18
         "ObjCForCollectionStmt Statement stack mismatch");
1483
18
  assert(!ObjCBcLabelNo.empty() &&
1484
18
         "ObjCForCollectionStmt - Label No stack empty");
1485
18
1486
18
  SourceLocation startLoc = S->getBeginLoc();
1487
18
  const char *startBuf = SM->getCharacterData(startLoc);
1488
18
  StringRef elementName;
1489
18
  std::string elementTypeAsString;
1490
18
  std::string buf;
1491
18
  buf = "\n{\n\t";
1492
18
  if (DeclStmt *DS = dyn_cast<DeclStmt>(S->getElement())) {
1493
9
    // type elem;
1494
9
    NamedDecl* D = cast<NamedDecl>(DS->getSingleDecl());
1495
9
    QualType ElementType = cast<ValueDecl>(D)->getType();
1496
9
    if (ElementType->isObjCQualifiedIdType() ||
1497
9
        
ElementType->isObjCQualifiedInterfaceType()8
)
1498
1
      // Simply use 'id' for all qualified types.
1499
1
      elementTypeAsString = "id";
1500
8
    else
1501
8
      elementTypeAsString = ElementType.getAsString(Context->getPrintingPolicy());
1502
9
    buf += elementTypeAsString;
1503
9
    buf += " ";
1504
9
    elementName = D->getName();
1505
9
    buf += elementName;
1506
9
    buf += ";\n\t";
1507
9
  }
1508
9
  else {
1509
9
    DeclRefExpr *DR = cast<DeclRefExpr>(S->getElement());
1510
9
    elementName = DR->getDecl()->getName();
1511
9
    ValueDecl *VD = DR->getDecl();
1512
9
    if (VD->getType()->isObjCQualifiedIdType() ||
1513
9
        VD->getType()->isObjCQualifiedInterfaceType())
1514
0
      // Simply use 'id' for all qualified types.
1515
0
      elementTypeAsString = "id";
1516
9
    else
1517
9
      elementTypeAsString = VD->getType().getAsString(Context->getPrintingPolicy());
1518
9
  }
1519
18
1520
18
  // struct __objcFastEnumerationState enumState = { 0 };
1521
18
  buf += "struct __objcFastEnumerationState enumState = { 0 };\n\t";
1522
18
  // id __rw_items[16];
1523
18
  buf += "id __rw_items[16];\n\t";
1524
18
  // id l_collection = (id)
1525
18
  buf += "id l_collection = (id)";
1526
18
  // Find start location of 'collection' the hard way!
1527
18
  const char *startCollectionBuf = startBuf;
1528
18
  startCollectionBuf += 3;  // skip 'for'
1529
18
  startCollectionBuf = strchr(startCollectionBuf, '(');
1530
18
  startCollectionBuf++; // skip '('
1531
18
  // find 'in' and skip it.
1532
151
  while (*startCollectionBuf != ' ' ||
1533
151
         
*(startCollectionBuf+1) != 'i'29
||
*(startCollectionBuf+2) != 'n'18
||
1534
151
         
(18
*(startCollectionBuf+3) != ' '18
&&
1535
18
          
*(startCollectionBuf+3) != '['3
&&
*(startCollectionBuf+3) != '('1
))
1536
133
    startCollectionBuf++;
1537
18
  startCollectionBuf += 3;
1538
18
1539
18
  // Replace: "for (type element in" with string constructed thus far.
1540
18
  ReplaceText(startLoc, startCollectionBuf - startBuf, buf);
1541
18
  // Replace ')' in for '(' type elem in collection ')' with ';'
1542
18
  SourceLocation rightParenLoc = S->getRParenLoc();
1543
18
  const char *rparenBuf = SM->getCharacterData(rightParenLoc);
1544
18
  SourceLocation lparenLoc = startLoc.getLocWithOffset(rparenBuf-startBuf);
1545
18
  buf = ";\n\t";
1546
18
1547
18
  // unsigned long limit = [l_collection countByEnumeratingWithState:&enumState
1548
18
  //                                   objects:__rw_items count:16];
1549
18
  // which is synthesized into:
1550
18
  // unsigned int limit =
1551
18
  // ((unsigned int (*)
1552
18
  //  (id, SEL, struct __objcFastEnumerationState *, id *, unsigned int))
1553
18
  //  (void *)objc_msgSend)((id)l_collection,
1554
18
  //                        sel_registerName(
1555
18
  //                          "countByEnumeratingWithState:objects:count:"),
1556
18
  //                        (struct __objcFastEnumerationState *)&state,
1557
18
  //                        (id *)__rw_items, (unsigned int)16);
1558
18
  buf += "unsigned long limit =\n\t\t";
1559
18
  SynthCountByEnumWithState(buf);
1560
18
  buf += ";\n\t";
1561
18
  /// if (limit) {
1562
18
  ///   unsigned long startMutations = *enumState.mutationsPtr;
1563
18
  ///   do {
1564
18
  ///        unsigned long counter = 0;
1565
18
  ///        do {
1566
18
  ///             if (startMutations != *enumState.mutationsPtr)
1567
18
  ///               objc_enumerationMutation(l_collection);
1568
18
  ///             elem = (type)enumState.itemsPtr[counter++];
1569
18
  buf += "if (limit) {\n\t";
1570
18
  buf += "unsigned long startMutations = *enumState.mutationsPtr;\n\t";
1571
18
  buf += "do {\n\t\t";
1572
18
  buf += "unsigned long counter = 0;\n\t\t";
1573
18
  buf += "do {\n\t\t\t";
1574
18
  buf += "if (startMutations != *enumState.mutationsPtr)\n\t\t\t\t";
1575
18
  buf += "objc_enumerationMutation(l_collection);\n\t\t\t";
1576
18
  buf += elementName;
1577
18
  buf += " = (";
1578
18
  buf += elementTypeAsString;
1579
18
  buf += ")enumState.itemsPtr[counter++];";
1580
18
  // Replace ')' in for '(' type elem in collection ')' with all of these.
1581
18
  ReplaceText(lparenLoc, 1, buf);
1582
18
1583
18
  ///            __continue_label: ;
1584
18
  ///        } while (counter < limit);
1585
18
  ///   } while (limit = [l_collection countByEnumeratingWithState:&enumState
1586
18
  ///                                  objects:__rw_items count:16]);
1587
18
  ///   elem = nil;
1588
18
  ///   __break_label: ;
1589
18
  ///  }
1590
18
  ///  else
1591
18
  ///       elem = nil;
1592
18
  ///  }
1593
18
  ///
1594
18
  buf = ";\n\t";
1595
18
  buf += "__continue_label_";
1596
18
  buf += utostr(ObjCBcLabelNo.back());
1597
18
  buf += ": ;";
1598
18
  buf += "\n\t\t";
1599
18
  buf += "} while (counter < limit);\n\t";
1600
18
  buf += "} while (limit = ";
1601
18
  SynthCountByEnumWithState(buf);
1602
18
  buf += ");\n\t";
1603
18
  buf += elementName;
1604
18
  buf += " = ((";
1605
18
  buf += elementTypeAsString;
1606
18
  buf += ")0);\n\t";
1607
18
  buf += "__break_label_";
1608
18
  buf += utostr(ObjCBcLabelNo.back());
1609
18
  buf += ": ;\n\t";
1610
18
  buf += "}\n\t";
1611
18
  buf += "else\n\t\t";
1612
18
  buf += elementName;
1613
18
  buf += " = ((";
1614
18
  buf += elementTypeAsString;
1615
18
  buf += ")0);\n\t";
1616
18
  buf += "}\n";
1617
18
1618
18
  // Insert all these *after* the statement body.
1619
18
  // FIXME: If this should support Obj-C++, support CXXTryStmt
1620
18
  if (isa<CompoundStmt>(S->getBody())) {
1621
12
    SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(1);
1622
12
    InsertText(endBodyLoc, buf);
1623
12
  } else {
1624
6
    /* Need to treat single statements specially. For example:
1625
6
     *
1626
6
     *     for (A *a in b) if (stuff()) break;
1627
6
     *     for (A *a in b) xxxyy;
1628
6
     *
1629
6
     * The following code simply scans ahead to the semi to find the actual end.
1630
6
     */
1631
6
    const char *stmtBuf = SM->getCharacterData(OrigEnd);
1632
6
    const char *semiBuf = strchr(stmtBuf, ';');
1633
6
    assert(semiBuf && "Can't find ';'");
1634
6
    SourceLocation endBodyLoc = OrigEnd.getLocWithOffset(semiBuf-stmtBuf+1);
1635
6
    InsertText(endBodyLoc, buf);
1636
6
  }
1637
18
  Stmts.pop_back();
1638
18
  ObjCBcLabelNo.pop_back();
1639
18
  return nullptr;
1640
18
}
1641
1642
/// RewriteObjCSynchronizedStmt -
1643
/// This routine rewrites @synchronized(expr) stmt;
1644
/// into:
1645
/// objc_sync_enter(expr);
1646
/// @try stmt @finally { objc_sync_exit(expr); }
1647
///
1648
3
Stmt *RewriteObjC::RewriteObjCSynchronizedStmt(ObjCAtSynchronizedStmt *S) {
1649
3
  // Get the start location and compute the semi location.
1650
3
  SourceLocation startLoc = S->getBeginLoc();
1651
3
  const char *startBuf = SM->getCharacterData(startLoc);
1652
3
1653
3
  assert((*startBuf == '@') && "bogus @synchronized location");
1654
3
1655
3
  std::string buf;
1656
3
  buf = "objc_sync_enter((id)";
1657
3
  const char *lparenBuf = startBuf;
1658
45
  while (*lparenBuf != '(') 
lparenBuf++42
;
1659
3
  ReplaceText(startLoc, lparenBuf-startBuf+1, buf);
1660
3
  // We can't use S->getSynchExpr()->getEndLoc() to find the end location, since
1661
3
  // the sync expression is typically a message expression that's already
1662
3
  // been rewritten! (which implies the SourceLocation's are invalid).
1663
3
  SourceLocation endLoc = S->getSynchBody()->getBeginLoc();
1664
3
  const char *endBuf = SM->getCharacterData(endLoc);
1665
9
  while (*endBuf != ')') 
endBuf--6
;
1666
3
  SourceLocation rparenLoc = startLoc.getLocWithOffset(endBuf-startBuf);
1667
3
  buf = ");\n";
1668
3
  // declare a new scope with two variables, _stack and _rethrow.
1669
3
  buf += "/* @try scope begin */ \n{ struct _objc_exception_data {\n";
1670
3
  buf += "int buf[18/*32-bit i386*/];\n";
1671
3
  buf += "char *pointers[4];} _stack;\n";
1672
3
  buf += "id volatile _rethrow = 0;\n";
1673
3
  buf += "objc_exception_try_enter(&_stack);\n";
1674
3
  buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1675
3
  ReplaceText(rparenLoc, 1, buf);
1676
3
  startLoc = S->getSynchBody()->getEndLoc();
1677
3
  startBuf = SM->getCharacterData(startLoc);
1678
3
1679
3
  assert((*startBuf == '}') && "bogus @synchronized block");
1680
3
  SourceLocation lastCurlyLoc = startLoc;
1681
3
  buf = "}\nelse {\n";
1682
3
  buf += "  _rethrow = objc_exception_extract(&_stack);\n";
1683
3
  buf += "}\n";
1684
3
  buf += "{ /* implicit finally clause */\n";
1685
3
  buf += "  if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1686
3
1687
3
  std::string syncBuf;
1688
3
  syncBuf += " objc_sync_exit(";
1689
3
1690
3
  Expr *syncExpr = S->getSynchExpr();
1691
3
  CastKind CK = syncExpr->getType()->isObjCObjectPointerType()
1692
3
                  ? CK_BitCast :
1693
3
                syncExpr->getType()->isBlockPointerType()
1694
0
                  ? CK_BlockPointerToObjCPointerCast
1695
0
                  : CK_CPointerToObjCPointerCast;
1696
3
  syncExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
1697
3
                                      CK, syncExpr);
1698
3
  std::string syncExprBufS;
1699
3
  llvm::raw_string_ostream syncExprBuf(syncExprBufS);
1700
3
  assert(syncExpr != nullptr && "Expected non-null Expr");
1701
3
  syncExpr->printPretty(syncExprBuf, nullptr, PrintingPolicy(LangOpts));
1702
3
  syncBuf += syncExprBuf.str();
1703
3
  syncBuf += ");";
1704
3
1705
3
  buf += syncBuf;
1706
3
  buf += "\n  if (_rethrow) objc_exception_throw(_rethrow);\n";
1707
3
  buf += "}\n";
1708
3
  buf += "}";
1709
3
1710
3
  ReplaceText(lastCurlyLoc, 1, buf);
1711
3
1712
3
  bool hasReturns = false;
1713
3
  HasReturnStmts(S->getSynchBody(), hasReturns);
1714
3
  if (hasReturns)
1715
3
    RewriteSyncReturnStmts(S->getSynchBody(), syncBuf);
1716
3
1717
3
  return nullptr;
1718
3
}
1719
1720
void RewriteObjC::WarnAboutReturnGotoStmts(Stmt *S)
1721
26
{
1722
26
  // Perform a bottom up traversal of all children.
1723
26
  for (Stmt *SubStmt : S->children())
1724
22
    if (SubStmt)
1725
22
      WarnAboutReturnGotoStmts(SubStmt);
1726
26
1727
26
  if (isa<ReturnStmt>(S) || 
isa<GotoStmt>(S)25
) {
1728
1
    Diags.Report(Context->getFullLoc(S->getBeginLoc()),
1729
1
                 TryFinallyContainsReturnDiag);
1730
1
  }
1731
26
}
1732
1733
void RewriteObjC::HasReturnStmts(Stmt *S, bool &hasReturns)
1734
23
{
1735
23
  // Perform a bottom up traversal of all children.
1736
23
  for (Stmt *SubStmt : S->children())
1737
16
    if (SubStmt)
1738
16
      HasReturnStmts(SubStmt, hasReturns);
1739
23
1740
23
  if (isa<ReturnStmt>(S))
1741
4
    hasReturns = true;
1742
23
}
1743
1744
2
void RewriteObjC::RewriteTryReturnStmts(Stmt *S) {
1745
2
  // Perform a bottom up traversal of all children.
1746
2
  for (Stmt *SubStmt : S->children())
1747
1
    if (SubStmt) {
1748
1
      RewriteTryReturnStmts(SubStmt);
1749
1
    }
1750
2
  if (isa<ReturnStmt>(S)) {
1751
1
    SourceLocation startLoc = S->getBeginLoc();
1752
1
    const char *startBuf = SM->getCharacterData(startLoc);
1753
1
    const char *semiBuf = strchr(startBuf, ';');
1754
1
    assert((*semiBuf == ';') && "RewriteTryReturnStmts: can't find ';'");
1755
1
    SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1756
1
1757
1
    std::string buf;
1758
1
    buf = "{ objc_exception_try_exit(&_stack); return";
1759
1
1760
1
    ReplaceText(startLoc, 6, buf);
1761
1
    InsertText(onePastSemiLoc, "}");
1762
1
  }
1763
2
}
1764
1765
12
void RewriteObjC::RewriteSyncReturnStmts(Stmt *S, std::string syncExitBuf) {
1766
12
  // Perform a bottom up traversal of all children.
1767
12
  for (Stmt *SubStmt : S->children())
1768
9
    if (SubStmt) {
1769
9
      RewriteSyncReturnStmts(SubStmt, syncExitBuf);
1770
9
    }
1771
12
  if (isa<ReturnStmt>(S)) {
1772
3
    SourceLocation startLoc = S->getBeginLoc();
1773
3
    const char *startBuf = SM->getCharacterData(startLoc);
1774
3
1775
3
    const char *semiBuf = strchr(startBuf, ';');
1776
3
    assert((*semiBuf == ';') && "RewriteSyncReturnStmts: can't find ';'");
1777
3
    SourceLocation onePastSemiLoc = startLoc.getLocWithOffset(semiBuf-startBuf+1);
1778
3
1779
3
    std::string buf;
1780
3
    buf = "{ objc_exception_try_exit(&_stack);";
1781
3
    buf += syncExitBuf;
1782
3
    buf += " return";
1783
3
1784
3
    ReplaceText(startLoc, 6, buf);
1785
3
    InsertText(onePastSemiLoc, "}");
1786
3
  }
1787
12
}
1788
1789
8
Stmt *RewriteObjC::RewriteObjCTryStmt(ObjCAtTryStmt *S) {
1790
8
  // Get the start location and compute the semi location.
1791
8
  SourceLocation startLoc = S->getBeginLoc();
1792
8
  const char *startBuf = SM->getCharacterData(startLoc);
1793
8
1794
8
  assert((*startBuf == '@') && "bogus @try location");
1795
8
1796
8
  std::string buf;
1797
8
  // declare a new scope with two variables, _stack and _rethrow.
1798
8
  buf = "/* @try scope begin */ { struct _objc_exception_data {\n";
1799
8
  buf += "int buf[18/*32-bit i386*/];\n";
1800
8
  buf += "char *pointers[4];} _stack;\n";
1801
8
  buf += "id volatile _rethrow = 0;\n";
1802
8
  buf += "objc_exception_try_enter(&_stack);\n";
1803
8
  buf += "if (!_setjmp(_stack.buf)) /* @try block continue */\n";
1804
8
1805
8
  ReplaceText(startLoc, 4, buf);
1806
8
1807
8
  startLoc = S->getTryBody()->getEndLoc();
1808
8
  startBuf = SM->getCharacterData(startLoc);
1809
8
1810
8
  assert((*startBuf == '}') && "bogus @try block");
1811
8
1812
8
  SourceLocation lastCurlyLoc = startLoc;
1813
8
  if (S->getNumCatchStmts()) {
1814
4
    startLoc = startLoc.getLocWithOffset(1);
1815
4
    buf = " /* @catch begin */ else {\n";
1816
4
    buf += " id _caught = objc_exception_extract(&_stack);\n";
1817
4
    buf += " objc_exception_try_enter (&_stack);\n";
1818
4
    buf += " if (_setjmp(_stack.buf))\n";
1819
4
    buf += "   _rethrow = objc_exception_extract(&_stack);\n";
1820
4
    buf += " else { /* @catch continue */";
1821
4
1822
4
    InsertText(startLoc, buf);
1823
4
  } else { /* no catch list */
1824
4
    buf = "}\nelse {\n";
1825
4
    buf += "  _rethrow = objc_exception_extract(&_stack);\n";
1826
4
    buf += "}";
1827
4
    ReplaceText(lastCurlyLoc, 1, buf);
1828
4
  }
1829
8
  Stmt *lastCatchBody = nullptr;
1830
14
  for (unsigned I = 0, N = S->getNumCatchStmts(); I != N; 
++I6
) {
1831
6
    ObjCAtCatchStmt *Catch = S->getCatchStmt(I);
1832
6
    VarDecl *catchDecl = Catch->getCatchParamDecl();
1833
6
1834
6
    if (I == 0)
1835
4
      buf = "if ("; // we are generating code for the first catch clause
1836
2
    else
1837
2
      buf = "else if (";
1838
6
    startLoc = Catch->getBeginLoc();
1839
6
    startBuf = SM->getCharacterData(startLoc);
1840
6
1841
6
    assert((*startBuf == '@') && "bogus @catch location");
1842
6
1843
6
    const char *lParenLoc = strchr(startBuf, '(');
1844
6
1845
6
    if (Catch->hasEllipsis()) {
1846
2
      // Now rewrite the body...
1847
2
      lastCatchBody = Catch->getCatchBody();
1848
2
      SourceLocation bodyLoc = lastCatchBody->getBeginLoc();
1849
2
      const char *bodyBuf = SM->getCharacterData(bodyLoc);
1850
2
      assert(*SM->getCharacterData(Catch->getRParenLoc()) == ')' &&
1851
2
             "bogus @catch paren location");
1852
2
      assert((*bodyBuf == '{') && "bogus @catch body location");
1853
2
1854
2
      buf += "1) { id _tmp = _caught;";
1855
2
      Rewrite.ReplaceText(startLoc, bodyBuf-startBuf+1, buf);
1856
4
    } else if (catchDecl) {
1857
4
      QualType t = catchDecl->getType();
1858
4
      if (t == Context->getObjCIdType()) {
1859
1
        buf += "1) { ";
1860
1
        ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1861
3
      } else if (const ObjCObjectPointerType *Ptr =
1862
3
                   t->getAs<ObjCObjectPointerType>()) {
1863
3
        // Should be a pointer to a class.
1864
3
        ObjCInterfaceDecl *IDecl = Ptr->getObjectType()->getInterface();
1865
3
        if (IDecl) {
1866
3
          buf += "objc_exception_match((struct objc_class *)objc_getClass(\"";
1867
3
          buf += IDecl->getNameAsString();
1868
3
          buf += "\"), (struct objc_object *)_caught)) { ";
1869
3
          ReplaceText(startLoc, lParenLoc-startBuf+1, buf);
1870
3
        }
1871
3
      }
1872
4
      // Now rewrite the body...
1873
4
      lastCatchBody = Catch->getCatchBody();
1874
4
      SourceLocation rParenLoc = Catch->getRParenLoc();
1875
4
      SourceLocation bodyLoc = lastCatchBody->getBeginLoc();
1876
4
      const char *bodyBuf = SM->getCharacterData(bodyLoc);
1877
4
      const char *rParenBuf = SM->getCharacterData(rParenLoc);
1878
4
      assert((*rParenBuf == ')') && "bogus @catch paren location");
1879
4
      assert((*bodyBuf == '{') && "bogus @catch body location");
1880
4
1881
4
      // Here we replace ") {" with "= _caught;" (which initializes and
1882
4
      // declares the @catch parameter).
1883
4
      ReplaceText(rParenLoc, bodyBuf-rParenBuf+1, " = _caught;");
1884
4
    } else {
1885
0
      llvm_unreachable("@catch rewrite bug");
1886
0
    }
1887
6
  }
1888
8
  // Complete the catch list...
1889
8
  if (lastCatchBody) {
1890
4
    SourceLocation bodyLoc = lastCatchBody->getEndLoc();
1891
4
    assert(*SM->getCharacterData(bodyLoc) == '}' &&
1892
4
           "bogus @catch body location");
1893
4
1894
4
    // Insert the last (implicit) else clause *before* the right curly brace.
1895
4
    bodyLoc = bodyLoc.getLocWithOffset(-1);
1896
4
    buf = "} /* last catch end */\n";
1897
4
    buf += "else {\n";
1898
4
    buf += " _rethrow = _caught;\n";
1899
4
    buf += " objc_exception_try_exit(&_stack);\n";
1900
4
    buf += "} } /* @catch end */\n";
1901
4
    if (!S->getFinallyStmt())
1902
4
      buf += "}\n";
1903
4
    InsertText(bodyLoc, buf);
1904
4
1905
4
    // Set lastCurlyLoc
1906
4
    lastCurlyLoc = lastCatchBody->getEndLoc();
1907
4
  }
1908
8
  if (ObjCAtFinallyStmt *finalStmt = S->getFinallyStmt()) {
1909
4
    startLoc = finalStmt->getBeginLoc();
1910
4
    startBuf = SM->getCharacterData(startLoc);
1911
4
    assert((*startBuf == '@') && "bogus @finally start");
1912
4
1913
4
    ReplaceText(startLoc, 8, "/* @finally */");
1914
4
1915
4
    Stmt *body = finalStmt->getFinallyBody();
1916
4
    SourceLocation startLoc = body->getBeginLoc();
1917
4
    SourceLocation endLoc = body->getEndLoc();
1918
4
    assert(*SM->getCharacterData(startLoc) == '{' &&
1919
4
           "bogus @finally body location");
1920
4
    assert(*SM->getCharacterData(endLoc) == '}' &&
1921
4
           "bogus @finally body location");
1922
4
1923
4
    startLoc = startLoc.getLocWithOffset(1);
1924
4
    InsertText(startLoc, " if (!_rethrow) objc_exception_try_exit(&_stack);\n");
1925
4
    endLoc = endLoc.getLocWithOffset(-1);
1926
4
    InsertText(endLoc, " if (_rethrow) objc_exception_throw(_rethrow);\n");
1927
4
1928
4
    // Set lastCurlyLoc
1929
4
    lastCurlyLoc = body->getEndLoc();
1930
4
1931
4
    // Now check for any return/continue/go statements within the @try.
1932
4
    WarnAboutReturnGotoStmts(S->getTryBody());
1933
4
  } else { /* no finally clause - make sure we synthesize an implicit one */
1934
4
    buf = "{ /* implicit finally clause */\n";
1935
4
    buf += " if (!_rethrow) objc_exception_try_exit(&_stack);\n";
1936
4
    buf += " if (_rethrow) objc_exception_throw(_rethrow);\n";
1937
4
    buf += "}";
1938
4
    ReplaceText(lastCurlyLoc, 1, buf);
1939
4
1940
4
    // Now check for any return/continue/go statements within the @try.
1941
4
    // The implicit finally clause won't called if the @try contains any
1942
4
    // jump statements.
1943
4
    bool hasReturns = false;
1944
4
    HasReturnStmts(S->getTryBody(), hasReturns);
1945
4
    if (hasReturns)
1946
1
      RewriteTryReturnStmts(S->getTryBody());
1947
4
  }
1948
8
  // Now emit the final closing curly brace...
1949
8
  lastCurlyLoc = lastCurlyLoc.getLocWithOffset(1);
1950
8
  InsertText(lastCurlyLoc, " } /* @try scope end */\n");
1951
8
  return nullptr;
1952
8
}
1953
1954
// This can't be done with ReplaceStmt(S, ThrowExpr), since
1955
// the throw expression is typically a message expression that's already
1956
// been rewritten! (which implies the SourceLocation's are invalid).
1957
2
Stmt *RewriteObjC::RewriteObjCThrowStmt(ObjCAtThrowStmt *S) {
1958
2
  // Get the start location and compute the semi location.
1959
2
  SourceLocation startLoc = S->getBeginLoc();
1960
2
  const char *startBuf = SM->getCharacterData(startLoc);
1961
2
1962
2
  assert((*startBuf == '@') && "bogus @throw location");
1963
2
1964
2
  std::string buf;
1965
2
  /* void objc_exception_throw(id) __attribute__((noreturn)); */
1966
2
  if (S->getThrowExpr())
1967
0
    buf = "objc_exception_throw(";
1968
2
  else // add an implicit argument
1969
2
    buf = "objc_exception_throw(_caught";
1970
2
1971
2
  // handle "@  throw" correctly.
1972
2
  const char *wBuf = strchr(startBuf, 'w');
1973
2
  assert((*wBuf == 'w') && "@throw: can't find 'w'");
1974
2
  ReplaceText(startLoc, wBuf-startBuf+1, buf);
1975
2
1976
2
  const char *semiBuf = strchr(startBuf, ';');
1977
2
  assert((*semiBuf == ';') && "@throw: can't find ';'");
1978
2
  SourceLocation semiLoc = startLoc.getLocWithOffset(semiBuf-startBuf);
1979
2
  ReplaceText(semiLoc, 1, ");");
1980
2
  return nullptr;
1981
2
}
1982
1983
3
Stmt *RewriteObjC::RewriteAtEncode(ObjCEncodeExpr *Exp) {
1984
3
  // Create a new string expression.
1985
3
  std::string StrEncoding;
1986
3
  Context->getObjCEncodingForType(Exp->getEncodedType(), StrEncoding);
1987
3
  Expr *Replacement = getStringLiteral(StrEncoding);
1988
3
  ReplaceStmt(Exp, Replacement);
1989
3
1990
3
  // Replace this subexpr in the parent.
1991
3
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
1992
3
  return Replacement;
1993
3
}
1994
1995
1
Stmt *RewriteObjC::RewriteAtSelector(ObjCSelectorExpr *Exp) {
1996
1
  if (!SelGetUidFunctionDecl)
1997
1
    SynthSelGetUidFunctionDecl();
1998
1
  assert(SelGetUidFunctionDecl && "Can't find sel_registerName() decl");
1999
1
  // Create a call to sel_registerName("selName").
2000
1
  SmallVector<Expr*, 8> SelExprs;
2001
1
  SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
2002
1
  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2003
1
                                                  SelExprs);
2004
1
  ReplaceStmt(Exp, SelExp);
2005
1
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2006
1
  return SelExp;
2007
1
}
2008
2009
CallExpr *
2010
RewriteObjC::SynthesizeCallToFunctionDecl(FunctionDecl *FD,
2011
                                          ArrayRef<Expr *> Args,
2012
                                          SourceLocation StartLoc,
2013
139
                                          SourceLocation EndLoc) {
2014
139
  // Get the type, we will need to reference it in a couple spots.
2015
139
  QualType msgSendType = FD->getType();
2016
139
2017
139
  // Create a reference to the objc_msgSend() declaration.
2018
139
  DeclRefExpr *DRE = new (Context) DeclRefExpr(*Context, FD, false, msgSendType,
2019
139
                                               VK_LValue, SourceLocation());
2020
139
2021
139
  // Now, we cast the reference to a pointer to the objc_msgSend type.
2022
139
  QualType pToFunc = Context->getPointerType(msgSendType);
2023
139
  ImplicitCastExpr *ICE =
2024
139
    ImplicitCastExpr::Create(*Context, pToFunc, CK_FunctionToPointerDecay,
2025
139
                             DRE, nullptr, VK_RValue);
2026
139
2027
139
  const auto *FT = msgSendType->castAs<FunctionType>();
2028
139
2029
139
  CallExpr *Exp = CallExpr::Create(
2030
139
      *Context, ICE, Args, FT->getCallResultType(*Context), VK_RValue, EndLoc);
2031
139
  return Exp;
2032
139
}
2033
2034
static bool scanForProtocolRefs(const char *startBuf, const char *endBuf,
2035
26
                                const char *&startRef, const char *&endRef) {
2036
360
  while (startBuf < endBuf) {
2037
360
    if (*startBuf == '<')
2038
26
      startRef = startBuf; // mark the start.
2039
360
    if (*startBuf == '>') {
2040
26
      if (startRef && *startRef == '<') {
2041
26
        endRef = startBuf; // mark the end.
2042
26
        return true;
2043
26
      }
2044
0
      return false;
2045
0
    }
2046
334
    startBuf++;
2047
334
  }
2048
26
  
return false0
;
2049
26
}
2050
2051
6
static void scanToNextArgument(const char *&argRef) {
2052
6
  int angle = 0;
2053
147
  while (*argRef != ')' && 
(144
*argRef != ','144
||
angle > 05
)) {
2054
141
    if (*argRef == '<')
2055
6
      angle++;
2056
135
    else if (*argRef == '>')
2057
6
      angle--;
2058
141
    argRef++;
2059
141
  }
2060
6
  assert(angle == 0 && "scanToNextArgument - bad protocol type syntax");
2061
6
}
2062
2063
371
bool RewriteObjC::needToScanForQualifiers(QualType T) {
2064
371
  if (T->isObjCQualifiedIdType())
2065
9
    return true;
2066
362
  if (const PointerType *PT = T->getAs<PointerType>()) {
2067
37
    if (PT->getPointeeType()->isObjCQualifiedIdType())
2068
1
      return true;
2069
361
  }
2070
361
  if (T->isObjCObjectPointerType()) {
2071
113
    T = T->getPointeeType();
2072
113
    return T->isObjCQualifiedInterfaceType();
2073
113
  }
2074
248
  if (T->isArrayType()) {
2075
3
    QualType ElemTy = Context->getBaseElementType(T);
2076
3
    return needToScanForQualifiers(ElemTy);
2077
3
  }
2078
245
  return false;
2079
245
}
2080
2081
31
void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Expr *E) {
2082
31
  QualType Type = E->getType();
2083
31
  if (needToScanForQualifiers(Type)) {
2084
7
    SourceLocation Loc, EndLoc;
2085
7
2086
7
    if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E)) {
2087
7
      Loc = ECE->getLParenLoc();
2088
7
      EndLoc = ECE->getRParenLoc();
2089
7
    } else {
2090
0
      Loc = E->getBeginLoc();
2091
0
      EndLoc = E->getEndLoc();
2092
0
    }
2093
7
    // This will defend against trying to rewrite synthesized expressions.
2094
7
    if (Loc.isInvalid() || EndLoc.isInvalid())
2095
0
      return;
2096
7
2097
7
    const char *startBuf = SM->getCharacterData(Loc);
2098
7
    const char *endBuf = SM->getCharacterData(EndLoc);
2099
7
    const char *startRef = nullptr, *endRef = nullptr;
2100
7
    if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2101
7
      // Get the locations of the startRef, endRef.
2102
7
      SourceLocation LessLoc = Loc.getLocWithOffset(startRef-startBuf);
2103
7
      SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-startBuf+1);
2104
7
      // Comment out the protocol references.
2105
7
      InsertText(LessLoc, "/*");
2106
7
      InsertText(GreaterLoc, "*/");
2107
7
    }
2108
7
  }
2109
31
}
2110
2111
265
void RewriteObjC::RewriteObjCQualifiedInterfaceTypes(Decl *Dcl) {
2112
265
  SourceLocation Loc;
2113
265
  QualType Type;
2114
265
  const FunctionProtoType *proto = nullptr;
2115
265
  if (VarDecl *VD = dyn_cast<VarDecl>(Dcl)) {
2116
149
    Loc = VD->getLocation();
2117
149
    Type = VD->getType();
2118
149
  }
2119
116
  else if (FunctionDecl *FD = dyn_cast<FunctionDecl>(Dcl)) {
2120
115
    Loc = FD->getLocation();
2121
115
    // Check for ObjC 'id' and class types that have been adorned with protocol
2122
115
    // information (id<p>, C<p>*). The protocol references need to be rewritten!
2123
115
    const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2124
115
    assert(funcType && "missing function type");
2125
115
    proto = dyn_cast<FunctionProtoType>(funcType);
2126
115
    if (!proto)
2127
23
      return;
2128
92
    Type = proto->getReturnType();
2129
92
  }
2130
1
  else if (FieldDecl *FD = dyn_cast<FieldDecl>(Dcl)) {
2131
1
    Loc = FD->getLocation();
2132
1
    Type = FD->getType();
2133
1
  }
2134
0
  else
2135
0
    return;
2136
242
2137
242
  if (needToScanForQualifiers(Type)) {
2138
13
    // Since types are unique, we need to scan the buffer.
2139
13
2140
13
    const char *endBuf = SM->getCharacterData(Loc);
2141
13
    const char *startBuf = endBuf;
2142
217
    while (*startBuf != ';' && *startBuf != '<' && 
startBuf != MainFileStart204
)
2143
204
      startBuf--; // scan backward (from the decl location) for return type.
2144
13
    const char *startRef = nullptr, *endRef = nullptr;
2145
13
    if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2146
13
      // Get the locations of the startRef, endRef.
2147
13
      SourceLocation LessLoc = Loc.getLocWithOffset(startRef-endBuf);
2148
13
      SourceLocation GreaterLoc = Loc.getLocWithOffset(endRef-endBuf+1);
2149
13
      // Comment out the protocol references.
2150
13
      InsertText(LessLoc, "/*");
2151
13
      InsertText(GreaterLoc, "*/");
2152
13
    }
2153
13
  }
2154
242
  if (!proto)
2155
150
      return; // most likely, was a variable
2156
92
  // Now check arguments.
2157
92
  const char *startBuf = SM->getCharacterData(Loc);
2158
92
  const char *startFuncBuf = startBuf;
2159
172
  for (unsigned i = 0; i < proto->getNumParams(); 
i++80
) {
2160
80
    if (needToScanForQualifiers(proto->getParamType(i))) {
2161
6
      // Since types are unique, we need to scan the buffer.
2162
6
2163
6
      const char *endBuf = startBuf;
2164
6
      // scan forward (from the decl location) for argument types.
2165
6
      scanToNextArgument(endBuf);
2166
6
      const char *startRef = nullptr, *endRef = nullptr;
2167
6
      if (scanForProtocolRefs(startBuf, endBuf, startRef, endRef)) {
2168
6
        // Get the locations of the startRef, endRef.
2169
6
        SourceLocation LessLoc =
2170
6
          Loc.getLocWithOffset(startRef-startFuncBuf);
2171
6
        SourceLocation GreaterLoc =
2172
6
          Loc.getLocWithOffset(endRef-startFuncBuf+1);
2173
6
        // Comment out the protocol references.
2174
6
        InsertText(LessLoc, "/*");
2175
6
        InsertText(GreaterLoc, "*/");
2176
6
      }
2177
6
      startBuf = ++endBuf;
2178
6
    }
2179
74
    else {
2180
74
      // If the function name is derived from a macro expansion, then the
2181
74
      // argument buffer will not follow the name. Need to speak with Chris.
2182
1.26k
      while (*startBuf && *startBuf != ')' && 
*startBuf != ','1.20k
)
2183
1.18k
        startBuf++; // scan forward (from the decl location) for argument types.
2184
74
      startBuf++;
2185
74
    }
2186
80
  }
2187
92
}
2188
2189
119
void RewriteObjC::RewriteTypeOfDecl(VarDecl *ND) {
2190
119
  QualType QT = ND->getType();
2191
119
  const Type* TypePtr = QT->getAs<Type>();
2192
119
  if (!isa<TypeOfExprType>(TypePtr))
2193
116
    return;
2194
9
  
while (3
isa<TypeOfExprType>(TypePtr)) {
2195
6
    const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
2196
6
    QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
2197
6
    TypePtr = QT->getAs<Type>();
2198
6
  }
2199
3
  // FIXME. This will not work for multiple declarators; as in:
2200
3
  // __typeof__(a) b,c,d;
2201
3
  std::string TypeAsString(QT.getAsString(Context->getPrintingPolicy()));
2202
3
  SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
2203
3
  const char *startBuf = SM->getCharacterData(DeclLoc);
2204
3
  if (ND->getInit()) {
2205
2
    std::string Name(ND->getNameAsString());
2206
2
    TypeAsString += " " + Name + " = ";
2207
2
    Expr *E = ND->getInit();
2208
2
    SourceLocation startLoc;
2209
2
    if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
2210
0
      startLoc = ECE->getLParenLoc();
2211
2
    else
2212
2
      startLoc = E->getBeginLoc();
2213
2
    startLoc = SM->getExpansionLoc(startLoc);
2214
2
    const char *endBuf = SM->getCharacterData(startLoc);
2215
2
    ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2216
2
  }
2217
1
  else {
2218
1
    SourceLocation X = ND->getEndLoc();
2219
1
    X = SM->getExpansionLoc(X);
2220
1
    const char *endBuf = SM->getCharacterData(X);
2221
1
    ReplaceText(DeclLoc, endBuf-startBuf-1, TypeAsString);
2222
1
  }
2223
3
}
2224
2225
// SynthSelGetUidFunctionDecl - SEL sel_registerName(const char *str);
2226
15
void RewriteObjC::SynthSelGetUidFunctionDecl() {
2227
15
  IdentifierInfo *SelGetUidIdent = &Context->Idents.get("sel_registerName");
2228
15
  SmallVector<QualType, 16> ArgTys;
2229
15
  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2230
15
  QualType getFuncType =
2231
15
    getSimpleFunctionType(Context->getObjCSelType(), ArgTys);
2232
15
  SelGetUidFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2233
15
                                               SourceLocation(),
2234
15
                                               SourceLocation(),
2235
15
                                               SelGetUidIdent, getFuncType,
2236
15
                                               nullptr, SC_Extern);
2237
15
}
2238
2239
136
void RewriteObjC::RewriteFunctionDecl(FunctionDecl *FD) {
2240
136
  // declared in <objc/objc.h>
2241
136
  if (FD->getIdentifier() &&
2242
136
      FD->getName() == "sel_registerName") {
2243
21
    SelGetUidFunctionDecl = FD;
2244
21
    return;
2245
21
  }
2246
115
  RewriteObjCQualifiedInterfaceTypes(FD);
2247
115
}
2248
2249
13
void RewriteObjC::RewriteBlockPointerType(std::string& Str, QualType Type) {
2250
13
  std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2251
13
  const char *argPtr = TypeString.c_str();
2252
13
  if (!strchr(argPtr, '^')) {
2253
6
    Str += TypeString;
2254
6
    return;
2255
6
  }
2256
105
  
while (7
*argPtr) {
2257
98
    Str += (*argPtr == '^' ? 
'*'7
:
*argPtr91
);
2258
98
    argPtr++;
2259
98
  }
2260
7
}
2261
2262
// FIXME. Consolidate this routine with RewriteBlockPointerType.
2263
void RewriteObjC::RewriteBlockPointerTypeVariable(std::string& Str,
2264
2
                                                  ValueDecl *VD) {
2265
2
  QualType Type = VD->getType();
2266
2
  std::string TypeString(Type.getAsString(Context->getPrintingPolicy()));
2267
2
  const char *argPtr = TypeString.c_str();
2268
2
  int paren = 0;
2269
29
  while (*argPtr) {
2270
27
    switch (*argPtr) {
2271
4
      case '(':
2272
4
        Str += *argPtr;
2273
4
        paren++;
2274
4
        break;
2275
4
      case ')':
2276
4
        Str += *argPtr;
2277
4
        paren--;
2278
4
        break;
2279
2
      case '^':
2280
2
        Str += '*';
2281
2
        if (paren == 1)
2282
2
          Str += VD->getNameAsString();
2283
2
        break;
2284
17
      default:
2285
17
        Str += *argPtr;
2286
17
        break;
2287
27
    }
2288
27
    argPtr++;
2289
27
  }
2290
2
}
2291
2292
30
void RewriteObjC::RewriteBlockLiteralFunctionDecl(FunctionDecl *FD) {
2293
30
  SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
2294
30
  const FunctionType *funcType = FD->getType()->getAs<FunctionType>();
2295
30
  const FunctionProtoType *proto = dyn_cast_or_null<FunctionProtoType>(funcType);
2296
30
  if (!proto)
2297
8
    return;
2298
22
  QualType Type = proto->getReturnType();
2299
22
  std::string FdStr = Type.getAsString(Context->getPrintingPolicy());
2300
22
  FdStr += " ";
2301
22
  FdStr += FD->getName();
2302
22
  FdStr +=  "(";
2303
22
  unsigned numArgs = proto->getNumParams();
2304
30
  for (unsigned i = 0; i < numArgs; 
i++8
) {
2305
8
    QualType ArgType = proto->getParamType(i);
2306
8
    RewriteBlockPointerType(FdStr, ArgType);
2307
8
    if (i+1 < numArgs)
2308
2
      FdStr += ", ";
2309
8
  }
2310
22
  FdStr +=  ");\n";
2311
22
  InsertText(FunLocStart, FdStr);
2312
22
  CurFunctionDeclToDeclareForBlock = nullptr;
2313
22
}
2314
2315
// SynthSuperConstructorFunctionDecl - id objc_super(id obj, id super);
2316
2
void RewriteObjC::SynthSuperConstructorFunctionDecl() {
2317
2
  if (SuperConstructorFunctionDecl)
2318
1
    return;
2319
1
  IdentifierInfo *msgSendIdent = &Context->Idents.get("__rw_objc_super");
2320
1
  SmallVector<QualType, 16> ArgTys;
2321
1
  QualType argT = Context->getObjCIdType();
2322
1
  assert(!argT.isNull() && "Can't find 'id' type");
2323
1
  ArgTys.push_back(argT);
2324
1
  ArgTys.push_back(argT);
2325
1
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2326
1
                                               ArgTys);
2327
1
  SuperConstructorFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2328
1
                                                     SourceLocation(),
2329
1
                                                     SourceLocation(),
2330
1
                                                     msgSendIdent, msgSendType,
2331
1
                                                     nullptr, SC_Extern);
2332
1
}
2333
2334
// SynthMsgSendFunctionDecl - id objc_msgSend(id self, SEL op, ...);
2335
36
void RewriteObjC::SynthMsgSendFunctionDecl() {
2336
36
  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend");
2337
36
  SmallVector<QualType, 16> ArgTys;
2338
36
  QualType argT = Context->getObjCIdType();
2339
36
  assert(!argT.isNull() && "Can't find 'id' type");
2340
36
  ArgTys.push_back(argT);
2341
36
  argT = Context->getObjCSelType();
2342
36
  assert(!argT.isNull() && "Can't find 'SEL' type");
2343
36
  ArgTys.push_back(argT);
2344
36
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2345
36
                                               ArgTys, /*variadic=*/true);
2346
36
  MsgSendFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2347
36
                                             SourceLocation(),
2348
36
                                             SourceLocation(),
2349
36
                                             msgSendIdent, msgSendType,
2350
36
                                             nullptr, SC_Extern);
2351
36
}
2352
2353
// SynthMsgSendSuperFunctionDecl - id objc_msgSendSuper(struct objc_super *, SEL op, ...);
2354
36
void RewriteObjC::SynthMsgSendSuperFunctionDecl() {
2355
36
  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSendSuper");
2356
36
  SmallVector<QualType, 16> ArgTys;
2357
36
  RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2358
36
                                      SourceLocation(), SourceLocation(),
2359
36
                                      &Context->Idents.get("objc_super"));
2360
36
  QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2361
36
  assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2362
36
  ArgTys.push_back(argT);
2363
36
  argT = Context->getObjCSelType();
2364
36
  assert(!argT.isNull() && "Can't find 'SEL' type");
2365
36
  ArgTys.push_back(argT);
2366
36
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2367
36
                                               ArgTys, /*variadic=*/true);
2368
36
  MsgSendSuperFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2369
36
                                                  SourceLocation(),
2370
36
                                                  SourceLocation(),
2371
36
                                                  msgSendIdent, msgSendType,
2372
36
                                                  nullptr, SC_Extern);
2373
36
}
2374
2375
// SynthMsgSendStretFunctionDecl - id objc_msgSend_stret(id self, SEL op, ...);
2376
36
void RewriteObjC::SynthMsgSendStretFunctionDecl() {
2377
36
  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_stret");
2378
36
  SmallVector<QualType, 16> ArgTys;
2379
36
  QualType argT = Context->getObjCIdType();
2380
36
  assert(!argT.isNull() && "Can't find 'id' type");
2381
36
  ArgTys.push_back(argT);
2382
36
  argT = Context->getObjCSelType();
2383
36
  assert(!argT.isNull() && "Can't find 'SEL' type");
2384
36
  ArgTys.push_back(argT);
2385
36
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2386
36
                                               ArgTys, /*variadic=*/true);
2387
36
  MsgSendStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2388
36
                                                  SourceLocation(),
2389
36
                                                  SourceLocation(),
2390
36
                                                  msgSendIdent, msgSendType,
2391
36
                                                  nullptr, SC_Extern);
2392
36
}
2393
2394
// SynthMsgSendSuperStretFunctionDecl -
2395
// id objc_msgSendSuper_stret(struct objc_super *, SEL op, ...);
2396
36
void RewriteObjC::SynthMsgSendSuperStretFunctionDecl() {
2397
36
  IdentifierInfo *msgSendIdent =
2398
36
    &Context->Idents.get("objc_msgSendSuper_stret");
2399
36
  SmallVector<QualType, 16> ArgTys;
2400
36
  RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2401
36
                                      SourceLocation(), SourceLocation(),
2402
36
                                      &Context->Idents.get("objc_super"));
2403
36
  QualType argT = Context->getPointerType(Context->getTagDeclType(RD));
2404
36
  assert(!argT.isNull() && "Can't build 'struct objc_super *' type");
2405
36
  ArgTys.push_back(argT);
2406
36
  argT = Context->getObjCSelType();
2407
36
  assert(!argT.isNull() && "Can't find 'SEL' type");
2408
36
  ArgTys.push_back(argT);
2409
36
  QualType msgSendType = getSimpleFunctionType(Context->getObjCIdType(),
2410
36
                                               ArgTys, /*variadic=*/true);
2411
36
  MsgSendSuperStretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2412
36
                                                       SourceLocation(),
2413
36
                                                       SourceLocation(),
2414
36
                                                       msgSendIdent,
2415
36
                                                       msgSendType, nullptr,
2416
36
                                                       SC_Extern);
2417
36
}
2418
2419
// SynthMsgSendFpretFunctionDecl - double objc_msgSend_fpret(id self, SEL op, ...);
2420
36
void RewriteObjC::SynthMsgSendFpretFunctionDecl() {
2421
36
  IdentifierInfo *msgSendIdent = &Context->Idents.get("objc_msgSend_fpret");
2422
36
  SmallVector<QualType, 16> ArgTys;
2423
36
  QualType argT = Context->getObjCIdType();
2424
36
  assert(!argT.isNull() && "Can't find 'id' type");
2425
36
  ArgTys.push_back(argT);
2426
36
  argT = Context->getObjCSelType();
2427
36
  assert(!argT.isNull() && "Can't find 'SEL' type");
2428
36
  ArgTys.push_back(argT);
2429
36
  QualType msgSendType = getSimpleFunctionType(Context->DoubleTy,
2430
36
                                               ArgTys, /*variadic=*/true);
2431
36
  MsgSendFpretFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2432
36
                                                  SourceLocation(),
2433
36
                                                  SourceLocation(),
2434
36
                                                  msgSendIdent, msgSendType,
2435
36
                                                  nullptr, SC_Extern);
2436
36
}
2437
2438
// SynthGetClassFunctionDecl - id objc_getClass(const char *name);
2439
36
void RewriteObjC::SynthGetClassFunctionDecl() {
2440
36
  IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getClass");
2441
36
  SmallVector<QualType, 16> ArgTys;
2442
36
  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2443
36
  QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2444
36
                                                ArgTys);
2445
36
  GetClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2446
36
                                              SourceLocation(),
2447
36
                                              SourceLocation(),
2448
36
                                              getClassIdent, getClassType,
2449
36
                                              nullptr, SC_Extern);
2450
36
}
2451
2452
// SynthGetSuperClassFunctionDecl - Class class_getSuperclass(Class cls);
2453
36
void RewriteObjC::SynthGetSuperClassFunctionDecl() {
2454
36
  IdentifierInfo *getSuperClassIdent =
2455
36
    &Context->Idents.get("class_getSuperclass");
2456
36
  SmallVector<QualType, 16> ArgTys;
2457
36
  ArgTys.push_back(Context->getObjCClassType());
2458
36
  QualType getClassType = getSimpleFunctionType(Context->getObjCClassType(),
2459
36
                                                ArgTys);
2460
36
  GetSuperClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2461
36
                                                   SourceLocation(),
2462
36
                                                   SourceLocation(),
2463
36
                                                   getSuperClassIdent,
2464
36
                                                   getClassType, nullptr,
2465
36
                                                   SC_Extern);
2466
36
}
2467
2468
// SynthGetMetaClassFunctionDecl - id objc_getMetaClass(const char *name);
2469
36
void RewriteObjC::SynthGetMetaClassFunctionDecl() {
2470
36
  IdentifierInfo *getClassIdent = &Context->Idents.get("objc_getMetaClass");
2471
36
  SmallVector<QualType, 16> ArgTys;
2472
36
  ArgTys.push_back(Context->getPointerType(Context->CharTy.withConst()));
2473
36
  QualType getClassType = getSimpleFunctionType(Context->getObjCIdType(),
2474
36
                                                ArgTys);
2475
36
  GetMetaClassFunctionDecl = FunctionDecl::Create(*Context, TUDecl,
2476
36
                                                  SourceLocation(),
2477
36
                                                  SourceLocation(),
2478
36
                                                  getClassIdent, getClassType,
2479
36
                                                  nullptr, SC_Extern);
2480
36
}
2481
2482
18
Stmt *RewriteObjC::RewriteObjCStringLiteral(ObjCStringLiteral *Exp) {
2483
18
  assert(Exp != nullptr && "Expected non-null ObjCStringLiteral");
2484
18
  QualType strType = getConstantStringStructType();
2485
18
2486
18
  std::string S = "__NSConstantStringImpl_";
2487
18
2488
18
  std::string tmpName = InFileName;
2489
18
  unsigned i;
2490
1.64k
  for (i=0; i < tmpName.length(); 
i++1.62k
) {
2491
1.62k
    char c = tmpName.at(i);
2492
1.62k
    // replace any non-alphanumeric characters with '_'.
2493
1.62k
    if (!isAlphanumeric(c))
2494
232
      tmpName[i] = '_';
2495
1.62k
  }
2496
18
  S += tmpName;
2497
18
  S += "_";
2498
18
  S += utostr(NumObjCStringLiterals++);
2499
18
2500
18
  Preamble += "static __NSConstantStringImpl " + S;
2501
18
  Preamble += " __attribute__ ((section (\"__DATA, __cfstring\"))) = {__CFConstantStringClassReference,";
2502
18
  Preamble += "0x000007c8,"; // utf8_str
2503
18
  // The pretty printer for StringLiteral handles escape characters properly.
2504
18
  std::string prettyBufS;
2505
18
  llvm::raw_string_ostream prettyBuf(prettyBufS);
2506
18
  Exp->getString()->printPretty(prettyBuf, nullptr, PrintingPolicy(LangOpts));
2507
18
  Preamble += prettyBuf.str();
2508
18
  Preamble += ",";
2509
18
  Preamble += utostr(Exp->getString()->getByteLength()) + "};\n";
2510
18
2511
18
  VarDecl *NewVD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
2512
18
                                   SourceLocation(), &Context->Idents.get(S),
2513
18
                                   strType, nullptr, SC_Static);
2514
18
  DeclRefExpr *DRE = new (Context)
2515
18
      DeclRefExpr(*Context, NewVD, false, strType, VK_LValue, SourceLocation());
2516
18
  Expr *Unop = new (Context)
2517
18
      UnaryOperator(DRE, UO_AddrOf, Context->getPointerType(DRE->getType()),
2518
18
                    VK_RValue, OK_Ordinary, SourceLocation(), false);
2519
18
  // cast to NSConstantString *
2520
18
  CastExpr *cast = NoTypeInfoCStyleCastExpr(Context, Exp->getType(),
2521
18
                                            CK_CPointerToObjCPointerCast, Unop);
2522
18
  ReplaceStmt(Exp, cast);
2523
18
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
2524
18
  return cast;
2525
18
}
2526
2527
// struct objc_super { struct objc_object *receiver; struct objc_class *super; };
2528
6
QualType RewriteObjC::getSuperStructType() {
2529
6
  if (!SuperStructDecl) {
2530
2
    SuperStructDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2531
2
                                         SourceLocation(), SourceLocation(),
2532
2
                                         &Context->Idents.get("objc_super"));
2533
2
    QualType FieldTypes[2];
2534
2
2535
2
    // struct objc_object *receiver;
2536
2
    FieldTypes[0] = Context->getObjCIdType();
2537
2
    // struct objc_class *super;
2538
2
    FieldTypes[1] = Context->getObjCClassType();
2539
2
2540
2
    // Create fields
2541
6
    for (unsigned i = 0; i < 2; 
++i4
) {
2542
4
      SuperStructDecl->addDecl(FieldDecl::Create(*Context, SuperStructDecl,
2543
4
                                                 SourceLocation(),
2544
4
                                                 SourceLocation(), nullptr,
2545
4
                                                 FieldTypes[i], nullptr,
2546
4
                                                 /*BitWidth=*/nullptr,
2547
4
                                                 /*Mutable=*/false,
2548
4
                                                 ICIS_NoInit));
2549
4
    }
2550
2
2551
2
    SuperStructDecl->completeDefinition();
2552
2
  }
2553
6
  return Context->getTagDeclType(SuperStructDecl);
2554
6
}
2555
2556
18
QualType RewriteObjC::getConstantStringStructType() {
2557
18
  if (!ConstantStringDecl) {
2558
4
    ConstantStringDecl = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
2559
4
                                            SourceLocation(), SourceLocation(),
2560
4
                         &Context->Idents.get("__NSConstantStringImpl"));
2561
4
    QualType FieldTypes[4];
2562
4
2563
4
    // struct objc_object *receiver;
2564
4
    FieldTypes[0] = Context->getObjCIdType();
2565
4
    // int flags;
2566
4
    FieldTypes[1] = Context->IntTy;
2567
4
    // char *str;
2568
4
    FieldTypes[2] = Context->getPointerType(Context->CharTy);
2569
4
    // long length;
2570
4
    FieldTypes[3] = Context->LongTy;
2571
4
2572
4
    // Create fields
2573
20
    for (unsigned i = 0; i < 4; 
++i16
) {
2574
16
      ConstantStringDecl->addDecl(FieldDecl::Create(*Context,
2575
16
                                                    ConstantStringDecl,
2576
16
                                                    SourceLocation(),
2577
16
                                                    SourceLocation(), nullptr,
2578
16
                                                    FieldTypes[i], nullptr,
2579
16
                                                    /*BitWidth=*/nullptr,
2580
16
                                                    /*Mutable=*/true,
2581
16
                                                    ICIS_NoInit));
2582
16
    }
2583
4
2584
4
    ConstantStringDecl->completeDefinition();
2585
4
  }
2586
18
  return Context->getTagDeclType(ConstantStringDecl);
2587
18
}
2588
2589
CallExpr *RewriteObjC::SynthMsgSendStretCallExpr(FunctionDecl *MsgSendStretFlavor,
2590
                                                QualType msgSendType,
2591
                                                QualType returnType,
2592
                                                SmallVectorImpl<QualType> &ArgTypes,
2593
                                                SmallVectorImpl<Expr*> &MsgExprs,
2594
1
                                                ObjCMethodDecl *Method) {
2595
1
  // Create a reference to the objc_msgSend_stret() declaration.
2596
1
  DeclRefExpr *STDRE =
2597
1
      new (Context) DeclRefExpr(*Context, MsgSendStretFlavor, false,
2598
1
                                msgSendType, VK_LValue, SourceLocation());
2599
1
  // Need to cast objc_msgSend_stret to "void *" (see above comment).
2600
1
  CastExpr *cast = NoTypeInfoCStyleCastExpr(Context,
2601
1
                                  Context->getPointerType(Context->VoidTy),
2602
1
                                  CK_BitCast, STDRE);
2603
1
  // Now do the "normal" pointer to function cast.
2604
1
  QualType castType = getSimpleFunctionType(returnType, ArgTypes,
2605
1
                                            Method ? Method->isVariadic()
2606
1
                                                   : 
false0
);
2607
1
  castType = Context->getPointerType(castType);
2608
1
  cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2609
1
                                            cast);
2610
1
2611
1
  // Don't forget the parens to enforce the proper binding.
2612
1
  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), cast);
2613
1
2614
1
  const auto *FT = msgSendType->castAs<FunctionType>();
2615
1
  CallExpr *STCE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2616
1
                                    VK_RValue, SourceLocation());
2617
1
  return STCE;
2618
1
}
2619
2620
Stmt *RewriteObjC::SynthMessageExpr(ObjCMessageExpr *Exp,
2621
                                    SourceLocation StartLoc,
2622
115
                                    SourceLocation EndLoc) {
2623
115
  if (!SelGetUidFunctionDecl)
2624
14
    SynthSelGetUidFunctionDecl();
2625
115
  if (!MsgSendFunctionDecl)
2626
36
    SynthMsgSendFunctionDecl();
2627
115
  if (!MsgSendSuperFunctionDecl)
2628
36
    SynthMsgSendSuperFunctionDecl();
2629
115
  if (!MsgSendStretFunctionDecl)
2630
36
    SynthMsgSendStretFunctionDecl();
2631
115
  if (!MsgSendSuperStretFunctionDecl)
2632
36
    SynthMsgSendSuperStretFunctionDecl();
2633
115
  if (!MsgSendFpretFunctionDecl)
2634
36
    SynthMsgSendFpretFunctionDecl();
2635
115
  if (!GetClassFunctionDecl)
2636
36
    SynthGetClassFunctionDecl();
2637
115
  if (!GetSuperClassFunctionDecl)
2638
36
    SynthGetSuperClassFunctionDecl();
2639
115
  if (!GetMetaClassFunctionDecl)
2640
36
    SynthGetMetaClassFunctionDecl();
2641
115
2642
115
  // default to objc_msgSend().
2643
115
  FunctionDecl *MsgSendFlavor = MsgSendFunctionDecl;
2644
115
  // May need to use objc_msgSend_stret() as well.
2645
115
  FunctionDecl *MsgSendStretFlavor = nullptr;
2646
115
  if (ObjCMethodDecl *mDecl = Exp->getMethodDecl()) {
2647
103
    QualType resultType = mDecl->getReturnType();
2648
103
    if (resultType->isRecordType())
2649
1
      MsgSendStretFlavor = MsgSendStretFunctionDecl;
2650
102
    else if (resultType->isRealFloatingType())
2651
0
      MsgSendFlavor = MsgSendFpretFunctionDecl;
2652
103
  }
2653
115
2654
115
  // Synthesize a call to objc_msgSend().
2655
115
  SmallVector<Expr*, 8> MsgExprs;
2656
115
  switch (Exp->getReceiverKind()) {
2657
1
  case ObjCMessageExpr::SuperClass: {
2658
1
    MsgSendFlavor = MsgSendSuperFunctionDecl;
2659
1
    if (MsgSendStretFlavor)
2660
0
      MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2661
1
    assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2662
1
2663
1
    ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2664
1
2665
1
    SmallVector<Expr*, 4> InitExprs;
2666
1
2667
1
    // set the receiver to self, the first argument to all methods.
2668
1
    InitExprs.push_back(
2669
1
      NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2670
1
                               CK_BitCast,
2671
1
                   new (Context) DeclRefExpr(*Context,
2672
1
                                             CurMethodDef->getSelfDecl(),
2673
1
                                             false,
2674
1
                                             Context->getObjCIdType(),
2675
1
                                             VK_RValue,
2676
1
                                             SourceLocation()))
2677
1
                        ); // set the 'receiver'.
2678
1
2679
1
    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2680
1
    SmallVector<Expr*, 8> ClsExprs;
2681
1
    ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
2682
1
    CallExpr *Cls = SynthesizeCallToFunctionDecl(GetMetaClassFunctionDecl,
2683
1
                                                 ClsExprs, StartLoc, EndLoc);
2684
1
    // (Class)objc_getClass("CurrentClass")
2685
1
    CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2686
1
                                             Context->getObjCClassType(),
2687
1
                                             CK_BitCast, Cls);
2688
1
    ClsExprs.clear();
2689
1
    ClsExprs.push_back(ArgExpr);
2690
1
    Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
2691
1
                                       StartLoc, EndLoc);
2692
1
    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2693
1
    // To turn off a warning, type-cast to 'id'
2694
1
    InitExprs.push_back( // set 'super class', using class_getSuperclass().
2695
1
                        NoTypeInfoCStyleCastExpr(Context,
2696
1
                                                 Context->getObjCIdType(),
2697
1
                                                 CK_BitCast, Cls));
2698
1
    // struct objc_super
2699
1
    QualType superType = getSuperStructType();
2700
1
    Expr *SuperRep;
2701
1
2702
1
    if (LangOpts.MicrosoftExt) {
2703
1
      SynthSuperConstructorFunctionDecl();
2704
1
      // Simulate a constructor call...
2705
1
      DeclRefExpr *DRE = new (Context)
2706
1
          DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
2707
1
                      VK_LValue, SourceLocation());
2708
1
      SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType,
2709
1
                                  VK_LValue, SourceLocation());
2710
1
      // The code for super is a little tricky to prevent collision with
2711
1
      // the structure definition in the header. The rewriter has it's own
2712
1
      // internal definition (__rw_objc_super) that is uses. This is why
2713
1
      // we need the cast below. For example:
2714
1
      // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2715
1
      //
2716
1
      SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2717
1
                               Context->getPointerType(SuperRep->getType()),
2718
1
                                             VK_RValue, OK_Ordinary,
2719
1
                                             SourceLocation(), false);
2720
1
      SuperRep = NoTypeInfoCStyleCastExpr(Context,
2721
1
                                          Context->getPointerType(superType),
2722
1
                                          CK_BitCast, SuperRep);
2723
1
    } else {
2724
0
      // (struct objc_super) { <exprs from above> }
2725
0
      InitListExpr *ILE =
2726
0
        new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
2727
0
                                   SourceLocation());
2728
0
      TypeSourceInfo *superTInfo
2729
0
        = Context->getTrivialTypeSourceInfo(superType);
2730
0
      SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2731
0
                                                   superType, VK_LValue,
2732
0
                                                   ILE, false);
2733
0
      // struct objc_super *
2734
0
      SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2735
0
                               Context->getPointerType(SuperRep->getType()),
2736
0
                                             VK_RValue, OK_Ordinary,
2737
0
                                             SourceLocation(), false);
2738
0
    }
2739
1
    MsgExprs.push_back(SuperRep);
2740
1
    break;
2741
0
  }
2742
0
2743
17
  case ObjCMessageExpr::Class: {
2744
17
    SmallVector<Expr*, 8> ClsExprs;
2745
17
    auto *Class =
2746
17
        Exp->getClassReceiver()->castAs<ObjCObjectType>()->getInterface();
2747
17
    IdentifierInfo *clsName = Class->getIdentifier();
2748
17
    ClsExprs.push_back(getStringLiteral(clsName->getName()));
2749
17
    CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2750
17
                                                 StartLoc, EndLoc);
2751
17
    MsgExprs.push_back(Cls);
2752
17
    break;
2753
0
  }
2754
0
2755
2
  case ObjCMessageExpr::SuperInstance:{
2756
2
    MsgSendFlavor = MsgSendSuperFunctionDecl;
2757
2
    if (MsgSendStretFlavor)
2758
0
      MsgSendStretFlavor = MsgSendSuperStretFunctionDecl;
2759
2
    assert(MsgSendFlavor && "MsgSendFlavor is NULL!");
2760
2
    ObjCInterfaceDecl *ClassDecl = CurMethodDef->getClassInterface();
2761
2
    SmallVector<Expr*, 4> InitExprs;
2762
2
2763
2
    InitExprs.push_back(
2764
2
      NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2765
2
                               CK_BitCast,
2766
2
                   new (Context) DeclRefExpr(*Context,
2767
2
                                             CurMethodDef->getSelfDecl(),
2768
2
                                             false,
2769
2
                                             Context->getObjCIdType(),
2770
2
                                             VK_RValue, SourceLocation()))
2771
2
                        ); // set the 'receiver'.
2772
2
2773
2
    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2774
2
    SmallVector<Expr*, 8> ClsExprs;
2775
2
    ClsExprs.push_back(getStringLiteral(ClassDecl->getIdentifier()->getName()));
2776
2
    CallExpr *Cls = SynthesizeCallToFunctionDecl(GetClassFunctionDecl, ClsExprs,
2777
2
                                                 StartLoc, EndLoc);
2778
2
    // (Class)objc_getClass("CurrentClass")
2779
2
    CastExpr *ArgExpr = NoTypeInfoCStyleCastExpr(Context,
2780
2
                                                 Context->getObjCClassType(),
2781
2
                                                 CK_BitCast, Cls);
2782
2
    ClsExprs.clear();
2783
2
    ClsExprs.push_back(ArgExpr);
2784
2
    Cls = SynthesizeCallToFunctionDecl(GetSuperClassFunctionDecl, ClsExprs,
2785
2
                                       StartLoc, EndLoc);
2786
2
2787
2
    // (id)class_getSuperclass((Class)objc_getClass("CurrentClass"))
2788
2
    // To turn off a warning, type-cast to 'id'
2789
2
    InitExprs.push_back(
2790
2
      // set 'super class', using class_getSuperclass().
2791
2
      NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2792
2
                               CK_BitCast, Cls));
2793
2
    // struct objc_super
2794
2
    QualType superType = getSuperStructType();
2795
2
    Expr *SuperRep;
2796
2
2797
2
    if (LangOpts.MicrosoftExt) {
2798
1
      SynthSuperConstructorFunctionDecl();
2799
1
      // Simulate a constructor call...
2800
1
      DeclRefExpr *DRE = new (Context)
2801
1
          DeclRefExpr(*Context, SuperConstructorFunctionDecl, false, superType,
2802
1
                      VK_LValue, SourceLocation());
2803
1
      SuperRep = CallExpr::Create(*Context, DRE, InitExprs, superType,
2804
1
                                  VK_LValue, SourceLocation());
2805
1
      // The code for super is a little tricky to prevent collision with
2806
1
      // the structure definition in the header. The rewriter has it's own
2807
1
      // internal definition (__rw_objc_super) that is uses. This is why
2808
1
      // we need the cast below. For example:
2809
1
      // (struct objc_super *)&__rw_objc_super((id)self, (id)objc_getClass("SUPER"))
2810
1
      //
2811
1
      SuperRep = new (Context) UnaryOperator(SuperRep, UO_AddrOf,
2812
1
                               Context->getPointerType(SuperRep->getType()),
2813
1
                               VK_RValue, OK_Ordinary,
2814
1
                               SourceLocation(), false);
2815
1
      SuperRep = NoTypeInfoCStyleCastExpr(Context,
2816
1
                               Context->getPointerType(superType),
2817
1
                               CK_BitCast, SuperRep);
2818
1
    } else {
2819
1
      // (struct objc_super) { <exprs from above> }
2820
1
      InitListExpr *ILE =
2821
1
        new (Context) InitListExpr(*Context, SourceLocation(), InitExprs,
2822
1
                                   SourceLocation());
2823
1
      TypeSourceInfo *superTInfo
2824
1
        = Context->getTrivialTypeSourceInfo(superType);
2825
1
      SuperRep = new (Context) CompoundLiteralExpr(SourceLocation(), superTInfo,
2826
1
                                                   superType, VK_RValue, ILE,
2827
1
                                                   false);
2828
1
    }
2829
2
    MsgExprs.push_back(SuperRep);
2830
2
    break;
2831
0
  }
2832
0
2833
95
  case ObjCMessageExpr::Instance: {
2834
95
    // Remove all type-casts because it may contain objc-style types; e.g.
2835
95
    // Foo<Proto> *.
2836
95
    Expr *recExpr = Exp->getInstanceReceiver();
2837
99
    while (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(recExpr))
2838
4
      recExpr = CE->getSubExpr();
2839
95
    CastKind CK = recExpr->getType()->isObjCObjectPointerType()
2840
95
                    ? CK_BitCast : recExpr->getType()->isBlockPointerType()
2841
0
                                     ? CK_BlockPointerToObjCPointerCast
2842
0
                                     : CK_CPointerToObjCPointerCast;
2843
95
2844
95
    recExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2845
95
                                       CK, recExpr);
2846
95
    MsgExprs.push_back(recExpr);
2847
95
    break;
2848
115
  }
2849
115
  }
2850
115
2851
115
  // Create a call to sel_registerName("selName"), it will be the 2nd argument.
2852
115
  SmallVector<Expr*, 8> SelExprs;
2853
115
  SelExprs.push_back(getStringLiteral(Exp->getSelector().getAsString()));
2854
115
  CallExpr *SelExp = SynthesizeCallToFunctionDecl(SelGetUidFunctionDecl,
2855
115
                                                  SelExprs, StartLoc, EndLoc);
2856
115
  MsgExprs.push_back(SelExp);
2857
115
2858
115
  // Now push any user supplied arguments.
2859
166
  for (unsigned i = 0; i < Exp->getNumArgs(); 
i++51
) {
2860
51
    Expr *userExpr = Exp->getArg(i);
2861
51
    // Make all implicit casts explicit...ICE comes in handy:-)
2862
51
    if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(userExpr)) {
2863
15
      // Reuse the ICE type, it is exactly what the doctor ordered.
2864
15
      QualType type = ICE->getType();
2865
15
      if (needToScanForQualifiers(type))
2866
1
        type = Context->getObjCIdType();
2867
15
      // Make sure we convert "type (^)(...)" to "type (*)(...)".
2868
15
      (void)convertBlockPointerToFunctionPointer(type);
2869
15
      const Expr *SubExpr = ICE->IgnoreParenImpCasts();
2870
15
      CastKind CK;
2871
15
      if (SubExpr->getType()->isIntegralType(*Context) &&
2872
15
          
type->isBooleanType()6
) {
2873
1
        CK = CK_IntegralToBoolean;
2874
14
      } else if (type->isObjCObjectPointerType()) {
2875
7
        if (SubExpr->getType()->isBlockPointerType()) {
2876
0
          CK = CK_BlockPointerToObjCPointerCast;
2877
7
        } else if (SubExpr->getType()->isPointerType()) {
2878
0
          CK = CK_CPointerToObjCPointerCast;
2879
7
        } else {
2880
7
          CK = CK_BitCast;
2881
7
        }
2882
7
      } else {
2883
7
        CK = CK_BitCast;
2884
7
      }
2885
15
2886
15
      userExpr = NoTypeInfoCStyleCastExpr(Context, type, CK, userExpr);
2887
15
    }
2888
36
    // Make id<P...> cast into an 'id' cast.
2889
36
    else if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(userExpr)) {
2890
20
      if (CE->getType()->isObjCQualifiedIdType()) {
2891
2
        while ((CE = dyn_cast<CStyleCastExpr>(userExpr)))
2892
1
          userExpr = CE->getSubExpr();
2893
1
        CastKind CK;
2894
1
        if (userExpr->getType()->isIntegralType(*Context)) {
2895
1
          CK = CK_IntegralToPointer;
2896
1
        } else 
if (0
userExpr->getType()->isBlockPointerType()0
) {
2897
0
          CK = CK_BlockPointerToObjCPointerCast;
2898
0
        } else if (userExpr->getType()->isPointerType()) {
2899
0
          CK = CK_CPointerToObjCPointerCast;
2900
0
        } else {
2901
0
          CK = CK_BitCast;
2902
0
        }
2903
1
        userExpr = NoTypeInfoCStyleCastExpr(Context, Context->getObjCIdType(),
2904
1
                                            CK, userExpr);
2905
1
      }
2906
20
    }
2907
51
    MsgExprs.push_back(userExpr);
2908
51
    // We've transferred the ownership to MsgExprs. For now, we *don't* null
2909
51
    // out the argument in the original expression (since we aren't deleting
2910
51
    // the ObjCMessageExpr). See RewritePropertyOrImplicitSetter() usage for more info.
2911
51
    //Exp->setArg(i, 0);
2912
51
  }
2913
115
  // Generate the funky cast.
2914
115
  CastExpr *cast;
2915
115
  SmallVector<QualType, 8> ArgTypes;
2916
115
  QualType returnType;
2917
115
2918
115
  // Push 'id' and 'SEL', the 2 implicit arguments.
2919
115
  if (MsgSendFlavor == MsgSendSuperFunctionDecl)
2920
3
    ArgTypes.push_back(Context->getPointerType(getSuperStructType()));
2921
112
  else
2922
112
    ArgTypes.push_back(Context->getObjCIdType());
2923
115
  ArgTypes.push_back(Context->getObjCSelType());
2924
115
  if (ObjCMethodDecl *OMD = Exp->getMethodDecl()) {
2925
103
    // Push any user argument types.
2926
103
    for (const auto *PI : OMD->parameters()) {
2927
35
      QualType t = PI->getType()->isObjCQualifiedIdType()
2928
35
                     ? 
Context->getObjCIdType()1
2929
35
                     : 
PI->getType()34
;
2930
35
      // Make sure we convert "t (^)(...)" to "t (*)(...)".
2931
35
      (void)convertBlockPointerToFunctionPointer(t);
2932
35
      ArgTypes.push_back(t);
2933
35
    }
2934
103
    returnType = Exp->getType();
2935
103
    convertToUnqualifiedObjCType(returnType);
2936
103
    (void)convertBlockPointerToFunctionPointer(returnType);
2937
103
  } else {
2938
12
    returnType = Context->getObjCIdType();
2939
12
  }
2940
115
  // Get the type, we will need to reference it in a couple spots.
2941
115
  QualType msgSendType = MsgSendFlavor->getType();
2942
115
2943
115
  // Create a reference to the objc_msgSend() declaration.
2944
115
  DeclRefExpr *DRE = new (Context) DeclRefExpr(
2945
115
      *Context, MsgSendFlavor, false, msgSendType, VK_LValue, SourceLocation());
2946
115
2947
115
  // Need to cast objc_msgSend to "void *" (to workaround a GCC bandaid).
2948
115
  // If we don't do this cast, we get the following bizarre warning/note:
2949
115
  // xx.m:13: warning: function called through a non-compatible type
2950
115
  // xx.m:13: note: if this code is reached, the program will abort
2951
115
  cast = NoTypeInfoCStyleCastExpr(Context,
2952
115
                                  Context->getPointerType(Context->VoidTy),
2953
115
                                  CK_BitCast, DRE);
2954
115
2955
115
  // Now do the "normal" pointer to function cast.
2956
115
  // If we don't have a method decl, force a variadic cast.
2957
115
  const ObjCMethodDecl *MD = Exp->getMethodDecl();
2958
115
  QualType castType =
2959
115
    getSimpleFunctionType(returnType, ArgTypes, MD ? 
MD->isVariadic()103
:
true12
);
2960
115
  castType = Context->getPointerType(castType);
2961
115
  cast = NoTypeInfoCStyleCastExpr(Context, castType, CK_BitCast,
2962
115
                                  cast);
2963
115
2964
115
  // Don't forget the parens to enforce the proper binding.
2965
115
  ParenExpr *PE = new (Context) ParenExpr(StartLoc, EndLoc, cast);
2966
115
2967
115
  const auto *FT = msgSendType->castAs<FunctionType>();
2968
115
  CallExpr *CE = CallExpr::Create(*Context, PE, MsgExprs, FT->getReturnType(),
2969
115
                                  VK_RValue, EndLoc);
2970
115
  Stmt *ReplacingStmt = CE;
2971
115
  if (MsgSendStretFlavor) {
2972
1
    // We have the method which returns a struct/union. Must also generate
2973
1
    // call to objc_msgSend_stret and hang both varieties on a conditional
2974
1
    // expression which dictate which one to envoke depending on size of
2975
1
    // method's return type.
2976
1
2977
1
    CallExpr *STCE = SynthMsgSendStretCallExpr(MsgSendStretFlavor,
2978
1
                                               msgSendType, returnType,
2979
1
                                               ArgTypes, MsgExprs,
2980
1
                                               Exp->getMethodDecl());
2981
1
2982
1
    // Build sizeof(returnType)
2983
1
    UnaryExprOrTypeTraitExpr *sizeofExpr =
2984
1
       new (Context) UnaryExprOrTypeTraitExpr(UETT_SizeOf,
2985
1
                                 Context->getTrivialTypeSourceInfo(returnType),
2986
1
                                 Context->getSizeType(), SourceLocation(),
2987
1
                                 SourceLocation());
2988
1
    // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
2989
1
    // FIXME: Value of 8 is base on ppc32/x86 ABI for the most common cases.
2990
1
    // For X86 it is more complicated and some kind of target specific routine
2991
1
    // is needed to decide what to do.
2992
1
    unsigned IntSize =
2993
1
      static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
2994
1
    IntegerLiteral *limit = IntegerLiteral::Create(*Context,
2995
1
                                                   llvm::APInt(IntSize, 8),
2996
1
                                                   Context->IntTy,
2997
1
                                                   SourceLocation());
2998
1
    BinaryOperator *lessThanExpr =
2999
1
      new (Context) BinaryOperator(sizeofExpr, limit, BO_LE, Context->IntTy,
3000
1
                                   VK_RValue, OK_Ordinary, SourceLocation(),
3001
1
                                   FPOptions());
3002
1
    // (sizeof(returnType) <= 8 ? objc_msgSend(...) : objc_msgSend_stret(...))
3003
1
    ConditionalOperator *CondExpr =
3004
1
      new (Context) ConditionalOperator(lessThanExpr,
3005
1
                                        SourceLocation(), CE,
3006
1
                                        SourceLocation(), STCE,
3007
1
                                        returnType, VK_RValue, OK_Ordinary);
3008
1
    ReplacingStmt = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3009
1
                                            CondExpr);
3010
1
  }
3011
115
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3012
115
  return ReplacingStmt;
3013
115
}
3014
3015
79
Stmt *RewriteObjC::RewriteMessageExpr(ObjCMessageExpr *Exp) {
3016
79
  Stmt *ReplacingStmt =
3017
79
      SynthMessageExpr(Exp, Exp->getBeginLoc(), Exp->getEndLoc());
3018
79
3019
79
  // Now do the actual rewrite.
3020
79
  ReplaceStmt(Exp, ReplacingStmt);
3021
79
3022
79
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3023
79
  return ReplacingStmt;
3024
79
}
3025
3026
// typedef struct objc_object Protocol;
3027
0
QualType RewriteObjC::getProtocolType() {
3028
0
  if (!ProtocolTypeDecl) {
3029
0
    TypeSourceInfo *TInfo
3030
0
      = Context->getTrivialTypeSourceInfo(Context->getObjCIdType());
3031
0
    ProtocolTypeDecl = TypedefDecl::Create(*Context, TUDecl,
3032
0
                                           SourceLocation(), SourceLocation(),
3033
0
                                           &Context->Idents.get("Protocol"),
3034
0
                                           TInfo);
3035
0
  }
3036
0
  return Context->getTypeDeclType(ProtocolTypeDecl);
3037
0
}
3038
3039
/// RewriteObjCProtocolExpr - Rewrite a protocol expression into
3040
/// a synthesized/forward data reference (to the protocol's metadata).
3041
/// The forward references (and metadata) are generated in
3042
/// RewriteObjC::HandleTranslationUnit().
3043
0
Stmt *RewriteObjC::RewriteObjCProtocolExpr(ObjCProtocolExpr *Exp) {
3044
0
  std::string Name = "_OBJC_PROTOCOL_" + Exp->getProtocol()->getNameAsString();
3045
0
  IdentifierInfo *ID = &Context->Idents.get(Name);
3046
0
  VarDecl *VD = VarDecl::Create(*Context, TUDecl, SourceLocation(),
3047
0
                                SourceLocation(), ID, getProtocolType(),
3048
0
                                nullptr, SC_Extern);
3049
0
  DeclRefExpr *DRE = new (Context) DeclRefExpr(
3050
0
      *Context, VD, false, getProtocolType(), VK_LValue, SourceLocation());
3051
0
  Expr *DerefExpr = new (Context) UnaryOperator(DRE, UO_AddrOf,
3052
0
                             Context->getPointerType(DRE->getType()),
3053
0
                             VK_RValue, OK_Ordinary, SourceLocation(), false);
3054
0
  CastExpr *castExpr = NoTypeInfoCStyleCastExpr(Context, DerefExpr->getType(),
3055
0
                                                CK_BitCast,
3056
0
                                                DerefExpr);
3057
0
  ReplaceStmt(Exp, castExpr);
3058
0
  ProtocolExprDecls.insert(Exp->getProtocol()->getCanonicalDecl());
3059
0
  // delete Exp; leak for now, see RewritePropertyOrImplicitSetter() usage for more info.
3060
0
  return castExpr;
3061
0
}
3062
3063
bool RewriteObjC::BufferContainsPPDirectives(const char *startBuf,
3064
39
                                             const char *endBuf) {
3065
878
  while (startBuf < endBuf) {
3066
839
    if (*startBuf == '#') {
3067
0
      // Skip whitespace.
3068
0
      for (++startBuf; startBuf[0] == ' ' || startBuf[0] == '\t'; ++startBuf)
3069
0
        ;
3070
0
      if (!strncmp(startBuf, "if", strlen("if")) ||
3071
0
          !strncmp(startBuf, "ifdef", strlen("ifdef")) ||
3072
0
          !strncmp(startBuf, "ifndef", strlen("ifndef")) ||
3073
0
          !strncmp(startBuf, "define", strlen("define")) ||
3074
0
          !strncmp(startBuf, "undef", strlen("undef")) ||
3075
0
          !strncmp(startBuf, "else", strlen("else")) ||
3076
0
          !strncmp(startBuf, "elif", strlen("elif")) ||
3077
0
          !strncmp(startBuf, "endif", strlen("endif")) ||
3078
0
          !strncmp(startBuf, "pragma", strlen("pragma")) ||
3079
0
          !strncmp(startBuf, "include", strlen("include")) ||
3080
0
          !strncmp(startBuf, "import", strlen("import")) ||
3081
0
          !strncmp(startBuf, "include_next", strlen("include_next")))
3082
0
        return true;
3083
839
    }
3084
839
    startBuf++;
3085
839
  }
3086
39
  return false;
3087
39
}
3088
3089
/// RewriteObjCInternalStruct - Rewrite one internal struct corresponding to
3090
/// an objective-c class with ivars.
3091
void RewriteObjC::RewriteObjCInternalStruct(ObjCInterfaceDecl *CDecl,
3092
120
                                               std::string &Result) {
3093
120
  assert(CDecl && "Class missing in SynthesizeObjCInternalStruct");
3094
120
  assert(CDecl->getName() != "" &&
3095
120
         "Name missing in SynthesizeObjCInternalStruct");
3096
120
  // Do not synthesize more than once.
3097
120
  if (ObjCSynthesizedStructs.count(CDecl))
3098
0
    return;
3099
120
  ObjCInterfaceDecl *RCDecl = CDecl->getSuperClass();
3100
120
  int NumIvars = CDecl->ivar_size();
3101
120
  SourceLocation LocStart = CDecl->getBeginLoc();
3102
120
  SourceLocation LocEnd = CDecl->getEndOfDefinitionLoc();
3103
120
3104
120
  const char *startBuf = SM->getCharacterData(LocStart);
3105
120
  const char *endBuf = SM->getCharacterData(LocEnd);
3106
120
3107
120
  // If no ivars and no root or if its root, directly or indirectly,
3108
120
  // have no ivars (thus not synthesized) then no need to synthesize this class.
3109
120
  if ((!CDecl->isThisDeclarationADefinition() || NumIvars == 0) &&
3110
120
      
(81
!RCDecl81
||
!ObjCSynthesizedStructs.count(RCDecl)10
)) {
3111
80
    endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3112
80
    ReplaceText(LocStart, endBuf-startBuf, Result);
3113
80
    return;
3114
80
  }
3115
40
3116
40
  // FIXME: This has potential of causing problem. If
3117
40
  // SynthesizeObjCInternalStruct is ever called recursively.
3118
40
  Result += "\nstruct ";
3119
40
  Result += CDecl->getNameAsString();
3120
40
  if (LangOpts.MicrosoftExt)
3121
30
    Result += "_IMPL";
3122
40
3123
40
  if (NumIvars > 0) {
3124
39
    const char *cursor = strchr(startBuf, '{');
3125
39
    assert((cursor && endBuf)
3126
39
           && "SynthesizeObjCInternalStruct - malformed @interface");
3127
39
    // If the buffer contains preprocessor directives, we do more fine-grained
3128
39
    // rewrites. This is intended to fix code that looks like (which occurs in
3129
39
    // NSURL.h, for example):
3130
39
    //
3131
39
    // #ifdef XYZ
3132
39
    // @interface Foo : NSObject
3133
39
    // #else
3134
39
    // @interface FooBar : NSObject
3135
39
    // #endif
3136
39
    // {
3137
39
    //    int i;
3138
39
    // }
3139
39
    // @end
3140
39
    //
3141
39
    // This clause is segregated to avoid breaking the common case.
3142
39
    if (BufferContainsPPDirectives(startBuf, cursor)) {
3143
0
      SourceLocation L = RCDecl ? CDecl->getSuperClassLoc() :
3144
0
                                  CDecl->getAtStartLoc();
3145
0
      const char *endHeader = SM->getCharacterData(L);
3146
0
      endHeader += Lexer::MeasureTokenLength(L, *SM, LangOpts);
3147
0
3148
0
      if (CDecl->protocol_begin() != CDecl->protocol_end()) {
3149
0
        // advance to the end of the referenced protocols.
3150
0
        while (endHeader < cursor && *endHeader != '>') endHeader++;
3151
0
        endHeader++;
3152
0
      }
3153
0
      // rewrite the original header
3154
0
      ReplaceText(LocStart, endHeader-startBuf, Result);
3155
39
    } else {
3156
39
      // rewrite the original header *without* disturbing the '{'
3157
39
      ReplaceText(LocStart, cursor-startBuf, Result);
3158
39
    }
3159
39
    if (RCDecl && 
ObjCSynthesizedStructs.count(RCDecl)6
) {
3160
1
      Result = "\n    struct ";
3161
1
      Result += RCDecl->getNameAsString();
3162
1
      Result += "_IMPL ";
3163
1
      Result += RCDecl->getNameAsString();
3164
1
      Result += "_IVARS;\n";
3165
1
3166
1
      // insert the super class structure definition.
3167
1
      SourceLocation OnePastCurly =
3168
1
        LocStart.getLocWithOffset(cursor-startBuf+1);
3169
1
      InsertText(OnePastCurly, Result);
3170
1
    }
3171
39
    cursor++; // past '{'
3172
39
3173
39
    // Now comment out any visibility specifiers.
3174
1.11k
    while (cursor < endBuf) {
3175
1.07k
      if (*cursor == '@') {
3176
12
        SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3177
12
        // Skip whitespace.
3178
12
        for (++cursor; cursor[0] == ' ' || cursor[0] == '\t'; 
++cursor0
)
3179
0
          /*scan*/;
3180
12
3181
12
        // FIXME: presence of @public, etc. inside comment results in
3182
12
        // this transformation as well, which is still correct c-code.
3183
12
        if (!strncmp(cursor, "public", strlen("public")) ||
3184
12
            
!strncmp(cursor, "private", strlen("private"))4
||
3185
12
            
!strncmp(cursor, "package", strlen("package"))0
||
3186
12
            
!strncmp(cursor, "protected", strlen("protected"))0
)
3187
12
          InsertText(atLoc, "// ");
3188
12
      }
3189
1.06k
      // FIXME: If there are cases where '<' is used in ivar declaration part
3190
1.06k
      // of user code, then scan the ivar list and use needToScanForQualifiers
3191
1.06k
      // for type checking.
3192
1.06k
      else if (*cursor == '<') {
3193
4
        SourceLocation atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3194
4
        InsertText(atLoc, "/* ");
3195
4
        cursor = strchr(cursor, '>');
3196
4
        cursor++;
3197
4
        atLoc = LocStart.getLocWithOffset(cursor-startBuf);
3198
4
        InsertText(atLoc, " */");
3199
1.06k
      } else if (*cursor == '^') { // rewrite block specifier.
3200
1
        SourceLocation caretLoc = LocStart.getLocWithOffset(cursor-startBuf);
3201
1
        ReplaceText(caretLoc, 1, "*");
3202
1
      }
3203
1.07k
      cursor++;
3204
1.07k
    }
3205
39
    // Don't forget to add a ';'!!
3206
39
    InsertText(LocEnd.getLocWithOffset(1), ";");
3207
39
  } else { // we don't have any instance variables - insert super struct.
3208
1
    endBuf += Lexer::MeasureTokenLength(LocEnd, *SM, LangOpts);
3209
1
    Result += " {\n    struct ";
3210
1
    Result += RCDecl->getNameAsString();
3211
1
    Result += "_IMPL ";
3212
1
    Result += RCDecl->getNameAsString();
3213
1
    Result += "_IVARS;\n};\n";
3214
1
    ReplaceText(LocStart, endBuf-startBuf, Result);
3215
1
  }
3216
40
  // Mark this struct as having been generated.
3217
40
  if (!ObjCSynthesizedStructs.insert(CDecl).second)
3218
40
    
llvm_unreachable0
("struct already synthesize- SynthesizeObjCInternalStruct");
3219
40
}
3220
3221
//===----------------------------------------------------------------------===//
3222
// Meta Data Emission
3223
//===----------------------------------------------------------------------===//
3224
3225
/// RewriteImplementations - This routine rewrites all method implementations
3226
/// and emits meta-data.
3227
3228
53
void RewriteObjC::RewriteImplementations() {
3229
53
  int ClsDefCount = ClassImplementation.size();
3230
53
  int CatDefCount = CategoryImplementation.size();
3231
53
3232
53
  // Rewrite implemented methods
3233
117
  for (int i = 0; i < ClsDefCount; 
i++64
)
3234
64
    RewriteImplementationDecl(ClassImplementation[i]);
3235
53
3236
59
  for (int i = 0; i < CatDefCount; 
i++6
)
3237
6
    RewriteImplementationDecl(CategoryImplementation[i]);
3238
53
}
3239
3240
void RewriteObjC::RewriteByRefString(std::string &ResultStr,
3241
                                     const std::string &Name,
3242
208
                                     ValueDecl *VD, bool def) {
3243
208
  assert(BlockByRefDeclNo.count(VD) &&
3244
208
         "RewriteByRefString: ByRef decl missing");
3245
208
  if (def)
3246
61
    ResultStr += "struct ";
3247
208
  ResultStr += "__Block_byref_" + Name +
3248
208
    "_" + utostr(BlockByRefDeclNo[VD]) ;
3249
208
}
3250
3251
825
static bool HasLocalVariableExternalStorage(ValueDecl *VD) {
3252
825
  if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3253
430
    return (Var->isFunctionOrMethodVarDecl() && 
!Var->hasLocalStorage()233
);
3254
395
  return false;
3255
395
}
3256
3257
std::string RewriteObjC::SynthesizeBlockFunc(BlockExpr *CE, int i,
3258
                                                   StringRef funcName,
3259
68
                                                   std::string Tag) {
3260
68
  const FunctionType *AFT = CE->getFunctionType();
3261
68
  QualType RT = AFT->getReturnType();
3262
68
  std::string StructRef = "struct " + Tag;
3263
68
  std::string S = "static " + RT.getAsString(Context->getPrintingPolicy()) + " __" +
3264
68
                  funcName.str() + "_" + "block_func_" + utostr(i);
3265
68
3266
68
  BlockDecl *BD = CE->getBlockDecl();
3267
68
3268
68
  if (isa<FunctionNoProtoType>(AFT)) {
3269
0
    // No user-supplied arguments. Still need to pass in a pointer to the
3270
0
    // block (to reference imported block decl refs).
3271
0
    S += "(" + StructRef + " *__cself)";
3272
68
  } else if (BD->param_empty()) {
3273
58
    S += "(" + StructRef + " *__cself)";
3274
58
  } else {
3275
10
    const FunctionProtoType *FT = cast<FunctionProtoType>(AFT);
3276
10
    assert(FT && "SynthesizeBlockFunc: No function proto");
3277
10
    S += '(';
3278
10
    // first add the implicit argument.
3279
10
    S += StructRef + " *__cself, ";
3280
10
    std::string ParamStr;
3281
10
    for (BlockDecl::param_iterator AI = BD->param_begin(),
3282
23
         E = BD->param_end(); AI != E; 
++AI13
) {
3283
13
      if (AI != BD->param_begin()) 
S += ", "3
;
3284
13
      ParamStr = (*AI)->getNameAsString();
3285
13
      QualType QT = (*AI)->getType();
3286
13
      (void)convertBlockPointerToFunctionPointer(QT);
3287
13
      QT.getAsStringInternal(ParamStr, Context->getPrintingPolicy());
3288
13
      S += ParamStr;
3289
13
    }
3290
10
    if (FT->isVariadic()) {
3291
0
      if (!BD->param_empty()) S += ", ";
3292
0
      S += "...";
3293
0
    }
3294
10
    S += ')';
3295
10
  }
3296
68
  S += " {\n";
3297
68
3298
68
  // Create local declarations to avoid rewriting all closure decl ref exprs.
3299
68
  // First, emit a declaration for all "by ref" decls.
3300
68
  for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
3301
104
       E = BlockByRefDecls.end(); I != E; 
++I36
) {
3302
36
    S += "  ";
3303
36
    std::string Name = (*I)->getNameAsString();
3304
36
    std::string TypeString;
3305
36
    RewriteByRefString(TypeString, Name, (*I));
3306
36
    TypeString += " *";
3307
36
    Name = TypeString + Name;
3308
36
    S += Name + " = __cself->" + (*I)->getNameAsString() + "; // bound by ref\n";
3309
36
  }
3310
68
  // Next, emit a declaration for all "by copy" declarations.
3311
68
  for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
3312
110
       E = BlockByCopyDecls.end(); I != E; 
++I42
) {
3313
42
    S += "  ";
3314
42
    // Handle nested closure invocation. For example:
3315
42
    //
3316
42
    //   void (^myImportedClosure)(void);
3317
42
    //   myImportedClosure  = ^(void) { setGlobalInt(x + y); };
3318
42
    //
3319
42
    //   void (^anotherClosure)(void);
3320
42
    //   anotherClosure = ^(void) {
3321
42
    //     myImportedClosure(); // import and invoke the closure
3322
42
    //   };
3323
42
    //
3324
42
    if (isTopLevelBlockPointerType((*I)->getType())) {
3325
2
      RewriteBlockPointerTypeVariable(S, (*I));
3326
2
      S += " = (";
3327
2
      RewriteBlockPointerType(S, (*I)->getType());
3328
2
      S += ")";
3329
2
      S += "__cself->" + (*I)->getNameAsString() + "; // bound by copy\n";
3330
2
    }
3331
40
    else {
3332
40
      std::string Name = (*I)->getNameAsString();
3333
40
      QualType QT = (*I)->getType();
3334
40
      if (HasLocalVariableExternalStorage(*I))
3335
2
        QT = Context->getPointerType(QT);
3336
40
      QT.getAsStringInternal(Name, Context->getPrintingPolicy());
3337
40
      S += Name + " = __cself->" +
3338
40
                              (*I)->getNameAsString() + "; // bound by copy\n";
3339
40
    }
3340
42
  }
3341
68
  std::string RewrittenStr = RewrittenBlockExprs[CE];
3342
68
  const char *cstr = RewrittenStr.c_str();
3343
341
  while (*cstr++ != '{') 
;273
3344
68
  S += cstr;
3345
68
  S += "\n";
3346
68
  return S;
3347
68
}
3348
3349
std::string RewriteObjC::SynthesizeBlockHelperFuncs(BlockExpr *CE, int i,
3350
                                                   StringRef funcName,
3351
41
                                                   std::string Tag) {
3352
41
  std::string StructRef = "struct " + Tag;
3353
41
  std::string S = "static void __";
3354
41
3355
41
  S += funcName;
3356
41
  S += "_block_copy_" + utostr(i);
3357
41
  S += "(" + StructRef;
3358
41
  S += "*dst, " + StructRef;
3359
41
  S += "*src) {";
3360
69
  for (ValueDecl *VD : ImportedBlockDecls) {
3361
69
    S += "_Block_object_assign((void*)&dst->";
3362
69
    S += VD->getNameAsString();
3363
69
    S += ", (void*)src->";
3364
69
    S += VD->getNameAsString();
3365
69
    if (BlockByRefDeclsPtrSet.count(VD))
3366
36
      S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3367
33
    else if (VD->getType()->isBlockPointerType())
3368
3
      S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3369
30
    else
3370
30
      S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3371
69
  }
3372
41
  S += "}\n";
3373
41
3374
41
  S += "\nstatic void __";
3375
41
  S += funcName;
3376
41
  S += "_block_dispose_" + utostr(i);
3377
41
  S += "(" + StructRef;
3378
41
  S += "*src) {";
3379
69
  for (ValueDecl *VD : ImportedBlockDecls) {
3380
69
    S += "_Block_object_dispose((void*)src->";
3381
69
    S += VD->getNameAsString();
3382
69
    if (BlockByRefDeclsPtrSet.count(VD))
3383
36
      S += ", " + utostr(BLOCK_FIELD_IS_BYREF) + "/*BLOCK_FIELD_IS_BYREF*/);";
3384
33
    else if (VD->getType()->isBlockPointerType())
3385
3
      S += ", " + utostr(BLOCK_FIELD_IS_BLOCK) + "/*BLOCK_FIELD_IS_BLOCK*/);";
3386
30
    else
3387
30
      S += ", " + utostr(BLOCK_FIELD_IS_OBJECT) + "/*BLOCK_FIELD_IS_OBJECT*/);";
3388
69
  }
3389
41
  S += "}\n";
3390
41
  return S;
3391
41
}
3392
3393
std::string RewriteObjC::SynthesizeBlockImpl(BlockExpr *CE, std::string Tag,
3394
68
                                             std::string Desc) {
3395
68
  std::string S = "\nstruct " + Tag;
3396
68
  std::string Constructor = "  " + Tag;
3397
68
3398
68
  S += " {\n  struct __block_impl impl;\n";
3399
68
  S += "  struct " + Desc;
3400
68
  S += "* Desc;\n";
3401
68
3402
68
  Constructor += "(void *fp, "; // Invoke function pointer.
3403
68
  Constructor += "struct " + Desc; // Descriptor pointer.
3404
68
  Constructor += " *desc";
3405
68
3406
68
  if (BlockDeclRefs.size()) {
3407
47
    // Output all "by copy" declarations.
3408
47
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
3409
89
         E = BlockByCopyDecls.end(); I != E; 
++I42
) {
3410
42
      S += "  ";
3411
42
      std::string FieldName = (*I)->getNameAsString();
3412
42
      std::string ArgName = "_" + FieldName;
3413
42
      // Handle nested closure invocation. For example:
3414
42
      //
3415
42
      //   void (^myImportedBlock)(void);
3416
42
      //   myImportedBlock  = ^(void) { setGlobalInt(x + y); };
3417
42
      //
3418
42
      //   void (^anotherBlock)(void);
3419
42
      //   anotherBlock = ^(void) {
3420
42
      //     myImportedBlock(); // import and invoke the closure
3421
42
      //   };
3422
42
      //
3423
42
      if (isTopLevelBlockPointerType((*I)->getType())) {
3424
2
        S += "struct __block_impl *";
3425
2
        Constructor += ", void *" + ArgName;
3426
40
      } else {
3427
40
        QualType QT = (*I)->getType();
3428
40
        if (HasLocalVariableExternalStorage(*I))
3429
2
          QT = Context->getPointerType(QT);
3430
40
        QT.getAsStringInternal(FieldName, Context->getPrintingPolicy());
3431
40
        QT.getAsStringInternal(ArgName, Context->getPrintingPolicy());
3432
40
        Constructor += ", " + ArgName;
3433
40
      }
3434
42
      S += FieldName + ";\n";
3435
42
    }
3436
47
    // Output all "by ref" declarations.
3437
47
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
3438
83
         E = BlockByRefDecls.end(); I != E; 
++I36
) {
3439
36
      S += "  ";
3440
36
      std::string FieldName = (*I)->getNameAsString();
3441
36
      std::string ArgName = "_" + FieldName;
3442
36
      {
3443
36
        std::string TypeString;
3444
36
        RewriteByRefString(TypeString, FieldName, (*I));
3445
36
        TypeString += " *";
3446
36
        FieldName = TypeString + FieldName;
3447
36
        ArgName = TypeString + ArgName;
3448
36
        Constructor += ", " + ArgName;
3449
36
      }
3450
36
      S += FieldName + "; // by ref\n";
3451
36
    }
3452
47
    // Finish writing the constructor.
3453
47
    Constructor += ", int flags=0)";
3454
47
    // Initialize all "by copy" arguments.
3455
47
    bool firsTime = true;
3456
47
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
3457
89
         E = BlockByCopyDecls.end(); I != E; 
++I42
) {
3458
42
      std::string Name = (*I)->getNameAsString();
3459
42
        if (firsTime) {
3460
29
          Constructor += " : ";
3461
29
          firsTime = false;
3462
29
        }
3463
13
        else
3464
13
          Constructor += ", ";
3465
42
        if (isTopLevelBlockPointerType((*I)->getType()))
3466
2
          Constructor += Name + "((struct __block_impl *)_" + Name + ")";
3467
40
        else
3468
40
          Constructor += Name + "(_" + Name + ")";
3469
42
    }
3470
47
    // Initialize all "by ref" arguments.
3471
47
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
3472
83
         E = BlockByRefDecls.end(); I != E; 
++I36
) {
3473
36
      std::string Name = (*I)->getNameAsString();
3474
36
      if (firsTime) {
3475
18
        Constructor += " : ";
3476
18
        firsTime = false;
3477
18
      }
3478
18
      else
3479
18
        Constructor += ", ";
3480
36
      Constructor += Name + "(_" + Name + "->__forwarding)";
3481
36
    }
3482
47
3483
47
    Constructor += " {\n";
3484
47
    if (GlobalVarDecl)
3485
0
      Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
3486
47
    else
3487
47
      Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
3488
47
    Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
3489
47
3490
47
    Constructor += "    Desc = desc;\n";
3491
47
  } else {
3492
21
    // Finish writing the constructor.
3493
21
    Constructor += ", int flags=0) {\n";
3494
21
    if (GlobalVarDecl)
3495
4
      Constructor += "    impl.isa = &_NSConcreteGlobalBlock;\n";
3496
17
    else
3497
17
      Constructor += "    impl.isa = &_NSConcreteStackBlock;\n";
3498
21
    Constructor += "    impl.Flags = flags;\n    impl.FuncPtr = fp;\n";
3499
21
    Constructor += "    Desc = desc;\n";
3500
21
  }
3501
68
  Constructor += "  ";
3502
68
  Constructor += "}\n";
3503
68
  S += Constructor;
3504
68
  S += "};\n";
3505
68
  return S;
3506
68
}
3507
3508
std::string RewriteObjC::SynthesizeBlockDescriptor(std::string DescTag,
3509
                                                   std::string ImplTag, int i,
3510
                                                   StringRef FunName,
3511
68
                                                   unsigned hasCopy) {
3512
68
  std::string S = "\nstatic struct " + DescTag;
3513
68
3514
68
  S += " {\n  unsigned long reserved;\n";
3515
68
  S += "  unsigned long Block_size;\n";
3516
68
  if (hasCopy) {
3517
41
    S += "  void (*copy)(struct ";
3518
41
    S += ImplTag; S += "*, struct ";
3519
41
    S += ImplTag; S += "*);\n";
3520
41
3521
41
    S += "  void (*dispose)(struct ";
3522
41
    S += ImplTag; S += "*);\n";
3523
41
  }
3524
68
  S += "} ";
3525
68
3526
68
  S += DescTag + "_DATA = { 0, sizeof(struct ";
3527
68
  S += ImplTag + ")";
3528
68
  if (hasCopy) {
3529
41
    S += ", __" + FunName.str() + "_block_copy_" + utostr(i);
3530
41
    S += ", __" + FunName.str() + "_block_dispose_" + utostr(i);
3531
41
  }
3532
68
  S += "};\n";
3533
68
  return S;
3534
68
}
3535
3536
void RewriteObjC::SynthesizeBlockLiterals(SourceLocation FunLocStart,
3537
150
                                          StringRef FunName) {
3538
150
  // Insert declaration for the function in which block literal is used.
3539
150
  if (CurFunctionDeclToDeclareForBlock && 
!Blocks.empty()54
)
3540
15
    RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
3541
150
  bool RewriteSC = (GlobalVarDecl &&
3542
150
                    
!Blocks.empty()9
&&
3543
150
                    
GlobalVarDecl->getStorageClass() == SC_Static4
&&
3544
150
                    
GlobalVarDecl->getType().getCVRQualifiers()3
);
3545
150
  if (RewriteSC) {
3546
3
    std::string SC(" void __");
3547
3
    SC += GlobalVarDecl->getNameAsString();
3548
3
    SC += "() {}";
3549
3
    InsertText(FunLocStart, SC);
3550
3
  }
3551
150
3552
150
  // Insert closures that were part of the function.
3553
218
  for (unsigned i = 0, count=0; i < Blocks.size(); 
i++68
) {
3554
68
    CollectBlockDeclRefInfo(Blocks[i]);
3555
68
    // Need to copy-in the inner copied-in variables not actually used in this
3556
68
    // block.
3557
89
    for (int j = 0; j < InnerDeclRefsCount[i]; 
j++21
) {
3558
21
      DeclRefExpr *Exp = InnerDeclRefs[count++];
3559
21
      ValueDecl *VD = Exp->getDecl();
3560
21
      BlockDeclRefs.push_back(Exp);
3561
21
      if (!VD->hasAttr<BlocksAttr>() && 
!BlockByCopyDeclsPtrSet.count(VD)12
) {
3562
12
        BlockByCopyDeclsPtrSet.insert(VD);
3563
12
        BlockByCopyDecls.push_back(VD);
3564
12
      }
3565
21
      if (VD->hasAttr<BlocksAttr>() && 
!BlockByRefDeclsPtrSet.count(VD)9
) {
3566
9
        BlockByRefDeclsPtrSet.insert(VD);
3567
9
        BlockByRefDecls.push_back(VD);
3568
9
      }
3569
21
      // imported objects in the inner blocks not used in the outer
3570
21
      // blocks must be copied/disposed in the outer block as well.
3571
21
      if (VD->hasAttr<BlocksAttr>() ||
3572
21
          
VD->getType()->isObjCObjectPointerType()12
||
3573
21
          
VD->getType()->isBlockPointerType()1
)
3574
20
        ImportedBlockDecls.insert(VD);
3575
21
    }
3576
68
3577
68
    std::string ImplTag = "__" + FunName.str() + "_block_impl_" + utostr(i);
3578
68
    std::string DescTag = "__" + FunName.str() + "_block_desc_" + utostr(i);
3579
68
3580
68
    std::string CI = SynthesizeBlockImpl(Blocks[i], ImplTag, DescTag);
3581
68
3582
68
    InsertText(FunLocStart, CI);
3583
68
3584
68
    std::string CF = SynthesizeBlockFunc(Blocks[i], i, FunName, ImplTag);
3585
68
3586
68
    InsertText(FunLocStart, CF);
3587
68
3588
68
    if (ImportedBlockDecls.size()) {
3589
41
      std::string HF = SynthesizeBlockHelperFuncs(Blocks[i], i, FunName, ImplTag);
3590
41
      InsertText(FunLocStart, HF);
3591
41
    }
3592
68
    std::string BD = SynthesizeBlockDescriptor(DescTag, ImplTag, i, FunName,
3593
68
                                               ImportedBlockDecls.size() > 0);
3594
68
    InsertText(FunLocStart, BD);
3595
68
3596
68
    BlockDeclRefs.clear();
3597
68
    BlockByRefDecls.clear();
3598
68
    BlockByRefDeclsPtrSet.clear();
3599
68
    BlockByCopyDecls.clear();
3600
68
    BlockByCopyDeclsPtrSet.clear();
3601
68
    ImportedBlockDecls.clear();
3602
68
  }
3603
150
  if (RewriteSC) {
3604
3
    // Must insert any 'const/volatile/static here. Since it has been
3605
3
    // removed as result of rewriting of block literals.
3606
3
    std::string SC;
3607
3
    if (GlobalVarDecl->getStorageClass() == SC_Static)
3608
3
      SC = "static ";
3609
3
    if (GlobalVarDecl->getType().isConstQualified())
3610
3
      SC += "const ";
3611
3
    if (GlobalVarDecl->getType().isVolatileQualified())
3612
0
      SC += "volatile ";
3613
3
    if (GlobalVarDecl->getType().isRestrictQualified())
3614
0
      SC += "restrict ";
3615
3
    InsertText(FunLocStart, SC);
3616
3
  }
3617
150
3618
150
  Blocks.clear();
3619
150
  InnerDeclRefsCount.clear();
3620
150
  InnerDeclRefs.clear();
3621
150
  RewrittenBlockExprs.clear();
3622
150
}
3623
3624
64
void RewriteObjC::InsertBlockLiteralsWithinFunction(FunctionDecl *FD) {
3625
64
  SourceLocation FunLocStart = FD->getTypeSpecStartLoc();
3626
64
  StringRef FuncName = FD->getName();
3627
64
3628
64
  SynthesizeBlockLiterals(FunLocStart, FuncName);
3629
64
}
3630
3631
static void BuildUniqueMethodName(std::string &Name,
3632
99
                                  ObjCMethodDecl *MD) {
3633
99
  ObjCInterfaceDecl *IFace = MD->getClassInterface();
3634
99
  Name = std::string(IFace->getName());
3635
99
  Name += "__" + MD->getSelector().getAsString();
3636
99
  // Convert colons to underscores.
3637
99
  std::string::size_type loc = 0;
3638
142
  while ((loc = Name.find(':', loc)) != std::string::npos)
3639
43
    Name.replace(loc, 1, "_");
3640
99
}
3641
3642
77
void RewriteObjC::InsertBlockLiteralsWithinMethod(ObjCMethodDecl *MD) {
3643
77
  // fprintf(stderr,"In InsertBlockLiteralsWitinMethod\n");
3644
77
  // SourceLocation FunLocStart = MD->getBeginLoc();
3645
77
  SourceLocation FunLocStart = MD->getBeginLoc();
3646
77
  std::string FuncName;
3647
77
  BuildUniqueMethodName(FuncName, MD);
3648
77
  SynthesizeBlockLiterals(FunLocStart, FuncName);
3649
77
}
3650
3651
1.85k
void RewriteObjC::GetBlockDeclRefExprs(Stmt *S) {
3652
1.85k
  for (Stmt *SubStmt : S->children())
3653
1.71k
    if (SubStmt) {
3654
1.71k
      if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt))
3655
0
        GetBlockDeclRefExprs(CBE->getBody());
3656
1.71k
      else
3657
1.71k
        GetBlockDeclRefExprs(SubStmt);
3658
1.71k
    }
3659
1.85k
  // Handle specific things.
3660
1.85k
  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S))
3661
426
    if (DRE->refersToEnclosingVariableOrCapture() ||
3662
426
        
HasLocalVariableExternalStorage(DRE->getDecl())304
)
3663
140
      // FIXME: Handle enums.
3664
140
      BlockDeclRefs.push_back(DRE);
3665
1.85k
}
3666
3667
void RewriteObjC::GetInnerBlockDeclRefExprs(Stmt *S,
3668
                SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs,
3669
642
                llvm::SmallPtrSetImpl<const DeclContext *> &InnerContexts) {
3670
642
  for (Stmt *SubStmt : S->children())
3671
574
    if (SubStmt) {
3672
574
      if (BlockExpr *CBE = dyn_cast<BlockExpr>(SubStmt)) {
3673
15
        InnerContexts.insert(cast<DeclContext>(CBE->getBlockDecl()));
3674
15
        GetInnerBlockDeclRefExprs(CBE->getBody(),
3675
15
                                  InnerBlockDeclRefs,
3676
15
                                  InnerContexts);
3677
15
      }
3678
559
      else
3679
559
        GetInnerBlockDeclRefExprs(SubStmt, InnerBlockDeclRefs, InnerContexts);
3680
574
    }
3681
642
  // Handle specific things.
3682
642
  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
3683
141
    if (DRE->refersToEnclosingVariableOrCapture() ||
3684
141
        
HasLocalVariableExternalStorage(DRE->getDecl())59
) {
3685
91
      if (!InnerContexts.count(DRE->getDecl()->getDeclContext()))
3686
90
        InnerBlockDeclRefs.push_back(DRE);
3687
91
      if (VarDecl *Var = cast<VarDecl>(DRE->getDecl()))
3688
91
        if (Var->isFunctionOrMethodVarDecl())
3689
72
          ImportedLocalExternalDecls.insert(Var);
3690
91
    }
3691
141
  }
3692
642
}
3693
3694
/// convertFunctionTypeOfBlocks - This routine converts a function type
3695
/// whose result type may be a block pointer or whose argument type(s)
3696
/// might be block pointers to an equivalent function type replacing
3697
/// all block pointers to function pointers.
3698
68
QualType RewriteObjC::convertFunctionTypeOfBlocks(const FunctionType *FT) {
3699
68
  const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3700
68
  // FTP will be null for closures that don't take arguments.
3701
68
  // Generate a funky cast.
3702
68
  SmallVector<QualType, 8> ArgTypes;
3703
68
  QualType Res = FT->getReturnType();
3704
68
  bool HasBlockType = convertBlockPointerToFunctionPointer(Res);
3705
68
3706
68
  if (FTP) {
3707
68
    for (auto &I : FTP->param_types()) {
3708
13
      QualType t = I;
3709
13
      // Make sure we convert "t (^)(...)" to "t (*)(...)".
3710
13
      if (convertBlockPointerToFunctionPointer(t))
3711
1
        HasBlockType = true;
3712
13
      ArgTypes.push_back(t);
3713
13
    }
3714
68
  }
3715
68
  QualType FuncType;
3716
68
  // FIXME. Does this work if block takes no argument but has a return type
3717
68
  // which is of block type?
3718
68
  if (HasBlockType)
3719
1
    FuncType = getSimpleFunctionType(Res, ArgTypes);
3720
67
  else FuncType = QualType(FT, 0);
3721
68
  return FuncType;
3722
68
}
3723
3724
14
Stmt *RewriteObjC::SynthesizeBlockCall(CallExpr *Exp, const Expr *BlockExp) {
3725
14
  // Navigate to relevant type information.
3726
14
  const BlockPointerType *CPT = nullptr;
3727
14
3728
14
  if (const DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(BlockExp)) {
3729
0
    CPT = DRE->getType()->getAs<BlockPointerType>();
3730
14
  } else if (const MemberExpr *MExpr = dyn_cast<MemberExpr>(BlockExp)) {
3731
0
    CPT = MExpr->getType()->getAs<BlockPointerType>();
3732
0
  }
3733
14
  else if (const ParenExpr *PRE = dyn_cast<ParenExpr>(BlockExp)) {
3734
0
    return SynthesizeBlockCall(Exp, PRE->getSubExpr());
3735
0
  }
3736
14
  else if (const ImplicitCastExpr *IEXPR = dyn_cast<ImplicitCastExpr>(BlockExp))
3737
14
    CPT = IEXPR->getType()->getAs<BlockPointerType>();
3738
0
  else if (const ConditionalOperator *CEXPR =
3739
0
            dyn_cast<ConditionalOperator>(BlockExp)) {
3740
0
    Expr *LHSExp = CEXPR->getLHS();
3741
0
    Stmt *LHSStmt = SynthesizeBlockCall(Exp, LHSExp);
3742
0
    Expr *RHSExp = CEXPR->getRHS();
3743
0
    Stmt *RHSStmt = SynthesizeBlockCall(Exp, RHSExp);
3744
0
    Expr *CONDExp = CEXPR->getCond();
3745
0
    ConditionalOperator *CondExpr =
3746
0
      new (Context) ConditionalOperator(CONDExp,
3747
0
                                      SourceLocation(), cast<Expr>(LHSStmt),
3748
0
                                      SourceLocation(), cast<Expr>(RHSStmt),
3749
0
                                      Exp->getType(), VK_RValue, OK_Ordinary);
3750
0
    return CondExpr;
3751
0
  } else if (const ObjCIvarRefExpr *IRE = dyn_cast<ObjCIvarRefExpr>(BlockExp)) {
3752
0
    CPT = IRE->getType()->getAs<BlockPointerType>();
3753
0
  } else if (const PseudoObjectExpr *POE
3754
0
               = dyn_cast<PseudoObjectExpr>(BlockExp)) {
3755
0
    CPT = POE->getType()->castAs<BlockPointerType>();
3756
0
  } else {
3757
0
    assert(false && "RewriteBlockClass: Bad type");
3758
0
  }
3759
14
  assert(CPT && "RewriteBlockClass: Bad type");
3760
14
  const FunctionType *FT = CPT->getPointeeType()->getAs<FunctionType>();
3761
14
  assert(FT && "RewriteBlockClass: Bad type");
3762
14
  const FunctionProtoType *FTP = dyn_cast<FunctionProtoType>(FT);
3763
14
  // FTP will be null for closures that don't take arguments.
3764
14
3765
14
  RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
3766
14
                                      SourceLocation(), SourceLocation(),
3767
14
                                      &Context->Idents.get("__block_impl"));
3768
14
  QualType PtrBlock = Context->getPointerType(Context->getTagDeclType(RD));
3769
14
3770
14
  // Generate a funky cast.
3771
14
  SmallVector<QualType, 8> ArgTypes;
3772
14
3773
14
  // Push the block argument type.
3774
14
  ArgTypes.push_back(PtrBlock);
3775
14
  if (FTP) {
3776
14
    for (auto &I : FTP->param_types()) {
3777
6
      QualType t = I;
3778
6
      // Make sure we convert "t (^)(...)" to "t (*)(...)".
3779
6
      if (!convertBlockPointerToFunctionPointer(t))
3780
6
        convertToUnqualifiedObjCType(t);
3781
6
      ArgTypes.push_back(t);
3782
6
    }
3783
14
  }
3784
14
  // Now do the pointer to function cast.
3785
14
  QualType PtrToFuncCastType = getSimpleFunctionType(Exp->getType(), ArgTypes);
3786
14
3787
14
  PtrToFuncCastType = Context->getPointerType(PtrToFuncCastType);
3788
14
3789
14
  CastExpr *BlkCast = NoTypeInfoCStyleCastExpr(Context, PtrBlock,
3790
14
                                               CK_BitCast,
3791
14
                                               const_cast<Expr*>(BlockExp));
3792
14
  // Don't forget the parens to enforce the proper binding.
3793
14
  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3794
14
                                          BlkCast);
3795
14
  //PE->dump();
3796
14
3797
14
  FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3798
14
                                    SourceLocation(),
3799
14
                                    &Context->Idents.get("FuncPtr"),
3800
14
                                    Context->VoidPtrTy, nullptr,
3801
14
                                    /*BitWidth=*/nullptr, /*Mutable=*/true,
3802
14
                                    ICIS_NoInit);
3803
14
  MemberExpr *ME = MemberExpr::CreateImplicit(
3804
14
      *Context, PE, true, FD, FD->getType(), VK_LValue, OK_Ordinary);
3805
14
3806
14
  CastExpr *FunkCast = NoTypeInfoCStyleCastExpr(Context, PtrToFuncCastType,
3807
14
                                                CK_BitCast, ME);
3808
14
  PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(), FunkCast);
3809
14
3810
14
  SmallVector<Expr*, 8> BlkExprs;
3811
14
  // Add the implicit argument.
3812
14
  BlkExprs.push_back(BlkCast);
3813
14
  // Add the user arguments.
3814
14
  for (CallExpr::arg_iterator I = Exp->arg_begin(),
3815
20
       E = Exp->arg_end(); I != E; 
++I6
) {
3816
6
    BlkExprs.push_back(*I);
3817
6
  }
3818
14
  CallExpr *CE = CallExpr::Create(*Context, PE, BlkExprs, Exp->getType(),
3819
14
                                  VK_RValue, SourceLocation());
3820
14
  return CE;
3821
14
}
3822
3823
// We need to return the rewritten expression to handle cases where the
3824
// BlockDeclRefExpr is embedded in another expression being rewritten.
3825
// For example:
3826
//
3827
// int main() {
3828
//    __block Foo *f;
3829
//    __block int i;
3830
//
3831
//    void (^myblock)() = ^() {
3832
//        [f test]; // f is a BlockDeclRefExpr embedded in a message (which is being rewritten).
3833
//        i = 77;
3834
//    };
3835
//}
3836
35
Stmt *RewriteObjC::RewriteBlockDeclRefExpr(DeclRefExpr *DeclRefExp) {
3837
35
  // Rewrite the byref variable into BYREFVAR->__forwarding->BYREFVAR
3838
35
  // for each DeclRefExp where BYREFVAR is name of the variable.
3839
35
  ValueDecl *VD = DeclRefExp->getDecl();
3840
35
  bool isArrow = DeclRefExp->refersToEnclosingVariableOrCapture() ||
3841
35
                 
HasLocalVariableExternalStorage(DeclRefExp->getDecl())8
;
3842
35
3843
35
  FieldDecl *FD = FieldDecl::Create(*Context, nullptr, SourceLocation(),
3844
35
                                    SourceLocation(),
3845
35
                                    &Context->Idents.get("__forwarding"),
3846
35
                                    Context->VoidPtrTy, nullptr,
3847
35
                                    /*BitWidth=*/nullptr, /*Mutable=*/true,
3848
35
                                    ICIS_NoInit);
3849
35
  MemberExpr *ME =
3850
35
      MemberExpr::CreateImplicit(*Context, DeclRefExp, isArrow, FD,
3851
35
                                 FD->getType(), VK_LValue, OK_Ordinary);
3852
35
3853
35
  StringRef Name = VD->getName();
3854
35
  FD = FieldDecl::Create(*Context, nullptr, SourceLocation(), SourceLocation(),
3855
35
                         &Context->Idents.get(Name),
3856
35
                         Context->VoidPtrTy, nullptr,
3857
35
                         /*BitWidth=*/nullptr, /*Mutable=*/true,
3858
35
                         ICIS_NoInit);
3859
35
  ME = MemberExpr::CreateImplicit(*Context, ME, true, FD, DeclRefExp->getType(),
3860
35
                                  VK_LValue, OK_Ordinary);
3861
35
3862
35
  // Need parens to enforce precedence.
3863
35
  ParenExpr *PE = new (Context) ParenExpr(DeclRefExp->getExprLoc(),
3864
35
                                          DeclRefExp->getExprLoc(),
3865
35
                                          ME);
3866
35
  ReplaceStmt(DeclRefExp, PE);
3867
35
  return PE;
3868
35
}
3869
3870
// Rewrites the imported local variable V with external storage
3871
// (static, extern, etc.) as *V
3872
//
3873
15
Stmt *RewriteObjC::RewriteLocalVariableExternalStorage(DeclRefExpr *DRE) {
3874
15
  ValueDecl *VD = DRE->getDecl();
3875
15
  if (VarDecl *Var = dyn_cast<VarDecl>(VD))
3876
15
    if (!ImportedLocalExternalDecls.count(Var))
3877
6
      return DRE;
3878
9
  Expr *Exp = new (Context) UnaryOperator(DRE, UO_Deref, DRE->getType(),
3879
9
                                          VK_LValue, OK_Ordinary,
3880
9
                                          DRE->getLocation(), false);
3881
9
  // Need parens to enforce precedence.
3882
9
  ParenExpr *PE = new (Context) ParenExpr(SourceLocation(), SourceLocation(),
3883
9
                                          Exp);
3884
9
  ReplaceStmt(DRE, PE);
3885
9
  return PE;
3886
9
}
3887
3888
31
void RewriteObjC::RewriteCastExpr(CStyleCastExpr *CE) {
3889
31
  SourceLocation LocStart = CE->getLParenLoc();
3890
31
  SourceLocation LocEnd = CE->getRParenLoc();
3891
31
3892
31
  // Need to avoid trying to rewrite synthesized casts.
3893
31
  if (LocStart.isInvalid())
3894
0
    return;
3895
31
  // Need to avoid trying to rewrite casts contained in macros.
3896
31
  if (!Rewriter::isRewritable(LocStart) || !Rewriter::isRewritable(LocEnd))
3897
0
    return;
3898
31
3899
31
  const char *startBuf = SM->getCharacterData(LocStart);
3900
31
  const char *endBuf = SM->getCharacterData(LocEnd);
3901
31
  QualType QT = CE->getType();
3902
31
  const Type* TypePtr = QT->getAs<Type>();
3903
31
  if (isa<TypeOfExprType>(TypePtr)) {
3904
3
    const TypeOfExprType *TypeOfExprTypePtr = cast<TypeOfExprType>(TypePtr);
3905
3
    QT = TypeOfExprTypePtr->getUnderlyingExpr()->getType();
3906
3
    std::string TypeAsString = "(";
3907
3
    RewriteBlockPointerType(TypeAsString, QT);
3908
3
    TypeAsString += ")";
3909
3
    ReplaceText(LocStart, endBuf-startBuf+1, TypeAsString);
3910
3
    return;
3911
3
  }
3912
28
  // advance the location to startArgList.
3913
28
  const char *argPtr = startBuf;
3914
28
3915
249
  while (*argPtr++ && (argPtr < endBuf)) {
3916
221
    switch (*argPtr) {
3917
0
    case '^':
3918
0
      // Replace the '^' with '*'.
3919
0
      LocStart = LocStart.getLocWithOffset(argPtr-startBuf);
3920
0
      ReplaceText(LocStart, 1, "*");
3921
0
      break;
3922
221
    }
3923
221
  }
3924
28
}
3925
3926
20
void RewriteObjC::RewriteBlockPointerFunctionArgs(FunctionDecl *FD) {
3927
20
  SourceLocation DeclLoc = FD->getLocation();
3928
20
  unsigned parenCount = 0;
3929
20
3930
20
  // We have 1 or more arguments that have closure pointers.
3931
20
  const char *startBuf = SM->getCharacterData(DeclLoc);
3932
20
  const char *startArgList = strchr(startBuf, '(');
3933
20
3934
20
  assert((*startArgList == '(') && "Rewriter fuzzy parser confused");
3935
20
3936
20
  parenCount++;
3937
20
  // advance the location to startArgList.
3938
20
  DeclLoc = DeclLoc.getLocWithOffset(startArgList-startBuf);
3939
20
  assert((DeclLoc.isValid()) && "Invalid DeclLoc");
3940
20
3941
20
  const char *argPtr = startArgList;
3942
20
3943
390
  while (*argPtr++ && parenCount) {
3944
370
    switch (*argPtr) {
3945
20
    case '^':
3946
20
      // Replace the '^' with '*'.
3947
20
      DeclLoc = DeclLoc.getLocWithOffset(argPtr-startArgList);
3948
20
      ReplaceText(DeclLoc, 1, "*");
3949
20
      break;
3950
40
    case '(':
3951
40
      parenCount++;
3952
40
      break;
3953
60
    case ')':
3954
60
      parenCount--;
3955
60
      break;
3956
370
    }
3957
370
  }
3958
20
}
3959
3960
46
bool RewriteObjC::PointerTypeTakesAnyBlockArguments(QualType QT) {
3961
46
  const FunctionProtoType *FTP;
3962
46
  const PointerType *PT = QT->getAs<PointerType>();
3963
46
  if (PT) {
3964
1
    FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
3965
45
  } else {
3966
45
    const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
3967
45
    assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3968
45
    FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
3969
45
  }
3970
46
  if (FTP) {
3971
44
    for (const auto &I : FTP->param_types())
3972
30
      if (isTopLevelBlockPointerType(I))
3973
3
        return true;
3974
44
  }
3975
46
  
return false43
;
3976
46
}
3977
3978
42
bool RewriteObjC::PointerTypeTakesAnyObjCQualifiedType(QualType QT) {
3979
42
  const FunctionProtoType *FTP;
3980
42
  const PointerType *PT = QT->getAs<PointerType>();
3981
42
  if (PT) {
3982
0
    FTP = PT->getPointeeType()->getAs<FunctionProtoType>();
3983
42
  } else {
3984
42
    const BlockPointerType *BPT = QT->getAs<BlockPointerType>();
3985
42
    assert(BPT && "BlockPointerTypeTakeAnyBlockArguments(): not a block pointer type");
3986
42
    FTP = BPT->getPointeeType()->getAs<FunctionProtoType>();
3987
42
  }
3988
42
  if (FTP) {
3989
40
    for (const auto &I : FTP->param_types()) {
3990
16
      if (I->isObjCQualifiedIdType())
3991
5
        return true;
3992
11
      if (I->isObjCObjectPointerType() &&
3993
11
          
I->getPointeeType()->isObjCQualifiedInterfaceType()4
)
3994
1
        return true;
3995
11
    }
3996
40
3997
40
  }
3998
42
  
return false36
;
3999
42
}
4000
4001
void RewriteObjC::GetExtentOfArgList(const char *Name, const char *&LParen,
4002
9
                                     const char *&RParen) {
4003
9
  const char *argPtr = strchr(Name, '(');
4004
9
  assert((*argPtr == '(') && "Rewriter fuzzy parser confused");
4005
9
4006
9
  LParen = argPtr; // output the start.
4007
9
  argPtr++; // skip past the left paren.
4008
9
  unsigned parenCount = 1;
4009
9
4010
884
  while (*argPtr && parenCount) {
4011
875
    switch (*argPtr) {
4012
10
    case '(': parenCount++; break;
4013
19
    case ')': parenCount--; break;
4014
846
    default: break;
4015
875
    }
4016
875
    if (parenCount) 
argPtr++866
;
4017
875
  }
4018
9
  assert((*argPtr == ')') && "Rewriter fuzzy parser confused");
4019
9
  RParen = argPtr; // output the end
4020
9
}
4021
4022
65
void RewriteObjC::RewriteBlockPointerDecl(NamedDecl *ND) {
4023
65
  if (FunctionDecl *FD = dyn_cast<FunctionDecl>(ND)) {
4024
20
    RewriteBlockPointerFunctionArgs(FD);
4025
20
    return;
4026
20
  }
4027
45
  // Handle Variables and Typedefs.
4028
45
  SourceLocation DeclLoc = ND->getLocation();
4029
45
  QualType DeclT;
4030
45
  if (VarDecl *VD = dyn_cast<VarDecl>(ND))
4031
25
    DeclT = VD->getType();
4032
20
  else if (TypedefNameDecl *TDD = dyn_cast<TypedefNameDecl>(ND))
4033
20
    DeclT = TDD->getUnderlyingType();
4034
0
  else if (FieldDecl *FD = dyn_cast<FieldDecl>(ND))
4035
0
    DeclT = FD->getType();
4036
0
  else
4037
0
    llvm_unreachable("RewriteBlockPointerDecl(): Decl type not yet handled");
4038
45
4039
45
  const char *startBuf = SM->getCharacterData(DeclLoc);
4040
45
  const char *endBuf = startBuf;
4041
45
  // scan backward (from the decl location) for the end of the previous decl.
4042
92
  while (*startBuf != '^' && 
*startBuf != ';'47
&&
startBuf != MainFileStart47
)
4043
47
    startBuf--;
4044
45
  SourceLocation Start = DeclLoc.getLocWithOffset(startBuf-endBuf);
4045
45
  std::string buf;
4046
45
  unsigned OrigLength=0;
4047
45
  // *startBuf != '^' if we are dealing with a pointer to function that
4048
45
  // may take block argument types (which will be handled below).
4049
45
  if (*startBuf == '^') {
4050
45
    // Replace the '^' with '*', computing a negative offset.
4051
45
    buf = '*';
4052
45
    startBuf++;
4053
45
    OrigLength++;
4054
45
  }
4055
440
  while (*startBuf != ')') {
4056
395
    buf += *startBuf;
4057
395
    startBuf++;
4058
395
    OrigLength++;
4059
395
  }
4060
45
  buf += ')';
4061
45
  OrigLength++;
4062
45
4063
45
  if (PointerTypeTakesAnyBlockArguments(DeclT) ||
4064
45
      
PointerTypeTakesAnyObjCQualifiedType(DeclT)42
) {
4065
9
    // Replace the '^' with '*' for arguments.
4066
9
    // Replace id<P> with id/*<>*/
4067
9
    DeclLoc = ND->getLocation();
4068
9
    startBuf = SM->getCharacterData(DeclLoc);
4069
9
    const char *argListBegin, *argListEnd;
4070
9
    GetExtentOfArgList(startBuf, argListBegin, argListEnd);
4071
453
    while (argListBegin < argListEnd) {
4072
444
      if (*argListBegin == '^')
4073
5
        buf += '*';
4074
439
      else if (*argListBegin ==  '<') {
4075
17
        buf += "/*";
4076
17
        buf += *argListBegin++;
4077
17
        OrigLength++;
4078
431
        while (*argListBegin != '>') {
4079
414
          buf += *argListBegin++;
4080
414
          OrigLength++;
4081
414
        }
4082
17
        buf += *argListBegin;
4083
17
        buf += "*/";
4084
17
      }
4085
422
      else
4086
422
        buf += *argListBegin;
4087
444
      argListBegin++;
4088
444
      OrigLength++;
4089
444
    }
4090
9
    buf += ')';
4091
9
    OrigLength++;
4092
9
  }
4093
45
  ReplaceText(Start, OrigLength, buf);
4094
45
}
4095
4096
/// SynthesizeByrefCopyDestroyHelper - This routine synthesizes:
4097
/// void __Block_byref_id_object_copy(struct Block_byref_id_object *dst,
4098
///                    struct Block_byref_id_object *src) {
4099
///  _Block_object_assign (&_dest->object, _src->object,
4100
///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4101
///                        [|BLOCK_FIELD_IS_WEAK]) // object
4102
///  _Block_object_assign(&_dest->object, _src->object,
4103
///                       BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4104
///                       [|BLOCK_FIELD_IS_WEAK]) // block
4105
/// }
4106
/// And:
4107
/// void __Block_byref_id_object_dispose(struct Block_byref_id_object *_src) {
4108
///  _Block_object_dispose(_src->object,
4109
///                        BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_OBJECT
4110
///                        [|BLOCK_FIELD_IS_WEAK]) // object
4111
///  _Block_object_dispose(_src->object,
4112
///                         BLOCK_BYREF_CALLER | BLOCK_FIELD_IS_BLOCK
4113
///                         [|BLOCK_FIELD_IS_WEAK]) // block
4114
/// }
4115
4116
std::string RewriteObjC::SynthesizeByrefCopyDestroyHelper(VarDecl *VD,
4117
8
                                                          int flag) {
4118
8
  std::string S;
4119
8
  if (CopyDestroyCache.count(flag))
4120
3
    return S;
4121
5
  CopyDestroyCache.insert(flag);
4122
5
  S = "static void __Block_byref_id_object_copy_";
4123
5
  S += utostr(flag);
4124
5
  S += "(void *dst, void *src) {\n";
4125
5
4126
5
  // offset into the object pointer is computed as:
4127
5
  // void * + void* + int + int + void* + void *
4128
5
  unsigned IntSize =
4129
5
  static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4130
5
  unsigned VoidPtrSize =
4131
5
  static_cast<unsigned>(Context->getTypeSize(Context->VoidPtrTy));
4132
5
4133
5
  unsigned offset = (VoidPtrSize*4 + IntSize + IntSize)/Context->getCharWidth();
4134
5
  S += " _Block_object_assign((char*)dst + ";
4135
5
  S += utostr(offset);
4136
5
  S += ", *(void * *) ((char*)src + ";
4137
5
  S += utostr(offset);
4138
5
  S += "), ";
4139
5
  S += utostr(flag);
4140
5
  S += ");\n}\n";
4141
5
4142
5
  S += "static void __Block_byref_id_object_dispose_";
4143
5
  S += utostr(flag);
4144
5
  S += "(void *src) {\n";
4145
5
  S += " _Block_object_dispose(*(void * *) ((char*)src + ";
4146
5
  S += utostr(offset);
4147
5
  S += "), ";
4148
5
  S += utostr(flag);
4149
5
  S += ");\n}\n";
4150
5
  return S;
4151
5
}
4152
4153
/// RewriteByRefVar - For each __block typex ND variable this routine transforms
4154
/// the declaration into:
4155
/// struct __Block_byref_ND {
4156
/// void *__isa;                  // NULL for everything except __weak pointers
4157
/// struct __Block_byref_ND *__forwarding;
4158
/// int32_t __flags;
4159
/// int32_t __size;
4160
/// void *__Block_byref_id_object_copy; // If variable is __block ObjC object
4161
/// void *__Block_byref_id_object_dispose; // If variable is __block ObjC object
4162
/// typex ND;
4163
/// };
4164
///
4165
/// It then replaces declaration of ND variable with:
4166
/// struct __Block_byref_ND ND = {__isa=0B, __forwarding=&ND, __flags=some_flag,
4167
///                               __size=sizeof(struct __Block_byref_ND),
4168
///                               ND=initializer-if-any};
4169
///
4170
///
4171
25
void RewriteObjC::RewriteByRefVar(VarDecl *ND) {
4172
25
  // Insert declaration for the function in which block literal is
4173
25
  // used.
4174
25
  if (CurFunctionDeclToDeclareForBlock)
4175
15
    RewriteBlockLiteralFunctionDecl(CurFunctionDeclToDeclareForBlock);
4176
25
  int flag = 0;
4177
25
  int isa = 0;
4178
25
  SourceLocation DeclLoc = ND->getTypeSpecStartLoc();
4179
25
  if (DeclLoc.isInvalid())
4180
0
    // If type location is missing, it is because of missing type (a warning).
4181
0
    // Use variable's location which is good for this case.
4182
0
    DeclLoc = ND->getLocation();
4183
25
  const char *startBuf = SM->getCharacterData(DeclLoc);
4184
25
  SourceLocation X = ND->getEndLoc();
4185
25
  X = SM->getExpansionLoc(X);
4186
25
  const char *endBuf = SM->getCharacterData(X);
4187
25
  std::string Name(ND->getNameAsString());
4188
25
  std::string ByrefType;
4189
25
  RewriteByRefString(ByrefType, Name, ND, true);
4190
25
  ByrefType += " {\n";
4191
25
  ByrefType += "  void *__isa;\n";
4192
25
  RewriteByRefString(ByrefType, Name, ND);
4193
25
  ByrefType += " *__forwarding;\n";
4194
25
  ByrefType += " int __flags;\n";
4195
25
  ByrefType += " int __size;\n";
4196
25
  // Add void *__Block_byref_id_object_copy;
4197
25
  // void *__Block_byref_id_object_dispose; if needed.
4198
25
  QualType Ty = ND->getType();
4199
25
  bool HasCopyAndDispose = Context->BlockRequiresCopying(Ty, ND);
4200
25
  if (HasCopyAndDispose) {
4201
8
    ByrefType += " void (*__Block_byref_id_object_copy)(void*, void*);\n";
4202
8
    ByrefType += " void (*__Block_byref_id_object_dispose)(void*);\n";
4203
8
  }
4204
25
4205
25
  QualType T = Ty;
4206
25
  (void)convertBlockPointerToFunctionPointer(T);
4207
25
  T.getAsStringInternal(Name, Context->getPrintingPolicy());
4208
25
4209
25
  ByrefType += " " + Name + ";\n";
4210
25
  ByrefType += "};\n";
4211
25
  // Insert this type in global scope. It is needed by helper function.
4212
25
  SourceLocation FunLocStart;
4213
25
  if (CurFunctionDef)
4214
17
     FunLocStart = CurFunctionDef->getTypeSpecStartLoc();
4215
8
  else {
4216
8
    assert(CurMethodDef && "RewriteByRefVar - CurMethodDef is null");
4217
8
    FunLocStart = CurMethodDef->getBeginLoc();
4218
8
  }
4219
25
  InsertText(FunLocStart, ByrefType);
4220
25
  if (Ty.isObjCGCWeak()) {
4221
2
    flag |= BLOCK_FIELD_IS_WEAK;
4222
2
    isa = 1;
4223
2
  }
4224
25
4225
25
  if (HasCopyAndDispose) {
4226
8
    flag = BLOCK_BYREF_CALLER;
4227
8
    QualType Ty = ND->getType();
4228
8
    // FIXME. Handle __weak variable (BLOCK_FIELD_IS_WEAK) as well.
4229
8
    if (Ty->isBlockPointerType())
4230
2
      flag |= BLOCK_FIELD_IS_BLOCK;
4231
6
    else
4232
6
      flag |= BLOCK_FIELD_IS_OBJECT;
4233
8
    std::string HF = SynthesizeByrefCopyDestroyHelper(ND, flag);
4234
8
    if (!HF.empty())
4235
5
      InsertText(FunLocStart, HF);
4236
8
  }
4237
25
4238
25
  // struct __Block_byref_ND ND =
4239
25
  // {0, &ND, some_flag, __size=sizeof(struct __Block_byref_ND),
4240
25
  //  initializer-if-any};
4241
25
  bool hasInit = (ND->getInit() != nullptr);
4242
25
  unsigned flags = 0;
4243
25
  if (HasCopyAndDispose)
4244
8
    flags |= BLOCK_HAS_COPY_DISPOSE;
4245
25
  Name = ND->getNameAsString();
4246
25
  ByrefType.clear();
4247
25
  RewriteByRefString(ByrefType, Name, ND);
4248
25
  std::string ForwardingCastType("(");
4249
25
  ForwardingCastType += ByrefType + " *)";
4250
25
  if (!hasInit) {
4251
5
    ByrefType += " " + Name + " = {(void*)";
4252
5
    ByrefType += utostr(isa);
4253
5
    ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
4254
5
    ByrefType += utostr(flags);
4255
5
    ByrefType += ", ";
4256
5
    ByrefType += "sizeof(";
4257
5
    RewriteByRefString(ByrefType, Name, ND);
4258
5
    ByrefType += ")";
4259
5
    if (HasCopyAndDispose) {
4260
2
      ByrefType += ", __Block_byref_id_object_copy_";
4261
2
      ByrefType += utostr(flag);
4262
2
      ByrefType += ", __Block_byref_id_object_dispose_";
4263
2
      ByrefType += utostr(flag);
4264
2
    }
4265
5
    ByrefType += "};\n";
4266
5
    unsigned nameSize = Name.size();
4267
5
    // for block or function pointer declaration. Name is already
4268
5
    // part of the declaration.
4269
5
    if (Ty->isBlockPointerType() || 
Ty->isFunctionPointerType()3
)
4270
2
      nameSize = 1;
4271
5
    ReplaceText(DeclLoc, endBuf-startBuf+nameSize, ByrefType);
4272
5
  }
4273
20
  else {
4274
20
    SourceLocation startLoc;
4275
20
    Expr *E = ND->getInit();
4276
20
    if (const CStyleCastExpr *ECE = dyn_cast<CStyleCastExpr>(E))
4277
1
      startLoc = ECE->getLParenLoc();
4278
19
    else
4279
19
      startLoc = E->getBeginLoc();
4280
20
    startLoc = SM->getExpansionLoc(startLoc);
4281
20
    endBuf = SM->getCharacterData(startLoc);
4282
20
    ByrefType += " " + Name;
4283
20
    ByrefType += " = {(void*)";
4284
20
    ByrefType += utostr(isa);
4285
20
    ByrefType += "," +  ForwardingCastType + "&" + Name + ", ";
4286
20
    ByrefType += utostr(flags);
4287
20
    ByrefType += ", ";
4288
20
    ByrefType += "sizeof(";
4289
20
    RewriteByRefString(ByrefType, Name, ND);
4290
20
    ByrefType += "), ";
4291
20
    if (HasCopyAndDispose) {
4292
6
      ByrefType += "__Block_byref_id_object_copy_";
4293
6
      ByrefType += utostr(flag);
4294
6
      ByrefType += ", __Block_byref_id_object_dispose_";
4295
6
      ByrefType += utostr(flag);
4296
6
      ByrefType += ", ";
4297
6
    }
4298
20
    ReplaceText(DeclLoc, endBuf-startBuf, ByrefType);
4299
20
4300
20
    // Complete the newly synthesized compound expression by inserting a right
4301
20
    // curly brace before the end of the declaration.
4302
20
    // FIXME: This approach avoids rewriting the initializer expression. It
4303
20
    // also assumes there is only one declarator. For example, the following
4304
20
    // isn't currently supported by this routine (in general):
4305
20
    //
4306
20
    // double __block BYREFVAR = 1.34, BYREFVAR2 = 1.37;
4307
20
    //
4308
20
    const char *startInitializerBuf = SM->getCharacterData(startLoc);
4309
20
    const char *semiBuf = strchr(startInitializerBuf, ';');
4310
20
    assert((*semiBuf == ';') && "RewriteByRefVar: can't find ';'");
4311
20
    SourceLocation semiLoc =
4312
20
      startLoc.getLocWithOffset(semiBuf-startInitializerBuf);
4313
20
4314
20
    InsertText(semiLoc, "}");
4315
20
  }
4316
25
}
4317
4318
136
void RewriteObjC::CollectBlockDeclRefInfo(BlockExpr *Exp) {
4319
136
  // Add initializers for any closure decl refs.
4320
136
  GetBlockDeclRefExprs(Exp->getBody());
4321
136
  if (BlockDeclRefs.size()) {
4322
80
    // Unique all "by copy" declarations.
4323
220
    for (unsigned i = 0; i < BlockDeclRefs.size(); 
i++140
)
4324
140
      if (!BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
4325
84
        if (!BlockByCopyDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4326
60
          BlockByCopyDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4327
60
          BlockByCopyDecls.push_back(BlockDeclRefs[i]->getDecl());
4328
60
        }
4329
84
      }
4330
80
    // Unique all "by ref" declarations.
4331
220
    for (unsigned i = 0; i < BlockDeclRefs.size(); 
i++140
)
4332
140
      if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>()) {
4333
56
        if (!BlockByRefDeclsPtrSet.count(BlockDeclRefs[i]->getDecl())) {
4334
54
          BlockByRefDeclsPtrSet.insert(BlockDeclRefs[i]->getDecl());
4335
54
          BlockByRefDecls.push_back(BlockDeclRefs[i]->getDecl());
4336
54
        }
4337
56
      }
4338
80
    // Find any imported blocks...they will need special attention.
4339
220
    for (unsigned i = 0; i < BlockDeclRefs.size(); 
i++140
)
4340
140
      if (BlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
4341
140
          
BlockDeclRefs[i]->getType()->isObjCObjectPointerType()84
||
4342
140
          
BlockDeclRefs[i]->getType()->isBlockPointerType()38
)
4343
110
        ImportedBlockDecls.insert(BlockDeclRefs[i]->getDecl());
4344
80
  }
4345
136
}
4346
4347
214
FunctionDecl *RewriteObjC::SynthBlockInitFunctionDecl(StringRef name) {
4348
214
  IdentifierInfo *ID = &Context->Idents.get(name);
4349
214
  QualType FType = Context->getFunctionNoProtoType(Context->VoidPtrTy);
4350
214
  return FunctionDecl::Create(*Context, TUDecl, SourceLocation(),
4351
214
                              SourceLocation(), ID, FType, nullptr, SC_Extern,
4352
214
                              false, false);
4353
214
}
4354
4355
Stmt *RewriteObjC::SynthBlockInitExpr(BlockExpr *Exp,
4356
68
                     const SmallVectorImpl<DeclRefExpr *> &InnerBlockDeclRefs) {
4357
68
  const BlockDecl *block = Exp->getBlockDecl();
4358
68
  Blocks.push_back(Exp);
4359
68
4360
68
  CollectBlockDeclRefInfo(Exp);
4361
68
4362
68
  // Add inner imported variables now used in current block.
4363
68
 int countOfInnerDecls = 0;
4364
68
  if (!InnerBlockDeclRefs.empty()) {
4365
136
    for (unsigned i = 0; i < InnerBlockDeclRefs.size(); 
i++90
) {
4366
90
      DeclRefExpr *Exp = InnerBlockDeclRefs[i];
4367
90
      ValueDecl *VD = Exp->getDecl();
4368
90
      if (!VD->hasAttr<BlocksAttr>() && 
!BlockByCopyDeclsPtrSet.count(VD)54
) {
4369
12
      // We need to save the copied-in variables in nested
4370
12
      // blocks because it is needed at the end for some of the API generations.
4371
12
      // See SynthesizeBlockLiterals routine.
4372
12
        InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4373
12
        BlockDeclRefs.push_back(Exp);
4374
12
        BlockByCopyDeclsPtrSet.insert(VD);
4375
12
        BlockByCopyDecls.push_back(VD);
4376
12
      }
4377
90
      if (VD->hasAttr<BlocksAttr>() && 
!BlockByRefDeclsPtrSet.count(VD)36
) {
4378
9
        InnerDeclRefs.push_back(Exp); countOfInnerDecls++;
4379
9
        BlockDeclRefs.push_back(Exp);
4380
9
        BlockByRefDeclsPtrSet.insert(VD);
4381
9
        BlockByRefDecls.push_back(VD);
4382
9
      }
4383
90
    }
4384
46
    // Find any imported blocks...they will need special attention.
4385
136
    for (unsigned i = 0; i < InnerBlockDeclRefs.size(); 
i++90
)
4386
90
      if (InnerBlockDeclRefs[i]->getDecl()->hasAttr<BlocksAttr>() ||
4387
90
          
InnerBlockDeclRefs[i]->getType()->isObjCObjectPointerType()54
||
4388
90
          
InnerBlockDeclRefs[i]->getType()->isBlockPointerType()19
)
4389
74
        ImportedBlockDecls.insert(InnerBlockDeclRefs[i]->getDecl());
4390
46
  }
4391
68
  InnerDeclRefsCount.push_back(countOfInnerDecls);
4392
68
4393
68
  std::string FuncName;
4394
68
4395
68
  if (CurFunctionDef)
4396
42
    FuncName = CurFunctionDef->getNameAsString();
4397
26
  else if (CurMethodDef)
4398
22
    BuildUniqueMethodName(FuncName, CurMethodDef);
4399
4
  else if (GlobalVarDecl)
4400
4
    FuncName = std::string(GlobalVarDecl->getNameAsString());
4401
68
4402
68
  std::string BlockNumber = utostr(Blocks.size()-1);
4403
68
4404
68
  std::string Tag = "__" + FuncName + "_block_impl_" + BlockNumber;
4405
68
  std::string Func = "__" + FuncName + "_block_func_" + BlockNumber;
4406
68
4407
68
  // Get a pointer to the function type so we can cast appropriately.
4408
68
  QualType BFT = convertFunctionTypeOfBlocks(Exp->getFunctionType());
4409
68
  QualType FType = Context->getPointerType(BFT);
4410
68
4411
68
  FunctionDecl *FD;
4412
68
  Expr *NewRep;
4413
68
4414
68
  // Simulate a constructor call...
4415
68
  FD = SynthBlockInitFunctionDecl(Tag);
4416
68
  DeclRefExpr *DRE = new (Context)
4417
68
      DeclRefExpr(*Context, FD, false, FType, VK_RValue, SourceLocation());
4418
68
4419
68
  SmallVector<Expr*, 4> InitExprs;
4420
68
4421
68
  // Initialize the block function.
4422
68
  FD = SynthBlockInitFunctionDecl(Func);
4423
68
  DeclRefExpr *Arg = new (Context) DeclRefExpr(
4424
68
      *Context, FD, false, FD->getType(), VK_LValue, SourceLocation());
4425
68
  CastExpr *castExpr =
4426
68
      NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, CK_BitCast, Arg);
4427
68
  InitExprs.push_back(castExpr);
4428
68
4429
68
  // Initialize the block descriptor.
4430
68
  std::string DescData = "__" + FuncName + "_block_desc_" + BlockNumber + "_DATA";
4431
68
4432
68
  VarDecl *NewVD = VarDecl::Create(
4433
68
      *Context, TUDecl, SourceLocation(), SourceLocation(),
4434
68
      &Context->Idents.get(DescData), Context->VoidPtrTy, nullptr, SC_Static);
4435
68
  UnaryOperator *DescRefExpr = new (Context) UnaryOperator(
4436
68
      new (Context) DeclRefExpr(*Context, NewVD, false, Context->VoidPtrTy,
4437
68
                                VK_LValue, SourceLocation()),
4438
68
      UO_AddrOf, Context->getPointerType(Context->VoidPtrTy), VK_RValue,
4439
68
      OK_Ordinary, SourceLocation(), false);
4440
68
  InitExprs.push_back(DescRefExpr);
4441
68
4442
68
  // Add initializers for any closure decl refs.
4443
68
  if (BlockDeclRefs.size()) {
4444
47
    Expr *Exp;
4445
47
    // Output all "by copy" declarations.
4446
47
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByCopyDecls.begin(),
4447
89
         E = BlockByCopyDecls.end(); I != E; 
++I42
) {
4448
42
      if (isObjCType((*I)->getType())) {
4449
7
        // FIXME: Conform to ABI ([[obj retain] autorelease]).
4450
7
        FD = SynthBlockInitFunctionDecl((*I)->getName());
4451
7
        Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
4452
7
                                        VK_LValue, SourceLocation());
4453
7
        if (HasLocalVariableExternalStorage(*I)) {
4454
1
          QualType QT = (*I)->getType();
4455
1
          QT = Context->getPointerType(QT);
4456
1
          Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4457
1
                                            OK_Ordinary, SourceLocation(),
4458
1
                                            false);
4459
1
        }
4460
35
      } else if (isTopLevelBlockPointerType((*I)->getType())) {
4461
2
        FD = SynthBlockInitFunctionDecl((*I)->getName());
4462
2
        Arg = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
4463
2
                                        VK_LValue, SourceLocation());
4464
2
        Exp = NoTypeInfoCStyleCastExpr(Context, Context->VoidPtrTy, CK_BitCast,
4465
2
                                       Arg);
4466
33
      } else {
4467
33
        FD = SynthBlockInitFunctionDecl((*I)->getName());
4468
33
        Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
4469
33
                                        VK_LValue, SourceLocation());
4470
33
        if (HasLocalVariableExternalStorage(*I)) {
4471
1
          QualType QT = (*I)->getType();
4472
1
          QT = Context->getPointerType(QT);
4473
1
          Exp = new (Context) UnaryOperator(Exp, UO_AddrOf, QT, VK_RValue,
4474
1
                                            OK_Ordinary, SourceLocation(),
4475
1
                                            false);
4476
1
        }
4477
33
      }
4478
42
      InitExprs.push_back(Exp);
4479
42
    }
4480
47
    // Output all "by ref" declarations.
4481
47
    for (SmallVectorImpl<ValueDecl *>::iterator I = BlockByRefDecls.begin(),
4482
83
         E = BlockByRefDecls.end(); I != E; 
++I36
) {
4483
36
      ValueDecl *ND = (*I);
4484
36
      std::string Name(ND->getNameAsString());
4485
36
      std::string RecName;
4486
36
      RewriteByRefString(RecName, Name, ND, true);
4487
36
      IdentifierInfo *II = &Context->Idents.get(RecName.c_str()
4488
36
                                                + sizeof("struct"));
4489
36
      RecordDecl *RD = RecordDecl::Create(*Context, TTK_Struct, TUDecl,
4490
36
                                          SourceLocation(), SourceLocation(),
4491
36
                                          II);
4492
36
      assert(RD && "SynthBlockInitExpr(): Can't find RecordDecl");
4493
36
      QualType castT = Context->getPointerType(Context->getTagDeclType(RD));
4494
36
4495
36
      FD = SynthBlockInitFunctionDecl((*I)->getName());
4496
36
      Exp = new (Context) DeclRefExpr(*Context, FD, false, FD->getType(),
4497
36
                                      VK_LValue, SourceLocation());
4498
36
      bool isNestedCapturedVar = false;
4499
36
      if (block)
4500
77
        
for (const auto &CI : block->captures())36
{
4501
77
          const VarDecl *variable = CI.getVariable();
4502
77
          if (variable == ND && 
CI.isNested()35
) {
4503
9
            assert (CI.isByRef() &&
4504
9
                    "SynthBlockInitExpr - captured block variable is not byref");
4505
9
            isNestedCapturedVar = true;
4506
9
            break;
4507
9
          }
4508
77
        }
4509
36
      // captured nested byref variable has its address passed. Do not take
4510
36
      // its address again.
4511
36
      if (!isNestedCapturedVar)
4512
27
        Exp = new (Context) UnaryOperator(
4513
27
            Exp, UO_AddrOf, Context->getPointerType(Exp->getType()), VK_RValue,
4514
27
            OK_Ordinary, SourceLocation(), false);
4515
36
      Exp = NoTypeInfoCStyleCastExpr(Context, castT, CK_BitCast, Exp);
4516
36
      InitExprs.push_back(Exp);
4517
36
    }
4518
47
  }
4519
68
  if (ImportedBlockDecls.size()) {
4520
41
    // generate BLOCK_HAS_COPY_DISPOSE(have helper funcs) | BLOCK_HAS_DESCRIPTOR
4521
41
    int flag = (BLOCK_HAS_COPY_DISPOSE | BLOCK_HAS_DESCRIPTOR);
4522
41
    unsigned IntSize =
4523
41
      static_cast<unsigned>(Context->getTypeSize(Context->IntTy));
4524
41
    Expr *FlagExp = IntegerLiteral::Create(*Context, llvm::APInt(IntSize, flag),
4525
41
                                           Context->IntTy, SourceLocation());
4526
41
    InitExprs.push_back(FlagExp);
4527
41
  }
4528
68
  NewRep = CallExpr::Create(*Context, DRE, InitExprs, FType, VK_LValue,
4529
68
                            SourceLocation());
4530
68
  NewRep = new (Context) UnaryOperator(
4531
68
      NewRep, UO_AddrOf, Context->getPointerType(NewRep->getType()), VK_RValue,
4532
68
      OK_Ordinary, SourceLocation(), false);
4533
68
  NewRep = NoTypeInfoCStyleCastExpr(Context, FType, CK_BitCast,
4534
68
                                    NewRep);
4535
68
  BlockDeclRefs.clear();
4536
68
  BlockByRefDecls.clear();
4537
68
  BlockByRefDeclsPtrSet.clear();
4538
68
  BlockByCopyDecls.clear();
4539
68
  BlockByCopyDeclsPtrSet.clear();
4540
68
  ImportedBlockDecls.clear();
4541
68
  return NewRep;
4542
68
}
4543
4544
13
bool RewriteObjC::IsDeclStmtInForeachHeader(DeclStmt *DS) {
4545
13
  if (const ObjCForCollectionStmt * CS =
4546
11
      dyn_cast<ObjCForCollectionStmt>(Stmts.back()))
4547
11
        return CS->getElement() == DS;
4548
2
  return false;
4549
2
}
4550
4551
//===----------------------------------------------------------------------===//
4552
// Function Body / Expression rewriting
4553
//===----------------------------------------------------------------------===//
4554
4555
2.13k
Stmt *RewriteObjC::RewriteFunctionBodyOrGlobalInitializer(Stmt *S) {
4556
2.13k
  if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4557
2.13k
      
isa<DoStmt>(S)2.12k
||
isa<ForStmt>(S)2.12k
)
4558
7
    Stmts.push_back(S);
4559
2.12k
  else if (isa<ObjCForCollectionStmt>(S)) {
4560
18
    Stmts.push_back(S);
4561
18
    ObjCBcLabelNo.push_back(++BcLabelCount);
4562
18
  }
4563
2.13k
4564
2.13k
  // Pseudo-object operations and ivar references need special
4565
2.13k
  // treatment because we're going to recursively rewrite them.
4566
2.13k
  if (PseudoObjectExpr *PseudoOp = dyn_cast<PseudoObjectExpr>(S)) {
4567
36
    if (isa<BinaryOperator>(PseudoOp->getSyntacticForm())) {
4568
14
      return RewritePropertyOrImplicitSetter(PseudoOp);
4569
22
    } else {
4570
22
      return RewritePropertyOrImplicitGetter(PseudoOp);
4571
22
    }
4572
2.09k
  } else if (ObjCIvarRefExpr *IvarRefExpr = dyn_cast<ObjCIvarRefExpr>(S)) {
4573
43
    return RewriteObjCIvarRefExpr(IvarRefExpr);
4574
43
  }
4575
2.05k
4576
2.05k
  SourceRange OrigStmtRange = S->getSourceRange();
4577
2.05k
4578
2.05k
  // Perform a bottom up rewrite of all children.
4579
2.05k
  for (Stmt *&childStmt : S->children())
4580
1.82k
    if (childStmt) {
4581
1.82k
      Stmt *newStmt = RewriteFunctionBodyOrGlobalInitializer(childStmt);
4582
1.82k
      if (newStmt) {
4583
1.78k
        childStmt = newStmt;
4584
1.78k
      }
4585
1.82k
    }
4586
2.05k
4587
2.05k
  if (BlockExpr *BE = dyn_cast<BlockExpr>(S)) {
4588
68
    SmallVector<DeclRefExpr *, 8> InnerBlockDeclRefs;
4589
68
    llvm::SmallPtrSet<const DeclContext *, 8> InnerContexts;
4590
68
    InnerContexts.insert(BE->getBlockDecl());
4591
68
    ImportedLocalExternalDecls.clear();
4592
68
    GetInnerBlockDeclRefExprs(BE->getBody(),
4593
68
                              InnerBlockDeclRefs, InnerContexts);
4594
68
    // Rewrite the block body in place.
4595
68
    Stmt *SaveCurrentBody = CurrentBody;
4596
68
    CurrentBody = BE->getBody();
4597
68
    PropParentMap = nullptr;
4598
68
    // block literal on rhs of a property-dot-sytax assignment
4599
68
    // must be replaced by its synthesize ast so getRewrittenText
4600
68
    // works as expected. In this case, what actually ends up on RHS
4601
68
    // is the blockTranscribed which is the helper function for the
4602
68
    // block literal; as in: self.c = ^() {[ace ARR];};
4603
68
    bool saveDisableReplaceStmt = DisableReplaceStmt;
4604
68
    DisableReplaceStmt = false;
4605
68
    RewriteFunctionBodyOrGlobalInitializer(BE->getBody());
4606
68
    DisableReplaceStmt = saveDisableReplaceStmt;
4607
68
    CurrentBody = SaveCurrentBody;
4608
68
    PropParentMap = nullptr;
4609
68
    ImportedLocalExternalDecls.clear();
4610
68
    // Now we snarf the rewritten text and stash it away for later use.
4611
68
    std::string Str = Rewrite.getRewrittenText(BE->getSourceRange());
4612
68
    RewrittenBlockExprs[BE] = Str;
4613
68
4614
68
    Stmt *blockTranscribed = SynthBlockInitExpr(BE, InnerBlockDeclRefs);
4615
68
4616
68
    //blockTranscribed->dump();
4617
68
    ReplaceStmt(S, blockTranscribed);
4618
68
    return blockTranscribed;
4619
68
  }
4620
1.98k
  // Handle specific things.
4621
1.98k
  if (ObjCEncodeExpr *AtEncode = dyn_cast<ObjCEncodeExpr>(S))
4622
3
    return RewriteAtEncode(AtEncode);
4623
1.98k
4624
1.98k
  if (ObjCSelectorExpr *AtSelector = dyn_cast<ObjCSelectorExpr>(S))
4625
1
    return RewriteAtSelector(AtSelector);
4626
1.98k
4627
1.98k
  if (ObjCStringLiteral *AtString = dyn_cast<ObjCStringLiteral>(S))
4628
18
    return RewriteObjCStringLiteral(AtString);
4629
1.96k
4630
1.96k
  if (ObjCMessageExpr *MessExpr = dyn_cast<ObjCMessageExpr>(S)) {
4631
#if 0
4632
    // Before we rewrite it, put the original message expression in a comment.
4633
    SourceLocation startLoc = MessExpr->getBeginLoc();
4634
    SourceLocation endLoc = MessExpr->getEndLoc();
4635
4636
    const char *startBuf = SM->getCharacterData(startLoc);
4637
    const char *endBuf = SM->getCharacterData(endLoc);
4638
4639
    std::string messString;
4640
    messString += "// ";
4641
    messString.append(startBuf, endBuf-startBuf+1);
4642
    messString += "\n";
4643
4644
    // FIXME: Missing definition of
4645
    // InsertText(clang::SourceLocation, char const*, unsigned int).
4646
    // InsertText(startLoc, messString);
4647
    // Tried this, but it didn't work either...
4648
    // ReplaceText(startLoc, 0, messString.c_str(), messString.size());
4649
#endif
4650
    return RewriteMessageExpr(MessExpr);
4651
79
  }
4652
1.88k
4653
1.88k
  if (ObjCAtTryStmt *StmtTry = dyn_cast<ObjCAtTryStmt>(S))
4654
8
    return RewriteObjCTryStmt(StmtTry);
4655
1.87k
4656
1.87k
  if (ObjCAtSynchronizedStmt *StmtTry = dyn_cast<ObjCAtSynchronizedStmt>(S))
4657
3
    return RewriteObjCSynchronizedStmt(StmtTry);
4658
1.87k
4659
1.87k
  if (ObjCAtThrowStmt *StmtThrow = dyn_cast<ObjCAtThrowStmt>(S))
4660
2
    return RewriteObjCThrowStmt(StmtThrow);
4661
1.87k
4662
1.87k
  if (ObjCProtocolExpr *ProtocolExp = dyn_cast<ObjCProtocolExpr>(S))
4663
0
    return RewriteObjCProtocolExpr(ProtocolExp);
4664
1.87k
4665
1.87k
  if (ObjCForCollectionStmt *StmtForCollection =
4666
18
        dyn_cast<ObjCForCollectionStmt>(S))
4667
18
    return RewriteObjCForCollectionStmt(StmtForCollection,
4668
18
                                        OrigStmtRange.getEnd());
4669
1.85k
  if (BreakStmt *StmtBreakStmt =
4670
6
      dyn_cast<BreakStmt>(S))
4671
6
    return RewriteBreakStmt(StmtBreakStmt);
4672
1.84k
  if (ContinueStmt *StmtContinueStmt =
4673
2
      dyn_cast<ContinueStmt>(S))
4674
2
    return RewriteContinueStmt(StmtContinueStmt);
4675
1.84k
4676
1.84k
  // Need to check for protocol refs (id <P>, Foo <P> *) in variable decls
4677
1.84k
  // and cast exprs.
4678
1.84k
  if (DeclStmt *DS = dyn_cast<DeclStmt>(S)) {
4679
141
    // FIXME: What we're doing here is modifying the type-specifier that
4680
141
    // precedes the first Decl.  In the future the DeclGroup should have
4681
141
    // a separate type-specifier that we can rewrite.
4682
141
    // NOTE: We need to avoid rewriting the DeclStmt if it is within
4683
141
    // the context of an ObjCForCollectionStmt. For example:
4684
141
    //   NSArray *someArray;
4685
141
    //   for (id <FooProtocol> index in someArray) ;
4686
141
    // This is because RewriteObjCForCollectionStmt() does textual rewriting
4687
141
    // and it depends on the original text locations/positions.
4688
141
    if (Stmts.empty() || 
!IsDeclStmtInForeachHeader(DS)13
)
4689
132
      RewriteObjCQualifiedInterfaceTypes(*DS->decl_begin());
4690
141
4691
141
    // Blocks rewrite rules.
4692
144
    for (auto *SD : DS->decls()) {
4693
144
      if (ValueDecl *ND = dyn_cast<ValueDecl>(SD)) {
4694
144
        if (isTopLevelBlockPointerType(ND->getType()))
4695
21
          RewriteBlockPointerDecl(ND);
4696
123
        else if (ND->getType()->isFunctionPointerType())
4697
1
          CheckFunctionPointerDecl(ND->getType(), ND);
4698
144
        if (VarDecl *VD = dyn_cast<VarDecl>(SD)) {
4699
144
          if (VD->hasAttr<BlocksAttr>()) {
4700
25
            static unsigned uniqueByrefDeclCount = 0;
4701
25
            assert(!BlockByRefDeclNo.count(ND) &&
4702
25
              "RewriteFunctionBodyOrGlobalInitializer: Duplicate byref decl");
4703
25
            BlockByRefDeclNo[ND] = uniqueByrefDeclCount++;
4704
25
            RewriteByRefVar(VD);
4705
25
          }
4706
119
          else
4707
119
            RewriteTypeOfDecl(VD);
4708
144
        }
4709
144
      }
4710
144
      if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(SD)) {
4711
0
        if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4712
0
          RewriteBlockPointerDecl(TD);
4713
0
        else if (TD->getUnderlyingType()->isFunctionPointerType())
4714
0
          CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4715
0
      }
4716
144
    }
4717
141
  }
4718
1.84k
4719
1.84k
  if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S))
4720
31
    RewriteObjCQualifiedInterfaceTypes(CE);
4721
1.84k
4722
1.84k
  if (isa<SwitchStmt>(S) || isa<WhileStmt>(S) ||
4723
1.84k
      
isa<DoStmt>(S)1.83k
||
isa<ForStmt>(S)1.83k
) {
4724
7
    assert(!Stmts.empty() && "Statement stack is empty");
4725
7
    assert ((isa<SwitchStmt>(Stmts.back()) || isa<WhileStmt>(Stmts.back()) ||
4726
7
             isa<DoStmt>(Stmts.back()) || isa<ForStmt>(Stmts.back()))
4727
7
            && "Statement stack mismatch");
4728
7
    Stmts.pop_back();
4729
7
  }
4730
1.84k
  // Handle blocks rewriting.
4731
1.84k
  if (DeclRefExpr *DRE = dyn_cast<DeclRefExpr>(S)) {
4732
369
    ValueDecl *VD = DRE->getDecl();
4733
369
    if (VD->hasAttr<BlocksAttr>())
4734
35
      return RewriteBlockDeclRefExpr(DRE);
4735
334
    if (HasLocalVariableExternalStorage(VD))
4736
15
      return RewriteLocalVariableExternalStorage(DRE);
4737
1.79k
  }
4738
1.79k
4739
1.79k
  if (CallExpr *CE = dyn_cast<CallExpr>(S)) {
4740
119
    if (CE->getCallee()->getType()->isBlockPointerType()) {
4741
14
      Stmt *BlockCall = SynthesizeBlockCall(CE, CE->getCallee());
4742
14
      ReplaceStmt(S, BlockCall);
4743
14
      return BlockCall;
4744
14
    }
4745
1.78k
  }
4746
1.78k
  if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(S)) {
4747
31
    RewriteCastExpr(CE);
4748
31
  }
4749
#if 0
4750
  if (ImplicitCastExpr *ICE = dyn_cast<ImplicitCastExpr>(S)) {
4751
    CastExpr *Replacement = new (Context) CastExpr(ICE->getType(),
4752
                                                   ICE->getSubExpr(),
4753
                                                   SourceLocation());
4754
    // Get the new text.
4755
    std::string SStr;
4756
    llvm::raw_string_ostream Buf(SStr);
4757
    Replacement->printPretty(Buf);
4758
    const std::string &Str = Buf.str();
4759
4760
    printf("CAST = %s\n", &Str[0]);
4761
    InsertText(ICE->getSubExpr()->getBeginLoc(), Str);
4762
    delete S;
4763
    return Replacement;
4764
  }
4765
#endif
4766
  // Return this stmt unmodified.
4767
1.78k
  return S;
4768
1.78k
}
4769
4770
11
void RewriteObjC::RewriteRecordBody(RecordDecl *RD) {
4771
18
  for (auto *FD : RD->fields()) {
4772
18
    if (isTopLevelBlockPointerType(FD->getType()))
4773
0
      RewriteBlockPointerDecl(FD);
4774
18
    if (FD->getType()->isObjCQualifiedIdType() ||
4775
18
        
FD->getType()->isObjCQualifiedInterfaceType()17
)
4776
1
      RewriteObjCQualifiedInterfaceTypes(FD);
4777
18
  }
4778
11
}
4779
4780
/// HandleDeclInMainFile - This is called for each top-level decl defined in the
4781
/// main file of the input.
4782
522
void RewriteObjC::HandleDeclInMainFile(Decl *D) {
4783
522
  switch (D->getKind()) {
4784
136
    case Decl::Function: {
4785
136
      FunctionDecl *FD = cast<FunctionDecl>(D);
4786
136
      if (FD->isOverloadedOperator())
4787
0
        return;
4788
136
4789
136
      // Since function prototypes don't have ParmDecl's, we check the function
4790
136
      // prototype. This enables us to rewrite function declarations and
4791
136
      // definitions using the same code.
4792
136
      RewriteBlocksInFunctionProtoType(FD->getType(), FD);
4793
136
4794
136
      if (!FD->isThisDeclarationADefinition())
4795
72
        break;
4796
64
4797
64
      // FIXME: If this should support Obj-C++, support CXXTryStmt
4798
64
      if (CompoundStmt *Body = dyn_cast_or_null<CompoundStmt>(FD->getBody())) {
4799
64
        CurFunctionDef = FD;
4800
64
        CurFunctionDeclToDeclareForBlock = FD;
4801
64
        CurrentBody = Body;
4802
64
        Body =
4803
64
        cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4804
64
        FD->setBody(Body);
4805
64
        CurrentBody = nullptr;
4806
64
        if (PropParentMap) {
4807
0
          delete PropParentMap;
4808
0
          PropParentMap = nullptr;
4809
0
        }
4810
64
        // This synthesizes and inserts the block "impl" struct, invoke function,
4811
64
        // and any copy/dispose helper functions.
4812
64
        InsertBlockLiteralsWithinFunction(FD);
4813
64
        CurFunctionDef = nullptr;
4814
64
        CurFunctionDeclToDeclareForBlock = nullptr;
4815
64
      }
4816
64
      break;
4817
64
    }
4818
77
    case Decl::ObjCMethod: {
4819
77
      ObjCMethodDecl *MD = cast<ObjCMethodDecl>(D);
4820
77
      if (CompoundStmt *Body = MD->getCompoundBody()) {
4821
77
        CurMethodDef = MD;
4822
77
        CurrentBody = Body;
4823
77
        Body =
4824
77
          cast_or_null<CompoundStmt>(RewriteFunctionBodyOrGlobalInitializer(Body));
4825
77
        MD->setBody(Body);
4826
77
        CurrentBody = nullptr;
4827
77
        if (PropParentMap) {
4828
0
          delete PropParentMap;
4829
0
          PropParentMap = nullptr;
4830
0
        }
4831
77
        InsertBlockLiteralsWithinMethod(MD);
4832
77
        CurMethodDef = nullptr;
4833
77
      }
4834
77
      break;
4835
64
    }
4836
64
    case Decl::ObjCImplementation: {
4837
64
      ObjCImplementationDecl *CI = cast<ObjCImplementationDecl>(D);
4838
64
      ClassImplementation.push_back(CI);
4839
64
      break;
4840
64
    }
4841
64
    case Decl::ObjCCategoryImpl: {
4842
6
      ObjCCategoryImplDecl *CI = cast<ObjCCategoryImplDecl>(D);
4843
6
      CategoryImplementation.push_back(CI);
4844
6
      break;
4845
64
    }
4846
64
    case Decl::Var: {
4847
17
      VarDecl *VD = cast<VarDecl>(D);
4848
17
      RewriteObjCQualifiedInterfaceTypes(VD);
4849
17
      if (isTopLevelBlockPointerType(VD->getType()))
4850
4
        RewriteBlockPointerDecl(VD);
4851
13
      else if (VD->getType()->isFunctionPointerType()) {
4852
0
        CheckFunctionPointerDecl(VD->getType(), VD);
4853
0
        if (VD->getInit()) {
4854
0
          if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4855
0
            RewriteCastExpr(CE);
4856
0
          }
4857
0
        }
4858
13
      } else if (VD->getType()->isRecordType()) {
4859
0
        RecordDecl *RD = VD->getType()->castAs<RecordType>()->getDecl();
4860
0
        if (RD->isCompleteDefinition())
4861
0
          RewriteRecordBody(RD);
4862
0
      }
4863
17
      if (VD->getInit()) {
4864
9
        GlobalVarDecl = VD;
4865
9
        CurrentBody = VD->getInit();
4866
9
        RewriteFunctionBodyOrGlobalInitializer(VD->getInit());
4867
9
        CurrentBody = nullptr;
4868
9
        if (PropParentMap) {
4869
0
          delete PropParentMap;
4870
0
          PropParentMap = nullptr;
4871
0
        }
4872
9
        SynthesizeBlockLiterals(VD->getTypeSpecStartLoc(), VD->getName());
4873
9
        GlobalVarDecl = nullptr;
4874
9
4875
9
        // This is needed for blocks.
4876
9
        if (CStyleCastExpr *CE = dyn_cast<CStyleCastExpr>(VD->getInit())) {
4877
0
            RewriteCastExpr(CE);
4878
0
        }
4879
9
      }
4880
17
      break;
4881
64
    }
4882
64
    case Decl::TypeAlias:
4883
50
    case Decl::Typedef: {
4884
50
      if (TypedefNameDecl *TD = dyn_cast<TypedefNameDecl>(D)) {
4885
50
        if (isTopLevelBlockPointerType(TD->getUnderlyingType()))
4886
20
          RewriteBlockPointerDecl(TD);
4887
30
        else if (TD->getUnderlyingType()->isFunctionPointerType())
4888
0
          CheckFunctionPointerDecl(TD->getUnderlyingType(), TD);
4889
50
      }
4890
50
      break;
4891
50
    }
4892
50
    case Decl::CXXRecord:
4893
14
    case Decl::Record: {
4894
14
      RecordDecl *RD = cast<RecordDecl>(D);
4895
14
      if (RD->isCompleteDefinition())
4896
11
        RewriteRecordBody(RD);
4897
14
      break;
4898
14
    }
4899
158
    default:
4900
158
      break;
4901
522
  }
4902
522
  // Nothing yet.
4903
522
}
4904
4905
86
void RewriteObjC::HandleTranslationUnit(ASTContext &C) {
4906
86
  if (Diags.hasErrorOccurred())
4907
0
    return;
4908
86
4909
86
  RewriteInclude();
4910
86
4911
86
  // Here's a great place to add any extra declarations that may be needed.
4912
86
  // Write out meta data for each @protocol(<expr>).
4913
86
  for (ObjCProtocolDecl *ProtDecl : ProtocolExprDecls)
4914
0
    RewriteObjCProtocolMetaData(ProtDecl, "", "", Preamble);
4915
86
4916
86
  InsertText(SM->getLocForStartOfFile(MainFileID), Preamble, false);
4917
86
  if (ClassImplementation.size() || 
CategoryImplementation.size()33
)
4918
53
    RewriteImplementations();
4919
86
4920
86
  // Get the buffer corresponding to MainFileID.  If we haven't changed it, then
4921
86
  // we are done.
4922
86
  if (const RewriteBuffer *RewriteBuf =
4923
86
      Rewrite.getRewriteBufferFor(MainFileID)) {
4924
86
    //printf("Changed:\n");
4925
86
    *OutFile << std::string(RewriteBuf->begin(), RewriteBuf->end());
4926
86
  } else {
4927
0
    llvm::errs() << "No changes\n";
4928
0
  }
4929
86
4930
86
  if (ClassImplementation.size() || 
CategoryImplementation.size()33
||
4931
86
      
ProtocolExprDecls.size()33
) {
4932
53
    // Rewrite Objective-c meta data*
4933
53
    std::string ResultStr;
4934
53
    RewriteMetaDataIntoBuffer(ResultStr);
4935
53
    // Emit metadata.
4936
53
    *OutFile << ResultStr;
4937
53
  }
4938
86
  OutFile->flush();
4939
86
}
4940
4941
86
void RewriteObjCFragileABI::Initialize(ASTContext &context) {
4942
86
  InitializeCommon(context);
4943
86
4944
86
  // declaring objc_selector outside the parameter list removes a silly
4945
86
  // scope related warning...
4946
86
  if (IsHeader)
4947
0
    Preamble = "#pragma once\n";
4948
86
  Preamble += "struct objc_selector; struct objc_class;\n";
4949
86
  Preamble += "struct __rw_objc_super { struct objc_object *object; ";
4950
86
  Preamble += "struct objc_object *superClass; ";
4951
86
  if (LangOpts.MicrosoftExt) {
4952
51
    // Add a constructor for creating temporary objects.
4953
51
    Preamble += "__rw_objc_super(struct objc_object *o, struct objc_object *s) "
4954
51
    ": ";
4955
51
    Preamble += "object(o), superClass(s) {} ";
4956
51
  }
4957
86
  Preamble += "};\n";
4958
86
  Preamble += "#ifndef _REWRITER_typedef_Protocol\n";
4959
86
  Preamble += "typedef struct objc_object Protocol;\n";
4960
86
  Preamble += "#define _REWRITER_typedef_Protocol\n";
4961
86
  Preamble += "#endif\n";
4962
86
  if (LangOpts.MicrosoftExt) {
4963
51
    Preamble += "#define __OBJC_RW_DLLIMPORT extern \"C\" __declspec(dllimport)\n";
4964
51
    Preamble += "#define __OBJC_RW_STATICIMPORT extern \"C\"\n";
4965
51
  } else
4966
35
    Preamble += "#define __OBJC_RW_DLLIMPORT extern\n";
4967
86
  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSend";
4968
86
  Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4969
86
  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_msgSendSuper";
4970
86
  Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
4971
86
  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSend_stret";
4972
86
  Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4973
86
  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object* objc_msgSendSuper_stret";
4974
86
  Preamble += "(struct objc_super *, struct objc_selector *, ...);\n";
4975
86
  Preamble += "__OBJC_RW_DLLIMPORT double objc_msgSend_fpret";
4976
86
  Preamble += "(struct objc_object *, struct objc_selector *, ...);\n";
4977
86
  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getClass";
4978
86
  Preamble += "(const char *);\n";
4979
86
  Preamble += "__OBJC_RW_DLLIMPORT struct objc_class *class_getSuperclass";
4980
86
  Preamble += "(struct objc_class *);\n";
4981
86
  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_getMetaClass";
4982
86
  Preamble += "(const char *);\n";
4983
86
  Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_throw(struct objc_object *);\n";
4984
86
  Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_enter(void *);\n";
4985
86
  Preamble += "__OBJC_RW_DLLIMPORT void objc_exception_try_exit(void *);\n";
4986
86
  Preamble += "__OBJC_RW_DLLIMPORT struct objc_object *objc_exception_extract(void *);\n";
4987
86
  Preamble += "__OBJC_RW_DLLIMPORT int objc_exception_match";
4988
86
  Preamble += "(struct objc_class *, struct objc_object *);\n";
4989
86
  // @synchronized hooks.
4990
86
  Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_enter(struct objc_object *);\n";
4991
86
  Preamble += "__OBJC_RW_DLLIMPORT int objc_sync_exit(struct objc_object *);\n";
4992
86
  Preamble += "__OBJC_RW_DLLIMPORT Protocol *objc_getProtocol(const char *);\n";
4993
86
  Preamble += "#ifndef __FASTENUMERATIONSTATE\n";
4994
86
  Preamble += "struct __objcFastEnumerationState {\n\t";
4995
86
  Preamble += "unsigned long state;\n\t";
4996
86
  Preamble += "void **itemsPtr;\n\t";
4997
86
  Preamble += "unsigned long *mutationsPtr;\n\t";
4998
86
  Preamble += "unsigned long extra[5];\n};\n";
4999
86
  Preamble += "__OBJC_RW_DLLIMPORT void objc_enumerationMutation(struct objc_object *);\n";
5000
86
  Preamble += "#define __FASTENUMERATIONSTATE\n";
5001
86
  Preamble += "#endif\n";
5002
86
  Preamble += "#ifndef __NSCONSTANTSTRINGIMPL\n";
5003
86
  Preamble += "struct __NSConstantStringImpl {\n";
5004
86
  Preamble += "  int *isa;\n";
5005
86
  Preamble += "  int flags;\n";
5006
86
  Preamble += "  char *str;\n";
5007
86
  Preamble += "  long length;\n";
5008
86
  Preamble += "};\n";
5009
86
  Preamble += "#ifdef CF_EXPORT_CONSTANT_STRING\n";
5010
86
  Preamble += "extern \"C\" __declspec(dllexport) int __CFConstantStringClassReference[];\n";
5011
86
  Preamble += "#else\n";
5012
86
  Preamble += "__OBJC_RW_DLLIMPORT int __CFConstantStringClassReference[];\n";
5013
86
  Preamble += "#endif\n";
5014
86
  Preamble += "#define __NSCONSTANTSTRINGIMPL\n";
5015
86
  Preamble += "#endif\n";
5016
86
  // Blocks preamble.
5017
86
  Preamble += "#ifndef BLOCK_IMPL\n";
5018
86
  Preamble += "#define BLOCK_IMPL\n";
5019
86
  Preamble += "struct __block_impl {\n";
5020
86
  Preamble += "  void *isa;\n";
5021
86
  Preamble += "  int Flags;\n";
5022
86
  Preamble += "  int Reserved;\n";
5023
86
  Preamble += "  void *FuncPtr;\n";
5024
86
  Preamble += "};\n";
5025
86
  Preamble += "// Runtime copy/destroy helper functions (from Block_private.h)\n";
5026
86
  Preamble += "#ifdef __OBJC_EXPORT_BLOCKS\n";
5027
86
  Preamble += "extern \"C\" __declspec(dllexport) "
5028
86
  "void _Block_object_assign(void *, const void *, const int);\n";
5029
86
  Preamble += "extern \"C\" __declspec(dllexport) void _Block_object_dispose(const void *, const int);\n";
5030
86
  Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteGlobalBlock[32];\n";
5031
86
  Preamble += "extern \"C\" __declspec(dllexport) void *_NSConcreteStackBlock[32];\n";
5032
86
  Preamble += "#else\n";
5033
86
  Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_assign(void *, const void *, const int);\n";
5034
86
  Preamble += "__OBJC_RW_DLLIMPORT void _Block_object_dispose(const void *, const int);\n";
5035
86
  Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteGlobalBlock[32];\n";
5036
86
  Preamble += "__OBJC_RW_DLLIMPORT void *_NSConcreteStackBlock[32];\n";
5037
86
  Preamble += "#endif\n";
5038
86
  Preamble += "#endif\n";
5039
86
  if (LangOpts.MicrosoftExt) {
5040
51
    Preamble += "#undef __OBJC_RW_DLLIMPORT\n";
5041
51
    Preamble += "#undef __OBJC_RW_STATICIMPORT\n";
5042
51
    Preamble += "#ifndef KEEP_ATTRIBUTES\n";  // We use this for clang tests.
5043
51
    Preamble += "#define __attribute__(X)\n";
5044
51
    Preamble += "#endif\n";
5045
51
    Preamble += "#define __weak\n";
5046
51
  }
5047
35
  else {
5048
35
    Preamble += "#define __block\n";
5049
35
    Preamble += "#define __weak\n";
5050
35
  }
5051
86
  // NOTE! Windows uses LLP64 for 64bit mode. So, cast pointer to long long
5052
86
  // as this avoids warning in any 64bit/32bit compilation model.
5053
86
  Preamble += "\n#define __OFFSETOFIVAR__(TYPE, MEMBER) ((long long) &((TYPE *)0)->MEMBER)\n";
5054
86
}
5055
5056
/// RewriteIvarOffsetComputation - This routine synthesizes computation of
5057
/// ivar offset.
5058
void RewriteObjCFragileABI::RewriteIvarOffsetComputation(ObjCIvarDecl *ivar,