Newer
Older
3001
3002
3003
3004
3005
3006
3007
3008
3009
3010
3011
3012
3013
3014
3015
3016
3017
3018
3019
3020
3021
3022
3023
3024
3025
3026
3027
3028
3029
3030
3031
3032
3033
3034
3035
3036
3037
3038
3039
3040
3041
3042
3043
3044
3045
3046
3047
3048
3049
3050
3051
3052
3053
3054
3055
3056
3057
3058
3059
3060
3061
3062
3063
3064
3065
3066
3067
3068
3069
3070
3071
3072
3073
3074
3075
3076
3077
3078
3079
3080
3081
3082
3083
3084
3085
3086
3087
3088
3089
3090
3091
3092
3093
3094
3095
3096
3097
Value *Arg = Call->getArgOperand(0);
Value *EarlierArg = EarlierCall->getArgOperand(0);
switch (PA.getAA()->alias(Arg, EarlierArg)) {
case AliasAnalysis::MustAlias:
Changed = true;
// If the load has a builtin retain, insert a plain retain for it.
if (Class == IC_LoadWeakRetained) {
CallInst *CI =
CallInst::Create(getRetainCallee(F.getParent()), EarlierCall,
"", Call);
CI->setTailCall();
}
// Zap the fully redundant load.
Call->replaceAllUsesWith(EarlierCall->getArgOperand(1));
Call->eraseFromParent();
goto clobbered;
case AliasAnalysis::MayAlias:
case AliasAnalysis::PartialAlias:
goto clobbered;
case AliasAnalysis::NoAlias:
break;
}
break;
}
case IC_MoveWeak:
case IC_CopyWeak:
// TOOD: Grab the copied value.
goto clobbered;
case IC_AutoreleasepoolPush:
case IC_None:
case IC_User:
// Weak pointers are only modified through the weak entry points
// (and arbitrary calls, which could call the weak entry points).
break;
default:
// Anything else could modify the weak pointer.
goto clobbered;
}
}
clobbered:;
}
// Then, for each destroyWeak with an alloca operand, check to see if
// the alloca and all its users can be zapped.
for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
Instruction *Inst = &*I++;
InstructionClass Class = GetBasicInstructionClass(Inst);
if (Class != IC_DestroyWeak)
continue;
CallInst *Call = cast<CallInst>(Inst);
Value *Arg = Call->getArgOperand(0);
if (AllocaInst *Alloca = dyn_cast<AllocaInst>(Arg)) {
for (Value::use_iterator UI = Alloca->use_begin(),
UE = Alloca->use_end(); UI != UE; ++UI) {
Instruction *UserInst = cast<Instruction>(*UI);
switch (GetBasicInstructionClass(UserInst)) {
case IC_InitWeak:
case IC_StoreWeak:
case IC_DestroyWeak:
continue;
default:
goto done;
}
}
Changed = true;
for (Value::use_iterator UI = Alloca->use_begin(),
UE = Alloca->use_end(); UI != UE; ) {
CallInst *UserInst = cast<CallInst>(*UI++);
if (!UserInst->use_empty())
UserInst->replaceAllUsesWith(UserInst->getOperand(1));
UserInst->eraseFromParent();
}
Alloca->eraseFromParent();
done:;
}
}
}
/// OptimizeSequences - Identify program paths which execute sequences of
/// retains and releases which can be eliminated.
bool ObjCARCOpt::OptimizeSequences(Function &F) {
/// Releases, Retains - These are used to store the results of the main flow
/// analysis. These use Value* as the key instead of Instruction* so that the
/// map stays valid when we get around to rewriting code and calls get
/// replaced by arguments.
DenseMap<Value *, RRInfo> Releases;
MapVector<Value *, RRInfo> Retains;
/// BBStates, This is used during the traversal of the function to track the
/// states for each identified object at each block.
DenseMap<const BasicBlock *, BBState> BBStates;
// Analyze the CFG of the function, and all instructions.
bool NestingDetected = Visit(F, BBStates, Retains, Releases);
// Transform.
return PerformCodePlacement(BBStates, Retains, Releases, F.getParent()) &&
NestingDetected;
3100
3101
3102
3103
3104
3105
3106
3107
3108
3109
3110
3111
3112
3113
3114
3115
3116
3117
3118
3119
3120
3121
3122
3123
3124
3125
3126
3127
3128
3129
3130
3131
3132
3133
3134
3135
3136
3137
3138
3139
3140
3141
3142
3143
3144
3145
3146
3147
3148
3149
3150
3151
3152
3153
3154
3155
3156
3157
3158
3159
3160
3161
3162
3163
3164
3165
3166
3167
3168
3169
3170
3171
3172
3173
3174
3175
3176
3177
3178
3179
3180
3181
3182
3183
3184
3185
3186
3187
3188
3189
3190
3191
3192
3193
3194
3195
3196
3197
3198
3199
3200
3201
3202
3203
3204
3205
3206
3207
3208
3209
3210
3211
3212
3213
3214
}
/// OptimizeReturns - Look for this pattern:
///
/// %call = call i8* @something(...)
/// %2 = call i8* @objc_retain(i8* %call)
/// %3 = call i8* @objc_autorelease(i8* %2)
/// ret i8* %3
///
/// And delete the retain and autorelease.
///
/// Otherwise if it's just this:
///
/// %3 = call i8* @objc_autorelease(i8* %2)
/// ret i8* %3
///
/// convert the autorelease to autoreleaseRV.
void ObjCARCOpt::OptimizeReturns(Function &F) {
if (!F.getReturnType()->isPointerTy())
return;
SmallPtrSet<Instruction *, 4> DependingInstructions;
SmallPtrSet<const BasicBlock *, 4> Visited;
for (Function::iterator FI = F.begin(), FE = F.end(); FI != FE; ++FI) {
BasicBlock *BB = FI;
ReturnInst *Ret = dyn_cast<ReturnInst>(&BB->back());
if (!Ret) continue;
const Value *Arg = StripPointerCastsAndObjCCalls(Ret->getOperand(0));
FindDependencies(NeedsPositiveRetainCount, Arg,
BB, Ret, DependingInstructions, Visited, PA);
if (DependingInstructions.size() != 1)
goto next_block;
{
CallInst *Autorelease =
dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
if (!Autorelease)
goto next_block;
InstructionClass AutoreleaseClass =
GetBasicInstructionClass(Autorelease);
if (!IsAutorelease(AutoreleaseClass))
goto next_block;
if (GetObjCArg(Autorelease) != Arg)
goto next_block;
DependingInstructions.clear();
Visited.clear();
// Check that there is nothing that can affect the reference
// count between the autorelease and the retain.
FindDependencies(CanChangeRetainCount, Arg,
BB, Autorelease, DependingInstructions, Visited, PA);
if (DependingInstructions.size() != 1)
goto next_block;
{
CallInst *Retain =
dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
// Check that we found a retain with the same argument.
if (!Retain ||
!IsRetain(GetBasicInstructionClass(Retain)) ||
GetObjCArg(Retain) != Arg)
goto next_block;
DependingInstructions.clear();
Visited.clear();
// Convert the autorelease to an autoreleaseRV, since it's
// returning the value.
if (AutoreleaseClass == IC_Autorelease) {
Autorelease->setCalledFunction(getAutoreleaseRVCallee(F.getParent()));
AutoreleaseClass = IC_AutoreleaseRV;
}
// Check that there is nothing that can affect the reference
// count between the retain and the call.
FindDependencies(CanChangeRetainCount, Arg, BB, Retain,
DependingInstructions, Visited, PA);
if (DependingInstructions.size() != 1)
goto next_block;
{
CallInst *Call =
dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
// Check that the pointer is the return value of the call.
if (!Call || Arg != Call)
goto next_block;
// Check that the call is a regular call.
InstructionClass Class = GetBasicInstructionClass(Call);
if (Class != IC_CallOrUser && Class != IC_Call)
goto next_block;
// If so, we can zap the retain and autorelease.
Changed = true;
++NumRets;
EraseInstruction(Retain);
EraseInstruction(Autorelease);
}
}
}
next_block:
DependingInstructions.clear();
Visited.clear();
}
}
bool ObjCARCOpt::doInitialization(Module &M) {
if (!EnableARCOpts)
return false;
Run = ModuleHasARC(M);
if (!Run)
return false;
// Identify the imprecise release metadata kind.
ImpreciseReleaseMDKind =
M.getContext().getMDKindID("clang.imprecise_release");
// Intuitively, objc_retain and others are nocapture, however in practice
// they are not, because they return their argument value. And objc_release
// calls finalizers.
// These are initialized lazily.
RetainRVCallee = 0;
AutoreleaseRVCallee = 0;
ReleaseCallee = 0;
RetainCallee = 0;
RetainBlockCallee = 0;
AutoreleaseCallee = 0;
return false;
}
bool ObjCARCOpt::runOnFunction(Function &F) {
if (!EnableARCOpts)
return false;
// If nothing in the Module uses ARC, don't do anything.
if (!Run)
return false;
3246
3247
3248
3249
3250
3251
3252
3253
3254
3255
3256
3257
3258
3259
3260
3261
3262
3263
3264
3265
3266
3267
3268
3269
3270
3271
3272
3273
3274
3275
3276
3277
3278
3279
3280
3281
3282
3283
3284
3285
3286
3287
3288
3289
3290
3291
3292
3293
3294
3295
3296
3297
3298
3299
3300
3301
3302
3303
3304
3305
3306
3307
3308
3309
Changed = false;
PA.setAA(&getAnalysis<AliasAnalysis>());
// This pass performs several distinct transformations. As a compile-time aid
// when compiling code that isn't ObjC, skip these if the relevant ObjC
// library functions aren't declared.
// Preliminary optimizations. This also computs UsedInThisFunction.
OptimizeIndividualCalls(F);
// Optimizations for weak pointers.
if (UsedInThisFunction & ((1 << IC_LoadWeak) |
(1 << IC_LoadWeakRetained) |
(1 << IC_StoreWeak) |
(1 << IC_InitWeak) |
(1 << IC_CopyWeak) |
(1 << IC_MoveWeak) |
(1 << IC_DestroyWeak)))
OptimizeWeakCalls(F);
// Optimizations for retain+release pairs.
if (UsedInThisFunction & ((1 << IC_Retain) |
(1 << IC_RetainRV) |
(1 << IC_RetainBlock)))
if (UsedInThisFunction & (1 << IC_Release))
// Run OptimizeSequences until it either stops making changes or
// no retain+release pair nesting is detected.
while (OptimizeSequences(F)) {}
// Optimizations if objc_autorelease is used.
if (UsedInThisFunction &
((1 << IC_Autorelease) | (1 << IC_AutoreleaseRV)))
OptimizeReturns(F);
return Changed;
}
void ObjCARCOpt::releaseMemory() {
PA.clear();
}
//===----------------------------------------------------------------------===//
// ARC contraction.
//===----------------------------------------------------------------------===//
// TODO: ObjCARCContract could insert PHI nodes when uses aren't
// dominated by single calls.
#include "llvm/Operator.h"
#include "llvm/InlineAsm.h"
#include "llvm/Analysis/Dominators.h"
STATISTIC(NumStoreStrongs, "Number objc_storeStrong calls formed");
namespace {
/// ObjCARCContract - Late ARC optimizations. These change the IR in a way
/// that makes it difficult to be analyzed by ObjCARCOpt, so it's run late.
class ObjCARCContract : public FunctionPass {
bool Changed;
AliasAnalysis *AA;
DominatorTree *DT;
ProvenanceAnalysis PA;
/// Run - A flag indicating whether this optimization pass should run.
bool Run;
3313
3314
3315
3316
3317
3318
3319
3320
3321
3322
3323
3324
3325
3326
3327
3328
3329
3330
3331
3332
3333
3334
3335
3336
3337
3338
3339
3340
3341
3342
3343
3344
3345
3346
3347
3348
3349
3350
3351
3352
3353
3354
3355
3356
3357
3358
3359
3360
3361
3362
3363
3364
3365
3366
3367
3368
3369
/// StoreStrongCallee, etc. - Declarations for ObjC runtime
/// functions, for use in creating calls to them. These are initialized
/// lazily to avoid cluttering up the Module with unused declarations.
Constant *StoreStrongCallee,
*RetainAutoreleaseCallee, *RetainAutoreleaseRVCallee;
/// RetainRVMarker - The inline asm string to insert between calls and
/// RetainRV calls to make the optimization work on targets which need it.
const MDString *RetainRVMarker;
Constant *getStoreStrongCallee(Module *M);
Constant *getRetainAutoreleaseCallee(Module *M);
Constant *getRetainAutoreleaseRVCallee(Module *M);
bool ContractAutorelease(Function &F, Instruction *Autorelease,
InstructionClass Class,
SmallPtrSet<Instruction *, 4>
&DependingInstructions,
SmallPtrSet<const BasicBlock *, 4>
&Visited);
void ContractRelease(Instruction *Release,
inst_iterator &Iter);
virtual void getAnalysisUsage(AnalysisUsage &AU) const;
virtual bool doInitialization(Module &M);
virtual bool runOnFunction(Function &F);
public:
static char ID;
ObjCARCContract() : FunctionPass(ID) {
initializeObjCARCContractPass(*PassRegistry::getPassRegistry());
}
};
}
char ObjCARCContract::ID = 0;
INITIALIZE_PASS_BEGIN(ObjCARCContract,
"objc-arc-contract", "ObjC ARC contraction", false, false)
INITIALIZE_AG_DEPENDENCY(AliasAnalysis)
INITIALIZE_PASS_DEPENDENCY(DominatorTree)
INITIALIZE_PASS_END(ObjCARCContract,
"objc-arc-contract", "ObjC ARC contraction", false, false)
Pass *llvm::createObjCARCContractPass() {
return new ObjCARCContract();
}
void ObjCARCContract::getAnalysisUsage(AnalysisUsage &AU) const {
AU.addRequired<AliasAnalysis>();
AU.addRequired<DominatorTree>();
AU.setPreservesCFG();
}
Constant *ObjCARCContract::getStoreStrongCallee(Module *M) {
if (!StoreStrongCallee) {
LLVMContext &C = M->getContext();
Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Type *I8XX = PointerType::getUnqual(I8X);
std::vector<Type *> Params;
Params.push_back(I8XX);
Params.push_back(I8X);
AttrListPtr Attributes;
Attributes.addAttr(~0u, Attribute::NoUnwind);
Attributes.addAttr(1, Attribute::NoCapture);
StoreStrongCallee =
M->getOrInsertFunction(
"objc_storeStrong",
FunctionType::get(Type::getVoidTy(C), Params, /*isVarArg=*/false),
Attributes);
}
return StoreStrongCallee;
}
Constant *ObjCARCContract::getRetainAutoreleaseCallee(Module *M) {
if (!RetainAutoreleaseCallee) {
LLVMContext &C = M->getContext();
Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
std::vector<Type *> Params;
Params.push_back(I8X);
FunctionType *FTy =
FunctionType::get(I8X, Params, /*isVarArg=*/false);
AttrListPtr Attributes;
Attributes.addAttr(~0u, Attribute::NoUnwind);
RetainAutoreleaseCallee =
M->getOrInsertFunction("objc_retainAutorelease", FTy, Attributes);
}
return RetainAutoreleaseCallee;
}
Constant *ObjCARCContract::getRetainAutoreleaseRVCallee(Module *M) {
if (!RetainAutoreleaseRVCallee) {
LLVMContext &C = M->getContext();
Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
std::vector<Type *> Params;
Params.push_back(I8X);
FunctionType *FTy =
3412
3413
3414
3415
3416
3417
3418
3419
3420
3421
3422
3423
3424
3425
3426
3427
3428
3429
3430
3431
3432
3433
3434
3435
3436
3437
3438
3439
3440
3441
3442
3443
3444
3445
3446
3447
3448
3449
3450
3451
3452
3453
3454
3455
3456
3457
3458
3459
3460
3461
3462
3463
3464
3465
3466
3467
3468
3469
3470
3471
3472
3473
3474
3475
3476
3477
FunctionType::get(I8X, Params, /*isVarArg=*/false);
AttrListPtr Attributes;
Attributes.addAttr(~0u, Attribute::NoUnwind);
RetainAutoreleaseRVCallee =
M->getOrInsertFunction("objc_retainAutoreleaseReturnValue", FTy,
Attributes);
}
return RetainAutoreleaseRVCallee;
}
/// ContractAutorelease - Merge an autorelease with a retain into a fused
/// call.
bool
ObjCARCContract::ContractAutorelease(Function &F, Instruction *Autorelease,
InstructionClass Class,
SmallPtrSet<Instruction *, 4>
&DependingInstructions,
SmallPtrSet<const BasicBlock *, 4>
&Visited) {
const Value *Arg = GetObjCArg(Autorelease);
// Check that there are no instructions between the retain and the autorelease
// (such as an autorelease_pop) which may change the count.
CallInst *Retain = 0;
if (Class == IC_AutoreleaseRV)
FindDependencies(RetainAutoreleaseRVDep, Arg,
Autorelease->getParent(), Autorelease,
DependingInstructions, Visited, PA);
else
FindDependencies(RetainAutoreleaseDep, Arg,
Autorelease->getParent(), Autorelease,
DependingInstructions, Visited, PA);
Visited.clear();
if (DependingInstructions.size() != 1) {
DependingInstructions.clear();
return false;
}
Retain = dyn_cast_or_null<CallInst>(*DependingInstructions.begin());
DependingInstructions.clear();
if (!Retain ||
GetBasicInstructionClass(Retain) != IC_Retain ||
GetObjCArg(Retain) != Arg)
return false;
Changed = true;
++NumPeeps;
if (Class == IC_AutoreleaseRV)
Retain->setCalledFunction(getRetainAutoreleaseRVCallee(F.getParent()));
else
Retain->setCalledFunction(getRetainAutoreleaseCallee(F.getParent()));
EraseInstruction(Autorelease);
return true;
}
/// ContractRelease - Attempt to merge an objc_release with a store, load, and
/// objc_retain to form an objc_storeStrong. This can be a little tricky because
/// the instructions don't always appear in order, and there may be unrelated
/// intervening instructions.
void ObjCARCContract::ContractRelease(Instruction *Release,
inst_iterator &Iter) {
LoadInst *Load = dyn_cast<LoadInst>(GetObjCArg(Release));
Eli Friedman
committed
if (!Load || !Load->isSimple()) return;
// For now, require everything to be in one basic block.
BasicBlock *BB = Release->getParent();
if (Load->getParent() != BB) return;
// Walk down to find the store.
BasicBlock::iterator I = Load, End = BB->end();
++I;
AliasAnalysis::Location Loc = AA->getLocation(Load);
while (I != End &&
(&*I == Release ||
IsRetain(GetBasicInstructionClass(I)) ||
!(AA->getModRefInfo(I, Loc) & AliasAnalysis::Mod)))
++I;
StoreInst *Store = dyn_cast<StoreInst>(I);
Eli Friedman
committed
if (!Store || !Store->isSimple()) return;
if (Store->getPointerOperand() != Loc.Ptr) return;
Value *New = StripPointerCastsAndObjCCalls(Store->getValueOperand());
// Walk up to find the retain.
I = Store;
BasicBlock::iterator Begin = BB->begin();
while (I != Begin && GetBasicInstructionClass(I) != IC_Retain)
--I;
Instruction *Retain = I;
if (GetBasicInstructionClass(Retain) != IC_Retain) return;
if (GetObjCArg(Retain) != New) return;
Changed = true;
++NumStoreStrongs;
LLVMContext &C = Release->getContext();
Type *I8X = PointerType::getUnqual(Type::getInt8Ty(C));
Type *I8XX = PointerType::getUnqual(I8X);
Value *Args[] = { Load->getPointerOperand(), New };
if (Args[0]->getType() != I8XX)
Args[0] = new BitCastInst(Args[0], I8XX, "", Store);
if (Args[1]->getType() != I8X)
Args[1] = new BitCastInst(Args[1], I8X, "", Store);
CallInst *StoreStrong =
CallInst::Create(getStoreStrongCallee(BB->getParent()->getParent()),
StoreStrong->setDoesNotThrow();
StoreStrong->setDebugLoc(Store->getDebugLoc());
if (&*Iter == Store) ++Iter;
Store->eraseFromParent();
Release->eraseFromParent();
EraseInstruction(Retain);
if (Load->use_empty())
Load->eraseFromParent();
}
bool ObjCARCContract::doInitialization(Module &M) {
Run = ModuleHasARC(M);
if (!Run)
return false;
3539
3540
3541
3542
3543
3544
3545
3546
3547
3548
3549
3550
3551
3552
3553
3554
3555
3556
3557
3558
3559
3560
3561
// These are initialized lazily.
StoreStrongCallee = 0;
RetainAutoreleaseCallee = 0;
RetainAutoreleaseRVCallee = 0;
// Initialize RetainRVMarker.
RetainRVMarker = 0;
if (NamedMDNode *NMD =
M.getNamedMetadata("clang.arc.retainAutoreleasedReturnValueMarker"))
if (NMD->getNumOperands() == 1) {
const MDNode *N = NMD->getOperand(0);
if (N->getNumOperands() == 1)
if (const MDString *S = dyn_cast<MDString>(N->getOperand(0)))
RetainRVMarker = S;
}
return false;
}
bool ObjCARCContract::runOnFunction(Function &F) {
if (!EnableARCOpts)
return false;
// If nothing in the Module uses ARC, don't do anything.
if (!Run)
return false;
3566
3567
3568
3569
3570
3571
3572
3573
3574
3575
3576
3577
3578
3579
3580
3581
3582
3583
3584
3585
3586
3587
3588
3589
3590
3591
3592
3593
3594
3595
3596
3597
3598
3599
3600
3601
3602
3603
3604
3605
3606
3607
3608
3609
3610
3611
3612
3613
3614
3615
3616
3617
3618
3619
3620
3621
3622
3623
3624
3625
3626
3627
3628
3629
3630
3631
3632
3633
3634
3635
3636
3637
3638
3639
3640
3641
3642
3643
3644
3645
3646
3647
3648
Changed = false;
AA = &getAnalysis<AliasAnalysis>();
DT = &getAnalysis<DominatorTree>();
PA.setAA(&getAnalysis<AliasAnalysis>());
// For ObjC library calls which return their argument, replace uses of the
// argument with uses of the call return value, if it dominates the use. This
// reduces register pressure.
SmallPtrSet<Instruction *, 4> DependingInstructions;
SmallPtrSet<const BasicBlock *, 4> Visited;
for (inst_iterator I = inst_begin(&F), E = inst_end(&F); I != E; ) {
Instruction *Inst = &*I++;
// Only these library routines return their argument. In particular,
// objc_retainBlock does not necessarily return its argument.
InstructionClass Class = GetBasicInstructionClass(Inst);
switch (Class) {
case IC_Retain:
case IC_FusedRetainAutorelease:
case IC_FusedRetainAutoreleaseRV:
break;
case IC_Autorelease:
case IC_AutoreleaseRV:
if (ContractAutorelease(F, Inst, Class, DependingInstructions, Visited))
continue;
break;
case IC_RetainRV: {
// If we're compiling for a target which needs a special inline-asm
// marker to do the retainAutoreleasedReturnValue optimization,
// insert it now.
if (!RetainRVMarker)
break;
BasicBlock::iterator BBI = Inst;
--BBI;
while (isNoopInstruction(BBI)) --BBI;
if (&*BBI == GetObjCArg(Inst)) {
InlineAsm *IA =
InlineAsm::get(FunctionType::get(Type::getVoidTy(Inst->getContext()),
/*isVarArg=*/false),
RetainRVMarker->getString(),
/*Constraints=*/"", /*hasSideEffects=*/true);
CallInst::Create(IA, "", Inst);
}
break;
}
case IC_InitWeak: {
// objc_initWeak(p, null) => *p = null
CallInst *CI = cast<CallInst>(Inst);
if (isNullOrUndef(CI->getArgOperand(1))) {
Value *Null =
ConstantPointerNull::get(cast<PointerType>(CI->getType()));
Changed = true;
new StoreInst(Null, CI->getArgOperand(0), CI);
CI->replaceAllUsesWith(Null);
CI->eraseFromParent();
}
continue;
}
case IC_Release:
ContractRelease(Inst, I);
continue;
default:
continue;
}
// Don't use GetObjCArg because we don't want to look through bitcasts
// and such; to do the replacement, the argument must have type i8*.
const Value *Arg = cast<CallInst>(Inst)->getArgOperand(0);
for (;;) {
// If we're compiling bugpointed code, don't get in trouble.
if (!isa<Instruction>(Arg) && !isa<Argument>(Arg))
break;
// Look through the uses of the pointer.
for (Value::const_use_iterator UI = Arg->use_begin(), UE = Arg->use_end();
UI != UE; ) {
Use &U = UI.getUse();
unsigned OperandNo = UI.getOperandNo();
++UI; // Increment UI now, because we may unlink its element.
if (Instruction *UserInst = dyn_cast<Instruction>(U.getUser()))
if (Inst != UserInst && DT->dominates(Inst, UserInst)) {
Changed = true;
Instruction *Replacement = Inst;
Type *UseTy = U.get()->getType();
3650
3651
3652
3653
3654
3655
3656
3657
3658
3659
3660
3661
3662
3663
3664
3665
3666
3667
3668
3669
3670
3671
3672
3673
3674
3675
3676
3677
3678
3679
3680
3681
3682
3683
3684
3685
3686
3687
3688
3689
3690
3691
3692
3693
if (PHINode *PHI = dyn_cast<PHINode>(UserInst)) {
// For PHI nodes, insert the bitcast in the predecessor block.
unsigned ValNo =
PHINode::getIncomingValueNumForOperand(OperandNo);
BasicBlock *BB =
PHI->getIncomingBlock(ValNo);
if (Replacement->getType() != UseTy)
Replacement = new BitCastInst(Replacement, UseTy, "",
&BB->back());
for (unsigned i = 0, e = PHI->getNumIncomingValues();
i != e; ++i)
if (PHI->getIncomingBlock(i) == BB) {
// Keep the UI iterator valid.
if (&PHI->getOperandUse(
PHINode::getOperandNumForIncomingValue(i)) ==
&UI.getUse())
++UI;
PHI->setIncomingValue(i, Replacement);
}
} else {
if (Replacement->getType() != UseTy)
Replacement = new BitCastInst(Replacement, UseTy, "", UserInst);
U.set(Replacement);
}
}
}
// If Arg is a no-op casted pointer, strip one level of casts and
// iterate.
if (const BitCastInst *BI = dyn_cast<BitCastInst>(Arg))
Arg = BI->getOperand(0);
else if (isa<GEPOperator>(Arg) &&
cast<GEPOperator>(Arg)->hasAllZeroIndices())
Arg = cast<GEPOperator>(Arg)->getPointerOperand();
else if (isa<GlobalAlias>(Arg) &&
!cast<GlobalAlias>(Arg)->mayBeOverridden())
Arg = cast<GlobalAlias>(Arg)->getAliasee();
else
break;
}
}
return Changed;
}